Skip to content

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

feat(tracing): open traces in a url-backed drawer (#62917)

Jon McCallum9380406e62c6
diff --git a/products/tracing/frontend/TraceWaterfallView.test.tsx b/products/tracing/frontend/TraceWaterfallView.test.tsx
new file mode 100644
index 000000000000..04fccc6c90ba
--- /dev/null
+++ b/products/tracing/frontend/TraceWaterfallView.test.tsx
@@ -0,0 +1,73 @@
+import { fireEvent, render, within } from '@testing-library/react'
+
+import { TraceWaterfallView } from './TraceWaterfallView'
+import type { Span } from './types'
+
+// Give the waterfall real dimensions so react-window renders rows (ResizeObserver is mocked globally
+// in jest.setup.ts; AutoSizer returns 0×0 in jsdom without this).
+jest.mock('lib/components/AutoSizer', () => ({
+ AutoSizer: ({ renderProp }: { renderProp: (size: { height: number; width: number }) => React.ReactNode }) =>
+ renderProp({ height: 600, width: 800 }),
+}))
+
+// uuid (ClickHouse row id) and span_id (OTel id) are deliberately DISTINCT so a test can tell which
+// identity the click emits — the inspector/URL/tree all key on span_id, so selection must too.
+function makeSpan(overrides: Partial<Span>): Span {
+ return {
+ uuid: 'uuid-x',
+ trace_id: 'trace-1',
+ span_id: 'span-x',
+ parent_span_id: '',
+ name: 'span',
+ kind: 1,
+ service_name: 'svc',
+ status_code: 0,
+ timestamp: '2026-06-11T08:00:00.000Z',
+ end_time: '2026-06-11T08:00:00.010Z',
+ duration_nano: 10_000_000,
+ is_root_span: false,
+ matched_filter: true,
+ attributes: {},
+ ...overrides,
+ }
+}
+
+const root = makeSpan({ uuid: 'uuid-root', span_id: 'span-root', name: 'root-operation', is_root_span: true })
+const child = makeSpan({
+ uuid: 'uuid-child',
+ span_id: 'span-child',
+ parent_span_id: 'span-root',
+ name: 'child-operation',
+})
+
+describe('TraceWaterfallView', () => {
+ // Scope to the render's own container (no auto-cleanup here, and the name renders in both the
+ // visible label and the Lemon Tooltip title — [0] is the label).
+ const clickSpanRow = (container: HTMLElement, name: string): void => {
+ fireEvent.click(within(container).getAllByText(name)[0])
+ }
+
+ it('emits the clicked span_id (not the row uuid) so the inspector and URL can resolve it', () => {
+ const onSpanSelect = jest.fn()
+ const { container } = render(<TraceWaterfallView spans={[root, child]} onSpanSelect={onSpanSelect} />)
+
+ clickSpanRow(container, 'child-operation')
+
+ expect(onSpanSelect).toHaveBeenCalledWith('span-child')
+ expect(onSpanSelect).not.toHaveBeenCalledWith('uuid-child')
+ })
+
+ it('toggles selection off when the same span is clicked twice', () => {
+ // Controlled: the parent (scene) flows the new selection back via the prop, so the second
+ // click sees `child` selected and emits null. Simulate that round-trip with a rerender.
+ const onSpanSelect = jest.fn()
+ const { container, rerender } = render(<TraceWaterfallView spans={[root, child]} onSpanSelect={onSpanSelect} />)
+
+ clickSpanRow(container, 'child-operation')
+ rerender(<TraceWaterfallView spans={[root, child]} selectedSpanId="span-child" onSpanSelect={onSpanSelect} />)
+ clickSpanRow(container, 'child-operation')
+
+ expect(onSpanSelect).toHaveBeenNthCalledWith(1, 'span-child')
+ expect(onSpanSelect).toHaveBeenNthCalledWith(2, null)
+ })
+})
diff --git a/products/tracing/frontend/TraceWaterfallView.tsx b/products/tracing/frontend/TraceWaterfallView.tsx
index 70a0ec0579a8..ec53cb8e4c7a 100644
--- a/products/tracing/frontend/TraceWaterfallView.tsx
+++ b/products/tracing/frontend/TraceWaterfallView.tsx
@@ -1,19 +1,20 @@
import { CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { List, useDynamicRowHeight } from 'react-window'
+import { List, useDynamicRowHeight, useListRef } from 'react-window'
import { IconWarning } from '@posthog/icons'
-import { LemonTag } from '@posthog/lemon-ui'
import { getSeriesColor } from 'lib/colors'
import { AutoSizer } from 'lib/components/AutoSizer'
import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { SPAN_KIND_LABELS, STATUS_CODE_LABELS } from './types'
import type { Span } from './types'
interface TraceWaterfallViewProps {
spans: Span[]
+ /** Currently-selected span (controlled by the scene's URL-canonical state). */
+ selectedSpanId?: string | null
+ onSpanSelect?: (spanId: string | null) => void
}
interface SpanNode {
@@ -148,7 +149,6 @@ const ROW_HEIGHT = 32
const MAX_WATERFALL_HEIGHT = 600
// Rough extra room reserved when a span's detail panel is open, so a selection near the top of a
// short trace doesn't pop an unexpected scrollbar.
-const SELECTED_DETAIL_RESERVE = 320
function clampLabelColumnWidth(px: number): number {
return Math.min(MAX_LABEL_COLUMN_WIDTH, Math.max(MIN_LABEL_COLUMN_WIDTH, Math.round(px)))
@@ -246,44 +246,6 @@ function TreeIndent({ node }: { node: SpanNode }): JSX.Element | null {
)
}
-function SpanDetailPanel({ span }: { span: Span }): JSX.Element {
- const status = STATUS_CODE_LABELS[span.status_code] ?? { label: String(span.status_code), type: 'default' as const }
- const isError = span.status_code === 2
-
- return (
- <div className={`border-t bg-surface-primary px-4 py-3 text-xs ${isError ? 'border-l-2 border-l-danger' : ''}`}>
- <div className="grid grid-cols-[auto_1fr] gap-x-6 gap-y-1.5">
- <span className="text-muted font-medium">Service</span>
- <span className="font-mono">{span.service_name}</span>
- <span className="text-muted font-medium">Operation</span>
- <span className="font-mono">{span.name}</span>
- <span className="text-muted font-medium">Duration</span>
- <span className="font-mono">{formatDuration(span.duration_nano)}</span>
- <span className="text-muted font-medium">Kind</span>
- <span>{SPAN_KIND_LABELS[span.kind] ?? span.kind}</span>
- <span className="text-muted font-medium">Status</span>
- <span>
- <LemonTag type={status.type} size="small">
- {status.label}
- </LemonTag>
- </span>
- <span className="text-muted font-medium">Span ID</span>
- <span className="font-mono">{span.span_id}</span>
- {span.parent_span_id && (
- <>
- <span className="text-muted font-medium">Parent ID</span>
- <span className="font-mono">{span.parent_span_id}</span>
- </>
- )}
- <span className="text-muted font-medium">Start</span>
- <span className="font-mono">{span.timestamp}</span>
- <span className="text-muted font-medium">End</span>
- <span className="font-mono">{span.end_time}</span>
- </div>
- </div>
- )
-}
-
interface WaterfallRowData {
flatSpans: SpanNode[]
traceStartUs: number
@@ -318,7 +280,9 @@ function WaterfallRow({
const seriesIndex = serviceColorMap.get(span.service_name) ?? 0
const seriesColor = isError ? ERROR_COLOR : getSeriesColor(seriesIndex)
const barColor = isUnmatched ? 'var(--border)' : seriesColor
- const isSelected = selectedSpanId === span.uuid
+ // Select by span_id (the OTel id the tree is keyed by, and what the inspector/URL resolve),
+ // not the ClickHouse row uuid.
+ const isSelected = selectedSpanId === span.span_id
return (
<div>
@@ -331,11 +295,11 @@ function WaterfallRow({
role="button"
tabIndex={0}
aria-pressed={isSelected}
- onClick={() => onSelect(span.uuid)}
+ onClick={() => onSelect(span.span_id)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
- onSelect(span.uuid)
+ onSelect(span.span_id)
}
}}
>
@@ -411,9 +375,6 @@ function WaterfallRow({
</Tooltip>
</div>
</div>
-
- {/* Detail panel */}
- {isSelected && <SpanDetailPanel span={span} />}
</div>
)
}
@@ -462,8 +423,11 @@ function WaterfallListRow({
)
}
-export function TraceWaterfallView({ spans }: TraceWaterfallViewProps): JSX.Element {
- const [selectedSpanId, setSelectedSpanId] = useState<string | null>(null)
+export function TraceWaterfallView({
+ spans,
+ selectedSpanId = null,
+ onSpanSelect,
+}: TraceWaterfallViewProps): JSX.Element {
const [cursorPct, setCursorPct] = useState<number | null>(null)
const [labelColumnWidth, setLabelColumnWidth] = useState(
() => readStoredLabelColumnWidth() ?? DEFAULT_LABEL_COLUMN_WIDTH
@@ -481,10 +445,33 @@ export function TraceWaterfallView({ spans }: TraceWaterfallViewProps): JSX.Elem
const tree = useMemo(() => buildSpanTree(spans), [spans])
const flatSpans = useMemo(() => flattenTree(tree), [tree])
const dynamicRowHeight = useDynamicRowHeight({ defaultRowHeight: ROW_HEIGHT })
+ const listRef = useListRef(null)
+
+ // Deep links land with a span anchor — scroll it into view once the tree is built. The anchor
+ // is captured at mount (the drawer keys this component by trace, so it remounts per trace) so
+ // later selection changes from clicking don't recenter, and data refreshes (full-trace fetch
+ // replacing the prefetch) don't yank scroll after the user has started exploring.
+ const initialSpanRef = useRef(selectedSpanId)
+ const scrolledToInitialRef = useRef(false)
+ useEffect(() => {
+ if (scrolledToInitialRef.current || !initialSpanRef.current || flatSpans.length === 0) {
+ return
+ }
+ const index = flatSpans.findIndex((node) => node.span.span_id === initialSpanRef.current)
+ if (index >= 0) {
+ listRef.current?.scrollToRow({ index, align: 'center' })
+ scrolledToInitialRef.current = true
+ }
+ }, [flatSpans, listRef])
- const handleSelect = useCallback((spanId: string): void => {
- setSelectedSpanId((cur) => (cur === spanId ? null : spanId))
- }, [])
+ // Controlled: emit the new selection (toggling off if the same span is clicked) and let the
+ // scene flow it back via `selectedSpanId`. No internal copy, so highlight can't drift from the URL.
+ const handleSelect = useCallback(
+ (spanId: string): void => {
+ onSpanSelect?.(selectedSpanId === spanId ? null : spanId)
+ },
+ [selectedSpanId, onSpanSelect]
+ )
const { traceStartUs, traceDurationUs } = useMemo(() => {
if (spans.length === 0) {
@@ -683,10 +670,7 @@ export function TraceWaterfallView({ spans }: TraceWaterfallViewProps): JSX.Elem
renderProp={({ width }: SizeProps) => (
<List<WaterfallRowData>
style={{
- height: Math.min(
- flatSpans.length * ROW_HEIGHT + (selectedSpanId ? SELECTED_DETAIL_RESERVE : 0),
- MAX_WATERFALL_HEIGHT
- ),
+ height: Math.min(flatSpans.length * ROW_HEIGHT, MAX_WATERFALL_HEIGHT),
width,
}}
overscanCount={10}
@@ -704,6 +688,7 @@ export function TraceWaterfallView({ spans }: TraceWaterfallViewProps): JSX.Elem
onSelect: handleSelect,
dynamicRowHeight,
}}
+ listRef={listRef}
/>
)}
/>
diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsx
index 6b9eea93c189..50d656c65294 100644
--- a/products/tracing/frontend/TracingScene.tsx
+++ b/products/tracing/frontend/TracingScene.tsx
@@ -4,7 +4,6 @@ import posthog from 'posthog-js'
import { LemonBanner, LemonButton, LemonModal, Link } from '@posthog/lemon-ui'
import { IconFeedback } from 'lib/lemon-ui/icons'
-import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { SceneExport } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
@@ -15,10 +14,10 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import { TracingSetupPrompt } from './components/SetupPrompt/SetupPrompt'
+import { TraceDrawer } from './components/TraceDrawer/TraceDrawer'
import { VirtualizedSpanList } from './components/VirtualizedSpanList/VirtualizedSpanList'
import { TraceCompareFlame } from './TraceCompareFlame'
import { TraceCompareTable } from './TraceCompareTable'
-import { TraceWaterfallView } from './TraceWaterfallView'
import { tracingDataLogic } from './tracingDataLogic'
import { TracingFilterBar } from './TracingFilterBar'
import { tracingFiltersLogic } from './tracingFiltersLogic'
@@ -50,10 +49,12 @@ function TracingSceneContents(): JSX.Element {
spansLoading,
isTraceOpen,
selectedTraceId,
+ selectedSpanId,
+ selectedTraceTs,
sparklineData,
sparklineLoading,
totalSpansMatchingFilters,
- modalSpans,
+ openTraceSpans,
isLoadingFullTrace,
aggregation,
aggregationLoading,
@@ -74,6 +75,7 @@ function TracingSceneContents(): JSX.Element {
const {
openTrace,
closeTrace,
+ selectSpan,
setDateRange,
setOverlayWindows,
openCompareFlame,
@@ -208,23 +210,21 @@ function TracingSceneContents(): JSX.Element {
// element; react-modal then scrolls it back into view when restoring focus
// on close. Blur so the restore target is <body>, which doesn't scroll.
;(document.activeElement as HTMLElement | null)?.blur?.()
- openTrace(span.trace_id)
+ openTrace(span.trace_id, { ts: span.timestamp })
}}
/>
)}
</TracingSetupPrompt>
- <LemonModal
- title="Trace waterfall"
- description={selectedTraceId ? `Trace ${selectedTraceId}` : undefined}
+ <TraceDrawer
isOpen={isTraceOpen}
+ traceId={selectedTraceId}
+ ts={selectedTraceTs}
+ spans={openTraceSpans}
+ loading={isLoadingFullTrace}
+ selectedSpanId={selectedSpanId}
+ onSelectSpan={selectSpan}
onClose={closeTrace}
- width="90vw"
- >
- <div className="relative min-h-32">
- {isLoadingFullTrace && <SpinnerOverlay />}
- <TraceWaterfallView spans={modalSpans} />
- </div>
- </LemonModal>
+ />
<LemonModal
title={`Call tree diff: ${compareFlameSpanName ?? ''}`}
isOpen={compareFlameSpanName !== null}
diff --git a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
new file mode 100644
index 000000000000..f3ce2b03f3eb
--- /dev/null
+++ b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
@@ -0,0 +1,139 @@
+import { useValues } from 'kea'
+import { useMemo, useRef } from 'react'
+
+import { LemonButton, LemonTag, SpinnerOverlay } from '@posthog/lemon-ui'
+
+import { Resizer } from 'lib/components/Resizer/Resizer'
+import { type ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
+import { IconLink } from 'lib/lemon-ui/icons'
+import { LemonDrawer } from 'lib/lemon-ui/LemonDrawer/LemonDrawer'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { cn } from 'lib/utils/css-classes'
+
+import { useKeepMountedWhileOpen } from '../../hooks/useKeepMountedWhileOpen'
+import { absoluteTraceUrl } from '../../traceLinks'
+import { formatDuration, TraceWaterfallView } from '../../TraceWaterfallView'
+import type { Span } from '../../types'
+import { ExpandedSpanContent } from '../VirtualizedSpanList/ExpandedSpanContent'
+
+// Below this the inspector's content (the attribute KVP tables) stops being readable; clamp so a
+// drag can't crush it. The max is a flex `max-w` so a too-wide drag can't starve the waterfall.
+const MIN_INSPECTOR_WIDTH = 320
+
+export interface TraceDrawerProps {
+ isOpen: boolean
+ traceId: string | null
+ /** Timestamp hint echoed into copy-links so cold loads can bound the lookup. */
+ ts: string | null
+ spans: Span[]
+ loading: boolean
+ selectedSpanId: string | null
+ onSelectSpan: (spanId: string | null) => void
+ onClose: () => void
+}
+
+// Master-detail split: waterfall on the left drives the span inspector on the right — the same
+// list→detail relationship the span list has with this drawer, one level down. Tabs were
+// deliberately rejected: they'd hide the waterfall while reading a span's attributes, breaking
+// the click-through-spans-and-compare loop.
+export function TraceDrawer({
+ isOpen,
+ traceId,
+ ts,
+ spans,
+ loading,
+ selectedSpanId,
+ onSelectSpan,
+ onClose,
+}: TraceDrawerProps): JSX.Element | null {
+ // Waterfall|inspector split. Persisted so a user's preferred split sticks across traces;
+ // desiredSize is null until the first drag, leaving the responsive default (w-2/5) in place.
+ // One props object feeds both the value-read and the <Resizer>, so the logicKey can't desync.
+ const inspectorRef = useRef<HTMLDivElement>(null)
+ const inspectorResizerProps: ResizerLogicProps = {
+ logicKey: 'tracing-span-inspector',
+ placement: 'left',
+ containerRef: inspectorRef,
+ persistent: true,
+ }
+ const { desiredSize: inspectorWidth } = useValues(resizerLogic(inspectorResizerProps))
+
+ // 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])
+ const selectedSpan = useMemo(
+ () => (selectedSpanId ? (spans.find((span) => span.span_id === selectedSpanId) ?? null) : null),
+ [spans, selectedSpanId]
+ )
+
+ // Gate mounting so a closed drawer holds no react-modal portal (and its listener surface).
+ const shouldRender = useKeepMountedWhileOpen(isOpen)
+ if (!shouldRender) {
+ return null
+ }
+
+ // The inspector always shows something: the selected span, falling back to the root.
+ const inspectedSpan = selectedSpan ?? rootSpan
+
+ return (
+ <LemonDrawer
+ isOpen={isOpen}
+ onClose={onClose}
+ width="90vw"
+ resizable
+ data-attr="tracing-trace-drawer"
+ title={
+ <div className="flex items-center gap-2 min-w-0">
+ <span className="truncate">{rootSpan?.name ?? 'Trace'}</span>
+ {rootSpan && <LemonTag>{formatDuration(rootSpan.duration_nano)}</LemonTag>}
+ <span className="font-mono text-xs text-muted truncate">{traceId}</span>
+ <LemonButton
+ size="xsmall"
+ icon={<IconLink />}
+ tooltip="Copy link to this trace"
+ data-attr="tracing-drawer-copy-link"
+ onClick={() =>
+ traceId &&
+ void copyToClipboard(
+ absoluteTraceUrl({ traceId, spanId: selectedSpanId, ts }),
+ 'trace link'
+ )
+ }
+ />
+ </div>
+ }
+ >
+ <div className="relative min-h-32 flex gap-4 items-start">
+ {loading && <SpinnerOverlay />}
+ <div className="flex-1 min-w-0">
+ {/* Keyed by trace so a new trace resets selection + scroll state. */}
+ <TraceWaterfallView
+ key={traceId ?? ''}
+ spans={spans}
+ selectedSpanId={selectedSpanId}
+ onSpanSelect={onSelectSpan}
+ />
+ </div>
+ <div
+ ref={inspectorRef}
+ className={cn(
+ 'relative shrink-0 border-l border-border pl-4 max-w-[70%]',
+ inspectorWidth == null && 'w-2/5'
+ )}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={
+ inspectorWidth != null ? { width: Math.max(MIN_INSPECTOR_WIDTH, inspectorWidth) } : undefined
+ }
+ data-attr="tracing-span-inspector"
+ >
+ <Resizer {...inspectorResizerProps} />
+ {inspectedSpan ? (
+ <ExpandedSpanContent span={inspectedSpan} />
+ ) : (
+ <div className="text-muted p-4">No spans in this trace</div>
+ )}
+ </div>
+ </div>
+ </LemonDrawer>
+ )
+}
diff --git a/products/tracing/frontend/components/VirtualizedSpanList/SpanRowActions.test.tsx b/products/tracing/frontend/components/VirtualizedSpanList/SpanRowActions.test.tsx
index 8c544a32fe5c..3445191e5a90 100644
--- a/products/tracing/frontend/components/VirtualizedSpanList/SpanRowActions.test.tsx
+++ b/products/tracing/frontend/components/VirtualizedSpanList/SpanRowActions.test.tsx
@@ -9,7 +9,7 @@ jest.mock('lib/utils/copyToClipboard', () => ({
copyToClipboard: jest.fn(),
}))
-const span = { trace_id: 'trace-abc-123', name: 'GET /api/projects' } as Span
+const span = { trace_id: 'trace-abc-123', name: 'GET /api/projects', timestamp: '2026-06-11T08:00:00.000Z' } as Span
describe('SpanRowActions', () => {
beforeEach(() => {
@@ -20,6 +20,7 @@ describe('SpanRowActions', () => {
const { container } = render(<SpanRowActions span={span} onViewTrace={jest.fn()} />)
expect(container.querySelector('[data-attr="tracing-view-trace"]')).toBeTruthy()
expect(container.querySelector('[data-attr="tracing-copy-trace-id"]')).toBeTruthy()
+ expect(container.querySelector('[data-attr="tracing-copy-link"]')).toBeTruthy()
})
it('fires onViewTrace when View trace is clicked', () => {
@@ -35,10 +36,19 @@ describe('SpanRowActions', () => {
expect(copyToClipboard).toHaveBeenCalledWith('trace-abc-123', 'trace ID')
})
+ it('copies a canonical trace link carrying the ts hint', () => {
+ const { container } = render(<SpanRowActions span={span} onViewTrace={jest.fn()} />)
+ fireEvent.click(container.querySelector('[data-attr="tracing-copy-link"]')!)
+ expect(copyToClipboard).toHaveBeenCalledWith(
+ `${window.location.origin}/tracing?trace=trace-abc-123&ts=2026-06-11T08%3A00%3A00.000Z`,
+ 'trace link'
+ )
+ })
+
// Both buttons stop propagation so a click never reaches the row's own onClick. This matters most
// for "View trace": in VirtualizedSpanList the row onClick and onViewTrace are the same handler, so
// dropping stopPropagation would open the trace modal twice on a single click.
- it.each(['tracing-view-trace', 'tracing-copy-trace-id'])(
+ it.each(['tracing-view-trace', 'tracing-copy-trace-id', 'tracing-copy-link'])(
'stops %s clicks from bubbling to the row body',
(dataAttr) => {
const onRowClick = jest.fn()
diff --git a/products/tracing/frontend/components/VirtualizedSpanList/SpanRowActions.tsx b/products/tracing/frontend/components/VirtualizedSpanList/SpanRowActions.tsx
index e8a1de3e8410..835b887c858f 100644
--- a/products/tracing/frontend/components/VirtualizedSpanList/SpanRowActions.tsx
+++ b/products/tracing/frontend/components/VirtualizedSpanList/SpanRowActions.tsx
@@ -1,8 +1,10 @@
import { IconCopy, IconListTree } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
+import { IconLink } from 'lib/lemon-ui/icons'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { absoluteTraceUrl } from '../../traceLinks'
import type { Span } from '../../types'
export interface SpanRowActionsProps {
@@ -39,6 +41,18 @@ export function SpanRowActions({ span, onViewTrace }: SpanRowActionsProps): JSX.
aria-label="Copy trace ID"
data-attr="tracing-copy-trace-id"
/>
+ <LemonButton
+ size="xsmall"
+ icon={<IconLink />}
+ onClick={(e) => {
+ e.stopPropagation()
+ // ts hint keeps the cold-load lookup bounded — the table is time-keyed.
+ void copyToClipboard(absoluteTraceUrl({ traceId: span.trace_id, ts: span.timestamp }), 'trace link')
+ }}
+ tooltip="Copy link to trace"
+ aria-label="Copy link to trace"
+ data-attr="tracing-copy-link"
+ />
</div>
)
}
diff --git a/products/tracing/frontend/hooks/useKeepMountedWhileOpen.ts b/products/tracing/frontend/hooks/useKeepMountedWhileOpen.ts
new file mode 100644
index 000000000000..317f6ca8d89e
--- /dev/null
+++ b/products/tracing/frontend/hooks/useKeepMountedWhileOpen.ts
@@ -0,0 +1,37 @@
+import { useEffect, useRef, useState } from 'react'
+
+// react-modal (under LemonModal/LemonDrawer) mounts a portal container the moment it
+// renders, even when closed, and React 18 binds its full delegated event surface to that
+// container. A modal that's rendered-but-closed therefore leaks that container + listeners
+// every time it mounts/unmounts (e.g. on navigation). Gate the modal on this so a
+// never-opened modal mounts no portal at all. Keep it mounted for `graceMs` after close so
+// react-modal's closeTimeoutMS exit animation can finish before we unmount.
+// Duplicated from products/logs/frontend/hooks (product isolation); promote to lib/hooks if a
+// third product needs it.
+export function useKeepMountedWhileOpen(isOpen: boolean, graceMs = 300): boolean {
+ const [shouldRender, setShouldRender] = useState(isOpen)
+ const timeoutRef = useRef<number | null>(null)
+
+ useEffect(() => {
+ if (timeoutRef.current !== null) {
+ clearTimeout(timeoutRef.current)
+ timeoutRef.current = null
+ }
+ if (isOpen) {
+ setShouldRender(true)
+ return
+ }
+ timeoutRef.current = window.setTimeout(() => {
+ setShouldRender(false)
+ timeoutRef.current = null
+ }, graceMs)
+ return () => {
+ if (timeoutRef.current !== null) {
+ clearTimeout(timeoutRef.current)
+ timeoutRef.current = null
+ }
+ }
+ }, [isOpen, graceMs])
+
+ return shouldRender
+}
diff --git a/products/tracing/frontend/traceLinks.test.ts b/products/tracing/frontend/traceLinks.test.ts
new file mode 100644
index 000000000000..567bc0fcbedd
--- /dev/null
+++ b/products/tracing/frontend/traceLinks.test.ts
@@ -0,0 +1,23 @@
+import { traceLookupDateRange, traceUrl } from './traceLinks'
+
+describe('traceLinks', () => {
+ it.each([
+ [{ traceId: 'abc123' }, '/tracing?trace=abc123'],
+ [{ traceId: 'abc123', spanId: 'def456' }, '/tracing?trace=abc123&span=def456'],
+ [
+ { traceId: 'abc123', spanId: 'def456', ts: '2026-06-11T08:00:00.000Z' },
+ '/tracing?trace=abc123&span=def456&ts=2026-06-11T08%3A00%3A00.000Z',
+ ],
+ // Null/undefined anchor and hint are simply omitted.
+ [{ traceId: 'abc123', spanId: null, ts: null }, '/tracing?trace=abc123'],
+ ])('traceUrl(%j) → %s', (params, expected) => {
+ expect(traceUrl(params)).toBe(expected)
+ })
+
+ it('traceLookupDateRange bounds the lookup to ±1h around the hint', () => {
+ expect(traceLookupDateRange('2026-06-11T08:00:00.000Z')).toEqual({
+ date_from: '2026-06-11T07:00:00.000Z',
+ date_to: '2026-06-11T09:00:00.000Z',
+ })
+ })
+})
diff --git a/products/tracing/frontend/traceLinks.ts b/products/tracing/frontend/traceLinks.ts
new file mode 100644
index 000000000000..21acbccbd8d7
--- /dev/null
+++ b/products/tracing/frontend/traceLinks.ts
@@ -0,0 +1,39 @@
+// Canonical trace URLs (JON-33). The URL is the atomic, shareable form of a trace view:
+// `/tracing?trace=<hex>` opens the drawer, `&span=<hex>` anchors a span, `&ts=<iso>` carries the
+// root timestamp so a cold load can bound the ClickHouse lookup (the table is time-keyed and OTel
+// trace ids embed no timestamp — an unhinted id lookup would scan the whole retention window).
+
+import { dayjs } from 'lib/dayjs'
+import { urls } from 'scenes/urls'
+
+export interface TraceLinkParams {
+ traceId: string
+ spanId?: string | null
+ /** ISO timestamp of (any span of) the trace, used to bound the cold-load query. */
+ ts?: string | null
+}
+
+/** Path + query for a trace view, relative to the app root. */
+export function traceUrl({ traceId, spanId, ts }: TraceLinkParams): string {
+ const params = new URLSearchParams({ trace: traceId })
+ if (spanId) {
+ params.set('span', spanId)
+ }
+ if (ts) {
+ params.set('ts', ts)
+ }
+ return `${urls.tracing()}?${params.toString()}`
+}
+
+/** Absolute, shareable URL for a trace view. */
+export function absoluteTraceUrl(params: TraceLinkParams): string {
+ return urls.absolute(traceUrl(params))
+}
+
+/** The window a `ts`-hinted cold load queries: ±1h is generous for any single trace's spans. */
+export function traceLookupDateRange(ts: string): { date_from: string; date_to: string } {
+ return {
+ date_from: dayjs(ts).subtract(1, 'hour').toISOString(),
+ date_to: dayjs(ts).add(1, 'hour').toISOString(),
+ }
+}
diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.ts
index a9035ac4bb7b..32e70e30017c 100644
--- a/products/tracing/frontend/tracingDataLogic.ts
+++ b/products/tracing/frontend/tracingDataLogic.ts
@@ -19,6 +19,7 @@ import {
type VisibleDurationRange,
visibleDurationRange,
} from './durationBuckets'
+import { traceLookupDateRange } from './traceLinks'
import type { tracingDataLogicType } from './tracingDataLogicType'
import { type TracingFilters, type TracingOrderBy, tracingFiltersLogic } from './tracingFiltersLogic'
import type { Span } from './types'
@@ -271,12 +272,20 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
traceSpans: [
[] as Span[],
{
- loadTraceSpans: async (traceId: string): Promise<Span[]> => {
+ loadTraceSpans: async ({ traceId, ts }: { traceId: string; ts?: string | null }): Promise<Span[]> => {
+ // A ts hint (from a shared/cold link) bounds the lookup tightly around the trace
+ // instead of the scene's current date range — the table is time-keyed, so this is
+ // what keeps an id lookup from scanning the whole window. Guard validity: a
+ // hand-edited/corrupted ?ts= would otherwise make dayjs throw on toISOString().
+ const dateRange =
+ ts && dayjs(ts).isValid()
+ ? traceLookupDateRange(ts)
+ : {
+ date_from: values.utcDateRange.date_from ?? '-24h',
+ date_to: values.utcDateRange.date_to ?? undefined,
+ }
const response = await api.tracing.getTrace(traceId, {
- dateRange: {
- date_from: values.utcDateRange.date_from ?? '-24h',
- date_to: values.utcDateRange.date_to ?? undefined,
- },
+ dateRange,
serviceNames: values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
filterGroup: values.filters.filterGroup as PropertyGroupFilter,
})
diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.ts
index 3bcc966296bc..30b8f488041e 100644
--- a/products/tracing/frontend/tracingSceneLogic.ts
+++ b/products/tracing/frontend/tracingSceneLogic.ts
@@ -69,7 +69,12 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
actions({
toggleExpandSpan: (uuid: string) => ({ uuid }),
- openTrace: (traceId: string) => ({ traceId }),
+ openTrace: (traceId: string, options?: { spanId?: string | null; ts?: string | null }) => ({
+ traceId,
+ spanId: options?.spanId ?? null,
+ ts: options?.ts ?? null,
+ }),
+ selectSpan: (spanId: string | null) => ({ spanId }),
closeTrace: true,
openCompareFlame: (spanName: string, serviceName: string) => ({ spanName, serviceName }),
closeCompareFlame: true,
@@ -101,6 +106,23 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
closeTrace: () => null,
},
],
+ selectedSpanId: [
+ null as string | null,
+ {
+ openTrace: (_, { spanId }) => spanId,
+ selectSpan: (_, { spanId }) => spanId,
+ closeTrace: () => null,
+ },
+ ],
+ // Timestamp hint for the open trace — echoed into copy-links so cold loads can bound the
+ // ClickHouse lookup (the spans table is time-keyed; OTel ids embed no timestamp).
+ selectedTraceTs: [
+ null as string | null,
+ {
+ openTrace: (_, { ts }) => ts,
+ closeTrace: () => null,
+ },
+ ],
compareFlameSpanName: [
null as string | null,
{
@@ -122,7 +144,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
(s) => [s.selectedTraceId],
(selectedTraceId: string | null): boolean => selectedTraceId !== null,
],
- modalSpans: [
+ openTraceSpans: [
(s) => [s.selectedTraceId, s.spans, s.traceSpans],
(selectedTraceId: string | null, spans: Span[], traceSpans: Span[]): Span[] => {
if (!selectedTraceId) {
@@ -149,11 +171,13 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
}),
listeners(({ actions, values }) => ({
- openTrace: ({ traceId }) => {
+ openTrace: ({ traceId, ts }) => {
posthog.capture('tracing trace opened')
const prefetchedSpans = values.spans.filter((s: Span) => s.trace_id === traceId)
- if (prefetchedSpans.length >= PREFETCH_SPANS) {
- actions.loadTraceSpans(traceId)
+ // Zero prefetched spans = the trace isn't in the loaded list (cold link) — fetch it by
+ // id. A full prefetch batch (>= PREFETCH_SPANS) may be truncated — fetch the rest.
+ if (prefetchedSpans.length === 0 || prefetchedSpans.length >= PREFETCH_SPANS) {
+ actions.loadTraceSpans({ traceId, ts })
}
},
openCompareFlame: ({ spanName, serviceName }) => {
@@ -260,12 +284,46 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
} else if (!values.hasRunQuery) {
actions.runQuery()
}
+
+ // Drawer params. Guarded on a state/URL mismatch so the actionToUrl writes below don't
+ // loop back through here, and so back/forward opens/closes the drawer correctly.
+ const traceFromUrl = typeof searchParams.trace === 'string' ? searchParams.trace : null
+ const spanFromUrl = typeof searchParams.span === 'string' ? searchParams.span : null
+ if (traceFromUrl && traceFromUrl !== values.selectedTraceId) {
+ actions.openTrace(traceFromUrl, {
+ spanId: spanFromUrl,
+ ts: typeof searchParams.ts === 'string' ? searchParams.ts : null,
+ })
+ } else if (traceFromUrl && spanFromUrl !== values.selectedSpanId) {
+ // Same trace already open, but the URL's span anchor changed (e.g. a shared span
+ // link to a trace the user already has open) — move the selection, don't reopen.
+ actions.selectSpan(spanFromUrl)
+ } else if (!traceFromUrl && values.selectedTraceId) {
+ actions.closeTrace()
+ }
},
})),
trackedActionToUrl(({ values, actions }) => {
+ // The drawer params (trace/span/ts) live alongside the filter params. They're written by
+ // their own handlers below (which must NOT re-run the list query), and preserved by
+ // buildUrl so a filter change doesn't silently strip an open drawer from the URL.
+ const drawerParams = (): Params => {
+ const params: Params = {}
+ if (values.selectedTraceId) {
+ params.trace = values.selectedTraceId
+ if (values.selectedSpanId) {
+ params.span = values.selectedSpanId
+ }
+ if (values.selectedTraceTs) {
+ params.ts = values.selectedTraceTs
+ }
+ }
+ return params
+ }
+
const buildUrl = (): [string, Params, Record<string, any>, { replace: boolean }] => {
- const searchParams: Params = {}
+ const searchParams: Params = { ...drawerParams() }
if (!equal(values.filters.dateRange, DEFAULT_DATE_RANGE)) {
searchParams.dateRange = JSON.stringify(values.filters.dateRange)
@@ -290,8 +348,24 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
}
+ // Merge the drawer's state into the CURRENT url (filters untouched, no query re-run).
+ // Opening/closing pushes a history entry (back closes the drawer); span selection replaces
+ // (clicking around a waterfall shouldn't spam history).
+ const drawerUrl = (replace: boolean): [string, Params, Record<string, any>, { replace: boolean }] => {
+ const { trace, span, ts, ...rest } = router.values.searchParams
+ return [
+ router.values.location.pathname,
+ { ...rest, ...drawerParams() },
+ router.values.hashParams,
+ { replace },
+ ]
+ }
+
return {
syncUrlAndRunQuery: () => buildUrl(),
+ openTrace: () => drawerUrl(false),
+ selectSpan: () => drawerUrl(true),
+ closeTrace: () => drawerUrl(false),
}
}),
])