: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tracing): add the span inspector to the trace dialog (#116950)
Jon McCallumcfb2c74dc79c
diff --git a/products/tracing/frontend/components/SpanInspector/SpanInspector.tsx b/products/tracing/frontend/components/SpanInspector/SpanInspector.tsxnew file mode 100644index 000000000000..7cef3d4eef7a--- /dev/null+++ b/products/tracing/frontend/components/SpanInspector/SpanInspector.tsx@@ -0,0 +1,158 @@+import { useValues } from 'kea'++import { LemonTabs } from '@posthog/lemon-ui'++import { CodeSnippet, Language } from 'lib/components/CodeSnippet'+import { JSONViewer } from 'lib/components/JSONViewer'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'++import { isAiEventSpan } from '../../aiEventSpans'+import type { ErrorScope } from '../../errorCorrelation'+import { getQueryText } from '../../spanSummary'+import type { Span, SpanInspectorTab } from '../../types'+import { SpanLogsTab } from '../TraceDrawer/SpanLogsTab'+import { SpanMetricsTab } from '../TraceDrawer/SpanMetricsTab'+import { SpanSummaryHeader } from '../TraceDrawer/SpanSummaryHeader'+import { TraceErrorsTab } from '../TraceDrawer/TraceErrorsTab'+import { ExpandedSpanContent } from '../VirtualizedSpanList/ExpandedSpanContent'++export interface SpanInspectorProps {+ span: Span+ /** Shared with the waterfall so a service is the same color in the bars and the summary header. */+ serviceColorMap: Map<string, number>+ /** Anchors the window the Errors tab's exceptions must fall in: the trace start where known. */+ traceTimestamp: string | null+ /** The trace's session for the Errors tab, or null when its spans resolve to no one session. */+ sessionId: string | null+ /** Show the Errors tab, which lists the issues connected to the trace. */+ showErrorsTab: boolean+ /** The scope the Errors tab opens on, when the caller named one. */+ errorsScope: ErrorScope | null+ /** The spans the session is resolved from are still arriving. */+ resolving: boolean+ tab: SpanInspectorTab+ onSelectTab: (tab: SpanInspectorTab) => void+ /** Offer include, exclude and column actions on each attribute. Off where no span list can use them. */+ showFilterActions?: boolean+}++export function SpanInspector({+ span,+ serviceColorMap,+ traceTimestamp,+ sessionId,+ showErrorsTab,+ errorsScope,+ resolving,+ tab,+ onSelectTab,+ showFilterActions = true,+}: SpanInspectorProps): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)++ // Metrics correlate to a trace via exemplars, so the tab only exists where the metrics+ // product does: its own flag, plus the metrics feature and view access.+ const showMetricsTab =+ !!featureFlags[FEATURE_FLAGS.TRACING_METRICS_TAB] && !!featureFlags[FEATURE_FLAGS.METRICS] && canViewMetrics()++ // Only DB spans carry a query; the Query tab appears only when one is present.+ const queryText = getQueryText(span)+ // The Query, Errors and Metrics tabs are conditional, so if the active tab disappears (a span+ // without a query, or one of the gates turning off), fall back to Attributes. Otherwise+ // activeKey would point at a tab LemonTabs has dropped and the inspector body would render+ // blank. Preference is preserved: a DB span re-shows Query.+ const activeTab: SpanInspectorTab =+ (tab === 'query' && !queryText) ||+ (tab === 'metrics' && !showMetricsTab) ||+ (tab === 'errors' && !showErrorsTab)+ ? 'attributes'+ : tab++ return (+ <>+ <SpanSummaryHeader span={span} serviceColorMap={serviceColorMap} />+ <LemonTabs+ activeKey={activeTab}+ onChange={onSelectTab}+ data-attr="tracing-inspector-tabs"+ tabs={[+ {+ key: 'attributes',+ label: 'Attributes',+ // The summary header carries the headline facts, so the tab+ // shows only the user attributes (no duplicate details table).+ content: (+ <ExpandedSpanContent+ span={span}+ showDetails={false}+ showFilterActions={showFilterActions}+ />+ ),+ },+ // Conditional (LemonTabs ignores falsy entries): only DB spans have a query.+ queryText+ ? {+ key: 'query',+ label: 'Query',+ content: (+ <CodeSnippet language={Language.SQL} wrap maxLinesWithoutExpansion={40}>+ {queryText}+ </CodeSnippet>+ ),+ }+ : null,+ {+ key: 'logs',+ label: 'Logs',+ // Keyed by trace, not span: a new trace remounts to reset the scope toggle+ // back to whole-trace, while selecting another span within the same trace+ // re-queries in place (the embedded viewer and memoized pinned filter handle+ // it) so we don't churn its logics or lose scroll.+ content: <SpanLogsTab key={span.trace_id} span={span} />,+ },+ // Conditional on its own flag. The tab is session-scoped, so it+ // stays available on a trace that resolved no session and+ // explains there what is missing.+ showErrorsTab+ ? {+ key: 'errors',+ label: 'Errors',+ content: (+ <TraceErrorsTab+ key={span.span_id}+ traceId={span.trace_id}+ // A synthetic AI row has no OTel span id, so it scopes to the trace.+ spanId={isAiEventSpan(span) ? null : span.span_id}+ timestamp={traceTimestamp}+ sessionId={sessionId}+ initialScope={errorsScope}+ resolving={resolving}+ />+ ),+ }+ : null,+ // Conditional: needs the metrics product (flag + access) and its own flag.+ showMetricsTab+ ? {+ key: 'metrics',+ label: 'Metrics',+ // Keyed by trace like the Logs tab: a new trace remounts to reset+ // the scope toggle; selecting another span re-renders in place.+ content: <SpanMetricsTab key={span.trace_id} span={span} />,+ }+ : null,+ {+ key: 'raw',+ label: 'Raw',+ // Interactive tree, matching the logs viewer's raw view (LogDetailsModal)+ // for cross-pane consistency. The span as the frontend holds it.+ content: <JSONViewer src={span} collapsed={2} sortKeys />,+ },+ ]}+ />+ </>+ )+}diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialog.tsxindex f7b2f9d8735c..73f2cee4a9e9 100644--- a/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx+++ b/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx@@ -1,20 +1,39 @@import { useActions, useValues } from 'kea'+import { useCallback, useState } from 'react'import { IconExternal } from '@posthog/icons'import { LemonBanner, LemonButton, LemonModal, LemonTag, Spinner } from '@posthog/lemon-ui'import { traceUrl } from 'lib/components/ViewTraceButton/traceUrl'+import { FloatingContainerContext } from 'lib/hooks/useFloatingContainerContext'import { pluralize } from 'lib/utils/strings'+import { SpanInspector } from 'products/tracing/frontend/components/SpanInspector/SpanInspector'+import { MissingParentSpanNotice } from 'products/tracing/frontend/components/TraceDrawer/MissingParentSpanNotice'import { formatDuration } from 'products/tracing/frontend/TraceWaterfallView'import { traceDialogLogic } from './traceDialogLogic'import { TraceDialogSpanTree } from './TraceDialogSpanTree'export function TraceDialog(): JSX.Element | null {- const { isOpen, trace, traceSpans, traceSpansLoading, traceSpansFailed, summary, timeline } =- useValues(traceDialogLogic)- const { closeTraceDialog, loadTraceSpans } = useActions(traceDialogLogic)+ const {+ isOpen,+ trace,+ traceSpans,+ traceSpansLoading,+ traceSpansFailed,+ summary,+ timeline,+ selectedSpan,+ missingParentSpanId,+ serviceColorMap,+ activeInspectorTab,+ sessionErrorBadgesEnabled,+ } = useValues(traceDialogLogic)+ const { closeTraceDialog, loadTraceSpans, setInspectorTab } = useActions(traceDialogLogic)+ // The dialog sits above popovers, so the inspector's menus and drawers portal inside it instead.+ const [floatingContainer, setFloatingContainer] = useState<HTMLDivElement | null>(null)+ const floatingContainerRef = useCallback((el: HTMLDivElement | null) => setFloatingContainer(el), [])if (!trace) {return null@@ -58,35 +77,69 @@ export function TraceDialog(): JSX.Element | null {</LemonButton>}>- {/* The span list virtualizes, so it needs a definite height to measure against. */}- <div className="flex flex-col gap-2 h-[65vh]">- {traceSpans?.truncated && (- <LemonBanner type="info">- Showing the first {summary.spanCount.toLocaleString()} spans. Open this trace in Tracing to see- all of them.- </LemonBanner>- )}- {traceSpansLoading ? (- <div className="flex flex-1 items-center justify-center">- <Spinner className="text-2xl" />- </div>- ) : traceSpansFailed ? (- <div className="flex flex-1 flex-col items-center justify-center gap-2">- <span>Couldn't load this trace.</span>- <LemonButton type="secondary" onClick={() => loadTraceSpans(trace)}>- Try again- </LemonButton>- </div>- ) : !traceSpans || traceSpans.spans.length === 0 ? (- <div className="flex flex-1 items-center justify-center text-muted">- No spans found for this trace. Open it in Tracing to search other time ranges.- </div>- ) : (- <div className="flex-1 min-h-0">- <TraceDialogSpanTree />- </div>- )}- </div>+ <FloatingContainerContext.Provider value={floatingContainer}>+ {/* The span list virtualizes, so it needs a definite height to measure against. */}+ <div className="flex flex-col gap-2 h-[65vh]">+ {traceSpans?.truncated && (+ <LemonBanner type="info">+ Showing the first {summary.spanCount.toLocaleString()} spans. Open this trace in Tracing to+ see all of them.+ </LemonBanner>+ )}+ {traceSpansLoading ? (+ <div className="flex flex-1 items-center justify-center">+ <Spinner className="text-2xl" />+ </div>+ ) : traceSpansFailed ? (+ <div className="flex flex-1 flex-col items-center justify-center gap-2">+ <span>Couldn't load this trace.</span>+ <LemonButton type="secondary" onClick={() => loadTraceSpans(trace)}>+ Try again+ </LemonButton>+ </div>+ ) : !traceSpans || traceSpans.spans.length === 0 ? (+ <div className="flex flex-1 items-center justify-center text-muted">+ No spans found for this trace. Open it in Tracing to search other time ranges.+ </div>+ ) : (+ <div className="@container/trace-dialog flex flex-1 min-h-0">+ <div className="flex flex-1 min-w-0 min-h-0 flex-col @min-[56rem]/trace-dialog:flex-row">+ <div className="flex-1 min-w-0 min-h-0">+ <TraceDialogSpanTree />+ </div>+ {(missingParentSpanId || selectedSpan) && (+ <div+ className="flex-1 min-h-0 overflow-y-auto border-t pt-4 @min-[56rem]/trace-dialog:flex-none @min-[56rem]/trace-dialog:w-2/5 @min-[56rem]/trace-dialog:border-t-0 @min-[56rem]/trace-dialog:border-l @min-[56rem]/trace-dialog:pt-0 @min-[56rem]/trace-dialog:pl-4"+ data-attr="trace-dialog-inspector"+ >+ {missingParentSpanId ? (+ <MissingParentSpanNotice+ traceId={trace.traceId}+ parentSpanId={missingParentSpanId}+ />+ ) : selectedSpan ? (+ <SpanInspector+ span={selectedSpan}+ serviceColorMap={serviceColorMap}+ traceTimestamp={summary.rootSpan?.timestamp ?? selectedSpan.timestamp}+ sessionId={null}+ showErrorsTab={sessionErrorBadgesEnabled}+ errorsScope="span"+ resolving={false}+ tab={activeInspectorTab}+ onSelectTab={setInspectorTab}+ // The dialog has no span list for an attribute filter to narrow.+ showFilterActions={false}+ />+ ) : null}+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ <div ref={floatingContainerRef} />+ </FloatingContainerContext.Provider></LemonModal>)}diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsxindex 909fe835fdb7..34024feeb353 100644--- a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx@@ -67,8 +67,17 @@ function SpanListRow({}export function TraceDialogSpanTree(): JSX.Element {- const { spanRows, spanTree, collapsedSpanIds, timeline, serviceColorMap, selectedSpanId, trace, openedAtUs } =- useValues(traceDialogLogic)+ const {+ spanRows,+ spanTree,+ collapsedSpanIds,+ timeline,+ serviceColorMap,+ selectedSpan,+ missingParentSpanId,+ trace,+ openedAtUs,+ } = useValues(traceDialogLogic)const { selectSpan, toggleSpanCollapsed, showAllChildren } = useActions(traceDialogLogic)const listRef = useListRef(null)const openedSpanId = trace?.spanId ?? null@@ -134,7 +143,7 @@ export function TraceDialogSpanTree(): JSX.Element {collapsedSpanIds,timeline,serviceColorMap,- selectedSpanId,+ selectedSpanId: missingParentSpanId ?? selectedSpan?.span_id ?? null,openedSpanId,openedAtUs,onSelect: selectSpan,diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.tsindex 9963b6ed5e42..7814f28bb439 100644--- a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts@@ -2,16 +2,21 @@ import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'import { initKeaTests } from '~/test/init'+import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'+import { logsViewerModalLogic } from 'products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic'import type { Span } from 'products/tracing/frontend/types'import { traceDialogLogic } from './traceDialogLogic'type TracePage = Awaited<ReturnType<typeof api.tracing.getTrace>>-function span(spanId: string): Span {+function span(spanId: string, statusCode = 0): Span {return {uuid: spanId,trace_id: 'abc123',@@ -20,7 +25,7 @@ function span(spanId: string): Span {name: spanId,kind: 0,service_name: 'agent-worker',- status_code: 0,+ status_code: statusCode,timestamp: '2026-10-14T10:00:00.000000Z',end_time: '2026-10-14T10:00:01.000000Z',duration_nano: 1_000_000_000,@@ -40,7 +45,16 @@ describe('traceDialogLogic', () => {let getTraceSpy: jest.SpyInstancebeforeEach(() => {+ window.POSTHOG_APP_CONTEXT = {+ ...window.POSTHOG_APP_CONTEXT,+ resource_access_control: {+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,+ [AccessControlResourceType.ErrorTracking]: AccessControlLevel.Viewer,+ },+ } as AppContextinitKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TRACING_SPAN_ERROR_BADGES]: true })getTraceSpy = jest.spyOn(api.tracing, 'getTrace').mockResolvedValue(page(['a'], null))router.actions.push('/logs')logic = traceDialogLogic()@@ -170,4 +184,58 @@ describe('traceDialogLogic', () => {.toDispatchActions(['loadTraceSpansSuccess']).toMatchValues({ traceSpansFailed: false })})++ it.each([+ ['leads with errors on an error span', 2, 'errors'],+ ['leads with logs on any other span', 0, 'logs'],+ ])('%s', async (_name, statusCode, expectedTab) => {+ getTraceSpy.mockResolvedValueOnce({ results: [span('a', statusCode)], hasMore: false, nextOffset: null })++ await expectLogic(logic, () => {+ logic.actions.openTraceDialog({ traceId: 'abc123', spanId: 'a' })+ })+ .toDispatchActions(['loadTraceSpansSuccess'])+ .toMatchValues({ activeInspectorTab: expectedTab })+ })++ it('keeps a picked tab across spans, and drops it for the next trace', async () => {+ getTraceSpy.mockResolvedValue({ results: [span('a', 2), span('b')], hasMore: false, nextOffset: null })+ logic.actions.openTraceDialog({ traceId: 'abc123', spanId: 'a' })+ await expectLogic(logic).toDispatchActions(['loadTraceSpansSuccess'])++ logic.actions.setInspectorTab('attributes')+ await expectLogic(logic, () => {+ logic.actions.selectSpan('b')+ }).toMatchValues({ activeInspectorTab: 'attributes' })++ await expectLogic(logic, () => {+ logic.actions.openTraceDialog({ traceId: 'def456', spanId: 'a' })+ })+ .toDispatchActions(['loadTraceSpansSuccess'])+ .toMatchValues({ activeInspectorTab: 'errors' })+ })++ it('treats a missing parent row as its own selection, not the root span', async () => {+ const orphan = { ...span('child'), parent_span_id: 'GONE' }+ getTraceSpy.mockResolvedValueOnce({ results: [span('a'), orphan], hasMore: false, nextOffset: null })+ logic.actions.openTraceDialog({ traceId: 'abc123', spanId: 'a' })+ await expectLogic(logic).toDispatchActions(['loadTraceSpansSuccess'])++ await expectLogic(logic, () => {+ logic.actions.selectSpan('GONE')+ }).toMatchValues({ missingParentSpanId: 'GONE' })++ await expectLogic(logic, () => {+ logic.actions.selectSpan('child')+ }).toMatchValues({ missingParentSpanId: null })+ })++ it.each([+ ['a recording opens', () => sessionPlayerModalLogic.actions.openSessionPlayer({ id: 'session-1' })],+ ['the full-screen logs viewer opens', () => logsViewerModalLogic.actions.openLogsViewerModal()],+ ])('closes when %s, since that modal sits behind the dialog', async (_name, open) => {+ logic.actions.openTraceDialog({ traceId: 'abc123' })++ await expectLogic(logic, open).toMatchValues({ isOpen: false })+ })})diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.tsindex 3428f4e1a25e..5e4eb1d406bd 100644--- a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts@@ -9,11 +9,23 @@ import { usableId } from 'lib/components/ViewTraceButton/usableId'import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'+import {+ type SessionPlayerModalContext,+ sessionPlayerModalLogic,+} from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'+import type { SessionRecordingType, UniversalFiltersGroup } from '~/types'++import type { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'+import {+ type OpenLogsViewerModalOptions,+ logsViewerModalLogic,+} from 'products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic'import { buildSpanTree, parseTimestampUs, type SpanNode } from 'products/tracing/frontend/spanTree'import { resolveTraceLookupRange } from 'products/tracing/frontend/traceLinks'import { buildServiceColorMap } from 'products/tracing/frontend/TraceWaterfallView'-import type { Span } from 'products/tracing/frontend/types'+import { tracingCorrelationConfigLogic } from 'products/tracing/frontend/tracingCorrelationConfigLogic'+import type { Span, SpanInspectorTab } from 'products/tracing/frontend/types'import { buildTraceDialogRows, countDescendantsById, type TraceDialogRow } from './traceDialogRows'@@ -56,12 +68,17 @@ export interface TraceDialogSummary {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface traceDialogLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic+ sessionErrorBadgesEnabled: boolean // tracingCorrelationConfigLogic+ activeInspectorTab: SpanInspectorTab+ chosenInspectorTab: SpanInspectorTab | nullcollapsedSpanIds: Set<string>dialogEnabled: booleanflatSpans: SpanNode[]fullChildListSpanIds: Set<string>isOpen: boolean+ missingParentSpanId: string | nullopenedAtUs: number | null+ selectedSpan: Span | nullselectedSpanId: string | nullserviceColorMap: Map<string, number>spanRows: TraceDialogRow[]@@ -76,6 +93,14 @@ export interface traceDialogLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface traceDialogLogicActions {+ openLogsViewerModal: (options?: OpenLogsViewerModalOptions | undefined) => {+ fullScreen: boolean+ id: string+ initialFilters: Partial<LogsViewerFilters> | null+ personId: string | null+ pinnedFilters: UniversalFiltersGroup | null+ sessionId: string | null+ } // logsViewerModalLogiclocationChanged: ({method,pathname,@@ -97,6 +122,15 @@ export interface traceDialogLogicActions {searchParams: Record<string, any>url: string} // router+ openSessionPlayer: (+ sessionRecording: Pick<SessionRecordingType, 'id' | 'matching_events'>,+ initialTimestamp?: number | null | undefined,+ modalContext?: SessionPlayerModalContext | undefined+ ) => {+ initialTimestamp: number | null+ modalContext: SessionPlayerModalContext+ sessionRecording: Pick<SessionRecordingType, 'id' | 'matching_events'>+ } // sessionPlayerModalLogiccloseTraceDialog: () => {value: true}@@ -125,6 +159,9 @@ export interface traceDialogLogicActions {selectSpan: (spanId: string) => {spanId: string}+ setInspectorTab: (tab: SpanInspectorTab) => {+ tab: SpanInspectorTab+ }showAllChildren: (spanId: string) => {spanId: string}@@ -145,6 +182,17 @@ export interface traceDialogLogicMeta {trace: TraceLinkParams | null) => TraceDialogRow[]flatSpans: (spanRows: TraceDialogRow[]) => SpanNode[]+ selectedSpan: (+ traceSpans: TraceDialogSpans | null,+ selectedSpanId: string | null,+ summary: TraceDialogSummary+ ) => Span | null+ missingParentSpanId: (traceSpans: TraceDialogSpans | null, selectedSpanId: string | null) => string | null+ activeInspectorTab: (+ chosenInspectorTab: SpanInspectorTab | null,+ selectedSpan: Span | null,+ sessionErrorBadgesEnabled: boolean+ ) => SpanInspectorTabserviceColorMap: (traceSpans: TraceDialogSpans | null) => Map<string, number>timeline: (traceSpans: TraceDialogSpans | null) => TraceDialogTimelinesummary: (traceSpans: TraceDialogSpans | null) => TraceDialogSummary@@ -162,8 +210,15 @@ export type traceDialogLogicType = MakeLogicType<export const traceDialogLogic = kea<traceDialogLogicType>([path(['products', 'tracing', 'frontend', 'components', 'TraceDialog', 'traceDialogLogic']),connect(() => ({- actions: [router, ['locationChanged']],- values: [featureFlagLogic, ['featureFlags']],+ actions: [+ router,+ ['locationChanged'],+ sessionPlayerModalLogic,+ ['openSessionPlayer'],+ logsViewerModalLogic,+ ['openLogsViewerModal'],+ ],+ values: [tracingCorrelationConfigLogic, ['sessionErrorBadgesEnabled'], featureFlagLogic, ['featureFlags']],})),actions({openTraceDialog: (trace: TraceLinkParams) => ({ trace: { ...trace, spanId: inApiCase(trace.spanId) } }),@@ -171,6 +226,7 @@ export const traceDialogLogic = kea<traceDialogLogicType>([selectSpan: (spanId: string) => ({ spanId }),toggleSpanCollapsed: (spanId: string) => ({ spanId }),showAllChildren: (spanId: string) => ({ spanId }),+ setInspectorTab: (tab: SpanInspectorTab) => ({ tab }),}),loaders(({ values }) => ({traceSpans: [@@ -260,6 +316,15 @@ export const traceDialogLogic = kea<traceDialogLogicType>([showAllChildren: (shown, { spanId }) => new Set(shown).add(spanId),},],+ // A tab the person picked sticks while they move between spans. Until they pick one, the+ // inspector chooses for the span in view.+ chosenInspectorTab: [+ null as SpanInspectorTab | null,+ {+ openTraceDialog: () => null,+ setInspectorTab: (_, { tab }) => tab,+ },+ ],}),selectors({// Every entry point checks this one place, so the flag cannot open the dialog from some@@ -303,6 +368,36 @@ export const traceDialogLogic = kea<traceDialogLogicType>([(spanRows: TraceDialogRow[]): SpanNode[] =>spanRows.flatMap((row) => (row.kind === 'span' ? [row.node] : [])),],+ selectedSpan: [+ (s) => [s.traceSpans, s.selectedSpanId, s.summary],+ (+ traceSpans: TraceDialogSpans | null,+ selectedSpanId: string | null,+ summary: TraceDialogSummary+ ): Span | null =>+ traceSpans?.spans.find((span) => span.span_id === selectedSpanId) ??+ summary.rootSpan ??+ traceSpans?.spans[0] ??+ null,+ ],+ // The tree's "<parent span missing>" row selects an id that only appears as a parent id.+ missingParentSpanId: [+ (s) => [s.traceSpans, s.selectedSpanId],+ (traceSpans: TraceDialogSpans | null, selectedSpanId: string | null): string | null =>+ selectedSpanId &&+ traceSpans &&+ !traceSpans.spans.some((span) => span.span_id === selectedSpanId) &&+ traceSpans.spans.some((span) => span.parent_span_id === selectedSpanId)+ ? selectedSpanId+ : null,+ ],+ activeInspectorTab: [+ (s) => [s.chosenInspectorTab, s.selectedSpan, s.sessionErrorBadgesEnabled],+ // An error span leads with its exceptions. Otherwise the logs lead, since the dialog+ // opens from a log.+ (chosen: SpanInspectorTab | null, selectedSpan: Span | null, errorsTabEnabled: boolean): SpanInspectorTab =>+ chosen ?? (errorsTabEnabled && selectedSpan?.status_code === 2 ? 'errors' : 'logs'),+ ],serviceColorMap: [(s) => [s.traceSpans],(traceSpans: TraceDialogSpans | null): Map<string, number> => buildServiceColorMap(traceSpans?.spans ?? []),@@ -357,6 +452,18 @@ export const traceDialogLogic = kea<traceDialogLogicType>([}}},+ // The player and the full-screen logs viewer are global modals that can sit below this one,+ // so opening either from the inspector would put it behind the dialog.+ openSessionPlayer: () => {+ if (values.isOpen) {+ actions.closeTraceDialog()+ }+ },+ openLogsViewerModal: () => {+ if (values.isOpen) {+ actions.closeTraceDialog()+ }+ },locationChanged: ({ pathname }) => {// Query and hash changes fire locationChanged too, so only a new pathname closes the dialog.if (pathname === cache.lastPathname) {diff --git a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsxindex eeee6bb840f6..83868bd51c23 100644--- a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx+++ b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx@@ -1,37 +1,26 @@import { useActions, useValues } from 'kea'import { useMemo, useRef } from 'react'-import { LemonBanner, LemonButton, LemonTabs, LemonTag, SpinnerOverlay } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonTag, SpinnerOverlay } from '@posthog/lemon-ui'-import { CodeSnippet, Language } from 'lib/components/CodeSnippet'-import { JSONViewer } from 'lib/components/JSONViewer'import { Resizer } from 'lib/components/Resizer/Resizer'import { type ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'-import { FEATURE_FLAGS } from 'lib/constants'import { IconLink } from 'lib/lemon-ui/icons'import { LemonDrawer } from 'lib/lemon-ui/LemonDrawer/LemonDrawer'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { cn } from 'lib/utils/css-classes'-import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'--import { buildAiEventSpans, isAiEventSpan } from '../../aiEventSpans'+import { buildAiEventSpans } from '../../aiEventSpans'import type { ErrorScope } from '../../errorCorrelation'import { useKeepMountedWhileOpen } from '../../hooks/useKeepMountedWhileOpen'-import { getQueryText } from '../../spanSummary'import type { TraceIdentity } from '../../traceIdentity'import { absoluteTraceUrl } from '../../traceLinks'import { buildServiceColorMap, formatDuration, TraceWaterfallView } from '../../TraceWaterfallView'import type { Span, SpanInspectorTab } from '../../types'-import { ExpandedSpanContent } from '../VirtualizedSpanList/ExpandedSpanContent'+import { SpanInspector } from '../SpanInspector/SpanInspector'import { MissingParentSpanNotice } from './MissingParentSpanNotice'-import { SpanLogsTab } from './SpanLogsTab'-import { SpanMetricsTab } from './SpanMetricsTab'-import { SpanSummaryHeader } from './SpanSummaryHeader'import { TraceAiEventsCapNotice } from './TraceAiEventsCapNotice'import { traceAiEventsLogic } from './traceAiEventsLogic'-import { TraceErrorsTab } from './TraceErrorsTab'import { TraceIdentityChips } from './TraceIdentityChips'import { TraceLoadErrorNotice } from './TraceLoadErrorNotice'import { TraceUnavailableNotice } from './TraceUnavailableNotice'@@ -130,13 +119,6 @@ export function TraceDrawer({persistent: true,}const { desiredSize: inspectorWidth } = useValues(resizerLogic(inspectorResizerProps))- const { featureFlags } = useValues(featureFlagLogic)-- // Metrics correlate to a trace via exemplars, so the tab only exists where the metrics- // product does: its own flag, plus the metrics feature and view access.- const showMetricsTab =- !!featureFlags[FEATURE_FLAGS.TRACING_METRICS_TAB] && !!featureFlags[FEATURE_FLAGS.METRICS] && canViewMetrics()-// Resolve the inspected span outside render churn: a resize drag re-renders this component on// every mousemove, and these scans are O(spans) — memoize so they only run when data/selection change.const rootSpan = useMemo(() => spans.find((span) => span.is_root_span) ?? spans[0] ?? null, [spans])@@ -164,19 +146,6 @@ export function TraceDrawer({return null}- // Only DB spans carry a query; the Query tab appears only when one is present.- const queryText = inspectedSpan ? getQueryText(inspectedSpan) : null- // The Query, Errors and Metrics tabs are conditional, so if the active tab disappears (a span- // without a query, or one of the gates turning off), fall back to Attributes. Otherwise- // activeKey would point at a tab LemonTabs has dropped and the inspector body would render- // blank. Preference is preserved: a DB span re-shows Query.- const activeInspectorTab: SpanInspectorTab =- (inspectorTab === 'query' && !queryText) ||- (inspectorTab === 'metrics' && !showMetricsTab) ||- (inspectorTab === 'errors' && !showErrorsTab)- ? 'attributes'- : inspectorTab-return (<LemonDrawerisOpen={isOpen}@@ -255,97 +224,17 @@ export function TraceDrawer({{missingParentSpanId ? (<MissingParentSpanNotice traceId={traceId ?? ''} parentSpanId={missingParentSpanId} />) : inspectedSpan ? (- <>- <SpanSummaryHeader span={inspectedSpan} serviceColorMap={serviceColorMap} />- <LemonTabs- activeKey={activeInspectorTab}- onChange={onSelectInspectorTab}- data-attr="tracing-inspector-tabs"- tabs={[- {- key: 'attributes',- label: 'Attributes',- // The summary header carries the headline facts, so the tab- // shows only the user attributes (no duplicate details table).- content: <ExpandedSpanContent span={inspectedSpan} showDetails={false} />,- },- // Conditional (LemonTabs ignores falsy entries): only DB spans have a query.- queryText- ? {- key: 'query',- label: 'Query',- content: (- <CodeSnippet- language={Language.SQL}- wrap- maxLinesWithoutExpansion={40}- >- {queryText}- </CodeSnippet>- ),- }- : null,- {- key: 'logs',- label: 'Logs',- // Keyed by trace, not span: a new trace remounts to reset the scope toggle- // back to whole-trace, while selecting another span within the same trace- // re-queries in place (the embedded viewer and memoized pinned filter handle- // it) so we don't churn its logics or lose scroll.- content: <SpanLogsTab key={inspectedSpan.trace_id} span={inspectedSpan} />,- },- // Conditional on its own flag. The tab is session-scoped, so it- // stays available on a trace that resolved no session and- // explains there what is missing.- showErrorsTab- ? {- key: 'errors',- label: 'Errors',- content: (- <TraceErrorsTab- key={inspectedSpan.span_id}- traceId={inspectedSpan.trace_id}- // A synthetic AI row has no OTel span id, so it scopes to the trace.- spanId={- isAiEventSpan(inspectedSpan)- ? null- : inspectedSpan.span_id- }- timestamp={- rootSpan?.timestamp ?? inspectedSpan.timestamp ?? ts- }- sessionId={sessionId}- initialScope={errorsScope}- resolving={loading}- />- ),- }- : null,- // Conditional: needs the metrics product (flag + access) and its own flag.- showMetricsTab- ? {- key: 'metrics',- label: 'Metrics',- // Keyed by trace like the Logs tab: a new trace remounts to reset- // the scope toggle; selecting another span re-renders in place.- content: (- <SpanMetricsTab- key={inspectedSpan.trace_id}- span={inspectedSpan}- />- ),- }- : null,- {- key: 'raw',- label: 'Raw',- // Interactive tree, matching the logs viewer's raw view (LogDetailsModal)- // for cross-pane consistency. The span as the frontend holds it.- content: <JSONViewer src={inspectedSpan} collapsed={2} sortKeys />,- },- ]}- />- </>+ <SpanInspector+ span={inspectedSpan}+ serviceColorMap={serviceColorMap}+ traceTimestamp={rootSpan?.timestamp ?? inspectedSpan.timestamp ?? ts}+ sessionId={sessionId}+ showErrorsTab={showErrorsTab}+ errorsScope={errorsScope}+ resolving={loading}+ tab={inspectorTab}+ onSelectTab={onSelectInspectorTab}+ />) : (<div className="text-muted p-4">No spans in this trace</div>)}diff --git a/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx b/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsxindex 6702aaac2f11..eab0d0f7dc43 100644--- a/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx+++ b/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx@@ -13,9 +13,15 @@ export interface ExpandedSpanContentProps {* already surfaces these facts, so it passes false. @default true*/showDetails?: boolean+ /** Offer include, exclude and column actions on each attribute. @default true */+ showFilterActions?: boolean}-export function ExpandedSpanContent({ span, showDetails = true }: ExpandedSpanContentProps): JSX.Element {+export function ExpandedSpanContent({+ span,+ showDetails = true,+ showFilterActions = true,+}: ExpandedSpanContentProps): JSX.Element {const status = STATUS_CODE_LABELS[span.status_code]// The OTel attributes the user set on the span — the thing the row is here to surface.@@ -42,7 +48,7 @@ export function ExpandedSpanContent({ span, showDetails = true }: ExpandedSpanCoemptyLabel="No attributes set on this span"// An AI row's attributes come from LLM analytics events, not trace_spans, so a span// attribute filter built from them matches no span and empties the span list.- showFilterActions={!isAiEventSpan(span)}+ showFilterActions={showFilterActions && !isAiEventSpan(span)}propertyType={PropertyFilterType.SpanAttribute}/>{/* Sibling section after the span attributes — same split the logs detail view uses.@@ -52,6 +58,7 @@ export function ExpandedSpanContent({ span, showDetails = true }: ExpandedSpanCotitle="Resource attributes"attributes={span.resource_attributes}emptyLabel="No resource attributes on this span"+ showFilterActions={showFilterActions}propertyType={PropertyFilterType.SpanResourceAttribute}/>)}