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): Conversation title on session table (including title logic fixes) (#61342)

Marcel Poelker7740201cb6ae
diff --git a/frontend/src/lib/utils/arrays.test.ts b/frontend/src/lib/utils/arrays.test.ts
index ea160d536136..5b774b525560 100644
--- a/frontend/src/lib/utils/arrays.test.ts
+++ b/frontend/src/lib/utils/arrays.test.ts
@@ -1,4 +1,4 @@
-import { range } from 'lib/utils/arrays'
+import { chunk, range } from 'lib/utils/arrays'
describe('arrays utils', () => {
describe('range', () => {
@@ -10,4 +10,25 @@ describe('arrays utils', () => {
expect(range(1, 5)).toEqual([1, 2, 3, 4])
})
})
+
+ describe('chunk', () => {
+ it('splits into evenly-sized chunks', () => {
+ expect(chunk([1, 2, 3, 4], 2)).toEqual([
+ [1, 2],
+ [3, 4],
+ ])
+ })
+
+ it('leaves a smaller final chunk when not evenly divisible', () => {
+ expect(chunk([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]])
+ })
+
+ it('returns one chunk when size exceeds length', () => {
+ expect(chunk([1, 2], 10)).toEqual([[1, 2]])
+ })
+
+ it('returns an empty array for an empty input', () => {
+ expect(chunk([], 3)).toEqual([])
+ })
+ })
})
diff --git a/frontend/src/lib/utils/arrays.ts b/frontend/src/lib/utils/arrays.ts
index e0f8a16c07a5..8acb8430dda6 100644
--- a/frontend/src/lib/utils/arrays.ts
+++ b/frontend/src/lib/utils/arrays.ts
@@ -74,6 +74,15 @@ export function range(startOrEnd: number, end?: number): number[] {
return Array.from({ length }, (_, i) => i + start)
}
+// Split an array into consecutive sub-arrays of at most `size` items.
+export function chunk<T>(arr: T[], size: number): T[][] {
+ const chunks: T[][] = []
+ for (let i = 0; i < arr.length; i += size) {
+ chunks.push(arr.slice(i, i + size))
+ }
+ return chunks
+}
+
export function interleave(arr: any[], delimiter: any): any[] {
return arr.flatMap((item, index, _arr) =>
_arr.length - 1 !== index // check for the last item
diff --git a/products/ai_observability/frontend/AIObservabilitySessionScene.tsx b/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
index f68d4c0ca627..74fba20d227f 100644
--- a/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
@@ -1,6 +1,6 @@
import { BindLogic, useActions, useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
-import { Suspense, lazy } from 'react'
+import { Suspense, lazy, useEffect } from 'react'
import { IconWrench } from '@posthog/icons'
import { LemonButton, LemonTag, Spinner, SpinnerOverlay, Tooltip } from '@posthog/lemon-ui'
@@ -9,6 +9,7 @@ import { AccessControlAction } from 'lib/components/AccessControlAction'
import { TZLabel } from 'lib/components/TZLabel'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { Link } from 'lib/lemon-ui/Link'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
@@ -29,8 +30,8 @@ import { SentimentBar } from './components/SentimentTag'
import { TranscriptBubbleStream } from './ConversationDisplay/TranscriptBubbleStream'
import { SessionTurn } from './extractSessionTurns'
import { llmSentimentLazyLoaderLogic } from './llmSentimentLazyLoaderLogic'
+import { llmSessionTitleLazyLoaderLogic } from './llmSessionTitleLazyLoaderLogic'
import { SENTIMENT_DATE_WINDOW_DAYS } from './sentimentUtils'
-import { resolveSessionTitle } from './sessionTitle'
import { formatLLMCost, getTraceTimestamp, sanitizeTraceUrlSearchParams } from './utils'
const LLMASessionFeedbackDisplay = lazy(() =>
@@ -93,20 +94,13 @@ 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,
- fullTraces,
- traceSummaries,
- } = useValues(aiObservabilitySessionDataLogic)
- const { sessionId } = useValues(aiObservabilitySessionLogic)
+ const { traces, responseLoading, responseError, sessionTurns, hasMoreData, nextDataLoading, summariesLoading } =
+ useValues(aiObservabilitySessionDataLogic)
+ const { sessionId, dateRange } = useValues(aiObservabilitySessionLogic)
const { summarizeAllTraces, loadNextData } = 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`.
const { searchParams } = useValues(router)
@@ -126,13 +120,12 @@ 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)
+ // Same loader as the sessions list, time-bounded to the page's date range.
+ const heroTitle = getSessionTitle(sessionId)
+ const titleLoading = heroTitle === undefined
+ useEffect(() => {
+ ensureSessionTitleLoaded(sessionId, dateRange ?? undefined)
+ }, [sessionId, dateRange, ensureSessionTitleLoaded])
if (responseLoading) {
return <SpinnerOverlay />
@@ -147,7 +140,11 @@ function SessionSceneWrapper(): JSX.Element {
return (
<div className="relative flex flex-col gap-4 max-w-[75rem]">
<SceneBreadcrumbBackButton />
- {heroTitle && <h1 className="text-2xl font-semibold leading-tight m-0 break-words">{heroTitle}</h1>}
+ {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>
+ )}
<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/AIObservabilitySessionsScene.tsx b/products/ai_observability/frontend/AIObservabilitySessionsScene.tsx
index 3e4256997326..65bf00da1b1e 100644
--- a/products/ai_observability/frontend/AIObservabilitySessionsScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilitySessionsScene.tsx
@@ -1,10 +1,12 @@
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'
@@ -18,9 +20,51 @@ import { LazyPersonColumnCell, ToolsDisplay } from './aiObservabilityColumnRende
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)
@@ -82,23 +126,9 @@ export function AIObservabilitySessionsScene(): JSX.Element {
),
columns: {
session_id: {
- title: 'Session ID',
- render: function RenderSessionId(x) {
- const sessionId = x.value as string
- const truncated = `${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()}`
- return (
- <strong>
- <Tooltip title={sessionId}>
- <Link className="ph-no-capture font-mono" to={sessionUrl}>
- {truncated}
- </Link>
- </Tooltip>
- </strong>
- )
+ title: 'Session',
+ render: function RenderSession(x) {
+ return <SessionColumn sessionId={x.value as string} />
},
},
distinct_id: {
diff --git a/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.ts b/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.ts
index 5ad8804764ed..0b60db635cbb 100644
--- a/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.ts
+++ b/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.ts
@@ -1,6 +1,7 @@
import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import api from 'lib/api'
+import { chunk } from 'lib/utils/arrays'
import { teamLogic } from 'scenes/teamLogic'
import type { llmGenerationSentimentLazyLoaderLogicType } from './llmGenerationSentimentLazyLoaderLogicType'
@@ -26,14 +27,6 @@ const BATCH_MAX_SIZE = 5
// rows, given the browser's per-origin connection limit (~6).
const MAX_CONCURRENT_BATCHES = 2
-function chunk<T>(arr: T[], size: number): T[][] {
- const chunks: T[][] = []
- for (let i = 0; i < arr.length; i += size) {
- chunks.push(arr.slice(i, i + size))
- }
- return chunks
-}
-
export const llmGenerationSentimentLazyLoaderLogic = kea<llmGenerationSentimentLazyLoaderLogicType>([
path(['products', 'ai_observability', 'frontend', 'llmGenerationSentimentLazyLoaderLogic']),
diff --git a/products/ai_observability/frontend/llmSentimentLazyLoaderLogic.ts b/products/ai_observability/frontend/llmSentimentLazyLoaderLogic.ts
index 3347178141d5..8c8de804f594 100644
--- a/products/ai_observability/frontend/llmSentimentLazyLoaderLogic.ts
+++ b/products/ai_observability/frontend/llmSentimentLazyLoaderLogic.ts
@@ -1,6 +1,7 @@
import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import api from 'lib/api'
+import { chunk } from 'lib/utils/arrays'
import { teamLogic } from 'scenes/teamLogic'
import type { llmSentimentLazyLoaderLogicType } from './llmSentimentLazyLoaderLogicType'
@@ -47,14 +48,6 @@ const BATCH_MAX_SIZE = 5
// loaders (trace messages, persons) on page loads with many rows.
const MAX_CONCURRENT_BATCHES = 2
-function chunk<T>(arr: T[], size: number): T[][] {
- const chunks: T[][] = []
- for (let i = 0; i < arr.length; i += size) {
- chunks.push(arr.slice(i, i + size))
- }
- return chunks
-}
-
export const llmSentimentLazyLoaderLogic = kea<llmSentimentLazyLoaderLogicType>([
path(['products', 'ai_observability', 'frontend', 'llmSentimentLazyLoaderLogic']),
diff --git a/products/ai_observability/frontend/llmSessionTitleLazyLoaderLogic.test.ts b/products/ai_observability/frontend/llmSessionTitleLazyLoaderLogic.test.ts
new file mode 100644
index 000000000000..f0d46761be76
--- /dev/null
+++ b/products/ai_observability/frontend/llmSessionTitleLazyLoaderLogic.test.ts
@@ -0,0 +1,204 @@
+import api from 'lib/api'
+
+import { initKeaTests } from '~/test/init'
+
+import { llmSessionTitleLazyLoaderLogic } from './llmSessionTitleLazyLoaderLogic'
+
+// A row as the loader's queries return it: [session_id, input_state, gen_input, trace_name].
+type Row = [string, unknown, unknown, unknown]
+
+function userInputState(text: string): string {
+ return JSON.stringify({ messages: [{ role: 'user', content: text }] })
+}
+
+// A date bound is required for the loader to query the shared `events` table.
+const DATE_RANGE = { dateFrom: '-30d', dateTo: null }
+
+// Let the listener's setTimeout(0) batch timer fire, then drain the api.query +
+// merge microtask chain (allSettled → map → fetchSessionTitles → allSettled).
+async function settle(): Promise<void> {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ for (let i = 0; i < 10; i++) {
+ await Promise.resolve()
+ }
+}
+
+describe('llmSessionTitleLazyLoaderLogic', () => {
+ let logic: ReturnType<typeof llmSessionTitleLazyLoaderLogic.build>
+
+ // Resolve api.query per source: `posthog.ai_events` rows vs shared `events` rows.
+ function mockSources(opts: { events?: Row[] | Error; aiEvents?: Row[] | Error }): void {
+ jest.spyOn(api, 'query').mockImplementation((node: any) => {
+ const q: string = node?.query ?? ''
+ const source = q.includes('posthog.ai_events') ? opts.aiEvents : opts.events
+ if (source instanceof Error) {
+ return Promise.reject(source)
+ }
+ return Promise.resolve({ results: source ?? [] } as any)
+ })
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = llmSessionTitleLazyLoaderLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.restoreAllMocks()
+ })
+
+ describe('state', () => {
+ it('getSessionTitle is undefined before a session is requested', () => {
+ expect(logic.values.getSessionTitle('s1')).toBeUndefined()
+ })
+
+ it('stores resolved titles and clears loading on batch success', async () => {
+ await expectStored(() => logic.actions.loadSessionTitlesBatchSuccess(new Map([['s1', 'hello']]), ['s1']))
+ expect(logic.values.getSessionTitle('s1')).toBe('hello')
+ expect(logic.values.loadingSessionIds.has('s1')).toBe(false)
+ })
+
+ it('stores null (not undefined) for a requested session with no resolved title', async () => {
+ await expectStored(() => logic.actions.loadSessionTitlesBatchSuccess(new Map(), ['s1']))
+ expect(logic.values.getSessionTitle('s1')).toBeNull()
+ })
+
+ it('stores null on batch failure', async () => {
+ await expectStored(() => logic.actions.loadSessionTitlesBatchFailure(['s1']))
+ expect(logic.values.getSessionTitle('s1')).toBeNull()
+ })
+
+ async function expectStored(run: () => void): Promise<void> {
+ run()
+ await Promise.resolve()
+ }
+ })
+
+ describe('fetchSessionTitles merge', () => {
+ it('resolves the title from the opening user message', async () => {
+ mockSources({ events: [['s1', userInputState('plan a trip to Japan'), '', '']] })
+ logic.actions.ensureSessionTitleLoaded('s1', DATE_RANGE)
+ await settle()
+ expect(logic.values.getSessionTitle('s1')).toBe('plan a trip to Japan')
+ })
+
+ it('handles a session id that collides with object prototype keys without polluting Object.prototype', async () => {
+ mockSources({ events: [['__proto__', userInputState('not prototype pollution'), '', '']] })
+ logic.actions.ensureSessionTitleLoaded('__proto__', DATE_RANGE)
+ await settle()
+ expect(logic.values.getSessionTitle('__proto__')).toBe('not prototype pollution')
+ // The merge must not have written the parsed payload onto Object.prototype.
+ expect(({} as Record<string, unknown>).inputState).toBeUndefined()
+ })
+
+ it('merges payloads split across the events and ai_events tables', async () => {
+ // Flipped team: the message lives in ai_events, the trace name on events.
+ // Both must merge, and the real user message must win.
+ mockSources({
+ events: [['s1', '', '', 'my-trace-name']],
+ aiEvents: [['s1', userInputState('what changed in the funnel?'), '', '']],
+ })
+ logic.actions.ensureSessionTitleLoaded('s1', DATE_RANGE)
+ await settle()
+ expect(logic.values.getSessionTitle('s1')).toBe('what changed in the funnel?')
+ })
+
+ it('falls back to the trace name from the events source when there is no user message', async () => {
+ mockSources({ events: [['s1', '', '', 'switch-project']] })
+ logic.actions.ensureSessionTitleLoaded('s1', DATE_RANGE)
+ await settle()
+ expect(logic.values.getSessionTitle('s1')).toBe('switch-project')
+ })
+
+ it('falls back to the trace name from the ai_events source', async () => {
+ mockSources({ aiEvents: [['s1', '', '', 'ingest-workflow']] })
+ logic.actions.ensureSessionTitleLoaded('s1')
+ await settle()
+ expect(logic.values.getSessionTitle('s1')).toBe('ingest-workflow')
+ })
+
+ it('rejects a generic framework trace name (no usable title → null)', async () => {
+ mockSources({ events: [['s1', '', '', 'LangGraph']] })
+ logic.actions.ensureSessionTitleLoaded('s1', DATE_RANGE)
+ await settle()
+ expect(logic.values.getSessionTitle('s1')).toBeNull()
+ })
+
+ it('tolerates one source failing and resolves from the other (allSettled)', async () => {
+ mockSources({
+ events: new Error('events table query failed'),
+ aiEvents: [['s1', userInputState('still works'), '', '']],
+ })
+ logic.actions.ensureSessionTitleLoaded('s1', DATE_RANGE)
+ await settle()
+ expect(logic.values.getSessionTitle('s1')).toBe('still works')
+ })
+
+ it('marks the batch failed (null) when every source query fails', async () => {
+ jest.spyOn(console, 'warn').mockImplementation(() => {}) // the loader warns on total failure
+ mockSources({ events: new Error('boom'), aiEvents: new Error('boom') })
+ logic.actions.ensureSessionTitleLoaded('s1', DATE_RANGE)
+ await settle()
+ expect(logic.values.getSessionTitle('s1')).toBeNull()
+ })
+
+ it('resolves titles for multiple sessions in one batch', async () => {
+ mockSources({
+ events: [
+ ['s1', userInputState('first session'), '', ''],
+ ['s2', '', '', 'named-trace'],
+ ],
+ })
+ logic.actions.ensureSessionTitleLoaded('s1', DATE_RANGE)
+ logic.actions.ensureSessionTitleLoaded('s2', DATE_RANGE)
+ await settle()
+ expect(logic.values.getSessionTitle('s1')).toBe('first session')
+ expect(logic.values.getSessionTitle('s2')).toBe('named-trace')
+ })
+ })
+
+ describe('date range bound', () => {
+ it('applies the passed date range to the events query, leaving ai_events TTL-bounded', async () => {
+ const queried: any[] = []
+ jest.spyOn(api, 'query').mockImplementation((node: any) => {
+ queried.push(node)
+ return Promise.resolve({ results: [] } as any)
+ })
+
+ logic.actions.ensureSessionTitleLoaded('s1', { dateFrom: '-7d', dateTo: null })
+ await settle()
+
+ const eventsNode = queried.find((n) => typeof n?.query === 'string' && n.query.includes('FROM events'))
+ const aiEventsNode = queried.find(
+ (n) => typeof n?.query === 'string' && n.query.includes('posthog.ai_events')
+ )
+
+ // events query is time-bounded via the shared {filters} idiom
+ expect(eventsNode?.query).toContain('{filters}')
+ expect(eventsNode?.filters?.dateRange?.date_from).toBe('-7d')
+ // ai_events is bounded by its TTL, not a date filter
+ expect(aiEventsNode?.query).not.toContain('{filters}')
+ expect(aiEventsNode?.filters).toBeUndefined()
+ })
+
+ it('does NOT query the unbounded events table when no date range is passed', async () => {
+ const queried: any[] = []
+ jest.spyOn(api, 'query').mockImplementation((node: any) => {
+ queried.push(node)
+ return Promise.resolve({ results: [] } as any)
+ })
+
+ logic.actions.ensureSessionTitleLoaded('s1')
+ await settle()
+
+ const eventsNode = queried.find((n) => typeof n?.query === 'string' && n.query.includes('FROM events'))
+ const aiEventsNode = queried.find(
+ (n) => typeof n?.query === 'string' && n.query.includes('posthog.ai_events')
+ )
+ expect(eventsNode).toBeUndefined() // conservative: events table skipped without a bound
+ expect(aiEventsNode).not.toBeUndefined() // ai_events (TTL-bounded) still runs
+ })
+ })
+})
diff --git a/products/ai_observability/frontend/llmSessionTitleLazyLoaderLogic.ts b/products/ai_observability/frontend/llmSessionTitleLazyLoaderLogic.ts
new file mode 100644
index 000000000000..dbb5f93de50a
--- /dev/null
+++ b/products/ai_observability/frontend/llmSessionTitleLazyLoaderLogic.ts
@@ -0,0 +1,330 @@
+import { actions, events, kea, listeners, path, reducers, selectors } from 'kea'
+
+import api from 'lib/api'
+import { chunk } from 'lib/utils/arrays'
+
+import { HogQLQuery, NodeKind } from '~/queries/schema/schema-general'
+import { escapeHogQLString } from '~/queries/utils'
+
+import type { llmSessionTitleLazyLoaderLogicType } from './llmSessionTitleLazyLoaderLogicType'
+import { resolveTitleFromInputs } from './sessionTitle'
+import type { DateRangeFilter } from './types'
+import { parsePartialJSON } from './utils'
+
+const BATCH_MAX_SIZE = 100
+// Cap per field. Titles only need the opening user message, so a small slice is
+// plenty and keeps the ClickHouse aggregation state + network payload bounded.
+const FIELD_TRUNCATE_CHARS = 1000
+// Trace names are short labels; cap them tighter than the message payloads.
+const TRACE_NAME_TRUNCATE_CHARS = 200
+const SESSION_ID_MAX_LENGTH = 256
+
+// We only need the opening user message, this method parses the head.
+// A similar truncate-then-parse pattern exists in traceMessagesLazyLoaderLogic
+function parseTruncatedJson(value: unknown): unknown {
+ if (typeof value !== 'string' || value.length === 0) {
+ return null
+ }
+ try {
+ return JSON.parse(value)
+ } catch {
+ try {
+ return parsePartialJSON(value)
+ } catch {
+ return null
+ }
+ }
+}
+
+// Per-session opening payloads collected from whichever table holds them.
+interface SessionPayloads {
+ inputState: unknown
+ genInput: unknown
+ traceName: string | null
+}
+
+// `dateFrom` is required (not nullable): the caller only builds this query once it has a lower
+// bound, so the scan over the huge, otherwise-unbounded `events` table is never unbounded.
+function eventsTableQuery(sessionIds: string, dateFrom: string, dateTo: string | null): HogQLQuery {
+ return {
+ kind: NodeKind.HogQLQuery,
+ query: `
+ SELECT
+ properties.$ai_session_id AS session_id,
+ argMinIf(
+ substring(toString(properties.$ai_input_state), 1, ${FIELD_TRUNCATE_CHARS}),
+ timestamp,
+ event = '$ai_trace' AND length(toString(properties.$ai_input_state)) > 0
+ ) AS first_input_state,
+ argMinIf(
+ substring(toString(properties.$ai_input), 1, ${FIELD_TRUNCATE_CHARS}),
+ timestamp,
+ event = '$ai_generation' AND length(toString(properties.$ai_input)) > 0
+ ) AS first_gen_input,
+ argMinIf(
+ substring(toString(properties.$ai_span_name), 1, ${TRACE_NAME_TRUNCATE_CHARS}),
+ timestamp,
+ event = '$ai_trace' AND length(toString(properties.$ai_span_name)) > 0
+ ) AS first_trace_name
+ FROM events
+ WHERE event IN ('$ai_trace', '$ai_generation')
+ AND properties.$ai_session_id IN (${sessionIds})
+ AND {filters}
+ GROUP BY session_id
+ `,
+ filters: {
+ dateRange: {
+ date_from: dateFrom,
+ date_to: dateTo,
+ },
+ },
+ }
+}
+
+function aiEventsTableQuery(sessionIds: string): HogQLQuery {
+ return {
+ kind: NodeKind.HogQLQuery,
+ // Not time-bounded: `ai_events` carries a ~30-day TTL so it is inherently bounded
+ // (unlike the shared `events` table), and the `{filters}` date placeholder targets the
+ // events table. The bloom-filter skip index on session_id prunes the scan.
+ query: `
+ SELECT
+ session_id,
+ argMinIf(
+ substring(input_state, 1, ${FIELD_TRUNCATE_CHARS}),
+ timestamp,
+ event = '$ai_trace' AND length(input_state) > 0
+ ) AS first_input_state,
+ argMinIf(
+ substring(input, 1, ${FIELD_TRUNCATE_CHARS}),
+ timestamp,
+ event = '$ai_generation' AND length(input) > 0
+ ) AS first_gen_input,
+ argMinIf(
+ substring(span_name, 1, ${TRACE_NAME_TRUNCATE_CHARS}),
+ timestamp,
+ event = '$ai_trace' AND length(span_name) > 0
+ ) AS first_trace_name
+ FROM posthog.ai_events AS ai_events
+ WHERE event IN ('$ai_trace', '$ai_generation')
+ AND session_id IN (${sessionIds})
+ GROUP BY session_id
+ `,
+ }
+}
+
+/**
+ * Fetch opening-message payloads for a batch of sessions from both the shared
+ * `events` table and the dedicated `ai_events` table, then resolve a title from
+ * whichever has data.
+ * Returns the resolved titles, or `null` if every source query failed (so the
+ * caller can mark the batch failed rather than cache empty titles).
+ */
+async function fetchSessionTitles(
+ batch: string[],
+ dateRange?: DateRangeFilter
+): Promise<Map<string, string | null> | null> {
+ const sessionIds = batch.map((id) => escapeHogQLString(id)).join(',')
+
+ const dateFrom = dateRange?.dateFrom
+ const eventsQuery = dateFrom ? [api.query(eventsTableQuery(sessionIds, dateFrom, dateRange?.dateTo ?? null))] : []
+ const settled = await Promise.allSettled([...eventsQuery, api.query(aiEventsTableQuery(sessionIds))])
+
+ if (settled.every((r) => r.status === 'rejected')) {
+ console.warn('Error loading session titles batch', settled)
+ return null
+ }
+
+ // Merge across both sources: keep the first non-empty payload per session.
+ // Keyed by a Map (not a plain object) so session ids that collide with object
+ // prototype keys (e.g. `__proto__`, sourced from untrusted event data) are
+ // treated as plain keys rather than reading or polluting Object.prototype.
+ const payloads = new Map<string, SessionPayloads>()
+ for (const result of settled) {
+ if (result.status !== 'fulfilled') {
+ continue
+ }
+ for (const row of result.value.results || []) {
+ const [sessionId, firstInputState, firstGenInput, firstTraceName] = row as [
+ string,
+ unknown,
+ unknown,
+ unknown,
+ ]
+ if (!sessionId) {
+ continue
+ }
+ let current = payloads.get(sessionId)
+ if (!current) {
+ current = { inputState: null, genInput: null, traceName: null }
+ payloads.set(sessionId, current)
+ }
+ if (current.inputState == null) {
+ current.inputState = parseTruncatedJson(firstInputState)
+ }
+ if (current.genInput == null) {
+ current.genInput = parseTruncatedJson(firstGenInput)
+ }
+ if (current.traceName == null && typeof firstTraceName === 'string' && firstTraceName.length > 0) {
+ current.traceName = firstTraceName
+ }
+ }
+ }
+
+ const titles = new Map<string, string | null>()
+ for (const sessionId of batch) {
+ const payload = payloads.get(sessionId)
+ titles.set(
+ sessionId,
+ payload ? resolveTitleFromInputs(payload.inputState, payload.genInput, payload.traceName) : null
+ )
+ }
+ return titles
+}
+
+/**
+ * Lazily derives a human-readable title for each session, shared by the Sessions
+ * list and the session detail hero. Both fetch by session id, time-bounded to the
+ * viewed date range (the events table is huge, so the bound guards performance); the
+ * title is the session's first turn within that range.
+ */
+export const llmSessionTitleLazyLoaderLogic = kea<llmSessionTitleLazyLoaderLogicType>([
+ path(['products', 'ai_observability', 'frontend', 'llmSessionTitleLazyLoaderLogic']),
+
+ actions({
+ ensureSessionTitleLoaded: (sessionId: string, dateRange?: DateRangeFilter) => ({ sessionId, dateRange }),
+ markSessionIdsLoading: (sessionIds: string[]) => ({ sessionIds }),
+ loadSessionTitlesBatchSuccess: (titles: Map<string, string | null>, requestedSessionIds: string[]) => ({
+ titles,
+ requestedSessionIds,
+ }),
+ loadSessionTitlesBatchFailure: (requestedSessionIds: string[]) => ({ requestedSessionIds }),
+ }),
+
+ reducers({
+ // Map keyed by session id. `undefined` (key absent) = not yet requested,
+ // `null` = resolved with no usable title. A Map keeps untrusted session ids
+ // (e.g. `__proto__`) from colliding with object prototype keys.
+ titlesBySessionId: [
+ new Map<string, string | null>(),
+ {
+ loadSessionTitlesBatchSuccess: (state, { titles, requestedSessionIds }) => {
+ const next = new Map(state)
+ for (const sessionId of requestedSessionIds) {
+ next.set(sessionId, titles.get(sessionId) ?? null)
+ }
+ return next
+ },
+ loadSessionTitlesBatchFailure: (state, { requestedSessionIds }) => {
+ const next = new Map(state)
+ for (const sessionId of requestedSessionIds) {
+ next.set(sessionId, null)
+ }
+ return next
+ },
+ },
+ ],
+
+ loadingSessionIds: [
+ new Set<string>(),
+ {
+ markSessionIdsLoading: (state, { sessionIds }) => {
+ const next = new Set(state)
+ for (const sessionId of sessionIds) {
+ if (sessionId) {
+ next.add(sessionId)
+ }
+ }
+ return next
+ },
+ loadSessionTitlesBatchSuccess: (state, { requestedSessionIds }) => {
+ const next = new Set(state)
+ for (const sessionId of requestedSessionIds) {
+ next.delete(sessionId)
+ }
+ return next
+ },
+ loadSessionTitlesBatchFailure: (state, { requestedSessionIds }) => {
+ const next = new Set(state)
+ for (const sessionId of requestedSessionIds) {
+ next.delete(sessionId)
+ }
+ return next
+ },
+ },
+ ],
+ }),
+
+ selectors({
+ getSessionTitle: [
+ (s) => [s.titlesBySessionId],
+ (titlesBySessionId): ((sessionId: string) => string | null | undefined) => {
+ return (sessionId: string) => titlesBySessionId.get(sessionId)
+ },
+ ],
+ }),
+
+ listeners(({ actions, values, cache }) => ({
+ ensureSessionTitleLoaded: ({ sessionId, dateRange }) => {
+ if (
+ !sessionId ||
+ sessionId.length > SESSION_ID_MAX_LENGTH ||
+ values.titlesBySessionId.has(sessionId) ||
+ values.loadingSessionIds.has(sessionId)
+ ) {
+ return
+ }
+
+ actions.markSessionIdsLoading([sessionId])
+
+ const pending = cache.pendingSessionIds as Set<string>
+ pending.add(sessionId)
+ // All rows in one view share the same date range; keep the latest seen for the batch.
+ if (dateRange) {
+ cache.pendingDateRange = dateRange
+ }
+
+ if (cache.batchTimer) {
+ return
+ }
+
+ cache.batchTimer = setTimeout(async () => {
+ const requested = Array.from(pending)
+ const dateRangeForBatch = cache.pendingDateRange as DateRangeFilter | undefined
+ pending.clear()
+ cache.pendingDateRange = undefined
+ cache.batchTimer = null
+
+ if (requested.length === 0) {
+ return
+ }
+
+ await Promise.allSettled(
+ chunk(requested, BATCH_MAX_SIZE).map(async (batch) => {
+ const titles = await fetchSessionTitles(batch, dateRangeForBatch)
+ if (titles) {
+ actions.loadSessionTitlesBatchSuccess(titles, batch)
+ } else {
+ actions.loadSessionTitlesBatchFailure(batch)
+ }
+ })
+ )
+ }, 0)
+ },
+ })),
+
+ events(({ cache }) => ({
+ afterMount: () => {
+ cache.pendingSessionIds = new Set<string>()
+ cache.pendingDateRange = undefined
+ cache.batchTimer = null
+ },
+ beforeUnmount: () => {
+ if (cache.batchTimer) {
+ clearTimeout(cache.batchTimer)
+ cache.batchTimer = null
+ }
+ ;(cache.pendingSessionIds as Set<string> | undefined)?.clear?.()
+ },
+ })),
+])
diff --git a/products/ai_observability/frontend/sessionTitle.test.ts b/products/ai_observability/frontend/sessionTitle.test.ts
index 309510b7654a..7d80174f0935 100644
--- a/products/ai_observability/frontend/sessionTitle.test.ts
+++ b/products/ai_observability/frontend/sessionTitle.test.ts
@@ -1,183 +1,132 @@
-import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
+import { resolveTitleFromInputs } from './sessionTitle'
-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()
+describe('resolveTitleFromInputs', () => {
+ it('returns null when no payload yields a title', () => {
+ expect(resolveTitleFromInputs(null, null)).toBeNull()
+ expect(resolveTitleFromInputs(undefined, undefined)).toBeNull()
+ expect(resolveTitleFromInputs({ messages: [] }, null)).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('prefers the first user message in the input_state messages wrapper', () => {
+ const inputState = {
+ agent_mode: null,
+ messages: [
+ { role: 'system', content: 'You are a helpful assistant' },
+ { role: 'user', content: 'Address Book analytic' },
+ ],
+ }
+ expect(resolveTitleFromInputs(inputState, null)).toBe('Address Book analytic')
})
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' }],
- },
- }),
+ const inputState = {
+ messages: [
+ { type: 'system', content: 'system prompt' },
+ { type: 'human', content: 'Hello, I need an export of subscribed users.' },
],
- { traceName: 'LangGraph', inputState: null }
- )
- expect(resolveSessionTitle(trace)).toBe('first user message via span')
+ }
+ expect(resolveTitleFromInputs(inputState, null)).toBe('Hello, I need an export of subscribed users.')
})
- 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' }
+ it('falls back to the generation input, skipping system messages', () => {
+ const genInput = [
+ { role: 'system', content: 'You are an expert in crisp conversation titles.' },
+ { role: 'system', content: 'You are currently in project Default project.' },
+ { role: 'user', content: 'I have connected PostHog Web Tracking and need a dashboard' },
+ ]
+ expect(resolveTitleFromInputs(null, genInput)).toBe(
+ 'I have connected PostHog Web Tracking and need a dashboard'
)
- 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.each([
+ { desc: 'a bare-string generation input', input: 'how do I add a feature flag?' },
+ { desc: 'a role-less message object', input: [{ content: 'how do I add a feature flag?' }] },
+ ])('treats role-less generation input as the user prompt: $desc', ({ input }) => {
+ expect(resolveTitleFromInputs(null, input)).toBe('how do I add a feature flag?')
})
- 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('uses the trace name when no user message is present', () => {
+ expect(resolveTitleFromInputs(null, null, 'switch-project')).toBe('switch-project')
})
it.each([['LangGraph'], ['RunnableSequence'], ['ChatPromptTemplate'], ['langgraph']])(
- 'rejects generic traceName %p as a title (returns null when no other signal)',
+ 'rejects generic trace name %p (returns null when no other signal)',
(name) => {
- const trace = makeTrace([], { traceName: name })
- expect(resolveSessionTitle(trace)).toBeNull()
+ expect(resolveTitleFromInputs(null, null, name)).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' }] },
- }),
+ it('prefers a real user message over the trace name', () => {
+ const inputState = { messages: [{ role: 'user', content: 'plan a trip to Japan' }] }
+ expect(resolveTitleFromInputs(inputState, null, 'switch-project')).toBe('plan a trip to Japan')
+ })
+
+ it.each([['system_reminder'], ['voice_mode'], ['attached_context']])(
+ 'skips internal <%s> scaffold messages and uses the first real user message',
+ (tag) => {
+ const inputState = {
+ messages: [
+ { role: 'user', content: `<${tag}>internal scaffold noise</${tag}>` },
+ { role: 'user', content: "What changed in last month's signup funnel?" },
+ ],
+ }
+ expect(resolveTitleFromInputs(inputState, null)).toBe("What changed in last month's signup funnel?")
+ }
+ )
+
+ it('skips a leading stack of internal scaffolds before the first human message', () => {
+ const inputState = {
+ messages: [
+ { role: 'user', content: '<system_reminder>Your initial mode is product_analytics.</system_reminder>' },
+ { role: 'user', content: '<voice_mode>The user is no longer in hands-free voice mode.</voice_mode>' },
+ { role: 'user', content: '<attached_context>Dashboards</attached_context>' },
+ { role: 'user', content: "What changed in last month's signup funnel?" },
],
- { traceName: 'LangGraph' }
- )
- expect(resolveSessionTitle(trace)).toBe('earlier span')
+ }
+ expect(resolveTitleFromInputs(inputState, null)).toBe("What changed in last month's signup funnel?")
})
it.each([
{
desc: 'collapses whitespace',
- messages: [{ role: 'user', content: 'multi\nline\n\nmessage with spaces' }],
+ 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' }],
+ 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' },
- ],
- },
+ 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',
+ ])('extracts title content: $desc', ({ content, expected }) => {
+ expect(resolveTitleFromInputs({ messages: [{ role: 'user', content }] }, null)).toBe(expected)
+ })
+
+ it('skips messages with empty content and uses the next user message', () => {
+ const inputState = {
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)
+ }
+ expect(resolveTitleFromInputs(inputState, null)).toBe('actual question')
})
it.each([
{
- desc: 'truncates long titles at a word boundary with an ellipsis',
+ desc: 'truncates a long title with an ellipsis at the default length',
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',
@@ -185,24 +134,21 @@ describe('resolveSessionTitle', () => {
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)
+ ])('$desc', ({ content, maxLength, maxOut }) => {
+ const inputState = { messages: [{ role: 'user', content }] }
+ const result =
+ maxLength === undefined
+ ? resolveTitleFromInputs(inputState, null)
+ : resolveTitleFromInputs(inputState, null, undefined, 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?')
+ it('backs off to a word boundary instead of cutting mid-word', () => {
+ const 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?"
+ const result = resolveTitleFromInputs({ messages: [{ role: 'user', content }] }, null)
+ expect(result).not.toContain('enjoyi…')
})
})
diff --git a/products/ai_observability/frontend/sessionTitle.ts b/products/ai_observability/frontend/sessionTitle.ts
index 8c65d42410b8..417c0d79674c 100644
--- a/products/ai_observability/frontend/sessionTitle.ts
+++ b/products/ai_observability/frontend/sessionTitle.ts
@@ -1,77 +1,52 @@
-import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
-
import { normalizeMessages } from './messageNormalization'
import { CompatMessage } from './types'
-import { extractTextContent, hasStringContentField, readAiInput } from './utils'
+import {
+ extractTextContent,
+ hasStringContentField,
+ isInternalTagMessage,
+ isInternalToolResultUserMessage,
+} from './utils'
+// Framework root-span names that carry no meaning as a title, so we ignore them.
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.
+ * Resolve a session title from its opening payloads, in priority order:
+ * 1. first real user message in the trace `input_state`,
+ * 2. first real user message in the earliest generation `input`,
+ * 3. the trace name, unless it's a generic framework root-span name.
*
- * Returns `null` if no signal is available, so that caller decides on fallback
+ * Returns `null` when none yield a usable title, 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)
+export function resolveTitleFromInputs(
+ inputState: unknown,
+ generationInput: unknown,
+ traceName?: unknown,
+ maxLength = DEFAULT_MAX_LENGTH
+): string | null {
+ const fromInputState = firstUserText(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)
- }
+ const fromGenInput = firstUserText(generationInput)
+ 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)
+ if (typeof traceName === 'string') {
+ const trimmed = traceName.trim()
+ if (trimmed.length > 0 && !GENERIC_TRACE_NAMES.has(trimmed.toLowerCase())) {
+ return truncate(trimmed, 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
@@ -94,6 +69,9 @@ function firstUserText(inputPayload: unknown): string | null {
if (message.role !== 'user') {
continue
}
+ if (isInternalTagMessage(message) || isInternalToolResultUserMessage(message)) {
+ continue
+ }
const text = messageContentToText(message.content)
if (text) {
return text
diff --git a/products/ai_observability/frontend/traceMessagesLazyLoaderLogic.ts b/products/ai_observability/frontend/traceMessagesLazyLoaderLogic.ts
index 53c526610c73..b8ba49f05fce 100644
--- a/products/ai_observability/frontend/traceMessagesLazyLoaderLogic.ts
+++ b/products/ai_observability/frontend/traceMessagesLazyLoaderLogic.ts
@@ -1,6 +1,7 @@
import { actions, events, kea, listeners, path, reducers, selectors } from 'kea'
import api from 'lib/api'
+import { chunk } from 'lib/utils/arrays'
import { HogQLQuery, NodeKind } from '~/queries/schema/schema-general'
import { escapeHogQLString } from '~/queries/utils'
@@ -31,14 +32,6 @@ const TRACE_ID_MAX_LENGTH = 128
// Matches TracesQueryDateRange.CAPTURE_RANGE_MINUTES on the backend runner.
const BATCH_WINDOW_BUFFER_MINUTES = 10
-function chunk<T>(arr: T[], size: number): T[][] {
- const chunks: T[][] = []
- for (let i = 0; i < arr.length; i += size) {
- chunks.push(arr.slice(i, i + size))
- }
- return chunks
-}
-
// "2026-04-11T19:20:55.828Z" → "2026-04-11 19:20:55" (ClickHouse toDateTime format, UTC).
function formatHogqlDateTime(d: Date): string {
return d.toISOString().replace('T', ' ').slice(0, 19)
diff --git a/products/ai_observability/frontend/traceReviews/traceReviewsLazyLoaderLogic.ts b/products/ai_observability/frontend/traceReviews/traceReviewsLazyLoaderLogic.ts
index fff779aedd16..5c832c043d26 100644
--- a/products/ai_observability/frontend/traceReviews/traceReviewsLazyLoaderLogic.ts
+++ b/products/ai_observability/frontend/traceReviews/traceReviewsLazyLoaderLogic.ts
@@ -1,5 +1,6 @@
import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { chunk } from 'lib/utils/arrays'
import { teamLogic } from 'scenes/teamLogic'
import { traceReviewsApi } from './traceReviewsApi'
@@ -8,16 +9,6 @@ import type { TraceReview } from './types'
const BATCH_MAX_SIZE = 100
-function chunk<T>(arr: T[], size: number): T[][] {
- const chunks: T[][] = []
-
- for (let i = 0; i < arr.length; i += size) {
- chunks.push(arr.slice(i, i + size))
- }
-
- return chunks
-}
-
export const traceReviewsLazyLoaderLogic = kea<traceReviewsLazyLoaderLogicType>([
path(['products', 'ai_observability', 'frontend', 'traceReviews', 'traceReviewsLazyLoaderLogic']),
diff --git a/products/ai_observability/frontend/types.ts b/products/ai_observability/frontend/types.ts
index 56255373bf21..26a53d0ff65c 100644
--- a/products/ai_observability/frontend/types.ts
+++ b/products/ai_observability/frontend/types.ts
@@ -1,3 +1,8 @@
+export interface DateRangeFilter {
+ dateFrom: string | null
+ dateTo: string | null
+}
+
export interface RoleBasedMessage {
role: string
content: string | { type: string; content: string } | MultiModalContentItem[]
diff --git a/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx b/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx
index 349bb5e494ef..44b7410b4f39 100644
--- a/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx
+++ b/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx
@@ -262,6 +262,9 @@ export function SupportTicketsTable({ embedded = false }: SupportTicketsTablePro
const getKey = useMemo(() => (t: Ticket) => t.id, [])
const bulk = useBulkSelection<Ticket, string>({ pageRecords: tickets, getKey })
+ // `bulk` is a fresh object every render, but its members are individually stable
+ // (callbacks/useState/useMemo or primitives). Destructure so hook deps reference the
+ // stable members instead of the unstable wrapper object.
const {
selectedKeys,
clearSelection,