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): Extract title to show on sessions page (#60667)

Marcel Poelker5b5b1275e2ec
diff --git a/products/ai_observability/frontend/AIObservabilitySessionScene.tsx b/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
index cb09b54990a6..0eb73bf3c11b 100644
--- a/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
@@ -31,6 +31,7 @@ import { TranscriptBubbleStream } from './ConversationDisplay/TranscriptBubbleSt
import { SessionTurn } from './extractSessionTurns'
import { llmSentimentLazyLoaderLogic } from './llmSentimentLazyLoaderLogic'
import { SENTIMENT_DATE_WINDOW_DAYS } from './sentimentUtils'
+import { resolveSessionTitle } from './sessionTitle'
import { formatLLMCost, getTraceTimestamp, sanitizeTraceUrlSearchParams } from './utils'
const LLMASessionFeedbackDisplay = lazy(() =>
@@ -93,8 +94,17 @@ function SessionSceneWrapper(): JSX.Element {
const showFeedback = !!featureFlags[FEATURE_FLAGS.POSTHOG_AI_CONVERSATION_FEEDBACK_LLMA_SESSIONS]
const showSentiment = !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_SENTIMENT]
- const { traces, responseLoading, responseError, sessionTurns, hasMoreData, nextDataLoading, summariesLoading } =
- useValues(aiObservabilitySessionDataLogic)
+ const {
+ traces,
+ responseLoading,
+ responseError,
+ sessionTurns,
+ hasMoreData,
+ nextDataLoading,
+ summariesLoading,
+ fullTraces,
+ traceSummaries,
+ } = useValues(aiObservabilitySessionDataLogic)
const { sessionId } = useValues(aiObservabilitySessionLogic)
const { summarizeAllTraces, loadNextData } = useActions(aiObservabilitySessionDataLogic)
const { dataProcessingAccepted } = useValues(maxGlobalLogic)
@@ -117,6 +127,14 @@ function SessionSceneWrapper(): JSX.Element {
{ totalCost: 0, totalLatency: 0, traceCount: 0 }
)
+ const firstTrace = traces[0]
+ const firstFullTrace = firstTrace ? fullTraces[firstTrace.id] : undefined
+ const cachedSummaryTitle = firstTrace ? traceSummaries[firstTrace.id]?.title : undefined
+ // Prefer the cached LLM summary when present; otherwise derive a title from
+ // the first trace (full event tree when loaded, else the lite trace for
+ // traceName fallback while loading).
+ const heroTitle = cachedSummaryTitle || resolveSessionTitle(firstFullTrace ?? firstTrace)
+
if (responseLoading) {
return <SpinnerOverlay />
}
@@ -131,6 +149,7 @@ function SessionSceneWrapper(): JSX.Element {
<div className="relative flex flex-col gap-4">
<SceneBreadcrumbBackButton />
<AIObservabilityRenameBanner />
+ {heroTitle && <h1 className="text-2xl font-semibold leading-tight m-0 break-words">{heroTitle}</h1>}
<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">
diff --git a/products/ai_observability/frontend/sessionTitle.test.ts b/products/ai_observability/frontend/sessionTitle.test.ts
new file mode 100644
index 000000000000..309510b7654a
--- /dev/null
+++ b/products/ai_observability/frontend/sessionTitle.test.ts
@@ -0,0 +1,208 @@
+import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
+
+import { resolveSessionTitle } from './sessionTitle'
+
+function makeEvent(
+ id: string,
+ event: string,
+ createdAt: string,
+ properties: Record<string, unknown> = {}
+): LLMTraceEvent {
+ return { id, event, createdAt, properties }
+}
+
+function makeTrace(events: LLMTraceEvent[], overrides: Partial<LLMTrace> = {}): LLMTrace {
+ return {
+ id: 't1',
+ createdAt: events[0]?.createdAt ?? '2026-05-29T00:00:00.000Z',
+ distinctId: 'user-1',
+ events,
+ ...overrides,
+ }
+}
+
+describe('resolveSessionTitle', () => {
+ it('returns null when the trace is undefined', () => {
+ expect(resolveSessionTitle(undefined)).toBeNull()
+ })
+
+ it('returns null when no signal is available', () => {
+ const trace = makeTrace([], { traceName: 'LangGraph' })
+ expect(resolveSessionTitle(trace)).toBeNull()
+ })
+
+ it('prefers the first user-role message in trace.inputState.messages', () => {
+ const trace = makeTrace([], {
+ traceName: 'LangGraph',
+ inputState: {
+ messages: [
+ { role: 'system', content: 'system prompt' },
+ { role: 'user', content: 'how do I add a feature flag?' },
+ { role: 'assistant', content: 'reply' },
+ ],
+ },
+ })
+ expect(resolveSessionTitle(trace)).toBe('how do I add a feature flag?')
+ })
+
+ it('treats LangChain type:"human" messages as user messages', () => {
+ const trace = makeTrace([], {
+ traceName: 'LangGraph',
+ inputState: {
+ messages: [
+ { type: 'system', content: 'system prompt' },
+ { type: 'human', content: 'Hello, I need an export of subscribed users.' },
+ ],
+ },
+ })
+ expect(resolveSessionTitle(trace)).toBe('Hello, I need an export of subscribed users.')
+ })
+
+ it('falls back to first event $ai_input_state.messages when trace.inputState is null', () => {
+ const trace = makeTrace(
+ [
+ makeEvent('e1', '$ai_span', '2026-05-29T00:00:00.000Z', {
+ $ai_input_state: {
+ messages: [{ role: 'user', content: 'first user message via span' }],
+ },
+ }),
+ ],
+ { traceName: 'LangGraph', inputState: null }
+ )
+ expect(resolveSessionTitle(trace)).toBe('first user message via span')
+ })
+
+ it('falls back to first generation $ai_input when no input_state is present', () => {
+ const trace = makeTrace(
+ [
+ makeEvent('s1', '$ai_span', '2026-05-29T00:00:00.000Z', {}),
+ makeEvent('g1', '$ai_generation', '2026-05-29T00:00:01.000Z', {
+ $ai_input: [
+ { role: 'system', content: 'sys' },
+ { role: 'user', content: 'message from $ai_input' },
+ ],
+ }),
+ ],
+ { traceName: 'LangGraph' }
+ )
+ expect(resolveSessionTitle(trace)).toBe('message from $ai_input')
+ })
+
+ it('uses $mcp_intent when no chat messages are present', () => {
+ const trace = makeTrace(
+ [
+ makeEvent('s1', '$ai_span', '2026-05-29T00:00:00.000Z', {
+ $mcp_intent: 'Switching PostHog context to Staging project before creating the experiment.',
+ }),
+ ],
+ { traceName: 'switch-project' }
+ )
+ expect(resolveSessionTitle(trace)).toBe(
+ 'Switching PostHog context to Staging project before creating the experiment.'
+ )
+ })
+
+ it('falls back to traceName when it is not a generic framework name', () => {
+ const trace = makeTrace([makeEvent('s1', '$ai_span', '2026-05-29T00:00:00.000Z', {})], {
+ traceName: 'switch-project',
+ })
+ expect(resolveSessionTitle(trace)).toBe('switch-project')
+ })
+
+ it.each([['LangGraph'], ['RunnableSequence'], ['ChatPromptTemplate'], ['langgraph']])(
+ 'rejects generic traceName %p as a title (returns null when no other signal)',
+ (name) => {
+ const trace = makeTrace([], { traceName: name })
+ expect(resolveSessionTitle(trace)).toBeNull()
+ }
+ )
+
+ it('picks the first event by timestamp, not array order', () => {
+ const trace = makeTrace(
+ [
+ makeEvent('later', '$ai_span', '2026-05-29T00:00:05.000Z', {
+ $ai_input_state: { messages: [{ role: 'user', content: 'later span' }] },
+ }),
+ makeEvent('earlier', '$ai_span', '2026-05-29T00:00:00.000Z', {
+ $ai_input_state: { messages: [{ role: 'user', content: 'earlier span' }] },
+ }),
+ ],
+ { traceName: 'LangGraph' }
+ )
+ expect(resolveSessionTitle(trace)).toBe('earlier span')
+ })
+
+ it.each([
+ {
+ desc: 'collapses whitespace',
+ messages: [{ role: 'user', content: 'multi\nline\n\nmessage with spaces' }],
+ expected: 'multi line message with spaces',
+ },
+ {
+ desc: 'does not truncate short titles',
+ messages: [{ role: 'user', content: 'short message' }],
+ expected: 'short message',
+ },
+ {
+ desc: 'extracts text from array-shaped content (Anthropic typed parts)',
+ messages: [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Look at this image' },
+ { type: 'image', url: 'https://example.com/a.png' },
+ ],
+ },
+ ],
+ expected: 'Look at this image',
+ },
+ {
+ desc: 'skips messages with empty content and uses the next user message',
+ messages: [
+ { role: 'user', content: '' },
+ { role: 'user', content: 'actual question' },
+ ],
+ expected: 'actual question',
+ },
+ ])('extracts title content: $desc', ({ messages, expected }) => {
+ const trace = makeTrace([], { inputState: { messages } })
+ expect(resolveSessionTitle(trace)).toBe(expected)
+ })
+
+ it.each([
+ {
+ desc: 'truncates long titles at a word boundary with an ellipsis',
+ content:
+ "We've just released SpicyCam - I want to know what the initial user engagement and intent is like - are the users enjoying the new feature?",
+ maxLength: undefined,
+ maxOut: 121, // 120 + ellipsis
+ // Word-boundary backoff: should not include the mid-word fragment "enjoyi".
+ notContain: 'enjoyi…',
+ },
+ {
+ desc: 'accepts a custom maxLength',
+ content: 'this is a moderately long sentence that should be cut',
+ maxLength: 20,
+ maxOut: 21,
+ },
+ ])('$desc', ({ content, maxLength, maxOut, notContain }) => {
+ const trace = makeTrace([], { inputState: { messages: [{ role: 'user', content }] } })
+ const result = maxLength === undefined ? resolveSessionTitle(trace) : resolveSessionTitle(trace, maxLength)
+ expect(result).toBeTruthy()
+ expect(result!.length).toBeLessThanOrEqual(maxOut)
+ expect(result!.endsWith('…')).toBe(true)
+ if (notContain) {
+ expect(result).not.toContain(notContain)
+ }
+ })
+
+ it.each([
+ { desc: 'a bare-string $ai_input', input: 'how do I add a feature flag?' },
+ { desc: 'a role-less message object in $ai_input', input: [{ content: 'how do I add a feature flag?' }] },
+ ])('treats role-less generation input as the user prompt: $desc', ({ input }) => {
+ const trace = makeTrace([makeEvent('g1', '$ai_generation', '2026-05-29T00:00:00.000Z', { $ai_input: input })], {
+ traceName: 'LangGraph',
+ })
+ expect(resolveSessionTitle(trace)).toBe('how do I add a feature flag?')
+ })
+})
diff --git a/products/ai_observability/frontend/sessionTitle.ts b/products/ai_observability/frontend/sessionTitle.ts
new file mode 100644
index 000000000000..7dbb2e1f1abc
--- /dev/null
+++ b/products/ai_observability/frontend/sessionTitle.ts
@@ -0,0 +1,127 @@
+import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
+
+import { CompatMessage } from './types'
+import { extractTextContent, hasStringContentField, normalizeMessages, readAiInput } from './utils'
+
+const GENERIC_TRACE_NAMES = new Set(['langgraph', 'runnablesequence', 'chatprompttemplate'])
+
+const DEFAULT_MAX_LENGTH = 120
+const WORD_BOUNDARY_LOOKBACK = 20
+
+/**
+ * Resolve a human-readable title for a session, given its first trace.
+ *
+ * Priority:
+ * 1. First user-role message in `trace.inputState.messages`.
+ * 2. First user-role message in the first event's `$ai_input_state.messages`.
+ * 3. First user-role message in the first generation's `$ai_input`.
+ * 4. `$mcp_intent` from the first event's properties.
+ * 5. `trace.traceName` when it's not a generic framework root span name.
+ *
+ * Returns `null` if no signal is available, so that caller decides on fallback
+ */
+export function resolveSessionTitle(trace: LLMTrace | undefined, maxLength = DEFAULT_MAX_LENGTH): string | null {
+ if (!trace) {
+ return null
+ }
+
+ const sortedEvents = sortByCreatedAt(trace.events)
+ const firstEvent = sortedEvents[0]
+
+ const fromInputState = firstUserText(trace.inputState)
+ if (fromInputState) {
+ return truncate(fromInputState, maxLength)
+ }
+
+ if (firstEvent) {
+ const fromSpanInputState = firstUserText(firstEvent.properties.$ai_input_state)
+ if (fromSpanInputState) {
+ return truncate(fromSpanInputState, maxLength)
+ }
+ }
+
+ const firstGeneration = sortedEvents.find((e) => e.event === '$ai_generation')
+ if (firstGeneration) {
+ const fromGenInput = firstUserText(readAiInput(firstGeneration.properties))
+ if (fromGenInput) {
+ return truncate(fromGenInput, maxLength)
+ }
+ }
+
+ if (firstEvent) {
+ const mcpIntent = firstEvent.properties.$mcp_intent
+ if (typeof mcpIntent === 'string' && mcpIntent.trim().length > 0) {
+ return truncate(mcpIntent, maxLength)
+ }
+ }
+
+ if (typeof trace.traceName === 'string' && trace.traceName.length > 0) {
+ if (!GENERIC_TRACE_NAMES.has(trace.traceName.toLowerCase())) {
+ return truncate(trace.traceName, maxLength)
+ }
+ }
+
+ return null
+}
+
+function sortByCreatedAt(events: LLMTraceEvent[] | undefined): LLMTraceEvent[] {
+ if (!events?.length) {
+ return []
+ }
+ return [...events].sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())
+}
+
+/**
+ * Extract the first user-role message's text from any payload shape
+ * `normalizeMessages` understands — including `{messages: [...]}` wrappers used
+ * by LangGraph/Claude Agent SDK input_state. Role mapping (`human` → `user`,
+ * `type` → `role`, etc.) is delegated entirely to `normalizeMessages`.
+ *
+ * We default to role `user` following the convention in the codebase
+ * (e.g. pickFirstInputMessage and sentiment/extraction.py)
+ */
+function firstUserText(inputPayload: unknown): string | null {
+ const messages = Array.isArray(inputPayload)
+ ? inputPayload
+ : inputPayload &&
+ typeof inputPayload === 'object' &&
+ Array.isArray((inputPayload as { messages?: unknown }).messages)
+ ? (inputPayload as { messages: unknown[] }).messages
+ : inputPayload
+ const normalized = normalizeMessages(messages, 'user')
+ for (const message of normalized) {
+ if (message.role !== 'user') {
+ continue
+ }
+ const text = messageContentToText(message.content)
+ if (text) {
+ return text
+ }
+ }
+ return null
+}
+
+function messageContentToText(content: CompatMessage['content']): string | null {
+ let raw: string | undefined
+ if (typeof content === 'string') {
+ raw = content
+ } else if (Array.isArray(content)) {
+ raw = content.map(extractTextContent).filter(Boolean).join(' ')
+ } else if (hasStringContentField(content)) {
+ raw = content.content
+ }
+ const collapsed = raw?.replace(/\s+/g, ' ').trim()
+ return collapsed ? collapsed : null
+}
+
+function truncate(value: string, maxLength: number): string {
+ if (value.length <= maxLength) {
+ return value
+ }
+ // Back off to the previous space within the last WORD_BOUNDARY_LOOKBACK chars
+ // so we don't cut mid-word; if no space is found, hard-cut.
+ const hardCut = value.slice(0, maxLength)
+ const lastSpace = hardCut.lastIndexOf(' ')
+ const cutAt = lastSpace > maxLength - WORD_BOUNDARY_LOOKBACK ? lastSpace : maxLength
+ return `${value.slice(0, cutAt).trimEnd()}…`
+}