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.

refactor(tracing): split trace view state out of the trace dialog logic (#121305)

Jon McCallum91f11bc5ab60
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx
index db3788fce6ba..7e7ded75ba56 100644
--- a/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx
@@ -1,63 +1,46 @@
-import { useActions, useValues } from 'kea'
-import { type CSSProperties, useCallback, useRef, useState } from 'react'
+import { BindLogic, useActions, useValues } from 'kea'
+import { useCallback, useState } from 'react'
import { IconCollapse45, IconExpand45, IconExternal, IconSidebarClose, IconSidebarOpen } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonModal, LemonTag, Spinner } from '@posthog/lemon-ui'
-import { Resizer } from 'lib/components/Resizer/Resizer'
-import { type ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
import { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'
import { traceUrl } from 'lib/components/ViewTraceButton/traceUrl'
import { FloatingContainerContext } from 'lib/hooks/useFloatingContainerContext'
import { cn } from 'lib/utils/css-classes'
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 { TraceIdentityChips } from 'products/tracing/frontend/components/TraceDrawer/TraceIdentityChips'
import { TraceLoadErrorNotice } from 'products/tracing/frontend/components/TraceDrawer/TraceLoadErrorNotice'
import { TraceUnavailableNotice } from 'products/tracing/frontend/components/TraceDrawer/TraceUnavailableNotice'
import { formatDuration } from 'products/tracing/frontend/TraceWaterfallView'
-import { TRACE_DIALOG_DATA_ATTR, traceDialogLogic } from './traceDialogLogic'
+import { TraceView } from '../TraceView/TraceView'
+import { traceViewLogic } from '../TraceView/traceViewLogic'
+import { TRACE_DIALOG_DATA_ATTR, TRACE_DIALOG_VIEW_ID, traceDialogLogic } from './traceDialogLogic'
import { TraceDialogOpenedFromLog } from './TraceDialogOpenedFromLog'
import { TraceDialogShortcuts } from './TraceDialogShortcuts'
-import { TraceDialogSpanTree } from './TraceDialogSpanTree'
-// Below this the attribute tables stop being readable, so a drag can't crush the inspector.
-const MIN_INSPECTOR_WIDTH = 320
+const TRACE_VIEW_PROPS = { id: TRACE_DIALOG_VIEW_ID }
export function TraceDialog(): JSX.Element | null {
- // Persisted under its own key: the dialog is wider than the drawer, so a split the person
- // picked in one would be wrong in the other.
- const inspectorRef = useRef<HTMLDivElement>(null)
- const inspectorResizerProps: ResizerLogicProps = {
- logicKey: 'trace-dialog-span-inspector',
- placement: 'left',
- containerRef: inspectorRef,
- persistent: true,
- }
- const { desiredSize: inspectorWidth } = useValues(resizerLogic(inspectorResizerProps))
const {
isOpen,
trace,
traceSpans,
traceSpansLoading,
traceSpansFailed,
- summary,
- timeline,
- selectedSpan,
- missingParentSpanId,
- serviceColorMap,
- activeInspectorTab,
sessionErrorBadgesEnabled,
traceIdentity,
traceSessionId,
inspectorOpen,
isFullscreen,
+ openedFrom,
+ openedAtUs,
} = useValues(traceDialogLogic)
- const { closeTraceDialog, loadTraceSpans, setInspectorTab, openInTracing, toggleInspector, toggleFullscreen } =
+ const { closeTraceDialog, loadTraceSpans, openInTracing, toggleInspector, toggleFullscreen } =
useActions(traceDialogLogic)
+ const { summary, timeline } = useValues(traceViewLogic(TRACE_VIEW_PROPS))
// The dialog sits above popovers, so the inspector's menus and drawers, and the person popover,
// portal inside it instead.
const [floatingContainer, setFloatingContainer] = useState<HTMLDivElement | null>(null)
@@ -154,61 +137,16 @@ export function TraceDialog(): JSX.Element | null {
// The dialog has no filters, and Open in Tracing below covers spans outside its time window.
<TraceUnavailableNotice traceId={trace.traceId} filtersActive={false} surface="trace_dialog" />
) : (
- <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>
- {inspectorOpen && (missingParentSpanId || selectedSpan) && (
- <div
- ref={inspectorRef}
- // Half the body at most side by side, so the span tree keeps room for its timeline bars.
- className="relative flex-1 min-h-0 border-t pt-4 @min-[56rem]/trace-dialog:flex-none @min-[56rem]/trace-dialog:w-(--trace-dialog-inspector-width) @min-[56rem]/trace-dialog:max-w-1/2 @min-[56rem]/trace-dialog:border-t-0 @min-[56rem]/trace-dialog:border-l @min-[56rem]/trace-dialog:pt-0"
- // The dragged width applies only side by side; stacked, the inspector is full width.
- // eslint-disable-next-line react/forbid-dom-props
- style={
- {
- '--trace-dialog-inspector-width':
- inspectorWidth != null
- ? `${Math.max(MIN_INSPECTOR_WIDTH, inspectorWidth)}px`
- : '40%',
- } as CSSProperties
- }
- data-attr="trace-dialog-inspector"
- >
- <Resizer
- {...inspectorResizerProps}
- className="hidden @min-[56rem]/trace-dialog:block"
- />
- {/* Scrolls inside the sized box, so the drag handle stays put. */}
- <div className="h-full overflow-y-auto @min-[56rem]/trace-dialog:pl-4">
- {missingParentSpanId ? (
- <MissingParentSpanNotice
- traceId={trace.traceId}
- parentSpanId={missingParentSpanId}
- />
- ) : selectedSpan ? (
- <SpanInspector
- span={selectedSpan}
- serviceColorMap={serviceColorMap}
- traceTimestamp={
- summary.rootSpan?.timestamp ?? selectedSpan.timestamp
- }
- sessionId={traceSessionId}
- 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>
+ <BindLogic logic={traceViewLogic} props={TRACE_VIEW_PROPS}>
+ <TraceView
+ traceId={trace.traceId}
+ inspectorOpen={inspectorOpen}
+ sessionId={traceSessionId}
+ showErrorsTab={sessionErrorBadgesEnabled}
+ openedFrom={openedFrom}
+ openedAtUs={openedAtUs}
+ />
+ </BindLogic>
)}
</div>
<div ref={floatingContainerRef} />
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogOpenedFromLog.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogOpenedFromLog.tsx
index 866b87999021..d1a9a870bf54 100644
--- a/products/tracing/frontend/components/TraceDialog/TraceDialogOpenedFromLog.tsx
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogOpenedFromLog.tsx
@@ -5,12 +5,16 @@ import { LemonButton } from '@posthog/lemon-ui'
import { LogTag } from 'products/logs/frontend/components/LogTag'
import { formatDuration } from 'products/tracing/frontend/TraceWaterfallView'
-import { traceDialogLogic } from './traceDialogLogic'
+import { traceViewLogic } from '../TraceView/traceViewLogic'
+import { TRACE_DIALOG_VIEW_ID, traceDialogLogic } from './traceDialogLogic'
import { TraceDialogLogMark } from './TraceDialogLogMark'
export function TraceDialogOpenedFromLog(): JSX.Element | null {
- const { openedFrom, openedSpan, openedAtUs, timeline } = useValues(traceDialogLogic)
- const { selectSpan, closeTraceDialog } = useActions(traceDialogLogic)
+ const { openedFrom, openedAtUs } = useValues(traceDialogLogic)
+ const { closeTraceDialog } = useActions(traceDialogLogic)
+ const view = traceViewLogic({ id: TRACE_DIALOG_VIEW_ID })
+ const { pinnedSpan: openedSpan, timeline } = useValues(view)
+ const { selectSpan } = useActions(view)
if (!openedFrom) {
return null
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx
index 916e2b49949f..fadf69774921 100644
--- a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx
@@ -7,7 +7,8 @@ import { cn } from 'lib/utils/css-classes'
import { parseTimestampUs } from 'products/tracing/frontend/spanTree'
import { formatDuration } from 'products/tracing/frontend/TraceWaterfallView'
-import type { TraceDialogSource, TraceDialogTimeline } from './traceDialogLogic'
+import type { TraceViewTimeline } from '../TraceView/traceViewLogic'
+import type { TraceDialogSource } from './traceDialogLogic'
import { LOG_MARK_TAG_TYPE, TraceDialogLogMark } from './TraceDialogLogMark'
import type { TraceDialogRow } from './traceDialogRows'
import { indentPx, MAX_VISUAL_DEPTH, TraceDialogTreeLines } from './TraceDialogTreeLines'
@@ -16,7 +17,7 @@ const ERROR_COLOR = 'var(--danger)'
export interface TraceDialogSpanRowProps {
row: Extract<TraceDialogRow, { kind: 'span' | 'chain' }>
- timeline: TraceDialogTimeline
+ timeline: TraceViewTimeline
serviceColorMap: Map<string, number>
isSelected: boolean
/** Set only on the span that emitted the record the dialog was opened from. */
@@ -41,7 +42,7 @@ function logTimingLabel(logUs: number, startUs: number, durationUs: number): str
return `+${formatDuration((logUs - startUs) * 1_000)} into this span`
}
-function percentOfTrace(us: number, timeline: TraceDialogTimeline): number {
+function percentOfTrace(us: number, timeline: TraceViewTimeline): number {
return timeline.durationUs > 0 ? ((us - timeline.startUs) / timeline.durationUs) * 100 : 0
}
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsx
index 0dafadd05fe2..dcecc20261d8 100644
--- a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsx
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsx
@@ -1,7 +1,7 @@
import '@testing-library/jest-dom'
import { cleanup, render, waitFor } from '@testing-library/react'
-import { Provider } from 'kea'
+import { BindLogic, Provider } from 'kea'
import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
@@ -10,7 +10,8 @@ import { initKeaTests } from '~/test/init'
import type { Span } from 'products/tracing/frontend/types'
-import { traceDialogLogic } from './traceDialogLogic'
+import { traceViewLogic } from '../TraceView/traceViewLogic'
+import { TRACE_DIALOG_VIEW_ID, traceDialogLogic } from './traceDialogLogic'
import { TraceDialogSpanTree } from './TraceDialogSpanTree'
function span(spanId: string, parentSpanId: string): Span {
@@ -60,7 +61,9 @@ describe('TraceDialogSpanTree', () => {
const { container } = render(
<Provider>
- <TraceDialogSpanTree />
+ <BindLogic logic={traceViewLogic} props={{ id: TRACE_DIALOG_VIEW_ID }}>
+ <TraceDialogSpanTree openedFrom={null} openedAtUs={null} />
+ </BindLogic>
</Provider>
)
logic.actions.selectNextSpan()
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx
index 0a67969ac652..31b9ed8f4cd9 100644
--- a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx
@@ -8,7 +8,8 @@ import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'
import { getTimelineTicks } from 'products/tracing/frontend/spanTree'
import { formatDuration } from 'products/tracing/frontend/TraceWaterfallView'
-import { traceDialogLogic, type TraceDialogSource, type TraceDialogTimeline } from './traceDialogLogic'
+import { traceViewLogic, type TraceViewTimeline } from '../TraceView/traceViewLogic'
+import type { TraceDialogSource } from './traceDialogLogic'
import { TraceDialogMoreSpansRow } from './TraceDialogMoreSpansRow'
import { rowSpanNode, type TraceDialogRow } from './traceDialogRows'
import { TraceDialogSpanRow } from './TraceDialogSpanRow'
@@ -19,7 +20,7 @@ interface SpanListRowData {
spanRows: TraceDialogRow[]
descendantCounts: Map<string, number>
collapsedSpanIds: Set<string>
- timeline: TraceDialogTimeline
+ timeline: TraceViewTimeline
serviceColorMap: Map<string, number>
selectedSpanId: string | null
openedSpanId: string | null
@@ -121,7 +122,12 @@ function rowLabel(row: TraceDialogRow): string {
const MAX_PINNED_ANCESTORS = 4
-export function TraceDialogSpanTree(): JSX.Element {
+export interface TraceDialogSpanTreeProps {
+ openedFrom: TraceDialogSource | null
+ openedAtUs: number | null
+}
+
+export function TraceDialogSpanTree({ openedFrom, openedAtUs }: TraceDialogSpanTreeProps): JSX.Element {
const {
spanRows,
spanTree,
@@ -130,14 +136,11 @@ export function TraceDialogSpanTree(): JSX.Element {
serviceColorMap,
selectedSpan,
missingParentSpanId,
- trace,
- openedAtUs,
- openedFrom,
- } = useValues(traceDialogLogic)
- const { selectSpan, toggleSpanCollapsed, toggleChain, showAllChildren } = useActions(traceDialogLogic)
+ pinnedSpanId: openedSpanId,
+ } = useValues(traceViewLogic)
+ const { selectSpan, toggleSpanCollapsed, toggleChain, showAllChildren } = useActions(traceViewLogic)
const [topIndex, setTopIndex] = useState(0)
const listRef = useListRef(null)
- const openedSpanId = trace?.spanId ?? null
const openedIndex = useMemo(
() =>
diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts
index 2d67f152cc2d..a46b873df02e 100644
--- a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts
+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts
@@ -13,7 +13,8 @@ import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/typ
import { logsViewerModalLogic } from 'products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic'
import type { Span } from 'products/tracing/frontend/types'
-import { traceDialogLogic } from './traceDialogLogic'
+import { traceViewLogic } from '../TraceView/traceViewLogic'
+import { TRACE_DIALOG_VIEW_ID, traceDialogLogic } from './traceDialogLogic'
type TracePage = Awaited<ReturnType<typeof api.tracing.getTrace>>
@@ -43,6 +44,7 @@ function page(spanIds: string[], nextOffset: number | null): TracePage {
describe('traceDialogLogic', () => {
let logic: ReturnType<typeof traceDialogLogic.build>
+ let view: ReturnType<typeof traceViewLogic.build>
let getTraceSpy: jest.SpyInstance
beforeEach(() => {
@@ -63,6 +65,7 @@ describe('traceDialogLogic', () => {
router.actions.push('/logs')
logic = traceDialogLogic()
logic.mount()
+ view = traceViewLogic({ id: TRACE_DIALOG_VIEW_ID })
})
afterEach(() => {
@@ -101,7 +104,7 @@ describe('traceDialogLogic', () => {
logic.actions.openTraceDialog({ traceId: 'abc123', spanId: openedSpanId }, { entryPoint: 'log_details' })
}).toDispatchActions(['loadTraceSpansSuccess'])
- expect(logic.values.selectedSpan?.span_id).toBe('B1')
+ expect(view.values.selectedSpan?.span_id).toBe('B1')
})
it.each([
@@ -170,8 +173,8 @@ describe('traceDialogLogic', () => {
logic.actions.toggleSpanCollapsed('A')
- expect(logic.values.selectedSpanId).toBe('A')
- expect(logic.values.flatSpans.map((node) => node.span.span_id)).toEqual(['ROOT', 'A'])
+ expect(view.values.selectedSpanId).toBe('A')
+ expect(view.values.flatSpans.map((node) => node.span.span_id)).toEqual(['ROOT', 'A'])
})
it('clears the failure once a retry succeeds', async () => {
@@ -197,9 +200,8 @@ describe('traceDialogLogic', () => {
await expectLogic(logic, () => {
logic.actions.openTraceDialog({ traceId: 'abc123', spanId: 'a' }, { entryPoint: 'log_details' })
- })
- .toDispatchActions(['loadTraceSpansSuccess'])
- .toMatchValues({ activeInspectorTab: expectedTab })
+ }).toDispatchActions(['loadTraceSpansSuccess'])
+ expect(view.values.activeInspectorTab).toBe(expectedTab)
})
it('keeps a picked tab across spans, and drops it for the next trace', async () => {
@@ -208,15 +210,13 @@ describe('traceDialogLogic', () => {
await expectLogic(logic).toDispatchActions(['loadTraceSpansSuccess'])
logic.actions.setInspectorTab('attributes')
- await expectLogic(logic, () => {
- logic.actions.selectSpan('b')
- }).toMatchValues({ activeInspectorTab: 'attributes' })
+ logic.actions.selectSpan('b')
+ expect(view.values.activeInspectorTab).toBe('attributes')
await expectLogic(logic, () => {
logic.actions.openTraceDialog({ traceId: 'def456', spanId: 'a' }, { entryPoint: 'log_details' })
- })
- .toDispatchActions(['loadTraceSpansSuccess'])
- .toMatchValues({ activeInspectorTab: 'errors' })
+ }).toDispatchActions(['loadTraceSpansSuccess'])
+ expect(view.values.activeInspectorTab).toBe('errors')
})
it('treats a missing parent row as its own selection, not the root span', async () => {
@@ -225,13 +225,11 @@ describe('traceDialogLogic', () => {
logic.actions.openTraceDialog({ traceId: 'abc123', spanId: 'a' }, { entryPoint: 'log_details' })
await expectLogic(logic).toDispatchActions(['loadTraceSpansSuccess'])
- await expectLogic(logic, () => {
- logic.actions.selectSpan('GONE')
- }).toMatchValues({ missingParentSpanId: 'GONE' })
+ logic.actions.selectSpan('GONE')
+ expect(view.values.missingParentSpanId).toBe('GONE')
- await expectLogic(logic, () => {
- logic.actions.selectSpan('child')
- }).toMatchValues({ missingParentSpanId: null })
+ logic.actions.selectSpan('child')
+ expect(view.values.missingParentSpanId).toBeNull()
})
it.each([
@@ -281,9 +279,9 @@ describe('traceDialogLogic', () => {
it('steps through spans and keeps the key from the page under the dialog', () => {
press('j')
- expect(logic.values.selectedSpan?.span_id).toBe('b')
+ expect(view.values.selectedSpan?.span_id).toBe('b')
press('k')
- expect(logic.values.selectedSpan?.span_id).toBe('a')
+ expect(view.values.selectedSpan?.span_id).toBe('a')
expect(pageListener).not.toHaveBeenCalled()
})
@@ -299,11 +297,11 @@ describe('traceDialogLogic', () => {
})
logic.actions.openTraceDialog({ traceId: 'abc123', spanId: 'A1' }, { entryPoint: 'log_details' })
await expectLogic(logic).toDispatchActions(['loadTraceSpansSuccess'])
- const visible = (): string[] => logic.values.flatSpans.map((node) => node.span.span_id)
+ const visible = (): string[] => view.values.flatSpans.map((node) => node.span.span_id)
// A1 has nothing to collapse, so left climbs to A, then collapses A.
press('ArrowLeft')
- expect(logic.values.selectedSpanId).toBe('A')
+ expect(view.values.selectedSpanId).toBe('A')
press('ArrowLeft')
expect(visible()).toEqual(['ROOT', 'A'])
@@ -311,7 +309,7 @@ describe('traceDialogLogic', () => {
press('ArrowRight')
expect(visible()).toEqual(['ROOT', 'A', 'A1'])
press('ArrowRight')
- expect(logic.values.selectedSpanId).toBe('A1')
+ expect(view.values.selectedSpanId).toBe('A1')
expect(pageListener).not.toHaveBeenCalled()
})
@@ -333,7 +331,7 @@ describe('traceDialogLogic', () => {
})
logic.actions.openTraceDialog({ traceId: 'abc123', spanId: 'ROOT' }, { entryPoint: 'log_details' })
await expectLogic(logic).toDispatchActions(['loadTraceSpansSuccess'])
- const visible = (): string[] => logic.values.flatSpans.map((node) => node.span.span_id)
+ const visible = (): string[] => view.values.flatSpans.map((node) => node.span.span_id)
expect(visible()).toEqual(['ROOT', 'A', 'LEAF'])
logic.actions.selectSpan('A')
@@ -342,7 +340,7 @@ describe('traceDialogLogic', () => {
logic.actions.selectSpan('C')
logic.actions.toggleChain('A')
- expect(logic.values.selectedSpanId).toBe('A')
+ expect(view.values.selectedSpanId).toBe('A')
})
it('steps onto a missing parent row and on past it', async () => {
@@ -352,14 +350,14 @@ describe('traceDialogLogic', () => {
await expectLogic(logic).toDispatchActions(['loadTraceSpansSuccess'])
press('j')
- expect(logic.values.missingParentSpanId).toBe('GONE')
+ expect(view.values.missingParentSpanId).toBe('GONE')
press('j')
- expect(logic.values.missingParentSpanId).toBeNull()
- expect(logic.values.selectedSpan?.span_id).toBe('b')
+ expect(view.values.missingParentSpanId).toBeNull()
+ expect(view.values.selectedSpan?.span_id).toBe('b')
press('k')
- expect(logic.values.missingParentSpanId).toBe('GONE')
+ expect(view.values.missingParentSpanId).toBe('GONE')
press('k')
- expect(logic.values.selectedSpan?.span_id).toBe('a')
+ expect(view.values.selectedSpan?.span_id).toBe('a')
})
it('leaves keys typed into an input in the dialog alone, but not one hidden behind it', () => {
@@ -371,11 +369,11 @@ describe('traceDialogLogic', () => {
document.body.append(dialog, behind)
press('j', inDialog)
- expect(logic.values.selectedSpan?.span_id).toBe('a')
+ expect(view.values.selectedSpan?.span_id).toBe('a')
expect(pageListener).toHaveBeenCalledTimes(1)
press('j', behind)
- expect(logic.values.selectedSpan?.span_id).toBe('b')
+ expect(view.values.selectedSpan?.span_id).toBe('b')
expect(pageListener).toHaveBeenCalledTimes(1)
dialog.remove()
behind.remove()
@@ -385,7 +383,7 @@ describe('traceDialogLogic', () => {
logic.actions.closeTraceDialog()
press('j')
- expect(logic.values.selectedSpan?.span_id).toBe('a')
+ expect(view.values.selectedSpan?.span_id).toBe('a')
expect(pageListener).toHaveBeenCalledTimes(1)
})
})
diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts
index 1632f4dba586..f3b4094fd4e5 100644
--- a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts
+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts
@@ -23,7 +23,7 @@ import {
type OpenLogsViewerModalOptions,
logsViewerModalLogic,
} from 'products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic'
-import { buildSpanTree, parseTimestampUs, type SpanNode } from 'products/tracing/frontend/spanTree'
+import { parseTimestampUs } from 'products/tracing/frontend/spanTree'
import {
EMPTY_TRACE_IDENTITY,
resolveTraceIdentity,
@@ -31,11 +31,10 @@ import {
type TraceIdentity,
} from 'products/tracing/frontend/traceIdentity'
import { resolveTraceLookupRange } from 'products/tracing/frontend/traceLinks'
-import { buildServiceColorMap } from 'products/tracing/frontend/TraceWaterfallView'
import { tracingCorrelationConfigLogic } from 'products/tracing/frontend/tracingCorrelationConfigLogic'
import type { Span, SpanInspectorTab } from 'products/tracing/frontend/types'
-import { buildTraceDialogRows, countDescendantsById, rowSpanNode, type TraceDialogRow } from './traceDialogRows'
+import { traceViewLogic } from '../TraceView/traceViewLogic'
// The trace endpoint pages at 2,000 spans, so this caps the dialog at 10,000. Bigger traces open in
// Tracing, which pages in on scroll.
@@ -45,6 +44,8 @@ const TRACE_DIALOG_MAX_PAGES = 5
export const TRACE_DIALOG_DATA_ATTR = 'trace-dialog'
const TRACE_DIALOG_SELECTOR = `[data-attr="${TRACE_DIALOG_DATA_ATTR}"]`
+export const TRACE_DIALOG_VIEW_ID = 'trace-dialog'
+
// The trace API returns hex span ids in uppercase, and logs and metrics carry them in lowercase. The
// dialog matches the opened span against the loaded spans exactly, so it keeps the API's case.
function inApiCase(spanId: string | null | undefined): string | null {
@@ -59,12 +60,6 @@ export interface TraceDialogSpans {
truncated: boolean
}
-export interface TraceDialogTree {
- roots: SpanNode[]
- nodesById: Map<string, SpanNode>
- descendantCounts: Map<string, number>
-}
-
/** The log the dialog was opened from, shown above the tree so the reason for the trace stays in view. */
export interface TraceDialogSource {
body: string
@@ -109,18 +104,6 @@ function captureClosed(session: TraceDialogSession, reason: TraceDialogCloseReas
})
}
-export interface TraceDialogTimeline {
- startUs: number
- durationUs: number
-}
-
-export interface TraceDialogSummary {
- rootSpan: Span | null
- spanCount: number
- serviceCount: number
- errorCount: number
-}
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceDialogLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
@@ -128,31 +111,12 @@ export interface traceDialogLogicValues {
configuredSessionIdKeys: string[] | undefined // tracingCorrelationConfigLogic
correlationLinksEnabled: boolean // tracingCorrelationConfigLogic
sessionErrorBadgesEnabled: boolean // tracingCorrelationConfigLogic
- activeInspectorTab: SpanInspectorTab
- chainStartIds: {
- folded: Set<string>
- opened: Set<string>
- }
- chosenInspectorTab: SpanInspectorTab | null
- collapsedSpanIds: Set<string>
dialogEnabled: boolean
- flatSpans: SpanNode[]
- fullChildListSpanIds: Set<string>
inspectorOpen: boolean
isFullscreen: boolean
isOpen: boolean
- missingParentSpanId: string | null
- openChainIds: Set<string>
openedAtUs: number | null
openedFrom: TraceDialogSource | null
- openedSpan: Span | null
- selectedSpan: Span | null
- selectedSpanId: string | null
- serviceColorMap: Map<string, number>
- spanRows: TraceDialogRow[]
- spanTree: TraceDialogTree
- summary: TraceDialogSummary
- timeline: TraceDialogTimeline
trace: TraceLinkParams | null
traceIdentity: TraceIdentity
traceSessionId: string | null
@@ -201,17 +165,41 @@ export interface traceDialogLogicActions {
modalContext: SessionPlayerModalContext
sessionRecording: Pick<SessionRecordingType, 'id' | 'matching_events'>
} // sessionPlayerModalLogic
- closeTraceDialog: (reason?: TraceDialogCloseReason) => {
- reason: TraceDialogCloseReason
- }
collapseSelectedSpan: () => {
value: true
- }
+ } // traceViewLogic
expandSelectedSpan: () => {
value: true
- }
- keepSelectionOnScreen: () => {
+ } // traceViewLogic
+ selectNextSpan: () => {
+ value: true
+ } // traceViewLogic
+ selectPreviousSpan: () => {
value: true
+ } // traceViewLogic
+ selectSpan: (spanId: string) => {
+ spanId: string
+ } // traceViewLogic
+ setInspectorTab: (tab: SpanInspectorTab) => {
+ tab: SpanInspectorTab
+ } // traceViewLogic
+ setSpans: (spans: Span[]) => {
+ spans: Span[]
+ } // traceViewLogic
+ showTrace: (pinnedSpanId: string | null) => {
+ pinnedSpanId: string | null
+ } // traceViewLogic
+ spanStepped: () => {
+ value: true
+ } // traceViewLogic
+ toggleChain: (spanId: string) => {
+ spanId: string
+ } // traceViewLogic
+ toggleSpanCollapsed: (spanId: string) => {
+ spanId: string
+ } // traceViewLogic
+ closeTraceDialog: (reason?: TraceDialogCloseReason) => {
+ reason: TraceDialogCloseReason
}
loadTraceSpans: (trace: TraceLinkParams) => TraceLinkParams
loadTraceSpansFailure: (
@@ -243,58 +231,18 @@ export interface traceDialogLogicActions {
ts?: string | null | undefined
}
}
- selectNextSpan: () => {
- value: true
- }
- selectPreviousSpan: () => {
- value: true
- }
- selectSpan: (spanId: string) => {
- spanId: string
- }
- setInspectorTab: (tab: SpanInspectorTab) => {
- tab: SpanInspectorTab
- }
- showAllChildren: (spanId: string) => {
- spanId: string
- }
- toggleChain: (spanId: string) => {
- spanId: string
- }
toggleFullscreen: () => {
value: true
}
toggleInspector: () => {
value: true
}
- toggleSpanCollapsed: (spanId: string) => {
- spanId: string
- }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceDialogLogicMeta {
__keaTypeGenInternalSelectorTypes: {
dialogEnabled: (featureFlags: FeatureFlagsSet) => boolean
- spanTree: (traceSpans: TraceDialogSpans | null) => TraceDialogTree
- spanRows: (
- spanTree: TraceDialogTree,
- collapsedSpanIds: Set<string>,
- fullChildListSpanIds: Set<string>,
- openChainIds: Set<string>,
- trace: TraceLinkParams | null
- ) => TraceDialogRow[]
- flatSpans: (spanRows: TraceDialogRow[]) => SpanNode[]
- chainStartIds: (spanRows: TraceDialogRow[]) => {
- folded: Set<string>
- opened: Set<string>
- }
- selectedSpan: (
- traceSpans: TraceDialogSpans | null,
- selectedSpanId: string | null,
- summary: TraceDialogSummary
- ) => Span | null
- missingParentSpanId: (traceSpans: TraceDialogSpans | null, selectedSpanId: string | null) => string | null
traceIdentity: (
traceSpans: TraceDialogSpans | null,
configuredDistinctIdKeys: string[] | undefined,
@@ -306,15 +254,6 @@ export interface traceDialogLogicMeta {
configuredSessionIdKeys: string[] | undefined,
sessionErrorBadgesEnabled: boolean
) => string | null
- openedSpan: (traceSpans: TraceDialogSpans | null, trace: TraceLinkParams | null) => Span | null
- activeInspectorTab: (
- chosenInspectorTab: SpanInspectorTab | null,
- selectedSpan: Span | null,
- sessionErrorBadgesEnabled: boolean
- ) => SpanInspectorTab
- serviceColorMap: (traceSpans: TraceDialogSpans | null) => Map<string, number>
- timeline: (traceSpans: TraceDialogSpans | null) => TraceDialogTimeline
- summary: (traceSpans: TraceDialogSpans | null) => TraceDialogSummary
openedAtUs: (trace: TraceLinkParams | null, openedFrom: TraceDialogSource | null) => number | null
}
}
@@ -336,6 +275,20 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
['openSessionPlayer'],
logsViewerModalLogic,
['openLogsViewerModal'],
+ traceViewLogic({ id: TRACE_DIALOG_VIEW_ID }),
+ [
+ 'showTrace',
+ 'setSpans',
+ 'selectSpan',
+ 'setInspectorTab',
+ 'toggleSpanCollapsed',
+ 'toggleChain',
+ 'spanStepped',
+ 'selectNextSpan',
+ 'selectPreviousSpan',
+ 'collapseSelectedSpan',
+ 'expandSelectedSpan',
+ ],
],
values: [
tracingCorrelationConfigLogic,
@@ -356,19 +309,9 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
entryPoint: options.entryPoint,
}),
openInTracing: true,
- selectNextSpan: true,
- selectPreviousSpan: true,
- collapseSelectedSpan: true,
- expandSelectedSpan: true,
closeTraceDialog: (reason: TraceDialogCloseReason = 'dismissed') => ({ reason }),
- selectSpan: (spanId: string) => ({ spanId }),
- toggleSpanCollapsed: (spanId: string) => ({ spanId }),
- showAllChildren: (spanId: string) => ({ spanId }),
- toggleChain: (spanId: string) => ({ spanId }),
- keepSelectionOnScreen: true,
toggleInspector: true,
toggleFullscreen: true,
- setInspectorTab: (tab: SpanInspectorTab) => ({ tab }),
}),
loaders(({ values }) => ({
traceSpans: [
@@ -437,47 +380,6 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
loadTraceSpansFailure: () => true,
},
],
- selectedSpanId: [
- null as string | null,
- {
- openTraceDialog: (_, { trace }) => trace.spanId ?? null,
- selectSpan: (_, { spanId }) => spanId,
- },
- ],
- collapsedSpanIds: [
- new Set<string>(),
- {
- openTraceDialog: () => new Set<string>(),
- toggleSpanCollapsed: (collapsed, { spanId }) => {
- const next = new Set(collapsed)
- if (!next.delete(spanId)) {
- next.add(spanId)
- }
- return next
- },
- },
- ],
- fullChildListSpanIds: [
- new Set<string>(),
- {
- openTraceDialog: () => new Set<string>(),
- showAllChildren: (shown, { spanId }) => new Set(shown).add(spanId),
- },
- ],
- // Chains fold by default, so this holds the opened ones.
- openChainIds: [
- new Set<string>(),
- {
- openTraceDialog: () => new Set<string>(),
- toggleChain: (opened, { spanId }) => {
- const next = new Set(opened)
- if (!next.delete(spanId)) {
- next.add(spanId)
- }
- return next
- },
- },
- ],
inspectorOpen: [
true,
{ persist: true },
@@ -492,15 +394,6 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
toggleFullscreen: (fullscreen) => !fullscreen,
},
],
- // 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
@@ -509,82 +402,6 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
(s) => [s.featureFlags],
(featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_TRACE_DIALOG],
],
- spanTree: [
- (s) => [s.traceSpans],
- (traceSpans: TraceDialogSpans | null): TraceDialogTree => {
- const roots = buildSpanTree(traceSpans?.spans ?? [])
- const nodesById = new Map<string, SpanNode>()
- const stack = [...roots]
- while (stack.length > 0) {
- const node = stack.pop()!
- nodesById.set(node.span.span_id, node)
- stack.push(...node.children)
- }
- return { roots, nodesById, descendantCounts: countDescendantsById(roots) }
- },
- ],
- spanRows: [
- (s) => [s.spanTree, s.collapsedSpanIds, s.fullChildListSpanIds, s.openChainIds, s.trace],
- (
- spanTree: TraceDialogTree,
- collapsedSpanIds: Set<string>,
- fullChildListSpanIds: Set<string>,
- openChainIds: Set<string>,
- trace: TraceLinkParams | null
- ): TraceDialogRow[] =>
- buildTraceDialogRows(spanTree.roots, {
- collapsedSpanIds,
- fullChildListSpanIds,
- openChainIds,
- pinned: (trace?.spanId && spanTree.nodesById.get(trace.spanId)) || null,
- }),
- ],
- flatSpans: [
- (s) => [s.spanRows],
- (spanRows: TraceDialogRow[]): SpanNode[] =>
- spanRows.flatMap((row) => {
- const node = rowSpanNode(row)
- return node ? [node] : []
- }),
- ],
- chainStartIds: [
- (s) => [s.spanRows],
- (spanRows: TraceDialogRow[]): { folded: Set<string>; opened: Set<string> } => {
- const folded = new Set<string>()
- const opened = new Set<string>()
- for (const row of spanRows) {
- if (row.kind === 'chain') {
- folded.add(row.nodes[0].span.span_id)
- } else if (row.kind === 'span' && row.openChainLength) {
- opened.add(row.node.span.span_id)
- }
- }
- return { folded, opened }
- },
- ],
- 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,
- ],
// A truncated trace may hold a second, conflicting person on a page the dialog never
// loaded, so it names no one rather than risk naming the wrong one.
traceIdentity: [
@@ -612,47 +429,6 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
? resolveTraceSessionId(traceSpans.spans, sessionIdKeys)
: null,
],
- openedSpan: [
- (s) => [s.traceSpans, s.trace],
- (traceSpans: TraceDialogSpans | null, trace: TraceLinkParams | null): Span | null =>
- trace?.spanId ? (traceSpans?.spans.find((span) => span.span_id === trace.spanId) ?? null) : 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 ?? []),
- ],
- timeline: [
- (s) => [s.traceSpans],
- (traceSpans: TraceDialogSpans | null): TraceDialogTimeline => {
- const spans = traceSpans?.spans ?? []
- if (spans.length === 0) {
- return { startUs: 0, durationUs: 0 }
- }
- const starts = spans.map((span) => parseTimestampUs(span.timestamp))
- const ends = spans.map((span, i) => starts[i] + span.duration_nano / 1_000)
- const startUs = Math.min(...starts)
- return { startUs, durationUs: Math.max(...ends) - startUs }
- },
- ],
- summary: [
- (s) => [s.traceSpans],
- (traceSpans: TraceDialogSpans | null): TraceDialogSummary => {
- const spans = traceSpans?.spans ?? []
- return {
- rootSpan: spans.find((span) => span.is_root_span) ?? null,
- spanCount: spans.length,
- serviceCount: new Set(spans.map((span) => span.service_name)).size,
- errorCount: spans.filter((span) => span.status_code === 2).length,
- }
- },
- ],
// When the record that opened the dialog was written: a log's timestamp, so its span can show
// when the log fired. Parsed to microseconds, like the timeline, so sub-millisecond spans place it right.
openedAtUs: [
@@ -684,6 +460,7 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
has_span: !!trace.spanId,
has_log: !!openedFrom,
})
+ actions.showTrace(trace.spanId)
actions.loadTraceSpans(trace)
// Capture phase, and stopped there, so the page under the dialog does not also act on
// the key: with log details open, the logs list binds J and K to its own cursor.
@@ -734,6 +511,7 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
}
},
loadTraceSpansSuccess: ({ traceSpans }) => {
+ actions.setSpans(traceSpans?.spans ?? [])
if (!cache.session || !traceSpans) {
return
}
@@ -757,103 +535,20 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
setInspectorTab: ({ tab }) => {
cache.session?.tabsViewed.add(tab)
},
- selectNextSpan: () => {
+ spanStepped: () => {
if (cache.session) {
cache.session.keyboardSteps += 1
}
- // A missing-parent row is selectable too, so step from it rather than from the root fallback.
- const currentId = values.missingParentSpanId ?? values.selectedSpan?.span_id
- const index = values.flatSpans.findIndex((node) => node.span.span_id === currentId)
- const next = values.flatSpans[Math.min(index + 1, values.flatSpans.length - 1)]
- if (next) {
- actions.selectSpan(next.span.span_id)
- }
- },
- selectPreviousSpan: () => {
- if (cache.session) {
- cache.session.keyboardSteps += 1
- }
- const currentId = values.missingParentSpanId ?? values.selectedSpan?.span_id
- const index = values.flatSpans.findIndex((node) => node.span.span_id === currentId)
- const previous = values.flatSpans[Math.max(index - 1, 0)]
- if (previous) {
- actions.selectSpan(previous.span.span_id)
- }
- },
- // Left collapses the selected span, or moves up to its parent once there is nothing to collapse.
- collapseSelectedSpan: () => {
- const node = values.spanTree.nodesById.get(values.missingParentSpanId ?? values.selectedSpan?.span_id ?? '')
- if (!node) {
- return
- }
- if (cache.session) {
- cache.session.keyboardSteps += 1
- }
- const spanId = node.span.span_id
- if (values.chainStartIds.opened.has(spanId)) {
- actions.toggleChain(spanId)
- } else if (node.children.length > 0 && !values.collapsedSpanIds.has(spanId)) {
- actions.toggleSpanCollapsed(spanId)
- } else if (node.parent) {
- // The parent can sit inside a folded chain, which stands for it on screen.
- const shown = new Set(values.flatSpans)
- let parent: SpanNode | null = node.parent
- while (parent && !shown.has(parent)) {
- parent = parent.parent
- }
- if (parent) {
- actions.selectSpan(parent.span.span_id)
- }
- }
- },
- // Right expands the selected span, or steps into its first child once it is open.
- expandSelectedSpan: () => {
- const node = values.spanTree.nodesById.get(values.missingParentSpanId ?? values.selectedSpan?.span_id ?? '')
- if (!node || node.children.length === 0) {
- return
- }
- if (values.chainStartIds.folded.has(node.span.span_id)) {
- if (cache.session) {
- cache.session.keyboardSteps += 1
- }
- actions.toggleChain(node.span.span_id)
- return
- }
- if (!values.collapsedSpanIds.has(node.span.span_id)) {
- actions.selectNextSpan()
- return
- }
- if (cache.session) {
- cache.session.keyboardSteps += 1
- }
- actions.toggleSpanCollapsed(node.span.span_id)
},
toggleSpanCollapsed: () => {
if (cache.session) {
cache.session.collapseToggles += 1
}
- actions.keepSelectionOnScreen()
},
toggleChain: () => {
if (cache.session) {
cache.session.collapseToggles += 1
}
- actions.keepSelectionOnScreen()
- },
- // The inspector must never show a span the list hides.
- keepSelectionOnScreen: () => {
- const selected = values.selectedSpanId ? values.spanTree.nodesById.get(values.selectedSpanId) : undefined
- if (!selected) {
- return
- }
- const shown = new Set(values.flatSpans)
- let node: SpanNode | null = selected
- while (node && !shown.has(node)) {
- node = node.parent
- }
- if (node && node !== selected) {
- actions.selectSpan(node.span.span_id)
- }
},
// 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.
diff --git a/products/tracing/frontend/components/TraceView/TraceView.tsx b/products/tracing/frontend/components/TraceView/TraceView.tsx
new file mode 100644
index 000000000000..2f9f5d2ce996
--- /dev/null
+++ b/products/tracing/frontend/components/TraceView/TraceView.tsx
@@ -0,0 +1,97 @@
+import { useActions, useValues } from 'kea'
+import { type CSSProperties, useRef } from 'react'
+
+import { Resizer } from 'lib/components/Resizer/Resizer'
+import { type ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
+
+import { SpanInspector } from 'products/tracing/frontend/components/SpanInspector/SpanInspector'
+import { MissingParentSpanNotice } from 'products/tracing/frontend/components/TraceDrawer/MissingParentSpanNotice'
+
+import type { TraceDialogSource } from '../TraceDialog/traceDialogLogic'
+import { TraceDialogSpanTree } from '../TraceDialog/TraceDialogSpanTree'
+import { traceViewLogic } from './traceViewLogic'
+
+// Below this the attribute tables stop being readable, so a drag can't crush the inspector.
+const MIN_INSPECTOR_WIDTH = 320
+
+export interface TraceViewProps {
+ traceId: string
+ inspectorOpen: boolean
+ sessionId: string | null
+ showErrorsTab: boolean
+ openedFrom?: TraceDialogSource | null
+ openedAtUs?: number | null
+}
+
+/** The span tree beside the inspector for the selected span. Mount it inside a `BindLogic` for `traceViewLogic`. */
+export function TraceView({
+ traceId,
+ inspectorOpen,
+ sessionId,
+ showErrorsTab,
+ openedFrom = null,
+ openedAtUs = null,
+}: TraceViewProps): JSX.Element {
+ const inspectorRef = useRef<HTMLDivElement>(null)
+ const inspectorResizerProps: ResizerLogicProps = {
+ // Pinned: the persisted inspector width lives under this key.
+ logicKey: 'trace-dialog-span-inspector',
+ placement: 'left',
+ containerRef: inspectorRef,
+ persistent: true,
+ }
+ const { desiredSize: inspectorWidth } = useValues(resizerLogic(inspectorResizerProps))
+ const { selectedSpan, missingParentSpanId, serviceColorMap, summary, activeInspectorTab } =
+ useValues(traceViewLogic)
+ const { setInspectorTab } = useActions(traceViewLogic)
+
+ return (
+ <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 openedFrom={openedFrom} openedAtUs={openedAtUs} />
+ </div>
+ {inspectorOpen && (missingParentSpanId || selectedSpan) && (
+ <div
+ ref={inspectorRef}
+ // Half the body at most side by side, so the span tree keeps room for its timeline bars.
+ className="relative flex-1 min-h-0 border-t pt-4 @min-[56rem]/trace-dialog:flex-none @min-[56rem]/trace-dialog:w-(--trace-dialog-inspector-width) @min-[56rem]/trace-dialog:max-w-1/2 @min-[56rem]/trace-dialog:border-t-0 @min-[56rem]/trace-dialog:border-l @min-[56rem]/trace-dialog:pt-0"
+ // The dragged width applies only side by side; stacked, the inspector is full width.
+ // eslint-disable-next-line react/forbid-dom-props
+ style={
+ {
+ '--trace-dialog-inspector-width':
+ inspectorWidth != null
+ ? `${Math.max(MIN_INSPECTOR_WIDTH, inspectorWidth)}px`
+ : '40%',
+ } as CSSProperties
+ }
+ data-attr="trace-dialog-inspector"
+ >
+ <Resizer {...inspectorResizerProps} className="hidden @min-[56rem]/trace-dialog:block" />
+ {/* Scrolls inside the sized box, so the drag handle stays put. */}
+ <div className="h-full overflow-y-auto @min-[56rem]/trace-dialog:pl-4">
+ {missingParentSpanId ? (
+ <MissingParentSpanNotice traceId={traceId} parentSpanId={missingParentSpanId} />
+ ) : selectedSpan ? (
+ <SpanInspector
+ span={selectedSpan}
+ serviceColorMap={serviceColorMap}
+ traceTimestamp={summary.rootSpan?.timestamp ?? selectedSpan.timestamp}
+ sessionId={sessionId}
+ showErrorsTab={showErrorsTab}
+ errorsScope="span"
+ resolving={false}
+ tab={activeInspectorTab}
+ onSelectTab={setInspectorTab}
+ // There is no span list here for an attribute filter to narrow.
+ showFilterActions={false}
+ />
+ ) : null}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/tracing/frontend/components/TraceView/traceViewLogic.ts b/products/tracing/frontend/components/TraceView/traceViewLogic.ts
new file mode 100644
index 000000000000..47370eb5af51
--- /dev/null
+++ b/products/tracing/frontend/components/TraceView/traceViewLogic.ts
@@ -0,0 +1,431 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+
+import { buildSpanTree, parseTimestampUs, type SpanNode } from 'products/tracing/frontend/spanTree'
+import { buildServiceColorMap } from 'products/tracing/frontend/TraceWaterfallView'
+import { tracingCorrelationConfigLogic } from 'products/tracing/frontend/tracingCorrelationConfigLogic'
+import type { Span, SpanInspectorTab } from 'products/tracing/frontend/types'
+
+import {
+ buildTraceDialogRows,
+ countDescendantsById,
+ rowSpanNode,
+ type TraceDialogRow,
+} from '../TraceDialog/traceDialogRows'
+
+export interface TraceViewLogicProps {
+ id: string
+}
+
+export interface TraceViewTree {
+ roots: SpanNode[]
+ nodesById: Map<string, SpanNode>
+ descendantCounts: Map<string, number>
+}
+
+export interface TraceViewTimeline {
+ startUs: number
+ durationUs: number
+}
+
+export interface TraceViewSummary {
+ rootSpan: Span | null
+ spanCount: number
+ serviceCount: number
+ errorCount: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceViewLogicValues {
+ sessionErrorBadgesEnabled: boolean // tracingCorrelationConfigLogic
+ activeInspectorTab: SpanInspectorTab
+ chainStartIds: {
+ folded: Set<string>
+ opened: Set<string>
+ }
+ chosenInspectorTab: SpanInspectorTab | null
+ collapsedSpanIds: Set<string>
+ flatSpans: SpanNode[]
+ fullChildListSpanIds: Set<string>
+ missingParentSpanId: string | null
+ openChainIds: Set<string>
+ pinnedSpan: Span | null
+ pinnedSpanId: string | null
+ selectedSpan: Span | null
+ selectedSpanId: string | null
+ serviceColorMap: Map<string, number>
+ spanRows: TraceDialogRow[]
+ spanTree: TraceViewTree
+ spans: Span[]
+ summary: TraceViewSummary
+ timeline: TraceViewTimeline
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceViewLogicActions {
+ collapseSelectedSpan: () => {
+ value: true
+ }
+ expandSelectedSpan: () => {
+ value: true
+ }
+ keepSelectionOnScreen: () => {
+ value: true
+ }
+ selectNextSpan: () => {
+ value: true
+ }
+ selectPreviousSpan: () => {
+ value: true
+ }
+ selectSpan: (spanId: string) => {
+ spanId: string
+ }
+ setInspectorTab: (tab: SpanInspectorTab) => {
+ tab: SpanInspectorTab
+ }
+ setSpans: (spans: Span[]) => {
+ spans: Span[]
+ }
+ showAllChildren: (spanId: string) => {
+ spanId: string
+ }
+ showTrace: (pinnedSpanId: string | null) => {
+ pinnedSpanId: string | null
+ }
+ spanStepped: () => {
+ value: true
+ }
+ toggleChain: (spanId: string) => {
+ spanId: string
+ }
+ toggleSpanCollapsed: (spanId: string) => {
+ spanId: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceViewLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ spanTree: (spans: Span[]) => TraceViewTree
+ spanRows: (
+ spanTree: TraceViewTree,
+ collapsedSpanIds: Set<string>,
+ fullChildListSpanIds: Set<string>,
+ openChainIds: Set<string>,
+ pinnedSpanId: string | null
+ ) => TraceDialogRow[]
+ flatSpans: (spanRows: TraceDialogRow[]) => SpanNode[]
+ chainStartIds: (spanRows: TraceDialogRow[]) => {
+ folded: Set<string>
+ opened: Set<string>
+ }
+ selectedSpan: (spans: Span[], selectedSpanId: string | null, summary: TraceViewSummary) => Span | null
+ missingParentSpanId: (spans: Span[], selectedSpanId: string | null) => string | null
+ pinnedSpan: (spans: Span[], pinnedSpanId: string | null) => Span | null
+ activeInspectorTab: (
+ chosenInspectorTab: SpanInspectorTab | null,
+ selectedSpan: Span | null,
+ sessionErrorBadgesEnabled: boolean
+ ) => SpanInspectorTab
+ serviceColorMap: (spans: Span[]) => Map<string, number>
+ timeline: (spans: Span[]) => TraceViewTimeline
+ summary: (spans: Span[]) => TraceViewSummary
+ }
+}
+
+export type traceViewLogicType = MakeLogicType<
+ traceViewLogicValues,
+ traceViewLogicActions,
+ TraceViewLogicProps,
+ traceViewLogicMeta
+>
+
+export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLogicType>([
+ props({} as TraceViewLogicProps),
+ key((props) => props.id),
+ path((key) => ['products', 'tracing', 'frontend', 'components', 'TraceView', 'traceViewLogic', key]),
+ connect(() => ({
+ values: [tracingCorrelationConfigLogic, ['sessionErrorBadgesEnabled']],
+ })),
+ actions({
+ showTrace: (pinnedSpanId: string | null) => ({ pinnedSpanId }),
+ setSpans: (spans: Span[]) => ({ spans }),
+ selectSpan: (spanId: string) => ({ spanId }),
+ selectNextSpan: true,
+ selectPreviousSpan: true,
+ collapseSelectedSpan: true,
+ expandSelectedSpan: true,
+ spanStepped: true,
+ toggleSpanCollapsed: (spanId: string) => ({ spanId }),
+ showAllChildren: (spanId: string) => ({ spanId }),
+ toggleChain: (spanId: string) => ({ spanId }),
+ keepSelectionOnScreen: true,
+ setInspectorTab: (tab: SpanInspectorTab) => ({ tab }),
+ }),
+ reducers({
+ spans: [
+ [] as Span[],
+ {
+ showTrace: () => [],
+ setSpans: (_, { spans }) => spans,
+ },
+ ],
+ // The span the trace was opened on: it stays listed even inside a folded branch.
+ pinnedSpanId: [
+ null as string | null,
+ {
+ showTrace: (_, { pinnedSpanId }) => pinnedSpanId,
+ },
+ ],
+ selectedSpanId: [
+ null as string | null,
+ {
+ showTrace: (_, { pinnedSpanId }) => pinnedSpanId,
+ selectSpan: (_, { spanId }) => spanId,
+ },
+ ],
+ collapsedSpanIds: [
+ new Set<string>(),
+ {
+ showTrace: () => new Set<string>(),
+ toggleSpanCollapsed: (collapsed, { spanId }) => {
+ const next = new Set(collapsed)
+ if (!next.delete(spanId)) {
+ next.add(spanId)
+ }
+ return next
+ },
+ },
+ ],
+ fullChildListSpanIds: [
+ new Set<string>(),
+ {
+ showTrace: () => new Set<string>(),
+ showAllChildren: (shown, { spanId }) => new Set(shown).add(spanId),
+ },
+ ],
+ // Chains fold by default, so this holds the opened ones.
+ openChainIds: [
+ new Set<string>(),
+ {
+ showTrace: () => new Set<string>(),
+ toggleChain: (opened, { spanId }) => {
+ const next = new Set(opened)
+ if (!next.delete(spanId)) {
+ next.add(spanId)
+ }
+ return next
+ },
+ },
+ ],
+ // 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,
+ {
+ showTrace: () => null,
+ setInspectorTab: (_, { tab }) => tab,
+ },
+ ],
+ }),
+ selectors({
+ spanTree: [
+ (s) => [s.spans],
+ (spans: Span[]): TraceViewTree => {
+ const roots = buildSpanTree(spans)
+ const nodesById = new Map<string, SpanNode>()
+ const stack = [...roots]
+ while (stack.length > 0) {
+ const node = stack.pop()!
+ nodesById.set(node.span.span_id, node)
+ stack.push(...node.children)
+ }
+ return { roots, nodesById, descendantCounts: countDescendantsById(roots) }
+ },
+ ],
+ spanRows: [
+ (s) => [s.spanTree, s.collapsedSpanIds, s.fullChildListSpanIds, s.openChainIds, s.pinnedSpanId],
+ (
+ spanTree: TraceViewTree,
+ collapsedSpanIds: Set<string>,
+ fullChildListSpanIds: Set<string>,
+ openChainIds: Set<string>,
+ pinnedSpanId: string | null
+ ): TraceDialogRow[] =>
+ buildTraceDialogRows(spanTree.roots, {
+ collapsedSpanIds,
+ fullChildListSpanIds,
+ openChainIds,
+ pinned: (pinnedSpanId && spanTree.nodesById.get(pinnedSpanId)) || null,
+ }),
+ ],
+ flatSpans: [
+ (s) => [s.spanRows],
+ (spanRows: TraceDialogRow[]): SpanNode[] =>
+ spanRows.flatMap((row) => {
+ const node = rowSpanNode(row)
+ return node ? [node] : []
+ }),
+ ],
+ chainStartIds: [
+ (s) => [s.spanRows],
+ (spanRows: TraceDialogRow[]): { folded: Set<string>; opened: Set<string> } => {
+ const folded = new Set<string>()
+ const opened = new Set<string>()
+ for (const row of spanRows) {
+ if (row.kind === 'chain') {
+ folded.add(row.nodes[0].span.span_id)
+ } else if (row.kind === 'span' && row.openChainLength) {
+ opened.add(row.node.span.span_id)
+ }
+ }
+ return { folded, opened }
+ },
+ ],
+ selectedSpan: [
+ (s) => [s.spans, s.selectedSpanId, s.summary],
+ (spans: Span[], selectedSpanId: string | null, summary: TraceViewSummary): Span | null =>
+ spans.find((span) => span.span_id === selectedSpanId) ?? summary.rootSpan ?? spans[0] ?? null,
+ ],
+ // The tree's "<parent span missing>" row selects an id that only appears as a parent id.
+ missingParentSpanId: [
+ (s) => [s.spans, s.selectedSpanId],
+ (spans: Span[], selectedSpanId: string | null): string | null =>
+ selectedSpanId &&
+ !spans.some((span) => span.span_id === selectedSpanId) &&
+ spans.some((span) => span.parent_span_id === selectedSpanId)
+ ? selectedSpanId
+ : null,
+ ],
+ pinnedSpan: [
+ (s) => [s.spans, s.pinnedSpanId],
+ (spans: Span[], pinnedSpanId: string | null): Span | null =>
+ pinnedSpanId ? (spans.find((span) => span.span_id === pinnedSpanId) ?? null) : null,
+ ],
+ activeInspectorTab: [
+ (s) => [s.chosenInspectorTab, s.selectedSpan, s.sessionErrorBadgesEnabled],
+ // An error span leads with its exceptions. Otherwise the logs lead.
+ (chosen: SpanInspectorTab | null, selectedSpan: Span | null, errorsTabEnabled: boolean): SpanInspectorTab =>
+ chosen ?? (errorsTabEnabled && selectedSpan?.status_code === 2 ? 'errors' : 'logs'),
+ ],
+ serviceColorMap: [(s) => [s.spans], (spans: Span[]): Map<string, number> => buildServiceColorMap(spans)],
+ timeline: [
+ (s) => [s.spans],
+ (spans: Span[]): TraceViewTimeline => {
+ if (spans.length === 0) {
+ return { startUs: 0, durationUs: 0 }
+ }
+ const starts = spans.map((span) => parseTimestampUs(span.timestamp))
+ const ends = spans.map((span, i) => starts[i] + span.duration_nano / 1_000)
+ const startUs = Math.min(...starts)
+ return { startUs, durationUs: Math.max(...ends) - startUs }
+ },
+ ],
+ summary: [
+ (s) => [s.spans],
+ (spans: Span[]): TraceViewSummary => ({
+ rootSpan: spans.find((span) => span.is_root_span) ?? null,
+ spanCount: spans.length,
+ serviceCount: new Set(spans.map((span) => span.service_name)).size,
+ errorCount: spans.filter((span) => span.status_code === 2).length,
+ }),
+ ],
+ }),
+ listeners(({ values, actions }) => ({
+ selectNextSpan: () => {
+ actions.spanStepped()
+ // A missing-parent row is selectable too, so step from it rather than from the root fallback.
+ const currentId = values.missingParentSpanId ?? values.selectedSpan?.span_id
+ const index = values.flatSpans.findIndex((node) => node.span.span_id === currentId)
+ const next = values.flatSpans[Math.min(index + 1, values.flatSpans.length - 1)]
+ if (next) {
+ actions.selectSpan(next.span.span_id)
+ }
+ },
+ selectPreviousSpan: () => {
+ actions.spanStepped()
+ const currentId = values.missingParentSpanId ?? values.selectedSpan?.span_id
+ const index = values.flatSpans.findIndex((node) => node.span.span_id === currentId)
+ const previous = values.flatSpans[Math.max(index - 1, 0)]
+ if (previous) {
+ actions.selectSpan(previous.span.span_id)
+ }
+ },
+ // Left collapses the selected span, or moves up to its parent once there is nothing to collapse.
+ collapseSelectedSpan: () => {
+ const node = values.spanTree.nodesById.get(values.missingParentSpanId ?? values.selectedSpan?.span_id ?? '')
+ if (!node) {
+ return
+ }
+ actions.spanStepped()
+ const spanId = node.span.span_id
+ if (values.chainStartIds.opened.has(spanId)) {
+ actions.toggleChain(spanId)
+ } else if (node.children.length > 0 && !values.collapsedSpanIds.has(spanId)) {
+ actions.toggleSpanCollapsed(spanId)
+ } else if (node.parent) {
+ // The parent can sit inside a folded chain, which stands for it on screen.
+ const shown = new Set(values.flatSpans)
+ let parent: SpanNode | null = node.parent
+ while (parent && !shown.has(parent)) {
+ parent = parent.parent
+ }
+ if (parent) {
+ actions.selectSpan(parent.span.span_id)
+ }
+ }
+ },
+ // Right expands the selected span, or steps into its first child once it is open.
+ expandSelectedSpan: () => {
+ const node = values.spanTree.nodesById.get(values.missingParentSpanId ?? values.selectedSpan?.span_id ?? '')
+ if (!node || node.children.length === 0) {
+ return
+ }
+ if (values.chainStartIds.folded.has(node.span.span_id)) {
+ actions.spanStepped()
+ actions.toggleChain(node.span.span_id)
+ return
+ }
+ if (!values.collapsedSpanIds.has(node.span.span_id)) {
+ actions.selectNextSpan()
+ return
+ }
+ actions.spanStepped()
+ actions.toggleSpanCollapsed(node.span.span_id)
+ },
+ toggleSpanCollapsed: () => {
+ actions.keepSelectionOnScreen()
+ },
+ toggleChain: () => {
+ actions.keepSelectionOnScreen()
+ },
+ // The inspector must never show a span the list hides.
+ keepSelectionOnScreen: () => {
+ const selected = values.selectedSpanId ? values.spanTree.nodesById.get(values.selectedSpanId) : undefined
+ if (!selected) {
+ return
+ }
+ const shown = new Set(values.flatSpans)
+ let node: SpanNode | null = selected
+ while (node && !shown.has(node)) {
+ node = node.parent
+ }
+ if (node && node !== selected) {
+ actions.selectSpan(node.span.span_id)
+ }
+ },
+ })),
+])