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 session replay player and merged session view (#65876)

Marco Gancitanofcc477d40b7a
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 110e520a5761..e8329ff638eb 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -187,7 +187,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/ai-observability/tools': ['AIObservability', 'aiObservabilityTools'],
'/ai-observability/sentiment': ['AIObservability', 'aiObservabilitySentiment'],
'/ai-observability/sessions': ['AIObservability', 'aiObservabilitySessions'],
- '/ai-observability/sessions/:id': ['AIObservabilitySession', 'aiObservability'],
+ '/ai-observability/sessions/:id': ['AIObservability', 'aiObservabilitySessions'],
'/ai-observability/playground': ['AIObservabilityPlayground', 'aiObservabilityPlayground'],
'/ai-observability/clusters': ['AIObservabilityClusters', 'aiObservabilityClusters'],
'/ai-observability/clusters/:runId': ['AIObservabilityClusters', 'aiObservabilityClusters'],
diff --git a/posthog/hogql_queries/ai/test/test_sessions_aggregation.py b/posthog/hogql_queries/ai/test/test_sessions_aggregation.py
index 279926be08eb..115e790787ca 100644
--- a/posthog/hogql_queries/ai/test/test_sessions_aggregation.py
+++ b/posthog/hogql_queries/ai/test/test_sessions_aggregation.py
@@ -2,7 +2,7 @@ import uuid
from datetime import datetime
from freezegun import freeze_time
-from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
from parameterized import parameterized
@@ -134,6 +134,7 @@ def _create_ai_embedding_event(
@freeze_time("2025-01-16T00:00:00Z")
class TestSessionsAggregation(ClickhouseTestMixin, BaseTest):
def _execute_sessions_query(self) -> list[dict]:
+ flush_persons_and_events()
query = get_sessions_query(order_by="last_seen", order_direction="DESC")
response = execute_hogql_query(query, team=self.team)
columns = response.columns or []
diff --git a/products/ai_observability/backend/queries/__init__.py b/products/ai_observability/backend/queries/__init__.py
index ccb8f7afbc1d..aa47bcf5228d 100644
--- a/products/ai_observability/backend/queries/__init__.py
+++ b/products/ai_observability/backend/queries/__init__.py
@@ -1,11 +1,24 @@
from pathlib import Path
-def _load_sql_query(filename: str, order_by: str, order_direction: str) -> str:
+def _load_sql_query(
+ filename: str,
+ order_by: str,
+ order_direction: str,
+ *,
+ limit: int | None = None,
+ offset: int | None = None,
+) -> str:
query_path = Path(__file__).parent / filename
with open(query_path) as f:
query_template = f.read()
- return query_template.replace("__ORDER_BY__", order_by).replace("__ORDER_DIRECTION__", order_direction)
+
+ query = query_template.replace("__ORDER_BY__", order_by).replace("__ORDER_DIRECTION__", order_direction)
+ if limit is not None:
+ query = query.replace("__LIMIT__", str(limit))
+ if offset is not None:
+ query = query.replace("__OFFSET__", str(offset))
+ return query
def get_errors_query(order_by: str = "last_seen", order_direction: str = "DESC") -> str:
@@ -13,6 +26,11 @@ def get_errors_query(order_by: str = "last_seen", order_direction: str = "DESC")
return _load_sql_query("errors.sql", order_by, order_direction)
-def get_sessions_query(order_by: str = "last_seen", order_direction: str = "DESC") -> str:
+def get_sessions_query(
+ order_by: str = "last_seen",
+ order_direction: str = "DESC",
+ limit: int = 50,
+ offset: int = 0,
+) -> str:
"""Load and parameterize the sessions aggregation query from sessions.sql."""
- return _load_sql_query("sessions.sql", order_by, order_direction)
+ return _load_sql_query("sessions.sql", order_by, order_direction, limit=limit, offset=offset)
diff --git a/products/ai_observability/backend/queries/sessions.sql b/products/ai_observability/backend/queries/sessions.sql
index 1598db5c8645..f8bf83881b60 100644
--- a/products/ai_observability/backend/queries/sessions.sql
+++ b/products/ai_observability/backend/queries/sessions.sql
@@ -64,4 +64,5 @@ FROM (
)
GROUP BY session_id
ORDER BY __ORDER_BY__ __ORDER_DIRECTION__
-LIMIT 50
+LIMIT __LIMIT__
+OFFSET __OFFSET__
diff --git a/products/ai_observability/frontend/AIObservabilityReloadAction.tsx b/products/ai_observability/frontend/AIObservabilityReloadAction.tsx
index 6c68bca5888d..3aa1884af2a0 100644
--- a/products/ai_observability/frontend/AIObservabilityReloadAction.tsx
+++ b/products/ai_observability/frontend/AIObservabilityReloadAction.tsx
@@ -18,6 +18,7 @@ import { EVALUATION_METRICS_COLLECTION_ID } from './evaluations/components/Evalu
import { evaluationMetricsLogic } from './evaluations/evaluationMetricsLogic'
import { llmEvaluationsLogic } from './evaluations/llmEvaluationsLogic'
import { aiObservabilityDashboardLogic } from './tabs/aiObservabilityDashboardLogic'
+import { aiObservabilitySessionsViewLogic } from './tabs/aiObservabilitySessionsViewLogic'
export function AIObservabilityReloadAction(): JSX.Element {
const { activeTab } = useValues(aiObservabilitySharedLogic)
@@ -56,8 +57,10 @@ export function AIObservabilityReloadAction(): JSX.Element {
)
const { refreshMetrics: refreshEvaluationMetrics } = useActions(evaluationMetricsLogic)
const { loadEvaluations } = useActions(llmEvaluationsLogic)
+ const { sessionsLoading } = useValues(aiObservabilitySessionsViewLogic)
+ const { loadSessions } = useActions(aiObservabilitySessionsViewLogic)
- const isLoading = shouldUseDashboardLogic ? dashboardLoading : false
+ const isLoading = shouldUseDashboardLogic ? dashboardLoading : activeTab === 'sessions' ? sessionsLoading : false
const lastRefresh = shouldUseDashboardLogic ? effectiveLastRefresh : null
const handleRefresh = (): void => {
@@ -68,6 +71,10 @@ export function AIObservabilityReloadAction(): JSX.Element {
loadEvaluations()
refreshEvaluationMetrics()
reloadEvaluationMetrics()
+ } else if (activeTab === 'sessions') {
+ // The sessions list is a custom loader, not part of the data-node collection reloadAll() drives.
+ // Force a recompute so the button surfaces newly-ingested sessions instead of a cached result.
+ loadSessions({ refresh: 'force_blocking' })
} else {
reloadAll()
}
diff --git a/products/ai_observability/frontend/AIObservabilityScene.tsx b/products/ai_observability/frontend/AIObservabilityScene.tsx
index a2c347a2e3ab..d2b665e2aa86 100644
--- a/products/ai_observability/frontend/AIObservabilityScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityScene.tsx
@@ -34,7 +34,7 @@ import { AccessControlLevel, AccessControlResourceType, DashboardPlacement, Even
import { aiObservabilityColumnRenderers } from './aiObservabilityColumnRenderers'
import { AIObservabilityErrors } from './AIObservabilityErrors'
import { AIObservabilityReloadAction } from './AIObservabilityReloadAction'
-import { AIObservabilitySessionsScene } from './AIObservabilitySessionsScene'
+import { AIObservabilitySessionsPlaylist } from './AIObservabilitySessionsPlaylist'
import { AIObservabilitySetupPrompt } from './AIObservabilitySetupPrompt'
import {
buildApplyUrlStatePayload,
@@ -578,7 +578,8 @@ function AIObservabilitySceneContent(): JSX.Element {
label: 'Sessions',
content: (
<AIObservabilitySetupPrompt>
- <AIObservabilitySessionsScene />
+ <Filters />
+ <AIObservabilitySessionsPlaylist />
</AIObservabilitySetupPrompt>
),
link: combineUrl(urls.aiObservabilitySessions(), searchParams).url,
@@ -597,6 +598,13 @@ function AIObservabilitySceneContent(): JSX.Element {
'data-attr': 'llma-reviews-tab',
})
+ // Sessions is a primary view — surface it right after Generations, not last.
+ const sessionsIdx = tabs.findIndex((t) => t.key === 'sessions')
+ if (sessionsIdx > -1) {
+ const [sessionsTab] = tabs.splice(sessionsIdx, 1)
+ tabs.splice(tabs.findIndex((t) => t.key === 'generations') + 1, 0, sessionsTab)
+ }
+
return (
<SceneContent>
<SceneTitleSection
diff --git a/products/ai_observability/frontend/AIObservabilitySessionScene.tsx b/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
index ded7bd268165..6dc033179f05 100644
--- a/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
@@ -1,9 +1,9 @@
import { BindLogic, useActions, useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
-import { Suspense, lazy, useEffect } from 'react'
+import { type Ref, Suspense, lazy, useEffect, useRef } from 'react'
-import { IconWrench } from '@posthog/icons'
-import { LemonButton, LemonTag, Spinner, SpinnerOverlay, Tooltip } from '@posthog/lemon-ui'
+import { IconWarning, IconWrench } from '@posthog/icons'
+import { LemonButton, LemonDrawer, LemonTag, Spinner, SpinnerOverlay, Tooltip } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { TZLabel } from 'lib/components/TZLabel'
@@ -22,25 +22,37 @@ import { SceneBreadcrumbBackButton } from '~/layout/scenes/components/SceneBread
import { LLMTrace } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
+import { LazyPersonAvatar } from './aiObservabilityColumnRenderers'
import { TraceSummary, aiObservabilitySessionDataLogic } from './aiObservabilitySessionDataLogic'
import { aiObservabilitySessionLogic } from './aiObservabilitySessionLogic'
+import { buildSessionTimeline } from './buildSessionTimeline'
import { AIObservabilityTraceEvents } from './components/AIObservabilityTraceEvents'
import { SentimentBar } from './components/SentimentTag'
+import { SessionPlayerControls } from './components/SessionPlayer/SessionPlayerControls'
+import { SessionSeekbar } from './components/SessionPlayer/SessionSeekbar'
+import { TypingIndicator } from './components/SessionPlayer/TypingIndicator'
import { TranscriptBubbleStream } from './ConversationDisplay/TranscriptBubbleStream'
import { SessionTurn } from './extractSessionTurns'
import { llmSessionTitleLazyLoaderLogic } from './llmSessionTitleLazyLoaderLogic'
+import { sessionPlaybackLogic } from './sessionPlaybackLogic'
import { formatLLMCost, getTraceTimestamp, sanitizeTraceUrlSearchParams } from './utils'
const LLMASessionFeedbackDisplay = lazy(() =>
import('./LLMASessionFeedbackDisplay').then((m) => ({ default: m.LLMASessionFeedbackDisplay }))
)
+type TurnPhase = 'userThinking' | 'aiThinking' | 'complete'
+
export const scene: SceneExport = {
component: AIObservabilitySessionScene,
logic: aiObservabilitySessionLogic,
}
export function AIObservabilitySessionScene(): JSX.Element {
+ return <SessionDetailPanel showBreadcrumb />
+}
+
+export function SessionDetailPanel({ showBreadcrumb = false }: { showBreadcrumb?: boolean }): JSX.Element {
const sessionLogic = aiObservabilitySessionLogic()
const { sessionId, query } = useValues(sessionLogic)
const sessionDataLogic = aiObservabilitySessionDataLogic({ sessionId, query })
@@ -50,7 +62,7 @@ export function AIObservabilitySessionScene(): JSX.Element {
return (
<BindLogic logic={aiObservabilitySessionLogic} props={{}}>
<BindLogic logic={aiObservabilitySessionDataLogic} props={{ sessionId, query }}>
- <SessionSceneWrapper />
+ <SessionSceneWrapper showBreadcrumb={showBreadcrumb} />
</BindLogic>
</BindLogic>
)
@@ -62,26 +74,102 @@ function SessionTraceSentimentBar({ sentiment }: { sentiment?: LLMTrace['sentime
}
return (
- <SentimentBar label={sentiment.label ?? 'neutral'} score={sentiment.score ?? 0} messages={sentiment.messages} />
+ <div className="flex w-full justify-end">
+ <div className="flex w-20 max-w-[75%] justify-end">
+ <SentimentBar
+ label={sentiment.label ?? 'neutral'}
+ score={sentiment.score ?? 0}
+ messages={sentiment.messages}
+ size="full"
+ />
+ </div>
+ </div>
)
}
-function SessionSceneWrapper(): JSX.Element {
+function SessionSceneWrapper({ showBreadcrumb = false }: { showBreadcrumb?: boolean }): JSX.Element {
const { featureFlags } = useValues(featureFlagLogic)
const showFeedback = !!featureFlags[FEATURE_FLAGS.POSTHOG_AI_CONVERSATION_FEEDBACK_LLMA_SESSIONS]
- const { traces, responseLoading, responseError, sessionTurns, hasMoreData, nextDataLoading, summariesLoading } =
- useValues(aiObservabilitySessionDataLogic)
+ const {
+ traces,
+ initialLoading,
+ responseError,
+ sessionTurns,
+ hasMoreData,
+ nextDataLoading,
+ summariesLoading,
+ drawerTraceId,
+ fullTraces,
+ loadingFullTraces,
+ expandedGenerationIds,
+ } = useValues(aiObservabilitySessionDataLogic)
const { sessionId, dateRange } = useValues(aiObservabilitySessionLogic)
- const { summarizeAllTraces, loadNextData } = useActions(aiObservabilitySessionDataLogic)
+ const { summarizeAllTraces, loadNextData, closeStepsDrawer, toggleGenerationExpanded } = useActions(
+ aiObservabilitySessionDataLogic
+ )
const { dataProcessingAccepted } = useValues(maxGlobalLogic)
const { getSessionTitle } = useValues(llmSessionTitleLazyLoaderLogic)
const { ensureSessionTitleLoaded } = useActions(llmSessionTitleLazyLoaderLogic)
- // Compute the URL search-param passthrough once for the page, not per turn —
- // every `SessionTurnView` consumes the same `traceSearchParams`.
+ // Computed once for the page, not per turn.
const { searchParams } = useValues(router)
const traceSearchParams = sanitizeTraceUrlSearchParams(searchParams, { removeSearch: true })
+ const drawerTurn = drawerTraceId ? sessionTurns.find((t) => t.trace.id === drawerTraceId) : undefined
+ const drawerTraceUrl = drawerTurn
+ ? combineUrl(urls.aiObservabilityTrace(drawerTurn.trace.id), {
+ ...traceSearchParams,
+ timestamp: getTraceTimestamp(drawerTurn.trace.createdAt),
+ }).url
+ : ''
+
+ const playback = sessionPlaybackLogic({ sessionId })
+ const { playing, speed, currentMs, durationMs } = useValues(playback)
+ const { togglePlay, setSpeed, seek, setTimeline } = useActions(playback)
+ const built = buildSessionTimeline(sessionTurns)
+ // Keep the player's duration in sync with the computed timeline. A late full-trace
+ // load can change a turn's latency (and the total duration) without changing the turn
+ // count, so depend on the duration itself rather than the turn count — otherwise the
+ // seekbar thumb (currentMs / durationMs) and the tick positions (built.durationMs)
+ // drift apart. setTimeline clamps the position instead of rewinding, so re-syncing
+ // mid-playback doesn't jump back to the start.
+ useEffect(() => {
+ setTimeline(built.durationMs)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [sessionId, built.durationMs])
+
+ // Idle: show the whole conversation. Scrubbing: reveal turns phase by phase.
+ const isScrubbing = playing || currentMs > 0
+ const revealedTurnCount = isScrubbing
+ ? built.turnRevealsMs.reduce((n, revealMs) => (revealMs <= currentMs ? n + 1 : n), 0)
+ : sessionTurns.length
+ const phaseOf = (i: number): TurnPhase =>
+ currentMs < built.turnStartsMs[i]
+ ? 'userThinking'
+ : currentMs < built.turnResponsesMs[i]
+ ? 'aiThinking'
+ : 'complete'
+
+ // While playing, keep the newest turn in view above the docked player.
+ const latestTurnRef = useRef<HTMLDivElement>(null)
+ useEffect(() => {
+ if (!playing || !latestTurnRef.current) {
+ return
+ }
+ // Scroll fully to the bottom so the newest turn clears the sticky player.
+ let scroller = latestTurnRef.current.parentElement
+ while (scroller && scroller.scrollHeight <= scroller.clientHeight) {
+ scroller = scroller.parentElement
+ }
+ if (scroller) {
+ scroller.scrollTo({ top: scroller.scrollHeight, behavior: 'smooth' })
+ } else {
+ latestTurnRef.current.scrollIntoView({ block: 'end', behavior: 'smooth' })
+ }
+ }, [playing, revealedTurnCount])
+
+ const showSessionSummarization = featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EARLY_ADOPTERS]
+
// Calculate session aggregates
const sessionStats = traces.reduce(
(acc, trace) => ({
@@ -95,11 +183,13 @@ function SessionSceneWrapper(): JSX.Element {
// Same loader as the sessions list, time-bounded to the page's date range.
const heroTitle = getSessionTitle(sessionId)
const titleLoading = heroTitle === undefined
+ // All traces in a session share the same user; show their avatar beside the title.
+ const sessionDistinctId = traces[0]?.distinctId
useEffect(() => {
ensureSessionTitleLoaded(sessionId, dateRange ?? undefined)
}, [sessionId, dateRange, ensureSessionTitleLoaded])
- if (responseLoading) {
+ if (initialLoading) {
return <SpinnerOverlay />
}
if (responseError) {
@@ -110,13 +200,16 @@ function SessionSceneWrapper(): JSX.Element {
}
return (
- <div className="relative flex flex-col gap-4 max-w-[75rem]">
- <SceneBreadcrumbBackButton />
- {titleLoading ? (
- <LemonSkeleton className="h-8 w-96 max-w-full" />
- ) : (
- heroTitle && <h1 className="text-2xl font-semibold leading-tight m-0 break-words">{heroTitle}</h1>
- )}
+ <div className="relative flex w-full flex-col gap-4 min-h-full">
+ {showBreadcrumb && <SceneBreadcrumbBackButton />}
+ <div className="flex items-center gap-2">
+ {sessionDistinctId && <LazyPersonAvatar distinctId={sessionDistinctId} />}
+ {titleLoading ? (
+ <LemonSkeleton className="h-8 w-96 max-w-full" />
+ ) : (
+ heroTitle && <h1 className="text-2xl font-semibold leading-tight m-0 break-words">{heroTitle}</h1>
+ )}
+ </div>
<header className="flex items-start justify-between gap-3 flex-wrap">
<div className="flex gap-1.5 flex-wrap">
<LemonTag size="medium" className="bg-surface-primary">
@@ -124,7 +217,7 @@ function SessionSceneWrapper(): JSX.Element {
</LemonTag>
<LemonTag size="medium" className="bg-surface-primary">
{sessionStats.traceCount}
- {hasMoreData ? '+' : ''} {sessionStats.traceCount === 1 ? 'turn' : 'turns'}
+ {hasMoreData ? '+' : ''} {sessionStats.traceCount === 1 ? 'trace' : 'traces'}
</LemonTag>
{sessionStats.totalCost > 0 && (
<LemonTag size="medium" className="bg-surface-primary">
@@ -149,9 +242,18 @@ function SessionSceneWrapper(): JSX.Element {
/>
</header>
- <div className="flex flex-col">
- {sessionTurns.map((turn) => (
- <SessionTurnView key={turn.trace.id} turn={turn} traceSearchParams={traceSearchParams} />
+ <div className="flex flex-col flex-1">
+ {(isScrubbing ? sessionTurns.slice(0, revealedTurnCount) : sessionTurns).map((turn, i, shown) => (
+ <SessionTurnView
+ key={turn.trace.id}
+ // Anchor for the player's auto-scroll: the last revealed turn.
+ rootRef={i === shown.length - 1 ? latestTurnRef : undefined}
+ turn={turn}
+ phase={isScrubbing ? phaseOf(i) : 'complete'}
+ showSentiment
+ showSessionSummarization={!!showSessionSummarization}
+ traceSearchParams={traceSearchParams}
+ />
))}
{hasMoreData && (
<div className="flex justify-center pt-4">
@@ -161,11 +263,66 @@ function SessionSceneWrapper(): JSX.Element {
onClick={loadNextData}
data-attr="llm-session-load-more-traces"
>
- Load more turns
+ Load more traces
</LemonButton>
</div>
)}
</div>
+
+ {/* Anchored to the bottom like a session-replay scrubber. */}
+ {durationMs > 0 && (
+ <div className="sticky bottom-0 z-10 mt-2 flex flex-col gap-2 rounded border border-primary bg-surface-primary p-3 shadow">
+ <SessionSeekbar
+ durationMs={durationMs}
+ currentMs={currentMs}
+ turnStartsMs={built.turnStartsMs}
+ turnResponsesMs={built.turnResponsesMs}
+ onSeek={seek}
+ />
+ <div className="flex items-center gap-3 text-[11px] text-muted">
+ <span className="flex items-center gap-1">
+ <span className="w-1 h-3 rounded-full bg-muted" /> User
+ </span>
+ <span className="flex items-center gap-1">
+ <span className="w-1 h-3 rounded-full bg-success" /> Assistant
+ </span>
+ </div>
+ <SessionPlayerControls
+ playing={playing}
+ speed={speed}
+ currentMs={currentMs}
+ durationMs={durationMs}
+ onTogglePlay={togglePlay}
+ onSetSpeed={setSpeed}
+ />
+ </div>
+ )}
+
+ <LemonDrawer
+ isOpen={!!drawerTraceId}
+ onClose={closeStepsDrawer}
+ title={drawerTurn?.trace.traceName || 'Trace steps'}
+ width={960}
+ data-attr="llm-session-steps-drawer"
+ description={
+ drawerTraceUrl ? (
+ <Link to={drawerTraceUrl} target="_blank" className="text-xs">
+ Open full trace
+ </Link>
+ ) : undefined
+ }
+ >
+ {drawerTraceId ? (
+ <div className="flex flex-col gap-3">
+ <AIObservabilityTraceEvents
+ trace={fullTraces[drawerTraceId]}
+ isLoading={loadingFullTraces.has(drawerTraceId)}
+ expandedEventIds={expandedGenerationIds}
+ onToggleEventExpand={toggleGenerationExpanded}
+ />
+ </div>
+ ) : null}
+ </LemonDrawer>
</div>
)
}
@@ -193,7 +350,7 @@ function SummarizeAllButton({
disabledReason="AI data processing must be approved to summarize traces"
data-attr="llm-session-summarize-all"
>
- Summarize all turns
+ Summarize all traces
</LemonButton>
</AccessControlAction>
</AIConsentPopoverWrapper>
@@ -211,7 +368,7 @@ function SummarizeAllButton({
loading={loading}
data-attr="llm-session-summarize-all"
>
- Summarize all turns
+ Summarize all traces
</LemonButton>
</AccessControlAction>
)
@@ -219,84 +376,128 @@ function SummarizeAllButton({
function SessionTurnView({
turn,
+ phase = 'complete',
+ showSentiment,
+ showSessionSummarization,
traceSearchParams,
+ rootRef,
}: {
turn: SessionTurn
+ phase?: TurnPhase
+ showSentiment: boolean
+ showSessionSummarization: boolean
traceSearchParams: Record<string, unknown>
+ rootRef?: Ref<HTMLDivElement>
}): JSX.Element {
- const { traceSummaries, loadingFullTraces, fullTraces, stepsExpandedTraceIds, expandedGenerationIds } = useValues(
+ const { traceSummaries, loadingFullTraces, fullTraces, expandedGenerationIds } = useValues(
aiObservabilitySessionDataLogic
)
- const { toggleSteps, toggleGenerationExpanded, loadFullTrace } = useActions(aiObservabilitySessionDataLogic)
+ const { openStepsDrawer, toggleGenerationExpanded, loadFullTrace } = useActions(aiObservabilitySessionDataLogic)
const trace = turn.trace
const summary: TraceSummary | undefined = traceSummaries[trace.id]
const isLoading = loadingFullTraces.has(trace.id)
- const stepsShown = stepsExpandedTraceIds.has(trace.id)
const fullTrace = fullTraces[trace.id]
const baseTraceParams = {
...traceSearchParams,
timestamp: getTraceTimestamp(trace.createdAt),
}
- const traceUrl = combineUrl(urls.aiObservabilityTrace(trace.id), baseTraceParams).url
const summaryUrl = combineUrl(urls.aiObservabilityTrace(trace.id), { ...baseTraceParams, tab: 'summary' }).url
+ const stepCount = (fullTrace?.events ?? []).filter(
+ (e) => e.event === '$ai_generation' || e.event === '$ai_span' || e.event === '$ai_embedding'
+ ).length
+ // Errors already surfaced by a red tool pill are excluded; the rest (e.g.
+ // generation failures) render as their own pills in the same style.
+ const otherErrors = turn.errors.filter((e) => !turn.tools.includes(e.label))
const hasTranscript = turn.isLoaded && !!turn.userVisibleTurn
- // Auto-show the Steps panel for span-only turns — they have no transcript to fall
- // back to, so the span tree IS the conversation.
- const showStepsPanel = (hasTranscript && stepsShown) || (turn.isLoaded && !turn.userVisibleTurn)
+ // Span-only turns have no transcript, so the span tree IS the conversation.
+ const isSpanOnly = turn.isLoaded && !turn.userVisibleTurn
+ // Only a settled turn shows its summary, tools, errors, steps, and sidebar.
+ const isComplete = phase === 'complete'
return (
- <div className="flex flex-col">
+ <div className="flex flex-col" ref={rootRef}>
<div className="flex items-center gap-3 py-3 text-xs text-muted">
<div className="flex-1 border-t" />
<TZLabel time={trace.createdAt} formatDate="MMM D, YYYY" formatTime="h:mm A" />
<div className="flex-1 border-t" />
</div>
- <div className="flex gap-10 pb-4">
+ <div className="pb-4">
<div className="flex-1 min-w-0 flex flex-col gap-2">
- {summary && <TurnSummaryLine summary={summary} summaryUrl={summaryUrl} />}
+ {isComplete && showSessionSummarization && summary && (
+ <TurnSummaryLine summary={summary} summaryUrl={summaryUrl} />
+ )}
- <TurnBody turn={turn} isLoading={isLoading} onLoad={() => loadFullTrace(trace.id)} />
+ <TurnBody
+ turn={turn}
+ phase={phase}
+ isLoading={isLoading}
+ sentiment={isComplete && showSentiment ? trace.sentiment : undefined}
+ onLoad={() => loadFullTrace(trace.id)}
+ />
- {turn.tools.length > 0 && (
+ {isComplete && turn.tools.length > 0 && (
<div className="flex items-center gap-1.5 flex-wrap text-xs text-muted">
- <IconWrench className="text-sm shrink-0" />
- {turn.tools.map((name) => (
- <LemonTag key={name} size="small" className="font-mono">
- {name}
- </LemonTag>
- ))}
+ {turn.tools.map((name) => {
+ // Tool spans and error labels both come from `$ai_span_name`,
+ // so an exact match flags the tool call that failed.
+ const toolError = turn.errors.find((e) => e.label === name)
+ const pill = (
+ <LemonTag
+ key={name}
+ size="small"
+ type={toolError ? 'danger' : undefined}
+ className="font-mono cursor-pointer hover:bg-fill-button-tertiary-hover"
+ onClick={() => openStepsDrawer(trace.id, name)}
+ icon={toolError ? <IconWarning /> : <IconWrench />}
+ >
+ {name}
+ </LemonTag>
+ )
+ return toolError ? (
+ <Tooltip key={name} title={toolError.message}>
+ {pill}
+ </Tooltip>
+ ) : (
+ pill
+ )
+ })}
</div>
)}
- {(trace.errorCount ?? 0) > 0 && (
- <div className="flex items-center gap-2 min-w-0">
- <LemonTag type="danger" size="small" className="shrink-0">
- {trace.errorCount === 1 ? '1 error' : `${trace.errorCount} errors`}
- </LemonTag>
- {turn.errors.length > 0 && (
- <Tooltip
- title={
- <div className="flex flex-col gap-1">
- {turn.errors.map((e, i) => (
- <div key={i}>
- <strong>{e.label}:</strong> {e.message}
- </div>
- ))}
- </div>
- }
- >
- <span className="text-xs text-muted truncate">
- {turn.errors[0].label} · {turn.errors[0].message}
- {turn.errors.length > 1 && ` · +${turn.errors.length - 1} more`}
- </span>
+ {isComplete && otherErrors.length > 0 && (
+ <div className="flex items-center gap-1.5 flex-wrap text-xs text-muted">
+ {otherErrors.map((e, i) => (
+ <Tooltip key={i} title={e.message}>
+ <LemonTag
+ type="danger"
+ size="small"
+ className="font-mono cursor-pointer hover:bg-fill-button-tertiary-hover"
+ onClick={() => openStepsDrawer(trace.id, e.label)}
+ icon={<IconWarning />}
+ >
+ {e.label}
+ </LemonTag>
</Tooltip>
- )}
+ ))}
+ </div>
+ )}
+
+ {isComplete && hasTranscript && (
+ <div>
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ onClick={() => openStepsDrawer(trace.id)}
+ data-attr="llm-session-view-steps"
+ >
+ View trace{stepCount > 0 ? ` (${stepCount} ${stepCount === 1 ? 'step' : 'steps'})` : ''}
+ </LemonButton>
</div>
)}
- {showStepsPanel && (
+ {isComplete && isSpanOnly && (
<StepsPanel
fullTrace={fullTrace}
expandedEventIds={expandedGenerationIds}
@@ -304,20 +505,6 @@ function SessionTurnView({
/>
)}
</div>
-
- <div className="w-40 shrink-0 flex flex-col gap-1 text-xs text-muted">
- <SessionTraceSentimentBar sentiment={trace.sentiment} />
- <div className="flex flex-col gap-1 items-start">
- {hasTranscript && (
- <LemonButton size="xsmall" type="tertiary" onClick={() => toggleSteps(trace.id)}>
- {stepsShown ? 'Hide steps' : 'Show steps'}
- </LemonButton>
- )}
- <Link to={traceUrl} target="_blank" className="text-xs">
- Open trace
- </Link>
- </div>
- </div>
</div>
</div>
)
@@ -348,11 +535,15 @@ function TurnSummaryLine({ summary, summaryUrl }: { summary: TraceSummary; summa
function TurnBody({
turn,
+ phase = 'complete',
isLoading,
+ sentiment,
onLoad,
}: {
turn: SessionTurn
+ phase?: TurnPhase
isLoading: boolean
+ sentiment?: LLMTrace['sentiment']
onLoad: () => void
}): JSX.Element | null {
if (isLoading) {
@@ -376,8 +567,27 @@ function TurnBody({
// No chat to render — the parent renders `StepsPanel` inline below as the substitute.
return null
}
+ // Before the request lands, the user is "composing" — a user-side typing indicator.
+ if (phase === 'userThinking') {
+ return <TypingIndicator type="human" />
+ }
+ // Request shown, response still in flight — request plus a typing indicator.
+ if (phase === 'aiThinking') {
+ return (
+ <div className="flex flex-col gap-1.5">
+ <TranscriptBubbleStream inputs={turn.newInputs} outputs={[]} />
+ <TypingIndicator />
+ </div>
+ )
+ }
// `turn.newInputs` / `outputs` come pre-deduped from `extractSessionTurns`.
- return <TranscriptBubbleStream inputs={turn.newInputs} outputs={turn.outputs} />
+ return (
+ <div className="flex flex-col gap-1.5">
+ <TranscriptBubbleStream inputs={turn.newInputs} outputs={[]} />
+ {turn.newInputs.length > 0 && <SessionTraceSentimentBar sentiment={sentiment} />}
+ <TranscriptBubbleStream inputs={[]} outputs={turn.outputs} />
+ </div>
+ )
}
function StepsPanel({
diff --git a/products/ai_observability/frontend/AIObservabilitySessionsPlaylist.tsx b/products/ai_observability/frontend/AIObservabilitySessionsPlaylist.tsx
new file mode 100644
index 000000000000..b5df28eaeb5f
--- /dev/null
+++ b/products/ai_observability/frontend/AIObservabilitySessionsPlaylist.tsx
@@ -0,0 +1,204 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useRef } from 'react'
+
+import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { Resizer } from 'lib/components/Resizer/Resizer'
+import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
+import { TZLabel } from 'lib/components/TZLabel'
+import { useWindowSize } from 'lib/hooks/useWindowSize'
+import { LemonTableLoader } from 'lib/lemon-ui/LemonTable/LemonTableLoader'
+import { cn } from 'lib/utils/css-classes'
+
+import { SessionDetailPanel } from './AIObservabilitySessionScene'
+import { SessionListRow, aiObservabilitySessionsViewLogic } from './tabs/aiObservabilitySessionsViewLogic'
+import { formatLLMCost } from './utils'
+
+const SESSION_LIST_DEFAULT_WIDTH = 300
+const SESSION_LIST_MIN_WIDTH = 260
+const SESSION_LIST_MAX_WIDTH = '50%'
+
+export function AIObservabilitySessionsPlaylist(): JSX.Element {
+ const { loadSessions } = useActions(aiObservabilitySessionsViewLogic)
+ const { isWindowLessThan } = useWindowSize()
+ const isVertical = isWindowLessThan('xl')
+
+ useEffect(() => {
+ loadSessions()
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+
+ return (
+ <div
+ className={cn(
+ 'w-full h-[calc(100vh-13rem)] min-h-[25rem] flex gap-2',
+ isVertical ? 'flex-col' : 'flex-row'
+ )}
+ >
+ {isVertical ? (
+ <>
+ <DetailPane className="flex-1 min-h-0 overflow-y-auto" />
+ <ListPane className="h-72 shrink-0" />
+ </>
+ ) : (
+ <HorizontalLayout />
+ )}
+ </div>
+ )
+}
+
+function HorizontalLayout(): JSX.Element {
+ const listRef = useRef<HTMLDivElement>(null)
+ const resizerLogicProps: ResizerLogicProps = {
+ logicKey: 'llma-sessions-list',
+ containerRef: listRef,
+ persistent: true,
+ placement: 'right',
+ }
+ const { desiredSize } = useValues(resizerLogic(resizerLogicProps))
+ const listWidth = Math.max(desiredSize ?? SESSION_LIST_DEFAULT_WIDTH, SESSION_LIST_MIN_WIDTH)
+
+ return (
+ <>
+ <div
+ ref={listRef}
+ className="relative flex flex-col shrink-0"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ width: listWidth, minWidth: SESSION_LIST_MIN_WIDTH, maxWidth: SESSION_LIST_MAX_WIDTH }}
+ >
+ <ListPane className="h-full" />
+ <Resizer {...resizerLogicProps} visible={false} offset="0.25rem" handleClassName="rounded my-1" />
+ </div>
+ <DetailPane className="flex-1 min-w-0 h-full overflow-y-auto" />
+ </>
+ )
+}
+
+function DetailPane({ className }: { className?: string }): JSX.Element {
+ const { selectedSessionId } = useValues(aiObservabilitySessionsViewLogic)
+ return (
+ <div className={cn('rounded border border-primary bg-surface-primary p-4', className)}>
+ {selectedSessionId ? (
+ <SessionDetailPanel />
+ ) : (
+ <div className="h-full flex items-center justify-center text-sm text-secondary">
+ Select a session to view it
+ </div>
+ )}
+ </div>
+ )
+}
+
+function ListPane({ className }: { className?: string }): JSX.Element {
+ const { sessions, sessionsLoading, selectedSessionId, getSessionTitle, hasMoreSessions, moreSessionsLoading } =
+ useValues(aiObservabilitySessionsViewLogic)
+ const { selectSession, loadMoreSessions } = useActions(aiObservabilitySessionsViewLogic)
+
+ return (
+ <div
+ className={cn(
+ 'relative flex flex-col min-h-0 overflow-hidden rounded border border-primary bg-surface-primary',
+ className
+ )}
+ >
+ <LemonTableLoader loading={sessionsLoading && sessions.length > 0} placement="top" />
+ <div className="flex-1 min-h-0 overflow-y-auto" data-attr="llma-sessions-list">
+ {sessionsLoading && sessions.length === 0 ? (
+ <div className="flex flex-col gap-2 p-2">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <LemonSkeleton key={i} className="h-12 w-full" />
+ ))}
+ </div>
+ ) : sessions.length === 0 ? (
+ <div className="p-4 text-center text-sm text-secondary">No sessions yet</div>
+ ) : (
+ <>
+ <ul className="flex flex-col list-none pl-0 m-0 divide-y divide-primary">
+ {sessions.map((session) => (
+ <li key={session.sessionId}>
+ <SessionPreview
+ session={session}
+ title={getSessionTitle(session.sessionId)}
+ isActive={session.sessionId === selectedSessionId}
+ onClick={() => selectSession(session.sessionId)}
+ />
+ </li>
+ ))}
+ </ul>
+ {hasMoreSessions && (
+ <div className="border-t border-primary p-2">
+ <LemonButton
+ type="secondary"
+ size="small"
+ fullWidth
+ loading={moreSessionsLoading}
+ onClick={loadMoreSessions}
+ data-attr="llma-load-more-sessions"
+ >
+ Load more sessions
+ </LemonButton>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ )
+}
+
+function SessionPreview({
+ session,
+ title,
+ isActive,
+ onClick,
+}: {
+ session: SessionListRow
+ // `undefined` while the title loads, `null` when no usable title was found.
+ title: string | null | undefined
+ isActive: boolean
+ onClick: () => void
+}): JSX.Element {
+ const fallbackLabel = session.distinctId || 'unknown'
+
+ return (
+ <button
+ type="button"
+ aria-pressed={isActive}
+ onClick={onClick}
+ className={cn(
+ 'ph-no-capture w-full min-w-0 text-left cursor-pointer border-l-2 px-2 py-1.5 text-xs flex flex-col gap-1',
+ isActive
+ ? 'border-l-accent bg-accent-highlight-secondary'
+ : 'border-l-transparent hover:bg-accent-highlight-secondary'
+ )}
+ data-attr="llma-session-preview"
+ >
+ <div className="flex min-w-0 items-center justify-between gap-2">
+ {title === undefined ? (
+ <LemonSkeleton className="h-4 w-40" />
+ ) : (
+ <span
+ className={cn('min-w-0 truncate', title ? 'font-semibold' : 'font-mono')}
+ title={title || undefined}
+ >
+ {title || fallbackLabel}
+ </span>
+ )}
+ <span className="shrink-0 text-secondary">
+ <TZLabel time={session.lastSeen} />
+ </span>
+ </div>
+ <div className="flex min-w-0 items-center justify-between gap-2 text-secondary">
+ <span className="min-w-0 font-mono truncate">{fallbackLabel}</span>
+ <span className="flex shrink-0 items-center gap-2">
+ <span>
+ {session.traces} {session.traces === 1 ? 'trace' : 'traces'}
+ </span>
+ {session.errors > 0 && <span className="text-danger">{session.errors} err</span>}
+ {session.totalCost > 0 && <span>{formatLLMCost(session.totalCost)}</span>}
+ <span>{session.totalLatency.toFixed(2)}s</span>
+ </span>
+ </div>
+ </button>
+ )
+}
diff --git a/products/ai_observability/frontend/AIObservabilitySessionsScene.tsx b/products/ai_observability/frontend/AIObservabilitySessionsScene.tsx
deleted file mode 100644
index 65bf00da1b1e..000000000000
--- a/products/ai_observability/frontend/AIObservabilitySessionsScene.tsx
+++ /dev/null
@@ -1,361 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { combineUrl, router } from 'kea-router'
-import { useEffect } from 'react'
-
-import { IconChevronDown, IconChevronRight, IconInfo } from '@posthog/icons'
-import { LemonTag } from '@posthog/lemon-ui'
-
-import { TZLabel } from 'lib/components/TZLabel'
-import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
-import { Link } from 'lib/lemon-ui/Link'
-import { Spinner } from 'lib/lemon-ui/Spinner'
-import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { urls } from 'scenes/urls'
-
-import { DataTable } from '~/queries/nodes/DataTable/DataTable'
-import { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'
-import { isHogQLQuery } from '~/queries/utils'
-
-import { LazyPersonColumnCell, ToolsDisplay } from './aiObservabilityColumnRenderers'
-import { buildApplyUrlStatePayload, aiObservabilitySharedLogic } from './aiObservabilitySharedLogic'
-import { AIObservabilityTraceEvents } from './components/AIObservabilityTraceEvents'
-import { useSortableColumns } from './hooks/useSortableColumns'
-import { llmSessionTitleLazyLoaderLogic } from './llmSessionTitleLazyLoaderLogic'
-import { aiObservabilitySessionsViewLogic } from './tabs/aiObservabilitySessionsViewLogic'
-import { formatLLMCost, getTraceTimestamp, sanitizeTraceUrlSearchParams } from './utils'
-
-function SessionColumn({ sessionId }: { sessionId: string }): JSX.Element {
- const { dateFilter } = useValues(aiObservabilitySharedLogic)
- const { getSessionTitle } = useValues(llmSessionTitleLazyLoaderLogic)
- const { ensureSessionTitleLoaded } = useActions(llmSessionTitleLazyLoaderLogic)
-
- useEffect(() => {
- if (sessionId) {
- ensureSessionTitleLoaded(sessionId, dateFilter)
- }
- }, [sessionId, dateFilter, ensureSessionTitleLoaded])
-
- const title = getSessionTitle(sessionId)
- const truncatedId = `${sessionId.slice(0, 4)}...${sessionId.slice(-4)}`
- const sessionUrl = `${urls.aiObservabilitySession(sessionId)}?${new URLSearchParams({
- ...(dateFilter.dateFrom && { date_from: dateFilter.dateFrom }),
- ...(dateFilter.dateTo && { date_to: dateFilter.dateTo }),
- }).toString()}`
-
- if (title === undefined) {
- return <LemonSkeleton className="h-4 w-48" />
- }
-
- if (!title) {
- return (
- <strong>
- <Tooltip title={sessionId}>
- <Link className="ph-no-capture font-mono" to={sessionUrl}>
- {truncatedId}
- </Link>
- </Tooltip>
- </strong>
- )
- }
-
- return (
- <Link className="ph-no-capture font-semibold truncate block max-w-md" to={sessionUrl} title={title}>
- {title}
- </Link>
- )
-}
-
-export function AIObservabilitySessionsScene(): JSX.Element {
- const { applyUrlState } = useActions(aiObservabilitySharedLogic)
- const { dateFilter, propertyFilters: currentPropertyFilters } = useValues(aiObservabilitySharedLogic)
- const { searchParams } = useValues(router)
- const traceSearchParams = sanitizeTraceUrlSearchParams(searchParams, { removeSearch: true })
-
- const { setSessionsSort, toggleSessionExpanded, toggleTraceExpanded, toggleGenerationExpanded } = useActions(
- aiObservabilitySessionsViewLogic
- )
- const {
- sessionsQuery,
- sessionsSort,
- expandedSessionIds,
- expandedTraceIds,
- expandedGenerationIds,
- sessionTraces,
- loadingSessionTraces,
- loadingFullTraces,
- fullTraces,
- } = useValues(aiObservabilitySessionsViewLogic)
-
- const { renderSortableColumnTitle } = useSortableColumns(sessionsSort, setSessionsSort)
-
- return (
- <DataTable
- attachTo={aiObservabilitySharedLogic}
- query={{
- ...sessionsQuery,
- showSavedFilters: true,
- }}
- setQuery={(query) => {
- if (!isHogQLQuery(query.source)) {
- console.warn('AIObservabilitySessions received a non-HogQL query:', query.source)
- return
- }
- const { filters = {} } = query.source
- const { dateRange = {} } = filters
- applyUrlState(
- buildApplyUrlStatePayload({
- dateFrom: dateRange.date_from || null,
- dateTo: dateRange.date_to || null,
- shouldFilterTestAccounts: filters.filterTestAccounts || false,
- propertyFilters: filters.properties || [],
- currentDateFilter: dateFilter,
- currentPropertyFilters,
- })
- )
- }}
- context={{
- emptyStateHeading: 'There were no AI sessions in this period',
- emptyStateDetail: (
- <>
- Try changing the date range or filters. AI sessions require the <code>$ai_session_id</code>{' '}
- property to group related traces.{' '}
- <Link to="https://posthog.com/docs/ai-observability/sessions" target="_blank">
- Learn more →
- </Link>
- </>
- ),
- columns: {
- session_id: {
- title: 'Session',
- render: function RenderSession(x) {
- return <SessionColumn sessionId={x.value as string} />
- },
- },
- distinct_id: {
- title: 'Person',
- render: function RenderPerson({ value }) {
- const distinctId = value as string
- if (!distinctId) {
- return <span>–</span>
- }
- return <LazyPersonColumnCell distinctId={distinctId} />
- },
- },
- tools: {
- renderTitle: () => <Tooltip title="Distinct tools called in this session">Tools</Tooltip>,
- render: function RenderTools({ value }) {
- return <ToolsDisplay tools={Array.isArray(value) ? (value as string[]) : []} />
- },
- },
- traces: {
- renderTitle: () => (
- <span className="inline-flex items-center gap-1">
- <Tooltip title="Number of traces in this session">
- {renderSortableColumnTitle('traces', 'Traces')}
- </Tooltip>
- <Tooltip title="Counts reflect events within the selected date range. They may change on reload as events age out of relative time windows.">
- <IconInfo className="text-muted text-xs" />
- </Tooltip>
- </span>
- ),
- },
- spans: {
- renderTitle: () => (
- <Tooltip title="Number of spans in this session">
- {renderSortableColumnTitle('spans', 'Spans')}
- </Tooltip>
- ),
- },
- generations: {
- renderTitle: () => (
- <Tooltip title="Number of generations in this session">
- {renderSortableColumnTitle('generations', 'Generations')}
- </Tooltip>
- ),
- },
- embeddings: {
- renderTitle: () => (
- <Tooltip title="Number of embeddings in this session">
- {renderSortableColumnTitle('embeddings', 'Embeddings')}
- </Tooltip>
- ),
- },
- errors: {
- renderTitle: () => (
- <Tooltip title="Number of errors in this session">
- {renderSortableColumnTitle('errors', 'Errors')}
- </Tooltip>
- ),
- render: function RenderErrors({ value }) {
- const count = Number(value)
- if (!count) {
- return <span>–</span>
- }
- return <LemonTag type="danger">{count}</LemonTag>
- },
- },
- total_cost: {
- renderTitle: () => (
- <Tooltip title="Total cost of all generations in this session">
- {renderSortableColumnTitle('total_cost', 'Cost')}
- </Tooltip>
- ),
- render: function RenderCost({ value }) {
- if (!value || !Number(value)) {
- return <span>N/A</span>
- }
- return <span>{formatLLMCost(Number(value))}</span>
- },
- },
- total_latency: {
- renderTitle: () => (
- <Tooltip title="Total latency of all generations in this session">
- {renderSortableColumnTitle('total_latency', 'Latency')}
- </Tooltip>
- ),
- render: function RenderLatency({ value }) {
- if (!value || !Number(value)) {
- return <span>N/A</span>
- }
- return <span>{Number(value).toFixed(2)} s</span>
- },
- },
- first_seen: {
- renderTitle: () => renderSortableColumnTitle('first_seen', 'First Seen'),
- render: function RenderFirstSeen({ value }) {
- return <TZLabel time={value as string} />
- },
- },
- last_seen: {
- renderTitle: () => renderSortableColumnTitle('last_seen', 'Last Seen'),
- render: function RenderLastSeen({ value }) {
- return <TZLabel time={value as string} />
- },
- },
- },
- expandable: {
- expandedRowRender: function renderExpandedSession({ result }: DataTableRow) {
- if (!Array.isArray(result) || result.length === 0) {
- return null
- }
-
- const sessionId = result[0] as string
- const traces = sessionTraces[sessionId]
- const isLoading = loadingSessionTraces.has(sessionId)
-
- if (isLoading) {
- return (
- <div className="p-4">
- <Spinner />
- </div>
- )
- }
-
- if (!traces || traces.length === 0) {
- return <div className="p-4">No traces found for this session</div>
- }
-
- return (
- <div className="pt-2 px-4 pb-4">
- <div className="space-y-2">
- {traces.map((trace) => {
- const isTraceExpanded = expandedTraceIds.has(trace.id)
-
- return (
- <div key={trace.id} className="border rounded">
- <div
- className="p-3 hover:bg-side-light cursor-pointer flex items-start gap-2"
- onClick={() => toggleTraceExpanded(trace.id)}
- >
- <div className="flex-shrink-0 mt-0.5">
- {isTraceExpanded ? (
- <IconChevronDown className="text-lg" />
- ) : (
- <IconChevronRight className="text-lg" />
- )}
- </div>
- <div className="flex-1">
- <div className="flex items-center gap-2 mb-2 flex-wrap">
- <strong className="font-mono text-xs">
- {trace.id.slice(0, 8)}...
- </strong>
- {trace.traceName && (
- <span className="text-sm">{trace.traceName}</span>
- )}
- {(trace.errorCount ?? 0) > 0 && (
- <LemonTag type="danger" size="small">
- {trace.errorCount === 1
- ? '1 error'
- : `${trace.errorCount} errors`}
- </LemonTag>
- )}
- {typeof trace.totalLatency === 'number' && (
- <LemonTag type="muted">
- {trace.totalLatency.toFixed(2)}s
- </LemonTag>
- )}
- {typeof trace.totalCost === 'number' && (
- <LemonTag type="muted">
- {formatLLMCost(trace.totalCost)}
- </LemonTag>
- )}
- <Link
- to={
- combineUrl(urls.aiObservabilityTrace(trace.id), {
- ...traceSearchParams,
- timestamp: getTraceTimestamp(trace.createdAt),
- }).url
- }
- onClick={(e) => e.stopPropagation()}
- className="text-xs"
- >
- View full trace →
- </Link>
- </div>
- <div className="text-xs text-muted">
- <TZLabel time={trace.createdAt} />
- </div>
- </div>
- </div>
- {isTraceExpanded && (
- <div className="border-t bg-bg-light">
- <div className="p-3 space-y-2">
- <AIObservabilityTraceEvents
- trace={fullTraces[trace.id]}
- isLoading={loadingFullTraces.has(trace.id)}
- expandedEventIds={expandedGenerationIds}
- onToggleEventExpand={(uuid: string) =>
- toggleGenerationExpanded(uuid, trace.id)
- }
- />
- </div>
- </div>
- )}
- </div>
- )
- })}
- </div>
- </div>
- )
- },
- rowExpandable: ({ result }: DataTableRow) =>
- !!result && Array.isArray(result) && result.length > 0 && !!result[0],
- isRowExpanded: ({ result }: DataTableRow) =>
- Array.isArray(result) && !!result[0] && expandedSessionIds.has(result[0] as string),
- onRowExpand: ({ result }: DataTableRow) => {
- if (Array.isArray(result) && result[0]) {
- toggleSessionExpanded(result[0] as string)
- }
- },
- onRowCollapse: ({ result }: DataTableRow) => {
- if (Array.isArray(result) && result[0]) {
- toggleSessionExpanded(result[0] as string)
- }
- },
- noIndent: true,
- },
- }}
- uniqueKey="llm-analytics-sessions"
- />
- )
-}
diff --git a/products/ai_observability/frontend/AIObservabilityTracesScene.tsx b/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
index 688a6b211e42..45026dcf2b29 100644
--- a/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
@@ -30,6 +30,7 @@ import {
formatLLMCost,
formatLLMLatency,
formatLLMUsage,
+ getTraceStepCount,
getTraceTimestamp,
LLM_TRACES_PAGE_SIZE,
sanitizeTraceUrlSearchParams,
@@ -175,6 +176,12 @@ 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,
@@ -334,6 +341,16 @@ 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/aiObservabilityColumnRenderers.tsx b/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx
index 4e9b2e1ba163..37cbf6ff79a2 100644
--- a/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx
+++ b/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx
@@ -6,7 +6,7 @@ import { IconFilter } from '@posthog/icons'
import { LemonButton, LemonTag, Link } from '@posthog/lemon-ui'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { PersonDisplay } from 'scenes/persons/PersonDisplay'
+import { PersonDisplay, PersonIcon } from 'scenes/persons/PersonDisplay'
import { urls } from 'scenes/urls'
import { DataTableNode, DataVisualizationNode } from '~/queries/schema/schema-general'
@@ -192,6 +192,31 @@ export function LazyPersonColumnCell({ distinctId }: { distinctId: string }): JS
return <PersonColumnCell person={personData} />
}
+// Avatar only (no name) for inline use beside a title; a click still opens the
+// full person popover. Shares the lazy person loader with LazyPersonColumnCell.
+export function LazyPersonAvatar({ distinctId }: { distinctId: string }): JSX.Element {
+ const { personsCache, currentTeamId } = useValues(llmPersonsLazyLoaderLogic)
+ const { ensurePersonLoaded } = useActions(llmPersonsLazyLoaderLogic)
+
+ const cached = personsCache[distinctId]
+
+ useEffect(() => {
+ if (currentTeamId && cached === undefined) {
+ ensurePersonLoaded(distinctId)
+ }
+ }, [currentTeamId, cached, distinctId, ensurePersonLoaded])
+
+ const personData: PersonData = cached
+ ? { distinct_id: cached.distinct_id, properties: cached.properties }
+ : { distinct_id: distinctId }
+
+ return (
+ <PersonDisplay person={personData}>
+ <PersonIcon person={personData} size="md" />
+ </PersonDisplay>
+ )
+}
+
function getStringColumnValue(record: unknown[], columns: string[], column: string): string | null {
const index = columns.findIndex((col) => col === column)
if (index < 0) {
diff --git a/products/ai_observability/frontend/aiObservabilityLogic.test.ts b/products/ai_observability/frontend/aiObservabilityLogic.test.ts
index 31c6b8c6bb85..b02f84d5e087 100644
--- a/products/ai_observability/frontend/aiObservabilityLogic.test.ts
+++ b/products/ai_observability/frontend/aiObservabilityLogic.test.ts
@@ -3,6 +3,8 @@ import { MOCK_TEAM_ID } from 'lib/api.mock'
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import api from 'lib/api'
+import { emptySceneParams } from 'scenes/scenes'
import { urls } from 'scenes/urls'
import { productRedirects } from '~/products'
@@ -12,6 +14,7 @@ import { PropertyFilterType, PropertyOperator } from '~/types'
import { sceneLogic } from '../../../frontend/src/scenes/sceneLogic'
import { aiObservabilitySharedLogic } from './aiObservabilitySharedLogic'
import { DisplayOption, aiObservabilityTraceLogic } from './aiObservabilityTraceLogic'
+import { llmSessionTitleLazyLoaderLogic } from './llmSessionTitleLazyLoaderLogic'
import { aiObservabilityDashboardLogic } from './tabs/aiObservabilityDashboardLogic'
import { aiObservabilityGenerationsLogic } from './tabs/aiObservabilityGenerationsLogic'
import { aiObservabilitySessionsViewLogic } from './tabs/aiObservabilitySessionsViewLogic'
@@ -173,257 +176,198 @@ describe('aiObservabilitySharedLogic', () => {
describe('aiObservabilitySessionsViewLogic', () => {
let sharedLogic: ReturnType<typeof aiObservabilitySharedLogic.build>
- let sessionsLogic: ReturnType<typeof aiObservabilitySessionsViewLogic.build>
+ let logic: ReturnType<typeof aiObservabilitySessionsViewLogic.build>
+ let querySpy: jest.SpyInstance
+ const sessionColumns = ['session_id', 'distinct_id', 'traces', 'total_cost', 'total_latency', 'errors', 'last_seen']
+
+ const urlState = {
+ propertyFilters: [],
+ dateFrom: '-14d',
+ dateTo: null,
+ shouldFilterTestAccounts: false,
+ datesChanged: true,
+ }
+
+ async function settleListeners(): Promise<void> {
+ for (let i = 0; i < 5; i++) {
+ await Promise.resolve()
+ }
+ }
+
+ function setActiveTab(sceneKey: string): void {
+ sceneLogic.actions.setScene('AIObservability', sceneKey, emptySceneParams)
+ }
+
+ function sessionRow(index: number): unknown[] {
+ return [
+ `session-${index}`,
+ `person-${index}`,
+ 1,
+ 0,
+ 0.5,
+ 0,
+ `2026-01-01T00:${String(index).padStart(2, '0')}:00Z`,
+ ]
+ }
+
+ function sessionResponse(indexes: number[]): { columns: string[]; results: unknown[][] } {
+ return {
+ columns: sessionColumns,
+ results: indexes.map((index) => sessionRow(index)),
+ }
+ }
+
+ function deferredResponse(): {
+ promise: Promise<{ columns: string[]; results: unknown[][] }>
+ resolve: (response: { columns: string[]; results: unknown[][] }) => void
+ reject: (error: unknown) => void
+ } {
+ let resolve!: (response: { columns: string[]; results: unknown[][] }) => void
+ let reject!: (error: unknown) => void
+ const promise = new Promise<{ columns: string[]; results: unknown[][] }>((promiseResolve, promiseReject) => {
+ resolve = promiseResolve
+ reject = promiseReject
+ })
+ return { promise, resolve, reject }
+ }
beforeEach(() => {
initKeaTests()
+ querySpy = jest.spyOn(api, 'query').mockResolvedValue({
+ columns: sessionColumns,
+ results: [],
+ } as any)
sceneLogic.mount()
- router.actions.push(urls.aiObservabilitySessions())
sharedLogic = aiObservabilitySharedLogic({})
sharedLogic.mount()
- sessionsLogic = aiObservabilitySessionsViewLogic({})
- sessionsLogic.mount()
+ logic = aiObservabilitySessionsViewLogic({})
+ logic.mount()
})
afterEach(() => {
- sessionsLogic.unmount()
+ logic.unmount()
sharedLogic.unmount()
+ sceneLogic.unmount()
+ jest.restoreAllMocks()
})
- describe('session expansion state', () => {
- it('toggles session expansion state', async () => {
- await expectLogic(sessionsLogic, () => {
- sessionsLogic.actions.toggleSessionExpanded('session-123')
- }).toMatchValues({
- expandedSessionIds: new Set(['session-123']),
- })
-
- // Toggle again to collapse
- await expectLogic(sessionsLogic, () => {
- sessionsLogic.actions.toggleSessionExpanded('session-123')
- }).toMatchValues({
- expandedSessionIds: new Set(),
- })
- })
-
- it('handles multiple expanded sessions', async () => {
- await expectLogic(sessionsLogic, () => {
- sessionsLogic.actions.toggleSessionExpanded('session-1')
- sessionsLogic.actions.toggleSessionExpanded('session-2')
- sessionsLogic.actions.toggleSessionExpanded('session-3')
- }).toMatchValues({
- expandedSessionIds: new Set(['session-1', 'session-2', 'session-3']),
- })
-
- // Collapse middle session
- await expectLogic(sessionsLogic, () => {
- sessionsLogic.actions.toggleSessionExpanded('session-2')
- }).toMatchValues({
- expandedSessionIds: new Set(['session-1', 'session-3']),
- })
- })
-
- it('clears expanded sessions when date filter changes', async () => {
- sessionsLogic.actions.toggleSessionExpanded('session-123')
+ it('reloads URL-applied session filters while the sessions tab is visible', async () => {
+ setActiveTab('aiObservabilitySessions')
+ querySpy.mockClear()
- await expectLogic(sessionsLogic, () => {
- sharedLogic.actions.setDates('-7d', null)
- }).toMatchValues({
- expandedSessionIds: new Set(),
- sessionTraces: {},
- })
- })
+ sharedLogic.actions.applyUrlState(urlState)
+ await settleListeners()
- it('clears expanded sessions when property filters change', async () => {
- sessionsLogic.actions.toggleSessionExpanded('session-456')
-
- await expectLogic(sessionsLogic, () => {
- sharedLogic.actions.setPropertyFilters([
- {
- type: PropertyFilterType.Event,
- key: 'browser',
- value: 'Chrome',
- operator: PropertyOperator.Exact,
- },
- ])
- }).toMatchValues({
- expandedSessionIds: new Set(),
- sessionTraces: {},
- })
- })
-
- it('clears expanded sessions when test accounts filter changes', async () => {
- sessionsLogic.actions.toggleSessionExpanded('session-789')
-
- await expectLogic(sessionsLogic, () => {
- sharedLogic.actions.setShouldFilterTestAccounts(true)
- }).toMatchValues({
- expandedSessionIds: new Set(),
- sessionTraces: {},
- })
- })
+ expect(querySpy).toHaveBeenCalledTimes(1)
})
- describe('trace expansion state', () => {
- it('toggles trace expansion state', async () => {
- await expectLogic(sessionsLogic, () => {
- sessionsLogic.actions.toggleTraceExpanded('trace-abc')
- }).toMatchValues({
- expandedTraceIds: new Set(['trace-abc']),
- })
+ it('does not reload sessions for hidden-tab URL state changes', async () => {
+ setActiveTab('aiObservabilityTraces')
+ querySpy.mockClear()
- // Toggle again to collapse
- await expectLogic(sessionsLogic, () => {
- sessionsLogic.actions.toggleTraceExpanded('trace-abc')
- }).toMatchValues({
- expandedTraceIds: new Set(),
- })
- })
-
- it('handles multiple expanded traces', async () => {
- await expectLogic(sessionsLogic, () => {
- sessionsLogic.actions.toggleTraceExpanded('trace-1')
- sessionsLogic.actions.toggleTraceExpanded('trace-2')
- }).toMatchValues({
- expandedTraceIds: new Set(['trace-1', 'trace-2']),
- })
- })
+ sharedLogic.actions.applyUrlState(urlState)
+ await settleListeners()
- it('clears expanded traces when filters change', async () => {
- sessionsLogic.actions.toggleTraceExpanded('trace-xyz')
-
- await expectLogic(sessionsLogic, () => {
- sharedLogic.actions.setDates('-14d', null)
- }).toMatchValues({
- expandedTraceIds: new Set(),
- fullTraces: {},
- })
- })
+ expect(querySpy).not.toHaveBeenCalled()
})
- describe('loading state tracking', () => {
- it('tracks loading state for session traces', async () => {
- sessionsLogic.actions.loadSessionTraces('session-123')
+ it('ignores stale session reloads after filters change', async () => {
+ setActiveTab('aiObservabilitySessions')
+ const staleResponse = deferredResponse()
+ const freshResponse = deferredResponse()
+ querySpy.mockImplementationOnce(() => staleResponse.promise).mockImplementationOnce(() => freshResponse.promise)
- expect(sessionsLogic.values.loadingSessionTraces.has('session-123')).toBe(true)
+ logic.actions.loadSessions()
+ await settleListeners()
- sessionsLogic.actions.loadSessionTracesSuccess('session-123', [])
+ sharedLogic.actions.applyUrlState(urlState)
+ await settleListeners()
- expect(sessionsLogic.values.loadingSessionTraces.has('session-123')).toBe(false)
- })
-
- it('clears loading state on failure', async () => {
- sessionsLogic.actions.loadSessionTraces('session-456')
-
- expect(sessionsLogic.values.loadingSessionTraces.has('session-456')).toBe(true)
-
- sessionsLogic.actions.loadSessionTracesFailure('session-456', new Error('Test error'))
-
- expect(sessionsLogic.values.loadingSessionTraces.has('session-456')).toBe(false)
- })
-
- it('tracks loading state for full traces', async () => {
- sessionsLogic.actions.loadFullTrace('trace-abc')
-
- expect(sessionsLogic.values.loadingFullTraces.has('trace-abc')).toBe(true)
+ freshResponse.resolve(sessionResponse([2]))
+ await settleListeners()
+ expect(logic.values.sessions.map((session) => session.sessionId)).toEqual(['session-2'])
+ expect(logic.values.sessionsLoading).toBe(false)
- const mockTrace = { id: 'trace-abc' } as any
- sessionsLogic.actions.loadFullTraceSuccess('trace-abc', mockTrace)
-
- expect(sessionsLogic.values.loadingFullTraces.has('trace-abc')).toBe(false)
- })
-
- it('handles multiple concurrent loading operations', async () => {
- sessionsLogic.actions.loadSessionTraces('session-1')
- sessionsLogic.actions.loadSessionTraces('session-2')
- sessionsLogic.actions.loadFullTrace('trace-1')
-
- expect(sessionsLogic.values.loadingSessionTraces.has('session-1')).toBe(true)
- expect(sessionsLogic.values.loadingSessionTraces.has('session-2')).toBe(true)
- expect(sessionsLogic.values.loadingFullTraces.has('trace-1')).toBe(true)
-
- sessionsLogic.actions.loadSessionTracesSuccess('session-1', [])
-
- expect(sessionsLogic.values.loadingSessionTraces.has('session-1')).toBe(false)
- expect(sessionsLogic.values.loadingSessionTraces.has('session-2')).toBe(true)
- expect(sessionsLogic.values.loadingFullTraces.has('trace-1')).toBe(true)
- })
+ staleResponse.resolve(sessionResponse([1]))
+ await settleListeners()
+ expect(logic.values.sessions.map((session) => session.sessionId)).toEqual(['session-2'])
+ expect(querySpy).toHaveBeenCalledTimes(2)
})
- describe('session traces data', () => {
- it('stores loaded session traces', async () => {
- const mockTraces = [{ id: 'trace-1' }, { id: 'trace-2' }] as any[]
+ it('ignores stale load-more responses after a first-page reload', async () => {
+ querySpy.mockResolvedValueOnce(sessionResponse(Array.from({ length: 50 }, (_, i) => i)))
- await expectLogic(sessionsLogic, () => {
- sessionsLogic.actions.loadSessionTracesSuccess('session-123', mockTraces)
- }).toMatchValues({
- sessionTraces: {
- 'session-123': mockTraces,
- },
- })
- })
+ logic.actions.loadSessions()
+ await settleListeners()
+ expect(logic.values.sessions).toHaveLength(50)
+ expect(logic.values.hasMoreSessions).toBe(true)
- it('stores traces for multiple sessions', async () => {
- const mockTraces1 = [{ id: 'trace-1' }] as any[]
- const mockTraces2 = [{ id: 'trace-2' }] as any[]
+ const staleLoadMoreResponse = deferredResponse()
+ const refreshResponse = deferredResponse()
+ querySpy
+ .mockImplementationOnce(() => staleLoadMoreResponse.promise)
+ .mockImplementationOnce(() => refreshResponse.promise)
- sessionsLogic.actions.loadSessionTracesSuccess('session-1', mockTraces1)
- sessionsLogic.actions.loadSessionTracesSuccess('session-2', mockTraces2)
+ logic.actions.loadMoreSessions()
+ await settleListeners()
+ expect(logic.values.moreSessionsLoading).toBe(true)
- expect(sessionsLogic.values.sessionTraces).toEqual({
- 'session-1': mockTraces1,
- 'session-2': mockTraces2,
- })
- })
+ logic.actions.loadSessions({ refresh: 'force_blocking' })
+ await settleListeners()
+ expect(logic.values.moreSessionsLoading).toBe(false)
- it('clears session traces when filters change', async () => {
- const mockTraces = [{ id: 'trace-1' }] as any[]
- sessionsLogic.actions.loadSessionTracesSuccess('session-123', mockTraces)
+ refreshResponse.resolve(sessionResponse([60]))
+ await settleListeners()
+ expect(logic.values.sessions.map((session) => session.sessionId)).toEqual(['session-60'])
- await expectLogic(sessionsLogic, () => {
- sharedLogic.actions.setDates('-30d', null)
- }).toMatchValues({
- sessionTraces: {},
- })
- })
+ staleLoadMoreResponse.resolve(sessionResponse([50]))
+ await settleListeners()
+ expect(logic.values.sessions.map((session) => session.sessionId)).toEqual(['session-60'])
+ expect(querySpy).toHaveBeenCalledTimes(3)
})
- describe('full traces data', () => {
- it('stores loaded full trace', async () => {
- const mockTrace = { id: 'trace-abc', events: [] } as any
-
- await expectLogic(sessionsLogic, () => {
- sessionsLogic.actions.loadFullTraceSuccess('trace-abc', mockTrace)
- }).toMatchValues({
- fullTraces: {
- 'trace-abc': mockTrace,
- },
+ it('appends additional session pages', async () => {
+ let page = 0
+ querySpy.mockImplementation(() => {
+ page += 1
+ return Promise.resolve({
+ columns: sessionColumns,
+ results: page === 1 ? Array.from({ length: 50 }, (_, i) => sessionRow(i)) : [sessionRow(50)],
})
})
- it('stores multiple full traces', async () => {
- const mockTrace1 = { id: 'trace-1' } as any
- const mockTrace2 = { id: 'trace-2' } as any
-
- sessionsLogic.actions.loadFullTraceSuccess('trace-1', mockTrace1)
- sessionsLogic.actions.loadFullTraceSuccess('trace-2', mockTrace2)
-
- expect(sessionsLogic.values.fullTraces).toEqual({
- 'trace-1': mockTrace1,
- 'trace-2': mockTrace2,
- })
- })
-
- it('clears full traces when filters change', async () => {
- const mockTrace = { id: 'trace-xyz' } as any
- sessionsLogic.actions.loadFullTraceSuccess('trace-xyz', mockTrace)
+ logic.actions.loadSessions()
+ await settleListeners()
+ expect(logic.values.sessions).toHaveLength(50)
+ expect(logic.values.hasMoreSessions).toBe(true)
+
+ logic.actions.loadMoreSessions()
+ await settleListeners()
+ expect(logic.values.sessions).toHaveLength(51)
+ expect(logic.values.sessions[50].sessionId).toBe('session-50')
+ expect(logic.values.hasMoreSessions).toBe(false)
+ expect(querySpy).toHaveBeenCalledTimes(2)
+ })
- await expectLogic(sessionsLogic, () => {
- sharedLogic.actions.setPropertyFilters([])
- }).toMatchValues({
- fullTraces: {},
- })
- })
+ it('preloads titles for appended session pages', async () => {
+ const titleLogic = llmSessionTitleLazyLoaderLogic()
+ titleLogic.mount()
+ try {
+ querySpy.mockResolvedValueOnce(sessionResponse(Array.from({ length: 50 }, (_, i) => i)))
+ querySpy.mockResolvedValueOnce(sessionResponse([50]))
+
+ logic.actions.loadSessions()
+ await settleListeners()
+ expect(logic.values.hasMoreSessions).toBe(true)
+
+ logic.actions.loadMoreSessions()
+ await settleListeners()
+
+ expect(logic.values.sessions[50].sessionId).toBe('session-50')
+ expect(titleLogic.values.loadingSessionIds.has('session-50')).toBe(true)
+ } finally {
+ titleLogic.unmount()
+ }
})
})
diff --git a/products/ai_observability/frontend/aiObservabilitySessionDataLogic.test.ts b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.test.ts
new file mode 100644
index 000000000000..0c9833efced1
--- /dev/null
+++ b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.test.ts
@@ -0,0 +1,94 @@
+import api from 'lib/api'
+
+import { LLMTrace, NodeKind, TraceQuery } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { aiObservabilitySessionDataLogic } from './aiObservabilitySessionDataLogic'
+import { aiObservabilitySessionLogic } from './aiObservabilitySessionLogic'
+
+describe('aiObservabilitySessionDataLogic', () => {
+ let sessionLogic: ReturnType<typeof aiObservabilitySessionLogic.build>
+ let logic: ReturnType<typeof aiObservabilitySessionDataLogic.build>
+ let querySpy: jest.SpyInstance
+
+ async function settleListeners(): Promise<void> {
+ for (let i = 0; i < 5; i++) {
+ await Promise.resolve()
+ }
+ }
+
+ function traceWithEvents(events: LLMTrace['events'] = []): LLMTrace {
+ return {
+ id: 'trace-1',
+ createdAt: '2026-01-01T00:00:00Z',
+ events,
+ } as LLMTrace
+ }
+
+ function traceQueryCalls(): TraceQuery[] {
+ return querySpy.mock.calls
+ .map(([query]) => query)
+ .filter((query): query is TraceQuery => query?.kind === NodeKind.TraceQuery)
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ querySpy = jest.spyOn(api, 'query').mockResolvedValue({ results: [traceWithEvents()] } as any)
+ sessionLogic = aiObservabilitySessionLogic()
+ sessionLogic.mount()
+ sessionLogic.actions.setSessionId('session-1')
+ sessionLogic.actions.setDateRange('-7d', null)
+ logic = aiObservabilitySessionDataLogic({
+ sessionId: 'session-1',
+ query: sessionLogic.values.query,
+ cachedResults: { results: [] } as any,
+ })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ sessionLogic.unmount()
+ jest.restoreAllMocks()
+ })
+
+ it('refetches full trace details after the date range changes', async () => {
+ logic.actions.loadFullTrace('trace-1')
+ await settleListeners()
+ expect(traceQueryCalls()).toHaveLength(1)
+ expect(traceQueryCalls()[0].dateRange?.date_from).toBe('-7d')
+
+ logic.actions.loadFullTrace('trace-1')
+ await settleListeners()
+ expect(traceQueryCalls()).toHaveLength(1)
+
+ sessionLogic.actions.setDateRange('-24h', null)
+ await settleListeners()
+ logic.actions.loadFullTrace('trace-1')
+ await settleListeners()
+
+ expect(traceQueryCalls()).toHaveLength(2)
+ expect(traceQueryCalls()[1].dateRange?.date_from).toBe('-24h')
+ })
+
+ it('expands the first trace event when opening the drawer without a focus target', async () => {
+ querySpy.mockImplementation((query) => {
+ return Promise.resolve({
+ results:
+ query?.kind === NodeKind.TraceQuery
+ ? [
+ traceWithEvents([
+ { id: 'second-event', event: '$ai_span', createdAt: '2026-01-01T00:00:02Z' },
+ { id: 'first-event', event: '$ai_generation', createdAt: '2026-01-01T00:00:01Z' },
+ ] as LLMTrace['events']),
+ ]
+ : [],
+ } as any)
+ })
+
+ logic.actions.openStepsDrawer('trace-1')
+ await settleListeners()
+
+ expect(logic.values.expandedGenerationIds).toEqual(new Set(['first-event']))
+ })
+})
diff --git a/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts
index 7411920ee357..23864641ce72 100644
--- a/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts
@@ -11,6 +11,7 @@ import {
AnyResponseType,
DataTableNode,
LLMTrace,
+ LLMTraceEvent,
NodeKind,
TraceQuery,
TracesQueryResponse,
@@ -22,6 +23,7 @@ import { aiObservabilitySessionLogic } from './aiObservabilitySessionLogic'
import { restoreTree } from './aiObservabilityTraceDataLogic'
import { SessionTurn, extractSessionTurns } from './extractSessionTurns'
import { llmAnalyticsSummarizationBatchCheckCreate } from './generated/api'
+import { eventLabel } from './utils'
export interface TraceSummary {
title: string
@@ -34,8 +36,12 @@ export interface TraceSummary {
// button. Picking first N and not first and last N, because cross-trace dedup walks
// chronologically and accumulates `seenSignatures`; any gap in loaded turns would
// let the later turns' running history show as "new" content.
-// Most sessions have less than 10 turns, a proper fix later is a bulk query.
-const AUTO_LOAD_LIMIT = 10
+// Kept small because each trace is a separate query fired in parallel — a single
+// session open must stay well under the per-org concurrent-query budget. The proper
+// fix is one bulk query for the first N traces' events.
+const AUTO_LOAD_LIMIT = 5
+
+type SessionDateRange = { dateFrom: string | null; dateTo: string | null } | null
export interface SessionDataLogicProps {
sessionId: string
@@ -58,6 +64,41 @@ function getDataNodeLogicProps({ sessionId, query, cachedResults }: SessionDataL
return dataNodeLogicProps
}
+function getTraceQueryDateRange(dateRange: SessionDateRange): TraceQuery['dateRange'] {
+ if (!dateRange?.dateFrom && !dateRange?.dateTo) {
+ return undefined
+ }
+
+ return {
+ date_from: dateRange.dateFrom || undefined,
+ date_to: dateRange.dateTo || undefined,
+ }
+}
+
+function getDateRangeCacheKey(dateRange: SessionDateRange): string {
+ return `${dateRange?.dateFrom ?? ''}\0${dateRange?.dateTo ?? ''}`
+}
+
+function getFirstTraceStepEventId(trace: LLMTrace): string | null {
+ const firstEvent = 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())[0]
+ return firstEvent?.id ?? null
+}
+
+// Maps a clicked tool/error pill to the trace event it represents so the drawer
+// can pre-expand that step. Tool spans and error labels both derive from the
+// event's `$ai_span_name`/`$ai_model` (via `eventLabel`), so an exact label match
+// finds the step; prefer the errored event when several share a label.
+function resolveFocusEventId(trace: LLMTrace, focusKey: string): string | null {
+ const events = trace.events ?? []
+ const isError = (e: LLMTraceEvent): boolean =>
+ e.properties?.$ai_is_error === true || e.properties?.$ai_is_error === 'true' || !!e.properties?.$ai_error
+ const match =
+ events.find((e) => eventLabel(e) === focusKey && isError(e)) ?? events.find((e) => eventLabel(e) === focusKey)
+ return match?.id ?? null
+}
+
export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLogicType>([
path(['scenes', 'ai-observability', 'aiObservabilitySessionDataLogic']),
props({} as SessionDataLogicProps),
@@ -65,7 +106,7 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLog
connect((props: SessionDataLogicProps) => ({
values: [
aiObservabilitySessionLogic,
- ['sessionId'],
+ ['sessionId', 'dateRange'],
dataNodeLogic(getDataNodeLogicProps(props)),
['response', 'responseLoading', 'responseError', 'canLoadNextData', 'hasMoreData', 'nextDataLoading'],
maxGlobalLogic,
@@ -73,17 +114,29 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLog
teamLogic,
['currentTeamId'],
],
- actions: [dataNodeLogic(getDataNodeLogicProps(props)), ['loadNextData']],
+ actions: [
+ aiObservabilitySessionLogic,
+ ['setDateRange'],
+ dataNodeLogic(getDataNodeLogicProps(props)),
+ ['loadNextData'],
+ ],
})),
actions({
- // Steps panel = the per-turn `AIObservabilityTraceEvents` tree shown via the
- // "Show steps" link. Distinct from "trace loaded" because the conversation
- // bubbles render as soon as the full trace is fetched, regardless of steps state.
- toggleSteps: (traceId: string) => ({ traceId }),
+ // Which trace's steps are open in the side drawer (one at a time, or null).
+ // `focusEventKey` (a tool name / error label) pre-expands the matching step.
+ openStepsDrawer: (traceId: string, focusEventKey: string | null = null) => ({ traceId, focusEventKey }),
+ closeStepsDrawer: true,
toggleGenerationExpanded: (generationId: string) => ({ generationId }),
+ // Expand only this step, collapsing the rest (timeline / pill focus).
+ focusGenerationExpanded: (generationId: string) => ({ generationId }),
+ clearTraceDetails: true,
loadFullTrace: (traceId: string) => ({ traceId }),
- loadFullTraceSuccess: (traceId: string, trace: LLMTrace) => ({ traceId, trace }),
+ loadFullTraceSuccess: (traceId: string, trace: LLMTrace, dateRangeCacheKey: string) => ({
+ traceId,
+ trace,
+ dateRangeCacheKey,
+ }),
loadFullTraceFailure: (traceId: string) => ({ traceId }),
loadCachedSummaries: (traceIds: string[]) => ({ traceIds }),
loadCachedSummariesSuccess: (summaries: Array<{ trace_id: string; title: string }>) => ({ summaries }),
@@ -95,18 +148,22 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLog
}),
reducers({
- stepsExpandedTraceIds: [
- new Set<string>() as Set<string>,
+ drawerTraceId: [
+ null as string | null,
{
- toggleSteps: (state, { traceId }) => {
- const newSet = new Set(state)
- if (newSet.has(traceId)) {
- newSet.delete(traceId)
- } else {
- newSet.add(traceId)
- }
- return newSet
- },
+ openStepsDrawer: (_, { traceId }) => traceId,
+ closeStepsDrawer: () => null,
+ clearTraceDetails: () => null,
+ },
+ ],
+ // A pending tool/error label to focus once the drawer's trace finishes loading.
+ drawerFocusKey: [
+ null as string | null,
+ {
+ openStepsDrawer: (_, { focusEventKey }) => focusEventKey,
+ closeStepsDrawer: () => null,
+ focusGenerationExpanded: () => null,
+ clearTraceDetails: () => null,
},
],
expandedGenerationIds: [
@@ -121,6 +178,8 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLog
}
return newSet
},
+ focusGenerationExpanded: (_, { generationId }) => new Set([generationId]),
+ clearTraceDetails: () => new Set<string>(),
},
],
fullTraces: [
@@ -130,6 +189,17 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLog
...state,
[traceId]: trace,
}),
+ clearTraceDetails: () => ({}),
+ },
+ ],
+ fullTraceDateRangeCacheKeys: [
+ {} as Record<string, string>,
+ {
+ loadFullTraceSuccess: (state, { traceId, dateRangeCacheKey }) => ({
+ ...state,
+ [traceId]: dateRangeCacheKey,
+ }),
+ clearTraceDetails: () => ({}),
},
],
loadingFullTraces: [
@@ -146,6 +216,7 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLog
newSet.delete(traceId)
return newSet
},
+ clearTraceDetails: () => new Set<string>(),
},
],
traceSummaries: [
@@ -199,6 +270,13 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLog
(traceSummaries: Record<string, TraceSummary>): boolean =>
Object.values(traceSummaries).some((s) => s.loading),
],
+ // Stay "loading" until the trace list AND the auto-loaded full traces settle,
+ // so the conversation appears at once instead of a second per-turn spinner.
+ initialLoading: [
+ (s) => [s.responseLoading, s.traces, s.loadingFullTraces],
+ (responseLoading: boolean, traces: LLMTrace[], loadingFullTraces: Set<string>): boolean =>
+ responseLoading || traces.slice(0, AUTO_LOAD_LIMIT).some((t) => loadingFullTraces.has(t.id)),
+ ],
}),
listeners(({ actions, values }) => {
@@ -213,6 +291,9 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLog
const inFlightTraceFetches = new Set<string>()
return {
+ setDateRange: () => {
+ actions.clearTraceDetails()
+ },
loadCachedSummaries: async ({ traceIds }) => {
if (traceIds.length === 0) {
return
@@ -241,19 +322,28 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLog
}
},
loadFullTrace: async ({ traceId }) => {
- if (values.fullTraces[traceId] || inFlightTraceFetches.has(traceId)) {
+ const dateRangeCacheKey = getDateRangeCacheKey(values.dateRange)
+ if (
+ (values.fullTraces[traceId] && values.fullTraceDateRangeCacheKeys[traceId] === dateRangeCacheKey) ||
+ inFlightTraceFetches.has(`${traceId}:${dateRangeCacheKey}`)
+ ) {
return
}
- inFlightTraceFetches.add(traceId)
+ inFlightTraceFetches.add(`${traceId}:${dateRangeCacheKey}`)
+ const dateRange = getTraceQueryDateRange(values.dateRange)
const traceQuery: TraceQuery = {
kind: NodeKind.TraceQuery,
traceId,
includeSentiment: true,
+ dateRange,
}
try {
const response = await api.query(traceQuery)
+ if (dateRangeCacheKey !== getDateRangeCacheKey(values.dateRange)) {
+ return
+ }
if (response.results && response.results[0]) {
- actions.loadFullTraceSuccess(traceId, response.results[0])
+ actions.loadFullTraceSuccess(traceId, response.results[0], dateRangeCacheKey)
} else {
actions.loadFullTraceFailure(traceId)
}
@@ -261,7 +351,35 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLog
console.error('Error loading full trace:', error)
actions.loadFullTraceFailure(traceId)
} finally {
- inFlightTraceFetches.delete(traceId)
+ inFlightTraceFetches.delete(`${traceId}:${dateRangeCacheKey}`)
+ }
+ },
+ openStepsDrawer: ({ traceId, focusEventKey }) => {
+ const trace = values.fullTraces[traceId]
+ const dateRangeCacheKey = getDateRangeCacheKey(values.dateRange)
+ const isTraceFresh = !!trace && values.fullTraceDateRangeCacheKeys[traceId] === dateRangeCacheKey
+ if (!isTraceFresh && !values.loadingFullTraces.has(traceId)) {
+ actions.loadFullTrace(traceId)
+ }
+ // Already loaded: focus the clicked step now. Otherwise the
+ // loadFullTraceSuccess listener picks it up once events arrive.
+ if (isTraceFresh && trace) {
+ const id = focusEventKey
+ ? resolveFocusEventId(trace, focusEventKey)
+ : getFirstTraceStepEventId(trace)
+ if (id) {
+ actions.focusGenerationExpanded(id)
+ }
+ }
+ },
+ loadFullTraceSuccess: ({ traceId, trace }) => {
+ if (traceId === values.drawerTraceId) {
+ const id = values.drawerFocusKey
+ ? resolveFocusEventId(trace, values.drawerFocusKey)
+ : getFirstTraceStepEventId(trace)
+ if (id) {
+ actions.focusGenerationExpanded(id)
+ }
}
},
summarizeAllTraces: async () => {
@@ -286,9 +404,11 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLog
// First fetch the full trace with all events (session query only has direct children)
let fullTrace: LLMTrace | undefined = values.fullTraces[traceId]
if (!fullTrace) {
+ const dateRange = getTraceQueryDateRange(values.dateRange)
const traceQuery: TraceQuery = {
kind: NodeKind.TraceQuery,
traceId,
+ dateRange,
}
const traceResponse = await api.query(traceQuery)
if (traceResponse.results && traceResponse.results[0]) {
diff --git a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
index a7bbebf07f85..9ca546d537b6 100644
--- a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
@@ -337,6 +337,7 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
[urls.aiObservabilityTools()]: (_, searchParams) => applyNonDashboard(searchParams),
[urls.aiObservabilitySentiment()]: (_, searchParams) => applyNonDashboard(searchParams),
[urls.aiObservabilitySessions()]: (_, searchParams) => applyNonDashboard(searchParams),
+ '/ai-observability/sessions/:id': (_, searchParams) => applyNonDashboard(searchParams),
[urls.aiObservabilityPlayground()]: (_, searchParams) => applyNonDashboard(searchParams),
// Cluster list and detail both honor the same `filters` / `filter_test_accounts`
// params so deep links from generations/traces tabs carry their filter set through.
diff --git a/products/ai_observability/frontend/buildSessionTimeline.test.ts b/products/ai_observability/frontend/buildSessionTimeline.test.ts
new file mode 100644
index 000000000000..32d3dc381bcb
--- /dev/null
+++ b/products/ai_observability/frontend/buildSessionTimeline.test.ts
@@ -0,0 +1,63 @@
+import { LLMTrace } from '~/queries/schema/schema-general'
+
+import { IDLE_CAP_MS, buildSessionTimeline } from './buildSessionTimeline'
+import { SessionTurn } from './extractSessionTurns'
+
+function turn(offsetMs: number, latencySec: number): SessionTurn {
+ return {
+ trace: {
+ id: `t-${offsetMs}`,
+ createdAt: new Date(1_000_000_000_000 + offsetMs).toISOString(),
+ totalLatency: latencySec,
+ } as LLMTrace,
+ isLoaded: true,
+ newInputs: [],
+ outputs: [],
+ tools: [],
+ errors: [],
+ }
+}
+
+describe('buildSessionTimeline', () => {
+ it('places the request behind a user-think lead-in, then the response after the AI latency', () => {
+ const { turnRevealsMs, turnStartsMs, turnResponsesMs } = buildSessionTimeline([turn(0, 1)])
+ expect(turnRevealsMs).toEqual([0]) // turn appears, user starts composing
+ expect(turnStartsMs).toEqual([600]) // request lands after the 600ms user-think floor
+ expect(turnResponsesMs).toEqual([1600]) // response 1s after the request
+ })
+
+ it('positions turns by elapsed time, splitting user-think, request, and response', () => {
+ const { turnRevealsMs, turnStartsMs, turnResponsesMs, durationMs } = buildSessionTimeline([
+ turn(0, 1),
+ turn(2000, 0.5),
+ ])
+ expect(turnRevealsMs).toEqual([0, 1600]) // 2nd turn reveals when the 1st response lands
+ expect(turnStartsMs).toEqual([600, 2600]) // 2nd user-think = 1000ms real gap after the 1st response
+ expect(turnResponsesMs).toEqual([1600, 3200]) // 2nd think floored to 600ms
+ expect(durationMs).toBe(3200)
+ })
+
+ it('caps long idle gaps between turns', () => {
+ // 60s real gap collapses to IDLE_CAP_MS (measured from the prior response)
+ const { turnStartsMs } = buildSessionTimeline([turn(0, 1), turn(61_000, 1)])
+ expect(turnStartsMs[1]).toBe(1600 + IDLE_CAP_MS)
+ })
+
+ it('handles a single turn', () => {
+ expect(buildSessionTimeline([turn(0, 2)])).toMatchObject({
+ turnRevealsMs: [0],
+ turnStartsMs: [600],
+ turnResponsesMs: [2600],
+ durationMs: 2600,
+ })
+ })
+
+ it('returns empty for no turns', () => {
+ expect(buildSessionTimeline([])).toEqual({
+ turnRevealsMs: [],
+ turnStartsMs: [],
+ turnResponsesMs: [],
+ durationMs: 0,
+ })
+ })
+})
diff --git a/products/ai_observability/frontend/buildSessionTimeline.ts b/products/ai_observability/frontend/buildSessionTimeline.ts
new file mode 100644
index 000000000000..522f37cb9f69
--- /dev/null
+++ b/products/ai_observability/frontend/buildSessionTimeline.ts
@@ -0,0 +1,41 @@
+import { SessionTurn } from './extractSessionTurns'
+
+// Idle gaps between turns are compressed so playback stays watchable; the
+// per-turn "think" windows are floored (always visible) and capped.
+export const IDLE_CAP_MS = 3000
+const MIN_THINK_MS = 600
+const THINK_CAP_MS = 12000
+const MIN_USER_THINK_MS = 600
+
+export interface SessionTimelineData {
+ turnRevealsMs: number[] // turn appears; the user starts composing
+ turnStartsMs: number[] // the user's request lands
+ turnResponsesMs: number[] // the assistant's response lands
+ durationMs: number
+}
+
+export function buildSessionTimeline(turns: SessionTurn[]): SessionTimelineData {
+ if (!turns.length) {
+ return { turnRevealsMs: [], turnStartsMs: [], turnResponsesMs: [], durationMs: 0 }
+ }
+
+ const rawStarts = turns.map((t) => new Date(t.trace.createdAt).getTime())
+ const latencies = turns.map((t) => Math.round((t.trace.totalLatency ?? 0) * 1000))
+
+ const turnRevealsMs: number[] = []
+ const turnStartsMs: number[] = []
+ const turnResponsesMs: number[] = []
+ let cursor = 0
+ turns.forEach((_, i) => {
+ const rawIdle = i > 0 ? Math.max(rawStarts[i] - (rawStarts[i - 1] + latencies[i - 1]), 0) : 0
+ const userThinkMs = Math.min(Math.max(rawIdle, MIN_USER_THINK_MS), IDLE_CAP_MS)
+ turnRevealsMs.push(cursor)
+ cursor += userThinkMs
+ turnStartsMs.push(cursor)
+ const thinkMs = Math.min(Math.max(latencies[i], MIN_THINK_MS), THINK_CAP_MS)
+ cursor += thinkMs
+ turnResponsesMs.push(cursor)
+ })
+
+ return { turnRevealsMs, turnStartsMs, turnResponsesMs, durationMs: cursor }
+}
diff --git a/products/ai_observability/frontend/components/SessionPlayer/SessionPlayerControls.tsx b/products/ai_observability/frontend/components/SessionPlayer/SessionPlayerControls.tsx
new file mode 100644
index 000000000000..7fc423e7b1b7
--- /dev/null
+++ b/products/ai_observability/frontend/components/SessionPlayer/SessionPlayerControls.tsx
@@ -0,0 +1,63 @@
+import { IconPause, IconPlay } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+} from 'lib/ui/quill'
+import { colonDelimitedDuration } from 'lib/utils/durations'
+
+import { PLAYBACK_SPEEDS } from '../../sessionPlaybackLogic'
+
+export function SessionPlayerControls({
+ playing,
+ speed,
+ currentMs,
+ durationMs,
+ onTogglePlay,
+ onSetSpeed,
+}: {
+ playing: boolean
+ speed: number
+ currentMs: number
+ durationMs: number
+ onTogglePlay: () => void
+ onSetSpeed: (speed: number) => void
+}): JSX.Element {
+ return (
+ <div className="flex items-center gap-2">
+ <LemonButton
+ size="small"
+ icon={playing ? <IconPause /> : <IconPlay />}
+ onClick={onTogglePlay}
+ aria-label={playing ? 'Pause' : 'Play'}
+ data-attr="session-player-play"
+ />
+ <span className="text-xs text-muted font-mono">
+ {colonDelimitedDuration(Math.floor(currentMs / 1000))} /{' '}
+ {colonDelimitedDuration(Math.floor(durationMs / 1000))}
+ </span>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <LemonButton size="small" type="secondary" data-attr="session-player-speed">
+ {speed}x
+ </LemonButton>
+ }
+ />
+ <DropdownMenuContent align="start" className="w-auto min-w-20">
+ <DropdownMenuRadioGroup value={String(speed)} onValueChange={(value) => onSetSpeed(Number(value))}>
+ {PLAYBACK_SPEEDS.map((s) => (
+ <DropdownMenuRadioItem key={s} value={String(s)}>
+ {s}x
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/components/SessionPlayer/SessionSeekbar.tsx b/products/ai_observability/frontend/components/SessionPlayer/SessionSeekbar.tsx
new file mode 100644
index 000000000000..06f9e5f18a2f
--- /dev/null
+++ b/products/ai_observability/frontend/components/SessionPlayer/SessionSeekbar.tsx
@@ -0,0 +1,85 @@
+import { useRef } from 'react'
+
+import { cn } from 'lib/utils/css-classes'
+
+// A session-replay-style scrubber. Clicking/dragging seeks; ticks jump to a turn —
+// muted = the user's message, green = the assistant's response.
+export function SessionSeekbar({
+ durationMs,
+ currentMs,
+ turnStartsMs,
+ turnResponsesMs,
+ onSeek,
+}: {
+ durationMs: number
+ currentMs: number
+ turnStartsMs: number[]
+ turnResponsesMs: number[]
+ onSeek: (ms: number) => void
+}): JSX.Element {
+ const trackRef = useRef<HTMLDivElement>(null)
+
+ const seekFromClientX = (clientX: number): void => {
+ const el = trackRef.current
+ if (!el || durationMs <= 0) {
+ return
+ }
+ const rect = el.getBoundingClientRect()
+ const fraction = Math.min(Math.max((clientX - rect.left) / rect.width, 0), 1)
+ onSeek(fraction * durationMs)
+ }
+
+ const at = (ms: number): number => (durationMs > 0 ? (ms / durationMs) * 100 : 0)
+ const progressPct = at(currentMs)
+
+ const tick = (ms: number, kind: 'user' | 'assistant', i: number): JSX.Element => (
+ <button
+ key={`${kind}-${i}`}
+ type="button"
+ aria-label={`Jump to the ${kind} message in turn ${i + 1}`}
+ title={`Turn ${i + 1} · ${kind}`}
+ onClick={(e) => {
+ e.stopPropagation()
+ onSeek(ms)
+ }}
+ className={cn(
+ 'absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-1 h-3.5 rounded-full hover:bg-default',
+ kind === 'user' ? 'bg-muted' : 'bg-success'
+ )}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ left: `${at(ms)}%` }}
+ />
+ )
+
+ return (
+ <div
+ ref={trackRef}
+ className="relative h-3 w-full rounded-full bg-border cursor-pointer select-none"
+ onPointerDown={(e) => {
+ ;(e.target as HTMLElement).setPointerCapture?.(e.pointerId)
+ seekFromClientX(e.clientX)
+ }}
+ onPointerMove={(e) => {
+ if (e.buttons === 1) {
+ seekFromClientX(e.clientX)
+ }
+ }}
+ data-attr="session-seekbar"
+ >
+ <div
+ className="absolute left-0 top-0 h-full rounded-full bg-accent"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ width: `${progressPct}%` }}
+ />
+ {turnStartsMs.map((ms, i) => tick(ms, 'user', i))}
+ {turnResponsesMs.map((ms, i) => tick(ms, 'assistant', i))}
+ <div
+ className={cn(
+ 'absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-3 h-3 rounded-full bg-accent shadow'
+ )}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ left: `${progressPct}%` }}
+ />
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/components/SessionPlayer/TypingIndicator.tsx b/products/ai_observability/frontend/components/SessionPlayer/TypingIndicator.tsx
new file mode 100644
index 000000000000..656c26f326b4
--- /dev/null
+++ b/products/ai_observability/frontend/components/SessionPlayer/TypingIndicator.tsx
@@ -0,0 +1,17 @@
+import { MessageTemplate } from 'products/posthog_ai/frontend/api/primitives'
+
+// Chat-app typing dots shown while a turn is in flight; `type` picks the side.
+export function TypingIndicator({ type = 'ai' }: { type?: 'human' | 'ai' }): JSX.Element {
+ return (
+ <MessageTemplate type={type} wrapperClassName="max-w-[75%]">
+ <span
+ className="flex gap-1 items-center py-0.5"
+ aria-label={type === 'human' ? 'User is typing' : 'Assistant is responding'}
+ >
+ <span className="w-1.5 h-1.5 rounded-full bg-muted animate-bounce" />
+ <span className="w-1.5 h-1.5 rounded-full bg-muted animate-bounce [animation-delay:150ms]" />
+ <span className="w-1.5 h-1.5 rounded-full bg-muted animate-bounce [animation-delay:300ms]" />
+ </span>
+ </MessageTemplate>
+ )
+}
diff --git a/products/ai_observability/frontend/sessionPlaybackLogic.test.ts b/products/ai_observability/frontend/sessionPlaybackLogic.test.ts
new file mode 100644
index 000000000000..3909237e5c29
--- /dev/null
+++ b/products/ai_observability/frontend/sessionPlaybackLogic.test.ts
@@ -0,0 +1,52 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { sessionPlaybackLogic } from './sessionPlaybackLogic'
+
+describe('sessionPlaybackLogic', () => {
+ let logic: ReturnType<typeof sessionPlaybackLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ jest.useFakeTimers()
+ logic = sessionPlaybackLogic({ sessionId: 's1' })
+ logic.mount()
+ logic.actions.setTimeline(6000)
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.useRealTimers()
+ })
+
+ it('seeks to an absolute position and pauses', async () => {
+ await expectLogic(logic, () => logic.actions.seek(2500)).toMatchValues({ currentMs: 2500, playing: false })
+ })
+
+ it('advances on tick scaled by speed and stops at the end', async () => {
+ logic.actions.setSpeed(2)
+ logic.actions.play()
+ logic.actions.tick(1000) // 1000ms * 2x = 2000ms
+ await expectLogic(logic).toMatchValues({ currentMs: 2000, playing: true })
+ logic.actions.tick(10_000) // clamps to duration, then pauses
+ await expectLogic(logic).toMatchValues({ currentMs: 6000, playing: false })
+ })
+
+ it('re-syncs a longer duration without rewinding the current position', async () => {
+ logic.actions.seek(2500)
+ // A late trace load extends the timeline; playback position is preserved.
+ await expectLogic(logic, () => logic.actions.setTimeline(8000)).toMatchValues({
+ currentMs: 2500,
+ durationMs: 8000,
+ })
+ })
+
+ it('clamps the current position when the duration shrinks', async () => {
+ logic.actions.seek(5000)
+ await expectLogic(logic, () => logic.actions.setTimeline(3000)).toMatchValues({
+ currentMs: 3000,
+ durationMs: 3000,
+ })
+ })
+})
diff --git a/products/ai_observability/frontend/sessionPlaybackLogic.ts b/products/ai_observability/frontend/sessionPlaybackLogic.ts
new file mode 100644
index 000000000000..3de18c2f29a8
--- /dev/null
+++ b/products/ai_observability/frontend/sessionPlaybackLogic.ts
@@ -0,0 +1,65 @@
+import { actions, kea, key, listeners, path, props, reducers } from 'kea'
+
+import type { sessionPlaybackLogicType } from './sessionPlaybackLogicType'
+
+export const PLAYBACK_SPEEDS = [0.5, 1, 1.5, 2, 3, 4, 8, 16]
+const TICK_MS = 50
+
+export interface SessionPlaybackLogicProps {
+ sessionId: string
+}
+
+export const sessionPlaybackLogic = kea<sessionPlaybackLogicType>([
+ path(['products', 'ai_observability', 'frontend', 'sessionPlaybackLogic']),
+ props({} as SessionPlaybackLogicProps),
+ key((props) => props.sessionId),
+
+ actions({
+ play: true,
+ pause: true,
+ togglePlay: true,
+ seek: (ms: number) => ({ ms }),
+ setSpeed: (speed: number) => ({ speed }),
+ setTimeline: (durationMs: number) => ({ durationMs }),
+ tick: (deltaMs: number) => ({ deltaMs }),
+ setCurrentMs: (ms: number) => ({ ms }),
+ }),
+
+ reducers({
+ playing: [false, { play: () => true, pause: () => false, seek: () => false }],
+ speed: [1, { setSpeed: (_, { speed }) => speed }],
+ durationMs: [0, { setTimeline: (_, { durationMs }) => durationMs }],
+ currentMs: [
+ 0,
+ {
+ seek: (_, { ms }) => Math.max(ms, 0),
+ setCurrentMs: (_, { ms }) => Math.max(ms, 0),
+ // A late trace load can change total duration without changing the turn
+ // count; keep the current position (clamped) instead of rewinding to 0.
+ setTimeline: (state, { durationMs }) => Math.min(state, durationMs),
+ },
+ ],
+ }),
+
+ listeners(({ actions, values, cache }) => ({
+ togglePlay: () => (values.playing ? actions.pause() : actions.play()),
+ seek: () => cache.disposables.dispose('playback-tick'),
+ tick: ({ deltaMs }) => {
+ const next = Math.min(values.currentMs + deltaMs * values.speed, values.durationMs)
+ actions.setCurrentMs(next)
+ if (next >= values.durationMs) {
+ actions.pause()
+ }
+ },
+ play: () => {
+ if (values.currentMs >= values.durationMs) {
+ actions.setCurrentMs(0)
+ }
+ cache.disposables.add(() => {
+ const id = setInterval(() => actions.tick(TICK_MS), TICK_MS)
+ return () => clearInterval(id)
+ }, 'playback-tick')
+ },
+ pause: () => cache.disposables.dispose('playback-tick'),
+ })),
+])
diff --git a/products/ai_observability/frontend/tabs/aiObservabilitySessionsViewLogic.ts b/products/ai_observability/frontend/tabs/aiObservabilitySessionsViewLogic.ts
index b23ef79f8c28..73c53896f6b5 100644
--- a/products/ai_observability/frontend/tabs/aiObservabilitySessionsViewLogic.ts
+++ b/products/ai_observability/frontend/tabs/aiObservabilitySessionsViewLogic.ts
@@ -1,292 +1,205 @@
import { actions, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
+import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'
+import { subscriptions } from 'kea-subscriptions'
import api from 'lib/api'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { urls } from 'scenes/urls'
import { groupsModel } from '~/models/groupsModel'
-import { DataTableNode, LLMTrace, NodeKind, TraceQuery, TracesQuery } from '~/queries/schema/schema-general'
-import { PropertyFilterType, PropertyOperator } from '~/types'
+import { DataTableNode, HogQLQuery, NodeKind, RefreshType } from '~/queries/schema/schema-general'
import sessionsQueryTemplate from '../../backend/queries/sessions.sql?raw'
-import { SortDirection, SortState, aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'
+import type { SortDirection, SortState } from '../aiObservabilitySharedLogic'
+import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'
+import { llmSessionTitleLazyLoaderLogic } from '../llmSessionTitleLazyLoaderLogic'
import type { aiObservabilitySessionsViewLogicType } from './aiObservabilitySessionsViewLogicType'
export type AIObservabilitySessionsViewLogicProps = Record<string, never>
+const SESSIONS_PAGE_SIZE = 50
+
+export interface SessionListRow {
+ sessionId: string
+ distinctId: string
+ traces: number
+ totalCost: number
+ totalLatency: number
+ errors: number
+ lastSeen: string
+}
+
+function buildSessionsQuery(sessionsSort: SortState, offset: number): string {
+ return sessionsQueryTemplate
+ .replace('__ORDER_BY__', sessionsSort.column)
+ .replace('__ORDER_DIRECTION__', sessionsSort.direction)
+ .replace('__LIMIT__', String(SESSIONS_PAGE_SIZE))
+ .replace('__OFFSET__', String(offset))
+}
+
+function parseSessionsResponse(response: { columns?: unknown[]; results?: unknown[] }): SessionListRow[] {
+ const columns = (response.columns ?? []) as string[]
+ const at = (name: string): number => columns.indexOf(name)
+ const rows = (response.results ?? []) as unknown[][]
+ return rows.map((row) => ({
+ sessionId: String(row[at('session_id')] ?? ''),
+ distinctId: String(row[at('distinct_id')] ?? ''),
+ traces: Number(row[at('traces')] ?? 0),
+ totalCost: Number(row[at('total_cost')] ?? 0),
+ totalLatency: Number(row[at('total_latency')] ?? 0),
+ errors: Number(row[at('errors')] ?? 0),
+ lastSeen: String(row[at('last_seen')] ?? ''),
+ }))
+}
+
export const aiObservabilitySessionsViewLogic = kea<aiObservabilitySessionsViewLogicType>([
path(['products', 'ai_observability', 'frontend', 'tabs', 'aiObservabilitySessionsViewLogic']),
props({} as AIObservabilitySessionsViewLogicProps),
connect(() => ({
values: [
aiObservabilitySharedLogic,
- ['dateFilter', 'shouldFilterTestAccounts', 'propertyFilters'],
+ ['activeTab', 'dateFilter', 'shouldFilterTestAccounts', 'propertyFilters'],
groupsModel,
['groupsTaxonomicTypes'],
+ llmSessionTitleLazyLoaderLogic,
+ ['getSessionTitle'],
],
- actions: [
- aiObservabilitySharedLogic,
- ['setDates', 'setPropertyFilters', 'setShouldFilterTestAccounts', 'applyUrlState'],
- ],
+ actions: [llmSessionTitleLazyLoaderLogic, ['ensureSessionTitleLoaded']],
})),
actions({
setSessionsSort: (column: string, direction: SortDirection) => ({ column, direction }),
- toggleSessionExpanded: (sessionId: string) => ({ sessionId }),
- toggleTraceExpanded: (traceId: string) => ({ traceId }),
- toggleGenerationExpanded: (uuid: string, traceId: string) => ({ uuid, traceId }),
- loadSessionTraces: (sessionId: string) => ({ sessionId }),
- loadSessionTracesSuccess: (sessionId: string, traces: LLMTrace[]) => ({ sessionId, traces }),
- loadSessionTracesFailure: (sessionId: string, error: Error) => ({ sessionId, error }),
- loadFullTrace: (traceId: string) => ({ traceId }),
- loadFullTraceSuccess: (traceId: string, trace: LLMTrace) => ({ traceId, trace }),
- loadFullTraceFailure: (traceId: string, error: Error) => ({ traceId, error }),
+ selectSession: (sessionId: string | null) => ({ sessionId }),
+ loadSessions: (payload?: { refresh?: RefreshType }) => ({ refresh: payload?.refresh }),
+ loadSessionsSuccess: (sessions: SessionListRow[], hasMoreSessions: boolean) => ({ sessions, hasMoreSessions }),
+ loadSessionsFailure: true,
+ loadMoreSessions: true,
+ loadMoreSessionsSuccess: (sessions: SessionListRow[], hasMoreSessions: boolean) => ({
+ sessions,
+ hasMoreSessions,
+ }),
+ loadMoreSessionsFailure: true,
}),
reducers({
- sessionsSort: [
- { column: 'last_seen', direction: 'DESC' } as SortState,
- {
- setSessionsSort: (_, { column, direction }): SortState => ({ column, direction }),
- },
- ],
-
- expandedSessionIds: [
- new Set<string>() as Set<string>,
- {
- toggleSessionExpanded: (state, { sessionId }) => {
- const newSet = new Set(state)
-
- if (newSet.has(sessionId)) {
- newSet.delete(sessionId)
- } else {
- newSet.add(sessionId)
- }
-
- return newSet
- },
- setDates: () => new Set<string>(),
- setPropertyFilters: () => new Set<string>(),
- setShouldFilterTestAccounts: () => new Set<string>(),
- applyUrlState: () => new Set<string>(),
- },
- ],
-
- expandedTraceIds: [
- new Set<string>() as Set<string>,
- {
- toggleTraceExpanded: (state, { traceId }) => {
- const newSet = new Set(state)
-
- if (newSet.has(traceId)) {
- newSet.delete(traceId)
- } else {
- newSet.add(traceId)
- }
-
- return newSet
- },
- setDates: () => new Set<string>(),
- setPropertyFilters: () => new Set<string>(),
- setShouldFilterTestAccounts: () => new Set<string>(),
- applyUrlState: () => new Set<string>(),
- },
- ],
-
- expandedGenerationIds: [
- new Set<string>() as Set<string>,
+ sessions: [
+ [] as SessionListRow[],
{
- toggleGenerationExpanded: (state, { uuid }) => {
- const newSet = new Set(state)
-
- if (newSet.has(uuid)) {
- newSet.delete(uuid)
- } else {
- newSet.add(uuid)
- }
-
- return newSet
- },
- setDates: () => new Set<string>(),
- setPropertyFilters: () => new Set<string>(),
- setShouldFilterTestAccounts: () => new Set<string>(),
- applyUrlState: () => new Set<string>(),
+ loadSessionsSuccess: (_, { sessions }) => sessions,
+ loadMoreSessionsSuccess: (state, { sessions }) => [...state, ...sessions],
},
],
-
- sessionTraces: [
- {} as Record<string, LLMTrace[]>,
+ sessionsLoading: [
+ false,
{
- loadSessionTracesSuccess: (state, { sessionId, traces }) => ({
- ...state,
- [sessionId]: traces,
- }),
- setDates: () => ({}),
- setPropertyFilters: () => ({}),
- setShouldFilterTestAccounts: () => ({}),
- applyUrlState: () => ({}),
+ loadSessions: () => true,
+ loadSessionsSuccess: () => false,
+ loadSessionsFailure: () => false,
},
],
-
- fullTraces: [
- {} as Record<string, LLMTrace>,
+ moreSessionsLoading: [
+ false,
{
- loadFullTraceSuccess: (state, { traceId, trace }) => ({
- ...state,
- [traceId]: trace,
- }),
- setDates: () => ({}),
- setPropertyFilters: () => ({}),
- setShouldFilterTestAccounts: () => ({}),
- applyUrlState: () => ({}),
+ loadSessions: () => false,
+ loadMoreSessions: () => true,
+ loadMoreSessionsSuccess: () => false,
+ loadMoreSessionsFailure: () => false,
},
],
-
- loadingSessionTraces: [
- new Set<string>() as Set<string>,
+ hasMoreSessions: [
+ false,
{
- loadSessionTraces: (state, { sessionId }) => new Set(state).add(sessionId),
- loadSessionTracesSuccess: (state, { sessionId }) => {
- const newSet = new Set(state)
- newSet.delete(sessionId)
- return newSet
- },
- loadSessionTracesFailure: (state, { sessionId }) => {
- const newSet = new Set(state)
- newSet.delete(sessionId)
- return newSet
- },
+ loadSessionsSuccess: (_, { hasMoreSessions }) => hasMoreSessions,
+ loadMoreSessionsSuccess: (_, { hasMoreSessions }) => hasMoreSessions,
+ loadSessionsFailure: () => false,
},
],
-
- loadingFullTraces: [
- new Set<string>() as Set<string>,
+ selectedSessionId: [
+ null as string | null,
{
- loadFullTrace: (state, { traceId }) => new Set(state).add(traceId),
- loadFullTraceSuccess: (state, { traceId }) => {
- const newSet = new Set(state)
- newSet.delete(traceId)
- return newSet
- },
- loadFullTraceFailure: (state, { traceId }) => {
- const newSet = new Set(state)
- newSet.delete(traceId)
- return newSet
- },
+ selectSession: (_, { sessionId }) => sessionId,
},
],
-
- sessionTracesErrors: [
- new Set<string>() as Set<string>,
- {
- loadSessionTracesFailure: (state, { sessionId }) => new Set(state).add(sessionId),
- loadSessionTracesSuccess: (state, { sessionId }) => {
- const newSet = new Set(state)
- newSet.delete(sessionId)
- return newSet
- },
- setDates: () => new Set<string>(),
- setPropertyFilters: () => new Set<string>(),
- setShouldFilterTestAccounts: () => new Set<string>(),
- applyUrlState: () => new Set<string>(),
- },
- ],
-
- fullTracesErrors: [
- new Set<string>() as Set<string>,
+ sessionsSort: [
+ { column: 'last_seen', direction: 'DESC' } as SortState,
{
- loadFullTraceFailure: (state, { traceId }) => new Set(state).add(traceId),
- loadFullTraceSuccess: (state, { traceId }) => {
- const newSet = new Set(state)
- newSet.delete(traceId)
- return newSet
- },
- setDates: () => new Set<string>(),
- setPropertyFilters: () => new Set<string>(),
- setShouldFilterTestAccounts: () => new Set<string>(),
- applyUrlState: () => new Set<string>(),
+ setSessionsSort: (_, { column, direction }): SortState => ({ column, direction }),
},
],
}),
- listeners(({ actions, values }) => ({
- toggleSessionExpanded: async ({ sessionId }) => {
- if (
- values.expandedSessionIds.has(sessionId) &&
- !values.sessionTraces[sessionId] &&
- !values.loadingSessionTraces.has(sessionId)
- ) {
- actions.loadSessionTraces(sessionId)
- }
- },
-
- loadSessionTraces: async ({ sessionId }) => {
- const dateFrom = values.dateFilter.dateFrom || undefined
- const dateTo = values.dateFilter.dateTo || undefined
+ listeners(({ actions, values }) => {
+ let loadSessionsRequestId = 0
+ let loadMoreSessionsRequestId = 0
- const tracesQuerySource: TracesQuery = {
- kind: NodeKind.TracesQuery,
- dateRange: {
- date_from: dateFrom,
- date_to: dateTo,
- },
- properties: [
- {
- type: PropertyFilterType.Event,
- key: '$ai_session_id',
- operator: PropertyOperator.Exact,
- value: sessionId,
- },
- ],
+ const preloadSessionTitles = (sessions: SessionListRow[]): void => {
+ for (const session of sessions) {
+ actions.ensureSessionTitleLoaded(session.sessionId, values.dateFilter)
}
-
- try {
- const response = await api.query(tracesQuerySource)
-
- if (response.results) {
- actions.loadSessionTracesSuccess(sessionId, response.results)
+ }
+
+ return {
+ loadSessions: async ({ refresh }) => {
+ const requestId = ++loadSessionsRequestId
+ // A first-page reload supersedes any pagination request already in flight.
+ loadMoreSessionsRequestId++
+ const source = values.sessionsQuery.source as HogQLQuery
+ try {
+ // Default loads use cache (fast, PostHog convention); the Refresh button forces a recompute
+ const response = await api.query(source, { refresh })
+ if (requestId !== loadSessionsRequestId) {
+ return
+ }
+ if (values.sessionsQuery.source !== source) {
+ actions.loadSessionsFailure()
+ return
+ }
+ const sessions = parseSessionsResponse(response)
+ actions.loadSessionsSuccess(sessions, sessions.length === SESSIONS_PAGE_SIZE)
+ } catch {
+ if (requestId === loadSessionsRequestId) {
+ actions.loadSessionsFailure()
+ }
}
- } catch (error) {
- console.error('Error loading traces for session:', error)
- actions.loadSessionTracesFailure(sessionId, error as Error)
- }
- },
-
- toggleTraceExpanded: async ({ traceId }) => {
- if (
- values.expandedTraceIds.has(traceId) &&
- !values.fullTraces[traceId] &&
- !values.loadingFullTraces.has(traceId)
- ) {
- actions.loadFullTrace(traceId)
- }
- },
-
- loadFullTrace: async ({ traceId }) => {
- const dateFrom = values.dateFilter.dateFrom || undefined
- const dateTo = values.dateFilter.dateTo || undefined
-
- const traceQuery: TraceQuery = {
- kind: NodeKind.TraceQuery,
- traceId,
- includeSentiment: true,
- dateRange: {
- date_from: dateFrom,
- date_to: dateTo,
- },
- }
-
- try {
- const response = await api.query(traceQuery)
-
- if (response.results && response.results[0]) {
- actions.loadFullTraceSuccess(traceId, response.results[0])
+ },
+ loadMoreSessions: async () => {
+ if (!values.hasMoreSessions) {
+ actions.loadMoreSessionsFailure()
+ return
}
- } catch (error) {
- console.error('Error loading full trace:', error)
- actions.loadFullTraceFailure(traceId, error as Error)
- }
- },
- })),
+ const requestId = ++loadMoreSessionsRequestId
+ const source = values.sessionsQuery.source as HogQLQuery
+ const offset = values.sessions.length
+ try {
+ const response = await api.query({
+ ...source,
+ query: buildSessionsQuery(values.sessionsSort, offset),
+ })
+ if (requestId !== loadMoreSessionsRequestId) {
+ return
+ }
+ if (values.sessionsQuery.source !== source || values.sessions.length !== offset) {
+ actions.loadMoreSessionsFailure()
+ return
+ }
+ const sessions = parseSessionsResponse(response)
+ actions.loadMoreSessionsSuccess(sessions, sessions.length === SESSIONS_PAGE_SIZE)
+ } catch {
+ if (requestId === loadMoreSessionsRequestId) {
+ actions.loadMoreSessionsFailure()
+ }
+ }
+ },
+ // Pre-load titles for the whole list (batched + deduped), so each row shows
+ // its name and re-selecting a listed session never re-queries its title.
+ loadSessionsSuccess: ({ sessions }) => {
+ preloadSessionTitles(sessions)
+ },
+ loadMoreSessionsSuccess: ({ sessions }) => {
+ preloadSessionTitles(sessions)
+ },
+ }
+ }),
selectors({
sessionsQuery: [
@@ -304,15 +217,11 @@ export const aiObservabilitySessionsViewLogic = kea<aiObservabilitySessionsViewL
sessionsSort: { column: string; direction: 'ASC' | 'DESC' },
groupsTaxonomicTypes: TaxonomicFilterGroupType[]
): DataTableNode => {
- const query = sessionsQueryTemplate
- .replace('__ORDER_BY__', sessionsSort.column)
- .replace('__ORDER_DIRECTION__', sessionsSort.direction)
-
return {
kind: NodeKind.DataTableNode,
source: {
kind: NodeKind.HogQLQuery,
- query,
+ query: buildSessionsQuery(sessionsSort, 0),
filters: {
dateRange: {
date_from: dateFilter.dateFrom || null,
@@ -338,7 +247,6 @@ export const aiObservabilitySessionsViewLogic = kea<aiObservabilitySessionsViewL
],
showDateRange: true,
showReload: true,
- showSearch: true,
showPropertyFilter: [
TaxonomicFilterGroupType.EventProperties,
TaxonomicFilterGroupType.PersonProperties,
@@ -347,11 +255,40 @@ export const aiObservabilitySessionsViewLogic = kea<aiObservabilitySessionsViewL
TaxonomicFilterGroupType.HogQLExpression,
],
showTestAccountFilters: true,
- showExport: true,
showColumnConfigurator: true,
- allowSorting: true,
}
},
],
}),
+
+ subscriptions(({ actions, values }) => ({
+ sessionsQuery: (_sessionsQuery, previousSessionsQuery: DataTableNode | undefined) => {
+ if (previousSessionsQuery === undefined || values.activeTab !== 'sessions') {
+ return
+ }
+ actions.loadSessions()
+ },
+ })),
+
+ urlToAction(({ actions, values }) => ({
+ '/ai-observability/sessions/:id': ({ id }) => {
+ if (id && id !== values.selectedSessionId) {
+ actions.selectSession(id)
+ }
+ },
+ '/ai-observability/sessions': () => {
+ if (values.selectedSessionId) {
+ actions.selectSession(null)
+ }
+ },
+ })),
+
+ actionToUrl(() => ({
+ selectSession: ({ sessionId }) => {
+ const search = router.values.searchParams
+ return sessionId
+ ? combineUrl(urls.aiObservabilitySession(sessionId), search).url
+ : combineUrl(urls.aiObservabilitySessions(), search).url
+ },
+ })),
])
diff --git a/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts b/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts
index bd1076a7d046..3234d1bd3a6b 100644
--- a/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts
+++ b/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts
@@ -131,6 +131,7 @@ 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 6c83e25f65d9..fa056098cbbb 100644
--- a/products/ai_observability/frontend/utils.test.ts
+++ b/products/ai_observability/frontend/utils.test.ts
@@ -12,6 +12,7 @@ import {
getInternalTagName,
getSessionID,
getSessionStartTimestamp,
+ getTraceStepCount,
hasCostBreakdown,
hasStringContentField,
isEmptyJSONStructure,
@@ -2610,6 +2611,29 @@ 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 c21b442c2ea0..f1fff067ce6a 100644
--- a/products/ai_observability/frontend/utils.ts
+++ b/products/ai_observability/frontend/utils.ts
@@ -248,6 +248,12 @@ 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'
diff --git a/products/ai_observability/manifest.tsx b/products/ai_observability/manifest.tsx
index 5964171a4a99..107f963fbc9d 100644
--- a/products/ai_observability/manifest.tsx
+++ b/products/ai_observability/manifest.tsx
@@ -144,7 +144,7 @@ export const manifest: ProductManifest = {
'/ai-observability/tools': ['AIObservability', 'aiObservabilityTools'],
'/ai-observability/sentiment': ['AIObservability', 'aiObservabilitySentiment'],
'/ai-observability/sessions': ['AIObservability', 'aiObservabilitySessions'],
- '/ai-observability/sessions/:id': ['AIObservabilitySession', 'aiObservability'],
+ '/ai-observability/sessions/:id': ['AIObservability', 'aiObservabilitySessions'],
'/ai-observability/playground': ['AIObservabilityPlayground', 'aiObservabilityPlayground'],
'/ai-observability/clusters': ['AIObservabilityClusters', 'aiObservabilityClusters'],
'/ai-observability/clusters/:runId': ['AIObservabilityClusters', 'aiObservabilityClusters'],