Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(aio): open traces in a drawer from the traces list (#127706)

Carlos Marchalb13405b44358
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f31545b06a97..6ee4628eff61 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9334,6 +9334,18 @@ snapshots:
hash: v1.k794b7964.f9a40c9c9f03ae241b4b55fc861c0fc470434eda5468b5048b5a99d47e146867.1_xlNXQFwOVz40TTjGKiUtC1KXVUSCh7xoBRPd5zz0M
scenes-app-ai-observability-sessions-empty-state--nothing-to-report--light:
hash: v1.k794b7964.a9311249692deb4f164fdd7fda156bd5e8430f54c579bcd19c25b9a6a00a6e6e.JnEBbVENuBOYVpulIIDVeeenCYSQ_6w03e2oYFCEHjs
+ scenes-app-ai-observability-shared-detail-panel--default--dark:
+ hash: v1.k794b7964.d7f56d2b8f36829fa0ace72e9c4e23de2d9168b3c95605f992ec0f8b96fbe609.3Bk9i46IW7BhrpEp9EmvfQsDhZSNxD446rqFdwo3NsA
+ scenes-app-ai-observability-shared-detail-panel--default--light:
+ hash: v1.k794b7964.d11a44085689d1607ab6496298fe079794ebb19f4cfbae1a5951f8a710da08e0.sER4KdBox5hp8MQweH6SWs3kXo54DybaPL9qY-zWGdA
+ scenes-app-ai-observability-shared-detail-panel--long-body--dark:
+ hash: v1.k794b7964.20c6eff59dfa11ef299eb6a089cd494f5a86897a2ee5e97bac87240614fbfac6.e9RbFLv_G-Vc7rvlCG3fj4JPnV6M1YJjGxZyk4pZ9Bw
+ scenes-app-ai-observability-shared-detail-panel--long-body--light:
+ hash: v1.k794b7964.9f08c1a8aa4b2b51a14895135e303e126e15e92d9317c3c2a2e43d000969c23e.Uf4T4m-BJCnDmsETWdMTNqCIrHVZJjPMGdeUOQiH1to
+ scenes-app-ai-observability-shared-detail-panel--narrow--dark:
+ hash: v1.k794b7964.edddc94e47c621d86f988f7be224ed57229ed582f3f8c33f19774581d4ccbf10.FzoAQ0cPipUyssPmSMkpxNX_nWyB1PrInvC7HtkuP3I
+ scenes-app-ai-observability-shared-detail-panel--narrow--light:
+ hash: v1.k794b7964.3f41b6accafce009828668d06490ec152ded7412f166894e0838ebdb522edebc.nOR5A07GhyWwH5D_gIXMSPKnf-ZsbWSDdCPyk-QQzvM
scenes-app-ai-observability-skills--skill-detail-side-by-side-above-2-xl-breakpoint--superwide--dark:
hash: v1.k794b7964.39ca895c7d8f0aafdd041e9578ce552d37520442d6df7a2d6d554dfdc032b5ba.dqxACinzs4OesVScmWpwTnoPMejqxFaHIHSidJnXKOs
scenes-app-ai-observability-skills--skill-detail-side-by-side-above-2-xl-breakpoint--superwide--light:
diff --git a/products/ai_observability/frontend/AIObservabilityTracesScene.test.tsx b/products/ai_observability/frontend/AIObservabilityTracesScene.test.tsx
index 11b50ec708c7..0bad04966c2a 100644
--- a/products/ai_observability/frontend/AIObservabilityTracesScene.test.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTracesScene.test.tsx
@@ -1,18 +1,40 @@
-import { cleanup, fireEvent, render, renderHook } from '@testing-library/react'
-import { router } from 'kea-router'
+import { RenderResult, act, cleanup, fireEvent, render, renderHook, waitFor } from '@testing-library/react'
+import { combineUrl, router } from 'kea-router'
+import { LemonDropdown } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
import { Link } from 'lib/lemon-ui/Link'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { newInternalTab } from 'lib/utils/newInternalTab'
import { urls } from 'scenes/urls'
-import { DataTableNode } from '~/queries/schema/schema-general'
+import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { DataTable } from '~/queries/nodes/DataTable/DataTable'
+import { performQuery } from '~/queries/query'
+import { DataTableNode, NodeKind } from '~/queries/schema/schema-general'
import { QueryContextColumnComponent } from '~/queries/types'
import { initKeaTests } from '~/test/init'
+import { PropertyFilterType, PropertyOperator } from '~/types'
-import { useTracesQueryContext } from './AIObservabilityTracesScene'
+import { aiObservabilitySharedLogic } from './aiObservabilitySharedLogic'
+import { AIObservabilityTraces, useTracesQueryContext } from './AIObservabilityTracesScene'
+import { traceDrawerLogic } from './redesign/trace/traceDrawerLogic'
jest.mock('lib/utils/newInternalTab')
+jest.mock('~/queries/query', () => ({ ...jest.requireActual('~/queries/query'), performQuery: jest.fn() }))
+jest.mock('~/queries/nodes/DataTable/DataTable', () => {
+ const actual = jest.requireActual('~/queries/nodes/DataTable/DataTable')
+ return { ...actual, DataTable: jest.fn(actual.DataTable) }
+})
+const PERSON = {
+ uuid: 'person-1',
+ distinct_id: 'user-1',
+ created_at: '2026-01-01T12:00:00Z',
+ properties: { email: '[email protected]' },
+}
const TRACE_RECORD = { result: { id: 'trace-1', createdAt: '2026-01-01T12:00:00Z', events: [] } }
const TRACE_PATH = urls.aiObservabilityTrace('trace-1')
const LINK_CELL_PATH = urls.aiObservabilitySessions()
@@ -52,7 +74,67 @@ function renderCell(columnName: string, record: unknown): string {
return container.textContent ?? ''
}
-describe('useTracesQueryContext', () => {
+const LIST_PATH = urls.aiObservabilityTraces()
+const DRAWER_TIMESTAMP = '2026-01-01T11:55:00Z'
+const OPEN_ROW_CLASS = 'LemonTable__row--status-highlighted'
+const TRACES = [
+ { id: 'trace-1', createdAt: '2026-01-01T12:00:00Z', events: [], traceName: 'first', person: PERSON },
+ { id: 'trace-2', createdAt: '2026-01-01T13:00:00Z', events: [], traceName: 'second', person: PERSON },
+]
+
+function tracesRequests(): number {
+ return jest.mocked(performQuery).mock.calls.filter(([query]) => query.kind === NodeKind.TracesQuery).length
+}
+
+async function renderTraces({ flag = true, url = LIST_PATH } = {}): Promise<RenderResult> {
+ initKeaTests()
+ localStorage.clear()
+ jest.mocked(newInternalTab).mockClear()
+ jest.mocked(DataTable).mockClear()
+ jest.mocked(performQuery).mockReset()
+ jest.mocked(performQuery).mockImplementation(async (query) =>
+ query.kind === NodeKind.TracesQuery ? { results: TRACES } : { results: [] }
+ )
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.AI_OBSERVABILITY_TRACE_REDESIGN], {
+ [FEATURE_FLAGS.AI_OBSERVABILITY_TRACE_REDESIGN]: flag,
+ })
+ panelLayoutLogic.mount()
+ router.actions.push(url)
+ const view = render(<AIObservabilityTraces />)
+ await waitFor(() => expect(view.container.querySelector('[data-attr="trace-id-link"]')).not.toBeNull())
+ return view
+}
+
+function tableRow(view: RenderResult, traceName: string): HTMLElement {
+ const row = view.getByText(traceName).closest('tr')
+ if (!row) {
+ throw new Error(`No row for ${traceName}`)
+ }
+ return row
+}
+
+function firstCell(view: RenderResult): HTMLElement {
+ return tableRow(view, 'first').querySelectorAll('td')[0]
+}
+
+function firstLink(view: RenderResult, dataAttr: string): HTMLElement {
+ const link = view.container.querySelector<HTMLElement>(`[data-attr="${dataAttr}"]`)
+ if (!link) {
+ throw new Error(`No ${dataAttr}`)
+ }
+ return link
+}
+
+function lastContext(): NonNullable<Parameters<typeof DataTable>[0]['context']> {
+ const context = jest.mocked(DataTable).mock.lastCall?.[0].context
+ if (!context) {
+ throw new Error('DataTable was not rendered')
+ }
+ return context
+}
+
+describe('AIObservabilityTracesScene', () => {
describe('row navigation', () => {
let pathnameBeforeClick: string
@@ -125,6 +207,191 @@ describe('useTracesQueryContext', () => {
})
})
+ describe('opening the trace drawer from the list', () => {
+ afterEach(cleanup)
+
+ it.each([
+ ['the row', firstCell],
+ ['the ID link', (view: RenderResult): HTMLElement => firstLink(view, 'trace-id-link')],
+ ['the name link', (view: RenderResult): HTMLElement => firstLink(view, 'trace-name-link')],
+ ])('opens the drawer on a plain click on %s', async (_name, target) => {
+ const view = await renderTraces()
+
+ fireEvent.click(target(view))
+
+ expect(router.values.location.pathname).toContain(LIST_PATH)
+ expect(router.values.searchParams).toMatchObject({ trace: 'trace-1', ts: DRAWER_TIMESTAMP })
+ expect(router.values.searchParams).not.toHaveProperty('back_to')
+ expect(newInternalTab).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['closed', LIST_PATH],
+ [
+ 'open on another trace',
+ combineUrl(LIST_PATH, { trace: 'trace-2', ts: DRAWER_TIMESTAMP, step: 'gen-1' }).url,
+ ],
+ ])('opens the page in a new tab on a Cmd-click on the row with the drawer %s', async (_name, url) => {
+ const view = await renderTraces({ url })
+ const listUrl = router.values.currentLocation
+
+ fireEvent.click(firstCell(view), { metaKey: true })
+
+ expect(router.values.currentLocation).toEqual(listUrl)
+ const pageUrl = combineUrl(jest.mocked(newInternalTab).mock.lastCall?.[0] ?? '')
+ expect(pageUrl.pathname).toContain(TRACE_PATH)
+ expect(pageUrl.searchParams).toMatchObject({ back_to: 'traces' })
+ expect(pageUrl.searchParams).not.toHaveProperty('trace')
+ expect(pageUrl.searchParams).not.toHaveProperty('ts')
+ expect(pageUrl.searchParams).not.toHaveProperty('step')
+ })
+
+ it('leaves the drawer params out of the trace links', async () => {
+ const view = await renderTraces({
+ url: combineUrl(LIST_PATH, { trace: 'trace-2', ts: DRAWER_TIMESTAMP, step: 'gen-1' }).url,
+ })
+
+ const { searchParams } = combineUrl(firstLink(view, 'trace-id-link').getAttribute('href') ?? '')
+
+ expect(searchParams).toMatchObject({ back_to: 'traces' })
+ expect(searchParams).not.toHaveProperty('trace')
+ expect(searchParams).not.toHaveProperty('step')
+ })
+
+ it('leaves a click inside an overlay opened from a cell to the overlay', async () => {
+ await renderTraces()
+ const onOverlayClick = jest.fn()
+ const { getByTestId } = render(
+ <table>
+ <tbody>
+ <tr {...(lastContext().rowProps?.({ result: TRACES[0] }) ?? {})}>
+ <td>
+ <LemonDropdown
+ visible
+ overlay={
+ <div data-attr="overlay-row" onClick={onOverlayClick}>
+ copy
+ </div>
+ }
+ >
+ <span>open</span>
+ </LemonDropdown>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ )
+
+ fireEvent.click(getByTestId('overlay-row'))
+
+ expect(onOverlayClick).toHaveBeenCalledTimes(1)
+ expect(router.values.searchParams).not.toHaveProperty('trace')
+ })
+
+ it('leaves a Cmd-click on the ID link for the browser to open the page in a new tab', async () => {
+ const view = await renderTraces()
+ const link = firstLink(view, 'trace-id-link')
+
+ const browserHandlesIt = fireEvent.click(link, { metaKey: true })
+
+ expect(browserHandlesIt).toBe(true)
+ expect(link.getAttribute('href')).toContain(TRACE_PATH)
+ expect(router.values.searchParams).not.toHaveProperty('trace')
+ })
+
+ it('leaves a click on the person link alone', async () => {
+ const view = await renderTraces()
+ const personLink = tableRow(view, 'first').querySelector<HTMLElement>('a[href*="/person/"]')
+ if (!personLink) {
+ throw new Error('No person link')
+ }
+
+ fireEvent.click(personLink)
+
+ expect(router.values.searchParams).not.toHaveProperty('trace')
+ })
+
+ it('closes back to the list and gives focus to the row that opened the panel, however far it stepped', async () => {
+ const view = await renderTraces()
+ act(() => panelLayoutLogic.actions.setMainContentRect(document.body.getBoundingClientRect()))
+ const logic = traceDrawerLogic({ listId: 'traces' })
+ await waitFor(() => expect(logic.values.rows).toHaveLength(2))
+
+ fireEvent.click(firstCell(view))
+
+ expect(document.activeElement).toBe(firstLink(view, 'trace-drawer'))
+
+ fireEvent.click(firstLink(view, 'trace-drawer-next'))
+ expect(router.values.searchParams).toMatchObject({ trace: 'trace-2' })
+ fireEvent.click(firstLink(view, 'trace-drawer-close'))
+
+ await waitFor(() => expect(view.container.querySelector('[data-attr="trace-drawer"]')).toBeNull())
+ expect(router.values.searchParams.trace).toBeUndefined()
+ expect(document.activeElement).toBe(firstLink(view, 'trace-id-link'))
+ })
+
+ it('marks only the open row', async () => {
+ const view = await renderTraces({ url: combineUrl(LIST_PATH, { trace: 'trace-2' }).url })
+
+ expect(tableRow(view, 'second').className).toContain(OPEN_ROW_CLASS)
+ expect(tableRow(view, 'first').className).not.toContain(OPEN_ROW_CLASS)
+ })
+
+ it('keeps pushing the page url when the flag is off', async () => {
+ const view = await renderTraces({ flag: false })
+
+ fireEvent.click(firstCell(view))
+
+ expect(router.values.location.pathname).toContain(TRACE_PATH)
+ expect(router.values.searchParams).toMatchObject({ back_to: 'traces', timestamp: DRAWER_TIMESTAMP })
+ expect(router.values.searchParams).not.toHaveProperty('trace')
+ })
+
+ it('keeps the drawer params through a filter change and does not query for writing them', async () => {
+ const view = await renderTraces()
+
+ fireEvent.click(firstCell(view))
+ act(() => traceDrawerLogic({ listId: 'traces' }).actions.requestStep('gen-1'))
+
+ expect(tracesRequests()).toBe(1)
+
+ act(() =>
+ aiObservabilitySharedLogic.actions.setPropertyFilters([
+ {
+ type: PropertyFilterType.Event,
+ key: '$ai_model',
+ value: 'gpt-4',
+ operator: PropertyOperator.Exact,
+ },
+ ])
+ )
+
+ await waitFor(() => expect(tracesRequests()).toBe(2))
+ expect(router.values.searchParams).toMatchObject({
+ trace: 'trace-1',
+ ts: DRAWER_TIMESTAMP,
+ step: 'gen-1',
+ })
+ })
+
+ it('gives the drawer the loaded rows and keeps the table context when the response changes', async () => {
+ await renderTraces()
+ const logic = traceDrawerLogic({ listId: 'traces' })
+ await waitFor(() => expect(logic.values.rows).toHaveLength(2))
+ expect(logic.values.rows[0]).toEqual({ traceId: 'trace-1', timestamp: DRAWER_TIMESTAMP, stepId: null })
+ const context = lastContext()
+
+ act(() =>
+ dataNodeLogic
+ .findMounted({ key: 'llm-analytics-traces' })
+ ?.actions.setResponse({ results: [TRACES[1]] })
+ )
+
+ expect(logic.values.rows).toEqual([{ traceId: 'trace-2', timestamp: '2026-01-01T12:55:00Z', stepId: null }])
+ expect(lastContext()).toBe(context)
+ })
+ })
+
// A row the response returned without a field `LLMTrace` types as present used to throw
// in the cell renderer, which reaches the scene error boundary and blanks the whole list.
describe('malformed cells', () => {
diff --git a/products/ai_observability/frontend/AIObservabilityTracesScene.tsx b/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
index 76f332a92d0c..cc49148f36c0 100644
--- a/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
@@ -1,6 +1,7 @@
+import clsx from 'clsx'
import { useActions, useMountedLogic, useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
-import { useCallback, useEffect } from 'react'
+import { MouseEvent, useCallback, useEffect, useMemo } from 'react'
import { IconGear } from '@posthog/icons'
import { LemonButton, LemonDropdown, LemonSwitch, LemonTag } from '@posthog/lemon-ui'
@@ -13,6 +14,7 @@ import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { newInternalTab } from 'lib/utils/newInternalTab'
import { urls } from 'scenes/urls'
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { DataTable } from '~/queries/nodes/DataTable/DataTable'
import { DataTableNode, LLMTrace } from '~/queries/schema/schema-general'
import { QueryContext, QueryContextColumnComponent } from '~/queries/types'
@@ -22,6 +24,10 @@ import { aiObservabilityColumnRenderers } from './aiObservabilityColumnRenderers
import { buildApplyUrlStatePayload, aiObservabilitySharedLogic } from './aiObservabilitySharedLogic'
import { LLMMessageDisplay } from './ConversationDisplay/ConversationMessagesDisplay'
import { normalizeMessages } from './messageNormalization'
+import { toFullPageListParams } from './redesign/trace/adapter/toBackLink'
+import { TraceDrawerHost } from './redesign/trace/TraceDrawerHost'
+import { traceDrawerLogic } from './redesign/trace/traceDrawerLogic'
+import { TraceListRow } from './redesign/trace/traceListRows'
import { aiObservabilityTracesTabLogic } from './tabs/aiObservabilityTracesTabLogic'
import { TraceMessages, traceMessagesLazyLoaderLogic } from './traceMessagesLazyLoaderLogic'
import { traceReviewsLazyLoaderLogic } from './traceReviews/traceReviewsLazyLoaderLogic'
@@ -36,9 +42,13 @@ import {
isToolResult,
isToolStepItem,
LLM_TRACES_PAGE_SIZE,
- sanitizeTraceUrlSearchParams,
} from './utils'
+const TRACES_DATA_NODE_KEY = 'llm-analytics-traces'
+const TRACE_DRAWER_LIST_ID = 'traces'
+const OPEN_ROW_CLASS = 'LemonTable__row--status-highlighted'
+const TRACE_LINKS = '[data-attr="trace-id-link"], [data-attr="trace-name-link"]'
+
export function AIObservabilityTraces(): JSX.Element {
useMountedLogic(traceReviewsLazyLoaderLogic)
useMountedLogic(traceMessagesLazyLoaderLogic)
@@ -49,8 +59,37 @@ export function AIObservabilityTraces(): JSX.Element {
const appliedSearchTerm = isTracesQuery(tracesQuery.source) ? tracesQuery.source.searchTerm : undefined
const baseContext = useTracesQueryContext()
+ const { rowProps: baseRowProps } = baseContext
+ const logic = traceDrawerLogic({ listId: TRACE_DRAWER_LIST_ID })
+ const { isEnabled, openTraceId } = useValues(logic)
+ const { openRow } = useActions(logic)
+ const drawerRowProps = useCallback<NonNullable<QueryContext['rowProps']>>(
+ (record) => {
+ const baseProps = baseRowProps?.(record) ?? {}
+ const trace = getTraceFromRow(record)
+ if (!trace) {
+ return baseProps
+ }
+ return {
+ ...baseProps,
+ className: clsx(baseProps.className, trace.id === openTraceId && OPEN_ROW_CLASS),
+ onClickCapture: (event) => {
+ if (opensTraceDrawer(event)) {
+ event.preventDefault()
+ event.stopPropagation()
+ // A row cannot take focus, and the panel gives focus back to what held it on opening.
+ event.currentTarget.querySelector<HTMLElement>(TRACE_LINKS)?.focus({ preventScroll: true })
+ openRow(toTraceListRow(trace))
+ }
+ },
+ }
+ },
+ [baseRowProps, openRow, openTraceId]
+ )
const context: QueryContext<DataTableNode> = {
...baseContext,
+ dataNodeLogicKey: TRACES_DATA_NODE_KEY,
+ rowProps: isEnabled ? drawerRowProps : baseRowProps,
...(appliedSearchTerm
? {
emptyStateHeading: 'No traces matched your search',
@@ -89,12 +128,28 @@ export function AIObservabilityTraces(): JSX.Element {
)
}}
context={context}
- uniqueKey="llm-analytics-traces"
+ uniqueKey={TRACES_DATA_NODE_KEY}
/>
+ {isEnabled ? <TraceDrawerRows query={tracesQuery.source} /> : null}
+ <TraceDrawerHost listId={TRACE_DRAWER_LIST_ID} />
</div>
)
}
+// A sibling after DataTable, so that DataTable builds the logic with its full props. Subscribing in
+// AIObservabilityTraces would also rebuild the table context on each poll and re-render every row.
+function TraceDrawerRows({ query }: { query: DataTableNode['source'] }): null {
+ const { response } = useValues(dataNodeLogic({ key: TRACES_DATA_NODE_KEY, query }))
+ const { setRows } = useActions(traceDrawerLogic({ listId: TRACE_DRAWER_LIST_ID }))
+ const rows = useMemo(() => toTraceListRows(response), [response])
+
+ useEffect(() => {
+ setRows(rows)
+ }, [rows, setRows])
+
+ return null
+}
+
function TracesOptionsMenu(): JSX.Element | null {
const { showInputOutputColumns, showSentimentColumn } = useValues(aiObservabilityTracesTabLogic)
const { setShowInputOutputColumns, setShowSentimentColumn } = useActions(aiObservabilityTracesTabLogic)
@@ -137,15 +192,33 @@ function TracesOptionsMenu(): JSX.Element | null {
)
}
+// An omitted timestamp makes the detail view use its wide default date range. A timestamp
+// built from a missing or unparseable `createdAt` would instead point the lookup at a
+// ten-minute window around the present, where an older trace is not found.
+function getTraceLookupTimestamp(row: LLMTrace): string | undefined {
+ return row.createdAt && dayjs(row.createdAt).isValid() ? getTraceTimestamp(row.createdAt) : undefined
+}
+
+function toTraceListRow(trace: LLMTrace): TraceListRow {
+ return { traceId: trace.id, timestamp: getTraceLookupTimestamp(trace) ?? null, stepId: null }
+}
+
+function toTraceListRows(response: unknown): TraceListRow[] {
+ const results = typeof response === 'object' && response && 'results' in response ? response.results : null
+ if (!Array.isArray(results)) {
+ return []
+ }
+ return results.flatMap((result) => {
+ const trace = getTraceFromRow({ result })
+ return trace ? [toTraceListRow(trace)] : []
+ })
+}
+
function buildTraceDetailUrl(row: LLMTrace, searchParams: Record<string, unknown>): string {
- const nonTraceSearchParams = sanitizeTraceUrlSearchParams(searchParams, { removeSearch: true })
return combineUrl(urls.aiObservabilityTrace(row.id), {
- ...nonTraceSearchParams,
+ ...toFullPageListParams(searchParams),
back_to: 'traces',
- // An omitted timestamp makes the detail view use its wide default date range. A timestamp
- // built from a missing or unparseable `createdAt` would instead point the lookup at a
- // ten-minute window around the present, where an older trace is not found.
- timestamp: row.createdAt && dayjs(row.createdAt).isValid() ? getTraceTimestamp(row.createdAt) : undefined,
+ timestamp: getTraceLookupTimestamp(row),
}).url
}
@@ -165,6 +238,14 @@ function hasOwnClickHandler(target: EventTarget | null): boolean {
return target instanceof Element && !!target.closest('button, a, [role="button"]')
}
+function opensTraceDrawer({ target, currentTarget, button, metaKey, ctrlKey, shiftKey, altKey }: MouseEvent): boolean {
+ // React capture also reaches the row from a portal, so an overlay opened from a cell would lose its own clicks.
+ const isInsideRow = target instanceof Node && currentTarget.contains(target)
+ const isPlainClick = button === 0 && !metaKey && !ctrlKey && !shiftKey && !altKey
+ const isTraceLink = target instanceof Element && !!target.closest(TRACE_LINKS)
+ return isInsideRow && isPlainClick && (isTraceLink || !hasOwnClickHandler(target))
+}
+
export const useTracesQueryContext = (): QueryContext<DataTableNode> => {
const { searchParams } = useValues(router)
const { push } = useActions(router)
diff --git a/products/ai_observability/frontend/redesign/shared/components/DetailPanel.scss b/products/ai_observability/frontend/redesign/shared/components/DetailPanel.scss
new file mode 100644
index 000000000000..2ee68ba414e9
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/shared/components/DetailPanel.scss
@@ -0,0 +1,17 @@
+@keyframes DetailPanel__slide-in {
+ from {
+ opacity: 0;
+ transform: translateX(2rem);
+ }
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ .DetailPanel {
+ animation: DetailPanel__slide-in 200ms ease-out;
+ }
+}
+
+// The visual test runner cuts animations to zero duration, and headless Chromium can then paint the first keyframe.
+.storybook-test-runner .DetailPanel {
+ animation: none;
+}
diff --git a/products/ai_observability/frontend/redesign/shared/components/DetailPanel.stories.tsx b/products/ai_observability/frontend/redesign/shared/components/DetailPanel.stories.tsx
new file mode 100644
index 000000000000..c5cd382dc69c
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/shared/components/DetailPanel.stories.tsx
@@ -0,0 +1,54 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { createRef } from 'react'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { DetailPanel } from './DetailPanel'
+
+const SCENE_TOP = 56
+const SCENE_HEIGHT = 560
+
+function sceneRect(width: number): { top: number; right: number; height: number; width: number } {
+ return { top: SCENE_TOP, right: window.innerWidth, height: SCENE_HEIGHT, width }
+}
+
+function Body({ paragraphs }: { paragraphs: number }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-3">
+ {Array.from({ length: paragraphs }, (_, index) => (
+ <p key={index} className="m-0">
+ Step {index + 1}: the model received the request, called a tool and returned an answer.
+ </p>
+ ))}
+ </div>
+ )
+}
+
+const meta: Meta<typeof DetailPanel> = {
+ title: 'Scenes-App/AI observability/Shared/Detail panel',
+ component: DetailPanel,
+ parameters: { testOptions: { snapshotTargetSelector: 'aside' } },
+ args: {
+ toolbar: <span className="font-semibold">Toolbar</span>,
+ children: <Body paragraphs={4} />,
+ width: 640,
+ resizer: null,
+ containerRef: createRef<HTMLElement>(),
+ 'aria-label': 'Trace detail',
+ 'data-attr': 'detail-panel',
+ rect: sceneRect(1000),
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof DetailPanel>
+
+export const Default: Story = {}
+
+export const Narrow: Story = {
+ args: { rect: sceneRect(640), toolbar: <LemonButton size="small">Close</LemonButton> },
+}
+
+export const LongBody: Story = {
+ args: { children: <Body paragraphs={40} /> },
+}
diff --git a/products/ai_observability/frontend/redesign/shared/components/DetailPanel.tsx b/products/ai_observability/frontend/redesign/shared/components/DetailPanel.tsx
new file mode 100644
index 000000000000..343a8ad3a648
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/shared/components/DetailPanel.tsx
@@ -0,0 +1,86 @@
+import './DetailPanel.scss'
+
+import { CSSProperties, ReactNode, RefObject, useEffect } from 'react'
+
+import { cn } from 'lib/utils/css-classes'
+
+export interface DetailPanelRect {
+ top: number
+ right: number
+ height: number
+ width: number
+}
+
+export interface DetailPanelProps {
+ toolbar: ReactNode
+ children: ReactNode
+ rect: DetailPanelRect
+ width: number
+ resizer: ReactNode
+ containerRef: RefObject<HTMLElement>
+ 'aria-label': string
+ 'data-attr': string
+}
+
+const FULL_WIDTH_BELOW_SCENE_WIDTH = 900
+const TOOLBAR_HEIGHT_REM = 3
+
+export function isDetailPanelFullWidth(sceneWidth: number): boolean {
+ return sceneWidth < FULL_WIDTH_BELOW_SCENE_WIDTH
+}
+
+export function DetailPanel({
+ toolbar,
+ children,
+ rect,
+ width,
+ resizer,
+ containerRef,
+ 'aria-label': ariaLabel,
+ 'data-attr': dataAttr,
+}: DetailPanelProps): JSX.Element {
+ useEffect(() => {
+ const previouslyFocused = document.activeElement
+ containerRef.current?.focus({ preventScroll: true })
+ return () => {
+ if (previouslyFocused instanceof HTMLElement && previouslyFocused.isConnected) {
+ previouslyFocused.focus({ preventScroll: true })
+ }
+ }
+ }, [containerRef])
+
+ // The panel is fixed, so a container query cannot see the scene width.
+ const isFullWidth = isDetailPanelFullWidth(rect.width)
+
+ return (
+ <aside
+ ref={containerRef}
+ tabIndex={-1}
+ aria-label={ariaLabel}
+ data-attr={dataAttr}
+ className={cn(
+ 'DetailPanel fixed top-[var(--detail-panel-top)] right-[var(--detail-panel-right)] h-[var(--detail-panel-height)] z-[var(--z-drawer)]',
+ 'flex flex-col bg-surface-primary border-l border-primary shadow-xl outline-none',
+ '[--scene-title-section-height:0px]',
+ '[--trace-view-height:calc(var(--detail-panel-height)_-_var(--detail-panel-toolbar-height))]'
+ )}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={
+ {
+ '--detail-panel-top': `${rect.top}px`,
+ '--detail-panel-right': `calc(100vw - ${rect.right}px)`,
+ '--detail-panel-height': `${rect.height}px`,
+ '--detail-panel-toolbar-height': `${TOOLBAR_HEIGHT_REM}rem`,
+ width: isFullWidth ? rect.width : width,
+ maxWidth: rect.width,
+ } as CSSProperties
+ }
+ >
+ {resizer}
+ <div className="flex h-[var(--detail-panel-toolbar-height)] shrink-0 items-center gap-2 border-b border-primary px-3">
+ {toolbar}
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto p-4">{children}</div>
+ </aside>
+ )
+}
diff --git a/products/ai_observability/frontend/redesign/trace/TraceDrawerHost.test.tsx b/products/ai_observability/frontend/redesign/trace/TraceDrawerHost.test.tsx
new file mode 100644
index 000000000000..e93dd0bbe73d
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/TraceDrawerHost.test.tsx
@@ -0,0 +1,193 @@
+import { RenderResult, act, cleanup, fireEvent, render, waitFor } from '@testing-library/react'
+import { combineUrl, router } from 'kea-router'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { urls } from 'scenes/urls'
+
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import {
+ decodeIdSegment,
+ makeEvaluationResults,
+ makeFeedback,
+ makeNodeDetail,
+ makeTraceResource,
+} from './adapter/testFixtures'
+import { TraceDrawerHost } from './TraceDrawerHost'
+import { traceDrawerLogic } from './traceDrawerLogic'
+import { TraceListRow } from './traceListRows'
+import { traceViewHostLogic } from './traceViewHostLogic'
+
+jest.mock('~/queries/query', () => ({ ...jest.requireActual('~/queries/query'), performQuery: jest.fn() }))
+jest.mock('../../utils', () => ({
+ ...jest.requireActual('../../utils'),
+ queryEvaluationRuns: jest.fn().mockResolvedValue([]),
+}))
+
+const TRACE_BASE_URL = '/api/projects/:team_id/ai_observability/traces/:id'
+const LIST_PATH = urls.aiObservabilityTraces()
+const LIST_ID = 'traces'
+const ROW_A: TraceListRow = { traceId: 'a', timestamp: '2026-09-01T10:15:00Z', stepId: null }
+const ROW_B: TraceListRow = { traceId: 'b', timestamp: '2026-09-01T10:20:00Z', stepId: null }
+
+type TraceReply = () => Promise<[number, unknown]>
+
+const answerTrace = (traceId: string): TraceReply => {
+ return async () => [200, makeTraceResource({ name: `answer-${traceId}`, defaultNodeId: 'gen-1' })]
+}
+
+function useTraceMocks(firstTraceReply: TraceReply): void {
+ useMocks({
+ get: {
+ [`${TRACE_BASE_URL}/`]: ({ params }) => {
+ const traceId = decodeIdSegment(String(params.id))
+ return traceId === 'a' ? firstTraceReply() : answerTrace(traceId)()
+ },
+ [`${TRACE_BASE_URL}/nodes/:node_id/`]: ({ params }) => [
+ 200,
+ makeNodeDetail({ id: decodeIdSegment(String(params.node_id)) }),
+ ],
+ [`${TRACE_BASE_URL}/evaluations/`]: () => [200, makeEvaluationResults()],
+ [`${TRACE_BASE_URL}/clusters/`]: () => [200, { clusters: [] }],
+ [`${TRACE_BASE_URL}/feedback/`]: () => [200, makeFeedback({ scores: [], responses: [] })],
+ },
+ })
+}
+
+function setUp(url: string, sceneRect: Partial<DOMRect> = {}): void {
+ initKeaTests()
+ localStorage.clear()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.AI_OBSERVABILITY_TRACE_REDESIGN], {
+ [FEATURE_FLAGS.AI_OBSERVABILITY_TRACE_REDESIGN]: true,
+ })
+ panelLayoutLogic.mount()
+ panelLayoutLogic.actions.setMainContentRect(Object.assign(document.body.getBoundingClientRect(), sceneRect))
+ router.actions.push(url)
+}
+
+function drawerUrl({ traceId, timestamp }: TraceListRow): string {
+ return combineUrl(LIST_PATH, { trace: traceId, ts: timestamp ?? undefined }).url
+}
+
+function renderHost(rows: TraceListRow[]): RenderResult {
+ const logic = traceDrawerLogic({ listId: LIST_ID })
+ logic.mount()
+ logic.actions.setRows(rows)
+ return render(<TraceDrawerHost listId={LIST_ID} />)
+}
+
+function attr(container: Element, name: string): HTMLElement {
+ const element = container.querySelector<HTMLElement>(`[data-attr="${name}"]`)
+ if (!element) {
+ throw new Error(`expected ${name} to render`)
+ }
+ return element
+}
+
+// jsdom leaves pageX out of mouse events, and the resizer measures the drag with it.
+function mouseEventAt(type: string, pageX: number): MouseEvent {
+ const event = new MouseEvent(type, { button: 0, bubbles: true })
+ Object.defineProperty(event, 'pageX', { value: pageX })
+ return event
+}
+
+describe('TraceDrawerHost', () => {
+ afterEach(() => {
+ cleanup()
+ resumeKeaLoadersErrors()
+ })
+
+ it.each<[string, (view: RenderResult) => Promise<HTMLElement>, () => { reply: TraceReply; release: () => void }]>([
+ [
+ 'loading',
+ (view) => view.findByLabelText('Loading trace'),
+ () => {
+ let release = (): void => {}
+ const answered = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ return {
+ reply: async () => {
+ await answered
+ return answerTrace('a')()
+ },
+ release,
+ }
+ },
+ ],
+ [
+ 'missing',
+ (view) => view.findByText("We couldn't load this trace"),
+ () => ({ reply: async () => [404, { detail: 'Not found.' }], release: () => {} }),
+ ],
+ ])('keeps the toolbar and moves on from a %s trace', async (_name, findScreen, makeReply) => {
+ silenceKeaLoadersErrors()
+ const { reply, release } = makeReply()
+ useTraceMocks(reply)
+ setUp(drawerUrl(ROW_A))
+ const view = renderHost([ROW_A, ROW_B])
+ await findScreen(view)
+ const close = attr(view.container, 'trace-drawer-close')
+ const host = traceViewHostLogic({ hostId: traceDrawerLogic({ listId: LIST_ID }).values.hostId })
+ act(() => host.actions.setMode('thread'))
+
+ expect(view.getByText('1 of 2')).toBeTruthy()
+ expect(view.queryByText(/^Back to/)).toBeNull()
+ expect(view.container.querySelector('[data-attr="trace-view-back"]')).toBeNull()
+
+ fireEvent.click(attr(view.container, 'trace-drawer-next'))
+
+ expect((await view.findAllByText('answer-b')).length).toBeGreaterThan(0)
+ expect(view.getByText('2 of 2')).toBeTruthy()
+ expect(router.values.searchParams.trace).toBe('b')
+ expect(attr(view.container, 'trace-drawer-close')).toBe(close)
+ expect(host.values.mode).toBe('thread')
+ release()
+ })
+
+ it('writes a clicked step to the list URL and stays on the list', async () => {
+ useTraceMocks(answerTrace('a'))
+ setUp(drawerUrl(ROW_A))
+ const { findByText } = renderHost([ROW_A])
+
+ fireEvent.click(await findByText('span-1'))
+
+ await waitFor(() => expect(router.values.searchParams.step).toBe('span-1'))
+ expect(router.values.location.pathname).toContain(LIST_PATH)
+ expect(router.values.searchParams.event).toBeUndefined()
+ })
+
+ it('opens at two thirds of the scene and follows the resizer', async () => {
+ useTraceMocks(answerTrace('a'))
+ setUp(drawerUrl(ROW_A), { width: 1200 })
+ const { container, findAllByText } = renderHost([ROW_A])
+ await findAllByText('answer-a')
+ const panel = attr(container, 'trace-drawer')
+ expect(panel.style.width).toBe('800px')
+
+ const resizer = container.querySelector('.Resizer')
+ if (!resizer) {
+ throw new Error('expected the panel to render a resizer')
+ }
+
+ fireEvent(resizer, mouseEventAt('mousedown', 1000))
+ fireEvent(document, mouseEventAt('mouseup', 100))
+
+ await waitFor(() => expect(panel.style.width).toBe('900px'))
+ })
+
+ it('has no resizer when the panel takes the whole scene', async () => {
+ useTraceMocks(answerTrace('a'))
+ setUp(drawerUrl(ROW_A), { width: 800 })
+ const { container, findAllByText } = renderHost([ROW_A])
+ await findAllByText('answer-a')
+
+ expect(attr(container, 'trace-drawer').style.width).toBe('800px')
+ expect(container.querySelector('.Resizer')).toBeNull()
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/TraceDrawerHost.tsx b/products/ai_observability/frontend/redesign/trace/TraceDrawerHost.tsx
new file mode 100644
index 000000000000..f41e421eb8ff
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/TraceDrawerHost.tsx
@@ -0,0 +1,65 @@
+import { useActions, useValues } from 'kea'
+import { useRef } from 'react'
+
+import { Resizer } from 'lib/lemon-ui/Resizer/Resizer'
+import { ResizerLogicProps, resizerLogic } from 'lib/lemon-ui/Resizer/resizerLogic'
+
+import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
+
+import { DetailPanel, isDetailPanelFullWidth } from '../shared/components/DetailPanel'
+import { TraceViewContainer } from './adapter/TraceViewContainer'
+import { TraceDrawerToolbar } from './components/TraceDrawerToolbar'
+import { traceDrawerLogic } from './traceDrawerLogic'
+
+export interface TraceDrawerHostProps {
+ listId: string
+}
+
+export function TraceDrawerHost({ listId }: TraceDrawerHostProps): JSX.Element | null {
+ const logic = traceDrawerLogic({ listId })
+ const { hostId, isEnabled, openRef, position, previousTrace, nextTrace, fullPageHref } = useValues(logic)
+ const { stepTo, close } = useActions(logic)
+ const { mainContentRect } = useValues(panelLayoutLogic)
+
+ const containerRef = useRef<HTMLDivElement>(null)
+ const resizerProps: ResizerLogicProps = {
+ containerRef,
+ logicKey: 'trace-drawer',
+ placement: 'left',
+ persistent: true,
+ minSize: 480,
+ }
+ const { desiredSize } = useValues(resizerLogic(resizerProps))
+
+ if (!isEnabled || !openRef || !fullPageHref || !mainContentRect) {
+ return null
+ }
+
+ return (
+ <DetailPanel
+ aria-label="Trace detail"
+ data-attr="trace-drawer"
+ rect={mainContentRect}
+ width={desiredSize ?? Math.round((mainContentRect.width * 2) / 3)}
+ containerRef={containerRef}
+ resizer={isDetailPanelFullWidth(mainContentRect.width) ? null : <Resizer {...resizerProps} />}
+ toolbar={
+ <TraceDrawerToolbar
+ position={position}
+ onPrevious={previousTrace ? () => stepTo('previous') : null}
+ onNext={nextTrace ? () => stepTo('next') : null}
+ fullPageHref={fullPageHref}
+ onClose={close}
+ />
+ }
+ >
+ <TraceViewContainer
+ key={openRef.traceId}
+ hostId={hostId}
+ traceId={openRef.traceId}
+ timestampHint={openRef.timestamp}
+ backLink={null}
+ />
+ </DetailPanel>
+ )
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/TraceViewContainer.tsx b/products/ai_observability/frontend/redesign/trace/adapter/TraceViewContainer.tsx
index fcb4443089fb..ef6b88e99cbd 100644
--- a/products/ai_observability/frontend/redesign/trace/adapter/TraceViewContainer.tsx
+++ b/products/ai_observability/frontend/redesign/trace/adapter/TraceViewContainer.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { memo } from 'react'
import { SaveToDatasetButton } from '../../../datasets/SaveToDatasetButton'
import { TraceView, TraceViewProps, TraceViewReadyProps } from '../components/TraceView'
@@ -129,7 +130,12 @@ function toReadyProps(values: ReadyValues, actions: ReadyActions): TraceViewRead
}
}
-export function TraceViewContainer({ hostId, traceId, timestampHint, backLink }: TraceViewContainerProps): JSX.Element {
+export const TraceViewContainer = memo(function TraceViewContainer({
+ hostId,
+ traceId,
+ timestampHint,
+ backLink,
+}: TraceViewContainerProps): JSX.Element {
const logic = traceViewModelLogic({ hostId, traceId, timestampHint })
// Every kea value getter is a hook, so read them all on every render, whatever the status.
const {
@@ -215,4 +221,4 @@ export function TraceViewContainer({ hostId, traceId, timestampHint, backLink }:
: { status: 'loading' }
return <TraceView {...props} />
-}
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toBackLink.ts b/products/ai_observability/frontend/redesign/trace/adapter/toBackLink.ts
index a43928abe181..78f101cc1086 100644
--- a/products/ai_observability/frontend/redesign/trace/adapter/toBackLink.ts
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toBackLink.ts
@@ -12,6 +12,11 @@ function listParams(searchParams: SearchParams): SearchParams {
return sanitizeTraceUrlSearchParams(searchParams, { removeSearch: true })
}
+export function toFullPageListParams(searchParams: SearchParams): SearchParams {
+ const { trace: _trace, ts: _ts, step: _step, ...params } = listParams(searchParams)
+ return params
+}
+
// Matches the legacy scene: a link opened from a review queue returns to that queue, other links to the reviews tab.
function reviewsBackHref(searchParams: SearchParams): string {
const inQueue = typeof searchParams.queue_id === 'string' && searchParams.queue_id !== ''
diff --git a/products/ai_observability/frontend/redesign/trace/components/TraceDrawerToolbar.stories.tsx b/products/ai_observability/frontend/redesign/trace/components/TraceDrawerToolbar.stories.tsx
new file mode 100644
index 000000000000..90a620b685b3
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/components/TraceDrawerToolbar.stories.tsx
@@ -0,0 +1,26 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { withWidth } from '../storyFixtures'
+import { TraceDrawerToolbar } from './TraceDrawerToolbar'
+
+const meta: Meta<typeof TraceDrawerToolbar> = {
+ title: 'Scenes-App/AI observability/Trace view/Trace drawer toolbar',
+ component: TraceDrawerToolbar,
+ decorators: [withWidth(640)],
+ parameters: { testOptions: { snapshotBrowsers: [] } },
+ args: {
+ position: { index: 1, total: 12 },
+ onPrevious: () => {},
+ onNext: () => {},
+ fullPageHref: '/traces/trace-1',
+ onClose: () => {},
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof TraceDrawerToolbar>
+
+export const Default: Story = {}
+export const FirstTrace: Story = { args: { position: { index: 0, total: 12 }, onPrevious: null } }
+export const NotInList: Story = { args: { position: null, onPrevious: null, onNext: null } }
+export const Narrow: Story = { decorators: [withWidth(480)] }
diff --git a/products/ai_observability/frontend/redesign/trace/components/TraceDrawerToolbar.tsx b/products/ai_observability/frontend/redesign/trace/components/TraceDrawerToolbar.tsx
new file mode 100644
index 000000000000..5fab3fe93805
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/components/TraceDrawerToolbar.tsx
@@ -0,0 +1,76 @@
+import { IconChevronDown, IconExpand45, IconX } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { KeyboardShortcut } from 'lib/lemon-ui/KeyboardShortcut/KeyboardShortcut'
+
+import type { TraceDrawerPosition } from '../traceDrawerLogic'
+
+export interface TraceDrawerToolbarProps {
+ /** Null when the open trace is not in the list. */
+ position: TraceDrawerPosition | null
+ onPrevious: (() => void) | null
+ onNext: (() => void) | null
+ fullPageHref: string
+ onClose: () => void
+}
+
+const NOT_IN_LIST_REASON = "This trace isn't in the list"
+
+export function TraceDrawerToolbar({
+ position,
+ onPrevious,
+ onNext,
+ fullPageHref,
+ onClose,
+}: TraceDrawerToolbarProps): JSX.Element {
+ return (
+ <div className="flex min-w-0 flex-1 items-center gap-1">
+ <LemonButton
+ size="small"
+ icon={<IconChevronDown className="rotate-180" />}
+ tooltip="Previous trace"
+ aria-label="Previous trace"
+ data-attr="trace-drawer-previous"
+ onClick={onPrevious ?? undefined}
+ disabledReason={onPrevious ? undefined : position ? 'This is the first trace' : NOT_IN_LIST_REASON}
+ />
+ <LemonButton
+ size="small"
+ icon={<IconChevronDown />}
+ tooltip="Next trace"
+ aria-label="Next trace"
+ data-attr="trace-drawer-next"
+ onClick={onNext ?? undefined}
+ disabledReason={onNext ? undefined : position ? 'This is the last loaded trace' : NOT_IN_LIST_REASON}
+ />
+ {position ? (
+ <span className="ml-1 whitespace-nowrap text-xs text-secondary">
+ {`${position.index + 1} of ${position.total}`}
+ </span>
+ ) : null}
+ <div className="ml-auto flex items-center gap-1">
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconExpand45 />}
+ to={fullPageHref}
+ data-attr="trace-drawer-full-page"
+ >
+ Open full page
+ </LemonButton>
+ <LemonButton
+ size="small"
+ icon={<IconX />}
+ tooltip={
+ <>
+ Close <KeyboardShortcut escape />
+ </>
+ }
+ aria-label="Close"
+ data-attr="trace-drawer-close"
+ onClick={onClose}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/redesign/trace/components/TraceSplitView.tsx b/products/ai_observability/frontend/redesign/trace/components/TraceSplitView.tsx
index 74dbfe2db1e3..9c94cd64417a 100644
--- a/products/ai_observability/frontend/redesign/trace/components/TraceSplitView.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/TraceSplitView.tsx
@@ -43,7 +43,7 @@ export function TraceSplitView({
matchStepCount={matchStepCount}
/>
</aside>
- <div className="min-w-0 flex-1 @3xl:sticky @3xl:top-[var(--scene-title-section-height,50px)] @3xl:max-h-[calc(100vh-var(--scene-title-section-height,50px))] @3xl:overflow-y-auto">
+ <div className="min-w-0 flex-1 @3xl:sticky @3xl:top-[var(--scene-title-section-height,50px)] @3xl:max-h-[calc(var(--trace-view-height,100vh)-var(--scene-title-section-height,50px))] @3xl:overflow-y-auto">
{detail ? (
<NodeDetail
{...detail}
diff --git a/products/ai_observability/frontend/redesign/trace/rawSearchParam.ts b/products/ai_observability/frontend/redesign/trace/rawSearchParam.ts
new file mode 100644
index 000000000000..8aa797a7bb1e
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/rawSearchParam.ts
@@ -0,0 +1,9 @@
+// kea-router reads a numeric param as a number, which turns a typed `1.50` into `1.5`. It also pads a value shaped like
+// a JSON array or object with one space, so it reads that value back as a string.
+export function rawSearchParam(search: string, name: string): string | null {
+ const value = new URLSearchParams(search).get(name)
+ if (!value) {
+ return null
+ }
+ return /^(\[.*\]|\{.*\}) +$/.test(value) ? value.slice(0, -1) : value
+}
diff --git a/products/ai_observability/frontend/redesign/trace/shouldCloseOnEscape.test.ts b/products/ai_observability/frontend/redesign/trace/shouldCloseOnEscape.test.ts
new file mode 100644
index 000000000000..503092015a12
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/shouldCloseOnEscape.test.ts
@@ -0,0 +1,34 @@
+import { shouldCloseOnEscape } from './shouldCloseOnEscape'
+
+describe('shouldCloseOnEscape', () => {
+ afterEach(() => {
+ document.body.innerHTML = ''
+ })
+
+ function pressKey(key: string, targetHtml: string, targetSelector: string): KeyboardEvent {
+ document.body.innerHTML = targetHtml
+ const event = new KeyboardEvent('keydown', { key, bubbles: true })
+ document.querySelector(targetSelector)?.dispatchEvent(event)
+ return event
+ }
+
+ it.each([
+ ['Escape on the page', 'Escape', '<button id="t"></button>', true],
+ ['another key', 'ArrowDown', '<button id="t"></button>', false],
+ ['Escape in an input', 'Escape', '<input id="t" />', false],
+ ['Escape in a textarea', 'Escape', '<textarea id="t"></textarea>', false],
+ ['Escape in a contenteditable', 'Escape', '<div contenteditable="true"><b id="t"></b></div>', false],
+ ['Escape in a read-only contenteditable', 'Escape', '<div contenteditable="false"><b id="t"></b></div>', true],
+ ['Escape with a modal open', 'Escape', '<div class="ReactModal__Overlay"></div><b id="t"></b>', false],
+ ['Escape with a popover open', 'Escape', '<div class="Popover"></div><b id="t"></b>', false],
+ ])('for %s', (_name, key, html, expected) => {
+ expect(shouldCloseOnEscape(pressKey(key, html, '#t'))).toBe(expected)
+ })
+
+ it('leaves an Escape that a handler in the page already took', () => {
+ const event = new KeyboardEvent('keydown', { key: 'Escape', cancelable: true })
+ event.preventDefault()
+
+ expect(shouldCloseOnEscape(event)).toBe(false)
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/shouldCloseOnEscape.ts b/products/ai_observability/frontend/redesign/trace/shouldCloseOnEscape.ts
new file mode 100644
index 000000000000..c07d1e24a34a
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/shouldCloseOnEscape.ts
@@ -0,0 +1,11 @@
+const EDITABLE_TARGET = 'input, textarea, [contenteditable]:not([contenteditable="false"])'
+// A modal or popover owns Escape while it is open.
+const ESCAPE_OWNERS = '.ReactModal__Overlay, .Popover'
+
+export function shouldCloseOnEscape(event: KeyboardEvent): boolean {
+ if (event.key !== 'Escape' || event.defaultPrevented) {
+ return false
+ }
+ const isEditing = event.target instanceof Element && event.target.closest(EDITABLE_TARGET) !== null
+ return !isEditing && document.querySelector(ESCAPE_OWNERS) === null
+}
diff --git a/products/ai_observability/frontend/redesign/trace/traceDrawerLogic.test.ts b/products/ai_observability/frontend/redesign/trace/traceDrawerLogic.test.ts
new file mode 100644
index 000000000000..17a8fe74dc3f
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/traceDrawerLogic.test.ts
@@ -0,0 +1,477 @@
+import { decodeParams, router } from 'kea-router'
+import { getRouterContext } from 'kea-router/lib/router'
+import posthog from 'posthog-js'
+
+import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { addProductIntent } from 'lib/utils/product-intents'
+import { urls } from 'scenes/urls'
+
+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { traceDrawerLogic } from './traceDrawerLogic'
+import { TraceListRow } from './traceListRows'
+import { traceViewHostLogic } from './traceViewHostLogic'
+import { traceViewPreferenceLogic } from './traceViewPreferenceLogic'
+
+jest.mock('lib/utils/product-intents', () => ({
+ ...jest.requireActual('lib/utils/product-intents'),
+ addProductIntent: jest.fn(),
+}))
+
+const FLAG = FEATURE_FLAGS.AI_OBSERVABILITY_TRACE_REDESIGN
+const LIST_PATH = urls.aiObservabilityTraces()
+
+const A: TraceListRow = { traceId: 'a', timestamp: null, stepId: 'x' }
+const A2: TraceListRow = { traceId: 'a', timestamp: null, stepId: 'y' }
+const B: TraceListRow = { traceId: 'b', timestamp: null, stepId: null }
+const C: TraceListRow = { traceId: 'c', timestamp: '2026-01-01T12:00:00+00:00', stepId: 'z' }
+
+describe('traceDrawerLogic', () => {
+ let logic: ReturnType<typeof traceDrawerLogic.build>
+ let host: ReturnType<typeof traceViewHostLogic.build>
+ let browserHistory: string[]
+ let capture: jest.SpyInstance
+
+ const param = (name: string): string | null => new URLSearchParams(router.values.location.search).get(name)
+ const capturedEvents = (): unknown[][] =>
+ capture.mock.calls.filter(([event]) => String(event).startsWith('llma trace drawer'))
+
+ // Back and forward decode the URL again, as a page load does.
+ function goTo(url: string): void {
+ const { pathname, search, hash } = new URL(url, 'https://example.com')
+ router.actions.locationChanged({
+ method: 'POP',
+ pathname,
+ search,
+ searchParams: decodeParams(search, '?'),
+ hash,
+ hashParams: decodeParams(hash, '#'),
+ url,
+ })
+ }
+
+ function routerHistory(): NonNullable<ReturnType<typeof getRouterContext>['history']> {
+ const { history } = getRouterContext()
+ if (!history) {
+ throw new Error('The router has no history in this test')
+ }
+ return history
+ }
+
+ function goBack(): void {
+ browserHistory.pop()
+ goTo(browserHistory[browserHistory.length - 1])
+ }
+
+ function mountDrawer(): void {
+ logic = traceDrawerLogic({ listId: 'traces' })
+ logic.mount()
+ host = traceViewHostLogic({ hostId: logic.values.hostId })
+ host.mount()
+ }
+
+ function setUp({ url = LIST_PATH, flag = true }: { url?: string; flag?: boolean } = {}): void {
+ initKeaTests()
+ localStorage.clear()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FLAG], { [FLAG]: flag })
+ goTo(url)
+
+ browserHistory = [url]
+ routerHistory().pushState = (_state: unknown, _title: string, target: string): void => {
+ browserHistory.push(target)
+ }
+ routerHistory().replaceState = (_state: unknown, _title: string, target: string): void => {
+ browserHistory[browserHistory.length - 1] = target
+ }
+
+ capture = jest.spyOn(posthog, 'capture')
+ mountDrawer()
+ }
+
+ afterEach(() => {
+ if (logic.isMounted()) {
+ logic.unmount()
+ }
+ jest.restoreAllMocks()
+ jest.mocked(addProductIntent).mockClear()
+ document.body.innerHTML = ''
+ })
+
+ it('steps by trace, so a repeated trace cannot trap next', () => {
+ setUp()
+ logic.actions.setRows([A, A2, B])
+ logic.actions.openRow(A)
+ expect(logic.values.position).toEqual({ index: 0, total: 2 })
+
+ logic.actions.stepTo('next')
+
+ expect(logic.values.openTraceId).toBe('b')
+ expect(logic.values.previousTrace).toEqual(A)
+ expect(logic.values.nextTrace).toBeNull()
+ })
+
+ it('does not revisit a repeat below a trace it passed', () => {
+ setUp()
+ logic.actions.setRows([A, B, A2])
+ logic.actions.openRow(B)
+
+ expect(logic.values.position).toEqual({ index: 1, total: 2 })
+ expect(logic.values.nextTrace).toBeNull()
+ })
+
+ it('stays open with no position when the open trace leaves the rows', () => {
+ setUp()
+ logic.actions.setRows([A, B])
+ logic.actions.openRow(A)
+
+ logic.actions.setRows([B])
+
+ expect(logic.values.openTraceId).toBe('a')
+ expect(logic.values).toMatchObject({ position: null, previousTrace: null, nextTrace: null })
+ })
+
+ it('does nothing when stepping past either end', () => {
+ setUp()
+ logic.actions.setRows([A])
+ logic.actions.openRow(A)
+ const entries = browserHistory.length
+
+ logic.actions.stepTo('next')
+ logic.actions.stepTo('previous')
+
+ expect(browserHistory).toHaveLength(entries)
+ expect(capturedEvents().filter(([event]) => event === 'llma trace drawer stepped')).toEqual([])
+ })
+
+ it('replaces the step for another row of the open trace and writes nothing for the row on show', () => {
+ setUp()
+ logic.actions.setRows([A, A2, B])
+ logic.actions.openRow(A)
+ const entries = browserHistory.length
+
+ logic.actions.openRow(A2)
+ expect(param('step')).toBe('y')
+ expect(logic.values.position).toEqual({ index: 0, total: 2 })
+ expect(browserHistory).toHaveLength(entries)
+
+ const url = browserHistory[browserHistory.length - 1]
+ logic.actions.openRow(A2)
+ expect(browserHistory[browserHistory.length - 1]).toBe(url)
+ })
+
+ it('keeps the selected step when a row with no step targets the open trace', () => {
+ setUp()
+ logic.actions.openRow(A)
+ host.actions.requestStep('y')
+ const url = browserHistory[browserHistory.length - 1]
+
+ logic.actions.openRow({ ...A, stepId: null })
+
+ expect(host.values.requestedStepId).toBe('y')
+ expect(browserHistory[browserHistory.length - 1]).toBe(url)
+ })
+
+ it('carries the mode and step tab between traces, and resets them when reopened', () => {
+ setUp()
+ logic.actions.setRows([A, B, C])
+ logic.actions.openRow(A)
+ host.actions.setMode('thread')
+ host.actions.setDetailTab('raw')
+
+ logic.actions.stepTo('next')
+ logic.actions.openRow(C)
+ expect(host.values).toMatchObject({ mode: 'thread', detailTab: 'raw' })
+
+ logic.actions.close()
+ logic.actions.openRow(A)
+ expect(host.values).toMatchObject({ mode: 'spans', detailTab: 'messages' })
+ })
+
+ it('goes back through each trace it stepped through, and back to the list', () => {
+ setUp()
+ logic.actions.setRows([A, B, C])
+ logic.actions.openRow(A)
+ logic.actions.stepTo('next')
+ host.actions.requestStep('b-step')
+ logic.actions.stepTo('next')
+
+ goBack()
+ expect(logic.values.openRef).toEqual({ ...B, stepId: 'b-step' })
+ expect(host.values.requestedStepId).toBe('b-step')
+
+ goBack()
+ expect(logic.values.openRef).toEqual(A)
+
+ goBack()
+ expect(logic.values.openRef).toBeNull()
+ })
+
+ it.each(['a/b#c', '123', '1.50', 'true', '[draft]', '{"a":1}'])('round-trips the trace id %s', (traceId) => {
+ setUp()
+ const row = { traceId, timestamp: '2026-01-01T12:00:00+00:00', stepId: traceId }
+
+ logic.actions.openRow(row)
+ expect(logic.values.openRef).toEqual(row)
+
+ goTo(browserHistory[browserHistory.length - 1])
+ expect(logic.values.openRef).toEqual(row)
+ })
+
+ it('reads a link with a numeric trace as text', () => {
+ setUp({ url: `${LIST_PATH}?trace=1.50&ts=2026&step=2.0` })
+
+ expect(logic.values.openRef).toEqual({ traceId: '1.50', timestamp: '2026', stepId: '2.0' })
+ })
+
+ it('keeps a numeric trace and step as text when another logic rewrites the URL', () => {
+ setUp({ url: `${LIST_PATH}?date_from=-7d&trace=1.50&ts=2026&step=2.0` })
+
+ router.actions.replace(router.values.location.pathname, { ...router.values.searchParams, date_from: '-1d' })
+
+ expect(logic.values.openRef).toEqual({ traceId: '1.50', timestamp: '2026', stepId: '2.0' })
+ expect(param('date_from')).toBe('-1d')
+ expect(browserHistory).toHaveLength(1)
+ })
+
+ it.each([
+ ['steps', ['01', '1'], (): void => logic.actions.stepTo('next'), '1'],
+ [
+ 'goes back',
+ ['1', '01'],
+ (): void => {
+ logic.actions.stepTo('next')
+ goBack()
+ },
+ '1',
+ ],
+ ])('%s between distinct numeric-looking traces', (_name, traceIds, navigate, expected) => {
+ setUp({ url: `${LIST_PATH}?trace=${traceIds[0]}` })
+ logic.actions.setRows(traceIds.map((traceId) => ({ traceId, timestamp: null, stepId: null })))
+
+ navigate()
+
+ expect(logic.values.openTraceId).toBe(expected)
+ })
+
+ it('treats an empty trace param as closed', () => {
+ setUp({ url: `${LIST_PATH}?trace=` })
+
+ expect(logic.values.openRef).toBeNull()
+ })
+
+ it.each([
+ ['opening', (): void => logic.actions.openRow(B)],
+ ['stepping', (): void => logic.actions.stepTo('next')],
+ ['a requested step', (): void => host.actions.requestStep('gen-2')],
+ ['closing', (): void => logic.actions.close()],
+ ])('keeps the other params and the hash when %s', (_name, write) => {
+ setUp({ url: `${LIST_PATH}?trace_search=1.50&date_from=-7d&trace=1.50&ts=2.50&step=3.50#panel=discussion` })
+ logic.actions.setRows([{ traceId: '1.50', timestamp: '2.50', stepId: '3.50' }, B])
+
+ write()
+
+ expect(param('trace_search')).toBe('1.50')
+ expect(param('date_from')).toBe('-7d')
+ expect(router.values.hashParams).toEqual({ panel: 'discussion' })
+ })
+
+ it('keeps the raw open trace when a step is written', () => {
+ setUp({ url: `${LIST_PATH}?trace=1.50&ts=2.50` })
+
+ host.actions.requestStep('gen-2')
+
+ expect(logic.values.openRef).toEqual({ traceId: '1.50', timestamp: '2.50', stepId: 'gen-2' })
+ expect(browserHistory).toHaveLength(1)
+ })
+
+ it('does not write a step the URL already holds', () => {
+ setUp({ url: `${LIST_PATH}?trace=a&step=1.50` })
+ const replaceState = jest.spyOn(routerHistory(), 'replaceState')
+
+ host.actions.requestStep('1.50')
+
+ expect(replaceState).not.toHaveBeenCalled()
+ })
+
+ it('leaves the list URL alone for a step requested while closed', () => {
+ setUp()
+
+ host.actions.requestStep('gen-2')
+
+ expect(param('step')).toBeNull()
+ })
+
+ it('hands the host the step before the new trace renders', () => {
+ setUp()
+ logic.actions.setRows([A, B])
+
+ logic.actions.openRow(A)
+ expect(host.values.requestedStepId).toBe('x')
+
+ logic.actions.stepTo('next')
+ expect(host.values.requestedStepId).toBeNull()
+ })
+
+ it.each([
+ ['the flag is off', (): void => undefined, false],
+ ['the person is on the old view', (): void => traceViewPreferenceLogic.actions.switchView('legacy'), true],
+ ])('sends a link to the trace page, without tracking, when %s', (_name, prepare, flag) => {
+ setUp({ flag })
+ prepare()
+ logic.unmount()
+ goTo(`${LIST_PATH}?date_from=-7d&trace=a%2Fb&ts=2026-01-01&step=gen-1`)
+
+ mountDrawer()
+
+ expect(logic.values.isEnabled).toBe(false)
+ expect(router.values.location.pathname).toContain(urls.aiObservabilityTrace('a/b'))
+ expect(router.values.searchParams).toEqual({ timestamp: '2026-01-01', event: 'gen-1' })
+ expect(capturedEvents()).toEqual([])
+ expect(addProductIntent).not.toHaveBeenCalled()
+ })
+
+ it('strips its params on unmount, so changing tab closes the drawer', () => {
+ setUp({ url: `${LIST_PATH}?trace_search=1.50&trace=a&ts=2026&step=x` })
+ logic.actions.setRows([A, B])
+ logic.actions.stepTo('next')
+
+ host.unmount()
+ logic.unmount()
+
+ expect(router.values.location.search).toBe('?trace_search=1.50')
+ expect(capturedEvents()).toContainEqual(['llma trace drawer closed', { steps: 1 }])
+ })
+
+ it.each(['/ai-observability/generations', '/project/1/ai-observability/generations'])(
+ 'still strips its params from the tab %s',
+ (tabPath) => {
+ setUp()
+ goTo(`${tabPath}?date_from=-7d&trace=a&ts=2026&step=x`)
+
+ logic.unmount()
+
+ expect(router.values.location.search).toBe('?date_from=-7d')
+ }
+ )
+
+ it.each([
+ ['enabled', true],
+ ['disabled', false],
+ ])('ignores a trace param on another product URL when %s', (_name, flag) => {
+ setUp({ flag })
+ const search = '?trace=0AF7651916CD43DD&ts=2026-01-01T00:00:00Z'
+ const replaceState = jest.spyOn(routerHistory(), 'replaceState')
+
+ goTo(`/tracing${search}`)
+ expect(logic.values.openRef).toBeNull()
+ logic.unmount()
+
+ expect(router.values.location.pathname).toBe('/tracing')
+ expect(router.values.location.search).toBe(search)
+ expect(replaceState).not.toHaveBeenCalled()
+ expect(capturedEvents()).toEqual([])
+ expect(addProductIntent).not.toHaveBeenCalled()
+ })
+
+ it('leaves the URL alone on unmount when closed', () => {
+ setUp({ url: `${LIST_PATH}?trace_search=1.50` })
+ const replaceState = jest.spyOn(routerHistory(), 'replaceState')
+
+ logic.unmount()
+
+ expect(replaceState).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['the close control', (): void => logic.actions.close()],
+ ['the back button', (): void => goTo(LIST_PATH)],
+ ])('counts the steps in the closed event, and only since this open, through %s', (_name, leave) => {
+ setUp()
+ logic.actions.setRows([A, B, C])
+ logic.actions.openRow(A)
+ logic.actions.stepTo('next')
+ logic.actions.stepTo('next')
+ logic.actions.stepTo('previous')
+ logic.actions.openRow(C)
+
+ leave()
+ logic.actions.openRow(A)
+ logic.actions.close()
+
+ expect(capturedEvents()).toEqual([
+ ['llma trace drawer opened', { list: 'traces' }],
+ ['llma trace drawer stepped', { direction: 'next' }],
+ ['llma trace drawer stepped', { direction: 'next' }],
+ ['llma trace drawer stepped', { direction: 'previous' }],
+ ['llma trace drawer closed', { steps: 3 }],
+ ['llma trace drawer opened', { list: 'traces' }],
+ ['llma trace drawer closed', { steps: 0 }],
+ ])
+ })
+
+ it('records one product intent and completes the setup tasks per open', () => {
+ setUp()
+ globalSetupLogic.mount()
+ const markTaskAsCompleted = jest.spyOn(globalSetupLogic.actions, 'markTaskAsCompleted')
+ logic.actions.setRows([A, B])
+ logic.actions.openRow(A)
+ logic.actions.stepTo('next')
+
+ expect(addProductIntent).toHaveBeenCalledTimes(1)
+ expect(addProductIntent).toHaveBeenCalledWith({
+ product_type: ProductKey.AI_OBSERVABILITY,
+ intent_context: ProductIntentContext.LLM_ANALYTICS_TRACE_VIEWED,
+ })
+ expect(markTaskAsCompleted).toHaveBeenCalledTimes(1)
+ expect(markTaskAsCompleted).toHaveBeenCalledWith([SetupTaskId.IngestFirstLlmEvent, SetupTaskId.ViewFirstTrace])
+ })
+
+ it('tracks an open from a reload or a shared link', () => {
+ setUp({ url: `${LIST_PATH}?trace=a` })
+
+ expect(capturedEvents()).toEqual([['llma trace drawer opened', { list: 'traces' }]])
+ expect(addProductIntent).toHaveBeenCalledTimes(1)
+ })
+
+ it('closes on Escape while open, and stops listening once closed', () => {
+ setUp()
+ logic.actions.setRows([A, B])
+ logic.actions.openRow(A)
+ logic.actions.stepTo('next')
+
+ const entries = browserHistory.length
+
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
+ expect(logic.values.openRef).toBeNull()
+ expect(browserHistory).toHaveLength(entries + 1)
+
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
+ expect(browserHistory).toHaveLength(entries + 1)
+ })
+
+ it('links to the full page with the selected step and the list params', () => {
+ setUp({ url: `${LIST_PATH}?trace_search=1.50&date_from=-7d&trace=a%2Fb%23c&ts=2026-01-01&step=gen-1` })
+ host.actions.requestStep('gen-2')
+
+ const href = logic.values.fullPageHref ?? ''
+
+ expect(href.split('?')[0]).toBe(urls.aiObservabilityTrace('a/b#c'))
+ expect(Object.fromEntries(new URLSearchParams(href.split('?')[1]))).toEqual({
+ trace_search: '1.50',
+ date_from: '-7d',
+ timestamp: '2026-01-01',
+ event: 'gen-2',
+ back_to: 'traces',
+ })
+ })
+
+ it('has no full page link while closed', () => {
+ setUp()
+
+ expect(logic.values.fullPageHref).toBeNull()
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/traceDrawerLogic.ts b/products/ai_observability/frontend/redesign/trace/traceDrawerLogic.ts
new file mode 100644
index 000000000000..d547d7d75ab3
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/traceDrawerLogic.ts
@@ -0,0 +1,338 @@
+import {
+ MakeLogicType,
+ actions,
+ beforeUnmount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+import { combineUrl, router } from 'kea-router'
+import { subscriptions } from 'kea-subscriptions'
+import posthog from 'posthog-js'
+
+import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { addProductIntent } from 'lib/utils/product-intents'
+import { urls } from 'scenes/urls'
+
+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
+
+import { toFullPageListParams } from './adapter/toBackLink'
+import { rawSearchParam } from './rawSearchParam'
+import { shouldCloseOnEscape } from './shouldCloseOnEscape'
+import { TraceListRow, uniqueTraces } from './traceListRows'
+import { traceViewHostLogic } from './traceViewHostLogic'
+import { traceViewPreferenceLogic } from './traceViewPreferenceLogic'
+import type { TraceViewChoice } from './types'
+
+export interface TraceDrawerLogicProps {
+ listId: string
+}
+
+export type TraceStepDirection = 'previous' | 'next'
+
+export interface TraceDrawerPosition {
+ index: number
+ total: number
+}
+
+const CLOSE_ON_ESCAPE_DISPOSABLE = 'closeOnEscape'
+
+const AI_OBSERVABILITY_PATH_PREFIX = '/ai-observability/'
+
+const TEXT_PARAMS = ['trace_search', 'trace', 'ts', 'step']
+
+function traceDrawerHostId(listId: string): string {
+ return `trace-drawer-${listId}`
+}
+
+// Other products use `trace` for their own ids, and tab links carry the drawer params across this product's paths.
+function isAIObservabilityPath(pathname: string): boolean {
+ return removeProjectIdIfPresent(pathname).startsWith(AI_OBSERVABILITY_PATH_PREFIX)
+}
+
+function withTextParams(searchParams: Record<string, unknown>, search: string): Record<string, unknown> {
+ const textParams = TEXT_PARAMS.map((name) => [name, rawSearchParam(search, name) ?? undefined])
+ return { ...searchParams, ...Object.fromEntries(textParams) }
+}
+
+function toDrawerParams(row: TraceListRow | null): Record<string, string | undefined> {
+ return { trace: row?.traceId, ts: row?.timestamp ?? undefined, step: row?.stepId ?? undefined }
+}
+
+let isDrawerWriting = false
+
+function writeUrlParams(method: 'push' | 'replace', changes: Record<string, string | undefined>): void {
+ const { pathname, search } = router.values.location
+ isDrawerWriting = true
+ try {
+ router.actions[method](
+ pathname,
+ { ...withTextParams(router.values.searchParams, search), ...changes },
+ router.values.hashParams
+ )
+ } finally {
+ isDrawerWriting = false
+ }
+}
+
+// Other logics write the router's decoded params back to the URL, and the router decodes `1.50` as the number 1.5.
+// The drawer's own writes and browser history moves are navigation, even between ids such as `01` and `1`.
+function isNumberRewriteOf(current: TraceListRow, previous: TraceListRow): boolean {
+ if (isDrawerWriting || router.values.lastMethod === 'POP') {
+ return false
+ }
+ const pairs = [
+ [previous.traceId, current.traceId],
+ [previous.stepId, current.stepId],
+ ]
+ return (
+ pairs.some(([before, after]) => before !== after) &&
+ pairs.every(([before, after]) => before === after || (before !== null && String(Number(before)) === after))
+ )
+}
+
+function trackDrawerClosed(cache: Record<string, any>): void {
+ if (cache.stepsTaken === undefined) {
+ return
+ }
+ posthog.capture('llma trace drawer closed', { steps: cache.stepsTaken })
+ cache.stepsTaken = undefined
+ cache.disposables.dispose(CLOSE_ON_ESCAPE_DISPOSABLE)
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceDrawerLogicValues {
+ requestedStepId: string | null // traceViewHostLogic
+ activeView: TraceViewChoice // traceViewPreferenceLogic
+ fullPageHref: string | null
+ hostId: string
+ isEnabled: boolean
+ nextTrace: TraceListRow | null
+ openIndex: number
+ openRef: TraceListRow | null
+ openTraceId: string | null
+ position: TraceDrawerPosition | null
+ previousTrace: TraceListRow | null
+ rows: TraceListRow[]
+ traces: TraceListRow[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceDrawerLogicActions {
+ requestStep: (stepId: string | null) => {
+ stepId: string | null
+ } // traceViewHostLogic
+ setDetailTab: (tab: import('./types').NodeDetailTab) => {
+ tab: import('./types').NodeDetailTab
+ } // traceViewHostLogic
+ setMode: (mode: import('./types').TraceMode) => {
+ mode: import('./types').TraceMode
+ } // traceViewHostLogic
+ close: () => {
+ value: true
+ }
+ openRow: (row: TraceListRow) => {
+ row: TraceListRow
+ }
+ setRows: (rows: TraceListRow[]) => {
+ rows: TraceListRow[]
+ }
+ stepTo: (direction: TraceStepDirection) => {
+ direction: TraceStepDirection
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceDrawerLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ hostId: (listId: string) => string
+ isEnabled: (activeView: TraceViewChoice) => boolean
+ openRef: (location: { hash: string; pathname: string; search: string }) => TraceListRow | null
+ openTraceId: (openRef: TraceListRow | null) => string | null
+ traces: (rows: TraceListRow[]) => TraceListRow[]
+ openIndex: (traces: TraceListRow[], openTraceId: string | null) => number
+ position: (traces: TraceListRow[], openIndex: number) => TraceDrawerPosition | null
+ previousTrace: (traces: TraceListRow[], openIndex: number) => TraceListRow | null
+ nextTrace: (traces: TraceListRow[], openIndex: number) => TraceListRow | null
+ fullPageHref: (
+ openRef: TraceListRow | null,
+ requestedStepId: string | null,
+ searchParams: Record<string, any>,
+ location: {
+ hash: string
+ pathname: string
+ search: string
+ }
+ ) => string | null
+ }
+}
+
+export type traceDrawerLogicType = MakeLogicType<
+ traceDrawerLogicValues,
+ traceDrawerLogicActions,
+ TraceDrawerLogicProps,
+ traceDrawerLogicMeta
+>
+
+export const traceDrawerLogic = kea<traceDrawerLogicType>([
+ path((key) => ['products', 'ai_observability', 'frontend', 'redesign', 'trace', 'traceDrawerLogic', key]),
+ props({} as TraceDrawerLogicProps),
+ key((props) => props.listId),
+ connect((props: TraceDrawerLogicProps) => ({
+ values: [
+ traceViewHostLogic({ hostId: traceDrawerHostId(props.listId) }),
+ ['requestedStepId'],
+ traceViewPreferenceLogic,
+ ['activeView'],
+ ],
+ actions: [
+ traceViewHostLogic({ hostId: traceDrawerHostId(props.listId) }),
+ ['requestStep', 'setMode', 'setDetailTab'],
+ ],
+ })),
+ actions({
+ setRows: (rows: TraceListRow[]) => ({ rows }),
+ openRow: (row: TraceListRow) => ({ row }),
+ stepTo: (direction: TraceStepDirection) => ({ direction }),
+ close: true,
+ }),
+ reducers({
+ rows: [
+ [] as TraceListRow[],
+ {
+ setRows: (_, { rows }) => rows,
+ },
+ ],
+ }),
+ selectors({
+ hostId: [(_, p) => [p.listId], (listId: string): string => traceDrawerHostId(listId)],
+ isEnabled: [(s) => [s.activeView], (activeView: TraceViewChoice): boolean => activeView === 'new'],
+ openRef: [
+ () => [router.selectors.location],
+ ({ pathname, search }: { pathname: string; search: string }): TraceListRow | null => {
+ const traceId = isAIObservabilityPath(pathname) ? rawSearchParam(search, 'trace') : null
+ return traceId
+ ? { traceId, timestamp: rawSearchParam(search, 'ts'), stepId: rawSearchParam(search, 'step') }
+ : null
+ },
+ ],
+ openTraceId: [(s) => [s.openRef], (openRef: TraceListRow | null): string | null => openRef?.traceId ?? null],
+ traces: [(s) => [s.rows], (rows: TraceListRow[]): TraceListRow[] => uniqueTraces(rows)],
+ openIndex: [
+ (s) => [s.traces, s.openTraceId],
+ (traces: TraceListRow[], openTraceId: string | null): number =>
+ traces.findIndex(({ traceId }) => traceId === openTraceId),
+ ],
+ position: [
+ (s) => [s.traces, s.openIndex],
+ (traces: TraceListRow[], openIndex: number): TraceDrawerPosition | null =>
+ openIndex < 0 ? null : { index: openIndex, total: traces.length },
+ ],
+ previousTrace: [
+ (s) => [s.traces, s.openIndex],
+ (traces: TraceListRow[], openIndex: number): TraceListRow | null =>
+ openIndex < 0 ? null : (traces[openIndex - 1] ?? null),
+ ],
+ nextTrace: [
+ (s) => [s.traces, s.openIndex],
+ (traces: TraceListRow[], openIndex: number): TraceListRow | null =>
+ openIndex < 0 ? null : (traces[openIndex + 1] ?? null),
+ ],
+ fullPageHref: [
+ (s) => [s.openRef, s.requestedStepId, router.selectors.searchParams, router.selectors.location],
+ (
+ openRef: TraceListRow | null,
+ requestedStepId: string | null,
+ searchParams: Record<string, unknown>,
+ { search }: { search: string }
+ ): string | null =>
+ openRef &&
+ combineUrl(urls.aiObservabilityTrace(openRef.traceId), {
+ ...toFullPageListParams(withTextParams(searchParams, search)),
+ timestamp: openRef.timestamp ?? undefined,
+ event: requestedStepId ?? undefined,
+ back_to: 'traces',
+ }).url,
+ ],
+ }),
+ listeners(({ actions, cache, values }) => ({
+ openRow: ({ row }) => {
+ if (row.traceId !== values.openTraceId) {
+ writeUrlParams('push', toDrawerParams(row))
+ } else if (row.stepId !== null) {
+ // A row with no step of its own would otherwise clear the selected step.
+ actions.requestStep(row.stepId)
+ }
+ },
+ stepTo: ({ direction }) => {
+ const target = direction === 'next' ? values.nextTrace : values.previousTrace
+ if (target) {
+ cache.stepsTaken += 1
+ posthog.capture('llma trace drawer stepped', { direction })
+ writeUrlParams('push', toDrawerParams(target))
+ }
+ },
+ close: () => {
+ writeUrlParams('push', toDrawerParams(null))
+ },
+ requestStep: ({ stepId }) => {
+ if (values.openRef && values.openRef.stepId !== stepId) {
+ writeUrlParams('replace', { step: stepId ?? undefined })
+ }
+ },
+ })),
+ subscriptions(({ actions, cache, props, values }) => ({
+ openRef: (openRef: TraceListRow | null, previousRef: TraceListRow | null | undefined) => {
+ if (openRef && previousRef && isNumberRewriteOf(openRef, previousRef)) {
+ writeUrlParams('replace', toDrawerParams(previousRef))
+ return
+ }
+ actions.requestStep(openRef?.stepId ?? null)
+ if (!openRef) {
+ trackDrawerClosed(cache)
+ } else if (!values.isEnabled) {
+ router.actions.replace(
+ urls.aiObservabilityTrace(openRef.traceId, {
+ timestamp: openRef.timestamp ?? undefined,
+ event: openRef.stepId ?? undefined,
+ })
+ )
+ } else if (cache.stepsTaken === undefined) {
+ cache.stepsTaken = 0
+ actions.setMode('spans')
+ actions.setDetailTab('messages')
+ posthog.capture('llma trace drawer opened', { list: props.listId })
+ void addProductIntent({
+ product_type: ProductKey.AI_OBSERVABILITY,
+ intent_context: ProductIntentContext.LLM_ANALYTICS_TRACE_VIEWED,
+ })
+ // Viewing a trace implies AI events were sent.
+ globalSetupLogic
+ .findMounted()
+ ?.actions.markTaskAsCompleted([SetupTaskId.IngestFirstLlmEvent, SetupTaskId.ViewFirstTrace])
+ cache.disposables.add(() => {
+ const closeOnEscape = (event: KeyboardEvent): void => {
+ if (shouldCloseOnEscape(event)) {
+ actions.close()
+ }
+ }
+ document.addEventListener('keydown', closeOnEscape)
+ return () => document.removeEventListener('keydown', closeOnEscape)
+ }, CLOSE_ON_ESCAPE_DISPOSABLE)
+ }
+ },
+ })),
+ beforeUnmount(({ cache, values }) => {
+ if (values.openRef) {
+ trackDrawerClosed(cache)
+ writeUrlParams('replace', toDrawerParams(null))
+ }
+ }),
+])
diff --git a/products/ai_observability/frontend/redesign/trace/traceListRows.test.ts b/products/ai_observability/frontend/redesign/trace/traceListRows.test.ts
new file mode 100644
index 000000000000..36011fad07d1
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/traceListRows.test.ts
@@ -0,0 +1,13 @@
+import { TraceListRow, uniqueTraces } from './traceListRows'
+
+describe('traceListRows', () => {
+ it('keeps the first row of each trace, in order of first appearance', () => {
+ const rows: TraceListRow[] = [
+ { traceId: 'a', timestamp: null, stepId: 'x' },
+ { traceId: 'b', timestamp: null, stepId: null },
+ { traceId: 'a', timestamp: null, stepId: 'y' },
+ ]
+
+ expect(uniqueTraces(rows)).toEqual([rows[0], rows[1]])
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/traceListRows.ts b/products/ai_observability/frontend/redesign/trace/traceListRows.ts
new file mode 100644
index 000000000000..ac5f788f5c0e
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/traceListRows.ts
@@ -0,0 +1,15 @@
+export interface TraceListRow {
+ traceId: string
+ timestamp: string | null
+ stepId: string | null
+}
+
+export function uniqueTraces(rows: TraceListRow[]): TraceListRow[] {
+ const firstRowByTrace = new Map<string, TraceListRow>()
+ for (const row of rows) {
+ if (!firstRowByTrace.has(row.traceId)) {
+ firstRowByTrace.set(row.traceId, row)
+ }
+ }
+ return [...firstRowByTrace.values()]
+}
diff --git a/products/ai_observability/frontend/redesign/trace/tracePageLogic.ts b/products/ai_observability/frontend/redesign/trace/tracePageLogic.ts
index 2285893aca55..84440706bb93 100644
--- a/products/ai_observability/frontend/redesign/trace/tracePageLogic.ts
+++ b/products/ai_observability/frontend/redesign/trace/tracePageLogic.ts
@@ -19,6 +19,7 @@ import { urls } from 'scenes/urls'
import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
import { toBackLink } from './adapter/toBackLink'
+import { rawSearchParam } from './rawSearchParam'
import { traceViewHostLogic } from './traceViewHostLogic'
import type { LabeledLink } from './types'
@@ -28,11 +29,8 @@ const EXCEPTION_LOOKUP_WINDOW_MINUTES = 20
const LAYOUT_NAV_OVERRIDE_OWNER = 'ai-trace-page'
-// kea-router reads a numeric param as a number, which turns a typed `1.50` into `1.5`. It also pads a value shaped like
-// a JSON array or object with one space, so it reads that value back as a string.
function searchParamFromUrl(): string {
- const value = new URLSearchParams(router.values.location.search).get('search') ?? ''
- return /^(\[.*\]|\{.*\}) +$/.test(value) ? value.slice(0, -1) : value
+ return rawSearchParam(router.values.location.search, 'search') ?? ''
}
function replaceUrlParams(changes: Record<string, string | undefined>): void {