: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): show the opening log and span keys in the trace dialog (#116958)
Jon McCallumb242112f44df
diff --git a/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.tsx b/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.tsxindex 536f3a899d46..a2025b67930f 100644--- a/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.tsx+++ b/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.tsx@@ -154,7 +154,7 @@ export function addLogsValueFilter(return mergeFilterIntoValues(currentValues, newPropertyFilter)}-export const LogsFilterSearch = (): JSX.Element => {+export const LogsFilterSearch = ({ autoFocus = true }: { autoFocus?: boolean }): JSX.Element => {const [visible, setVisible] = useState<boolean>(false)const { utcDateRange, queryFilterGroup } = useValues(logsViewerFiltersLogic)const { focusFilter } = useActions(logsViewerFiltersLogic)@@ -216,6 +216,7 @@ export const LogsFilterSearch = (): JSX.Element => {<TaxonomicFilterSearchInputonClick={() => setVisible(true)}searchInputRef={searchInputRef}+ autoFocus={autoFocus}onClose={() => onClose()}onChange={() => setVisible(true)}/>diff --git a/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsQueryBar.tsx b/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsQueryBar.tsxindex 393949cdac1a..7db86a73ef30 100644--- a/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsQueryBar.tsx+++ b/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsQueryBar.tsx@@ -18,10 +18,12 @@ import { LogsAppliedFilters, LogsFilterGroup, LogsFilterSearch, LogsQueryControlexport const LogsQueryBar = ({showSavedViewsButton = false,showFullScreenButton = false,+ autoFocusSearch = true,scope,}: {showSavedViewsButton?: booleanshowFullScreenButton?: boolean+ autoFocusSearch?: booleanscope?: LogsViewerScope}): JSX.Element => {const { id } = useValues(logsViewerFiltersLogic)@@ -32,7 +34,7 @@ export const LogsQueryBar = ({<div className="flex gap-2 flex-wrap w-full justify-between"><div className="flex shrink-0 flex-1 gap-1.5"><div className="flex-1 min-w-[300px]">- <LogsFilterSearch />+ <LogsFilterSearch autoFocus={autoFocusSearch} /></div><FilterHistoryDropdown />{showSavedViewsButton && <SavedViewsButton id={id} iconOnly />}diff --git a/products/logs/frontend/components/LogsViewer/LogContextLinks/LogContextLinks.tsx b/products/logs/frontend/components/LogsViewer/LogContextLinks/LogContextLinks.tsxindex 665685d5dcad..13b7d5a75d19 100644--- a/products/logs/frontend/components/LogsViewer/LogContextLinks/LogContextLinks.tsx+++ b/products/logs/frontend/components/LogsViewer/LogContextLinks/LogContextLinks.tsx@@ -74,7 +74,13 @@ export function LogContextLinks({traceId={traceId}spanId={log.span_id}timestamp={log.timestamp}- onClick={(event) => openTraceDialog(event, { traceId, spanId: log.span_id, ts: log.timestamp })}+ onClick={(event) =>+ openTraceDialog(+ event,+ { traceId, spanId: log.span_id, ts: log.timestamp },+ { openedFrom: { body: log.cleanBody, severity: log.severity_text } }+ )+ }size="xsmall"type="secondary"data-attr={TRACE_DATA_ATTR[surface]}diff --git a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx b/products/logs/frontend/components/LogsViewer/LogsViewer.tsxindex 26497b8f2be5..c9a0cc6d45f8 100644--- a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx+++ b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx@@ -22,6 +22,7 @@ import { logsExportLogic } from 'products/logs/frontend/components/LogsViewer/loimport { QueryFailedOverlay } from 'products/logs/frontend/components/QueryFailedOverlay'import { VirtualizedLogsList } from 'products/logs/frontend/components/VirtualizedLogsList/VirtualizedLogsList'import { virtualizedLogsListLogic } from 'products/logs/frontend/components/VirtualizedLogsList/virtualizedLogsListLogic'+import { traceDialogLogic } from 'products/tracing/frontend/components/TraceDialog/traceDialogLogic'import { LogDetailsModal } from './LogDetailsModal'import { logDetailsModalLogic } from './LogDetailsModal/logDetailsModalLogic'@@ -52,6 +53,8 @@ export interface LogsViewerProps {defaultFacetRailCollapsed?: boolean// Same, for the volume chart. Panels embedded in a short pane start without it.defaultSparklineCollapsed?: boolean+ // A panel embedded under other keyboard controls leaves focus where it is.+ autoFocusSearch?: boolean}export function LogsViewer({@@ -64,6 +67,7 @@ export function LogsViewer({sessionId,defaultFacetRailCollapsed,defaultSparklineCollapsed,+ autoFocusSearch = true,}: LogsViewerProps): JSX.Element {return (<BindLogic logic={logsViewerFiltersLogic} props={{ id, initialFilters, pinnedFilters, personId, sessionId }}>@@ -79,6 +83,7 @@ export function LogsViewer({<LogsViewerContentshowFullScreenButton={showFullScreenButton}showSavedViewsButton={showSavedViewsButton}+ autoFocusSearch={autoFocusSearch}scope={{ initialFilters, pinnedFilters, personId, sessionId }}/></BindLogic>@@ -102,10 +107,12 @@ function ConnectedLogsSparkline(props: Omit<LogsViewerSparklineProps, 'visibleRofunction LogsViewerContent({showFullScreenButton,showSavedViewsButton,+ autoFocusSearch,scope,}: {showFullScreenButton: booleanshowSavedViewsButton: boolean+ autoFocusSearch: booleanscope: LogsViewerScope}): JSX.Element {const {@@ -132,6 +139,7 @@ function LogsViewerContent({togglePrettifyLog,} = useActions(logsViewerLogic)const { orderBy, sparklineCollapsed, facetRailCollapsed, viewMode } = useValues(logsViewerConfigLogic)+ const { isOpen: isTraceDialogOpen } = useValues(traceDialogLogic)const { setOrderBy, toggleSparklineCollapsed } = useActions(logsViewerConfigLogic)const {logsLoading,@@ -189,7 +197,7 @@ function LogsViewerContent({// Handle keyboard scroll with keydown/keyup for smooth 60fps scrollinguseEffect(() => {- if (!isFocused || wrapBody) {+ if (!isFocused || wrapBody || isTraceDialogOpen) {return}@@ -220,7 +228,7 @@ function LogsViewerContent({window.removeEventListener('keyup', handleKeyUp)stopScrolling()}- }, [isFocused, wrapBody, startScrolling, stopScrolling])+ }, [isFocused, wrapBody, isTraceDialogOpen, startScrolling, stopScrolling])const tzLabelFormat: Pick<TZLabelProps, 'formatDate' | 'formatTime' | 'displayTimezone'> = {formatDate: 'YYYY-MM-DD',@@ -242,12 +250,16 @@ function LogsViewerContent({[moveCursorUp])+ // The trace dialog opens over the viewer, so the viewer's keys stop while it is open.+ const listKeysEnabled = keyboardNavEnabled && !isTraceDialogOpen+ const focusedListKeysEnabled = isFocused && !isTraceDialogOpen+useKeyboardHotkeys({- arrowdown: { action: handleMoveDown, disabled: !keyboardNavEnabled, allowRepeat: true },- j: { action: handleMoveDown, disabled: !keyboardNavEnabled, allowRepeat: true },- arrowup: { action: handleMoveUp, disabled: !keyboardNavEnabled, allowRepeat: true },- k: { action: handleMoveUp, disabled: !keyboardNavEnabled, allowRepeat: true },+ arrowdown: { action: handleMoveDown, disabled: !listKeysEnabled, allowRepeat: true },+ j: { action: handleMoveDown, disabled: !listKeysEnabled, allowRepeat: true },+ arrowup: { action: handleMoveUp, disabled: !listKeysEnabled, allowRepeat: true },+ k: { action: handleMoveUp, disabled: !listKeysEnabled, allowRepeat: true },// arrowleft, arrowright, h, l handled by native keydown/keyup for smooth 60fps scrollingenter: {action: () => {@@ -255,7 +267,7 @@ function LogsViewerContent({openLogDetails(parsedLogs[cursorIndex])}},- disabled: !keyboardNavEnabled,+ disabled: !listKeysEnabled,},r: {action: () => {@@ -264,7 +276,7 @@ function LogsViewerContent({refreshQuery()}},- disabled: !isFocused,+ disabled: !focusedListKeysEnabled,},space: {action: (e: KeyboardEvent) => {@@ -273,7 +285,7 @@ function LogsViewerContent({toggleSelectLog(cursorLogId)}},- disabled: !isFocused,+ disabled: !focusedListKeysEnabled,},escape: {action: () => {@@ -283,7 +295,7 @@ function LogsViewerContent({clearSelection()}},- disabled: !keyboardNavEnabled,+ disabled: !listKeysEnabled,},p: {action: () => {@@ -291,12 +303,13 @@ function LogsViewerContent({togglePrettifyLog(cursorLogId)}},- disabled: !isFocused,+ disabled: !focusedListKeysEnabled,},},[isFocused,keyboardNavEnabled,+ isTraceDialogOpen,isLogDetailsOpen,cursorIndex,parsedLogs,@@ -410,6 +423,7 @@ function LogsViewerContent({<LogsQueryBarshowSavedViewsButton={showSavedViewsButton}showFullScreenButton={showFullScreenButton}+ autoFocusSearch={autoFocusSearch}scope={scope}/>{sparklineSection}diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialog.tsxindex 73f2cee4a9e9..1e944f625504 100644--- a/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx+++ b/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx@@ -12,7 +12,9 @@ import { SpanInspector } from 'products/tracing/frontend/components/SpanInspectoimport { MissingParentSpanNotice } from 'products/tracing/frontend/components/TraceDrawer/MissingParentSpanNotice'import { formatDuration } from 'products/tracing/frontend/TraceWaterfallView'-import { traceDialogLogic } from './traceDialogLogic'+import { TRACE_DIALOG_DATA_ATTR, traceDialogLogic } from './traceDialogLogic'+import { TraceDialogOpenedFromLog } from './TraceDialogOpenedFromLog'+import { TraceDialogShortcuts } from './TraceDialogShortcuts'import { TraceDialogSpanTree } from './TraceDialogSpanTree'export function TraceDialog(): JSX.Element | null {@@ -63,23 +65,28 @@ export function TraceDialog(): JSX.Element | null {</div>}forceAbovePopovers+ data-attr={TRACE_DIALOG_DATA_ATTR}width="90vw"maxWidth={1600}footer={- <LemonButton- type="secondary"- icon={<IconExternal />}- to={traceUrl(trace)}- onClick={closeTraceDialog}- data-attr="trace-dialog-open-in-tracing"- >- Open in Tracing- </LemonButton>+ <div className="flex flex-wrap items-center justify-between gap-2 w-full">+ <TraceDialogShortcuts />+ <LemonButton+ type="secondary"+ icon={<IconExternal />}+ to={traceUrl(trace)}+ onClick={closeTraceDialog}+ data-attr="trace-dialog-open-in-tracing"+ >+ Open in Tracing+ </LemonButton>+ </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]">+ <TraceDialogOpenedFromLog />{traceSpans?.truncated && (<LemonBanner type="info">Showing the first {summary.spanCount.toLocaleString()} spans. Open this trace in Tracing todiff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogOpenedFromLog.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogOpenedFromLog.tsxnew file mode 100644index 000000000000..c10acb752dca--- /dev/null+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogOpenedFromLog.tsx@@ -0,0 +1,60 @@+import { useActions, useValues } from 'kea'++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'++export function TraceDialogOpenedFromLog(): JSX.Element | null {+ const { openedFrom, openedSpan, openedAtUs, timeline } = useValues(traceDialogLogic)+ const { selectSpan, closeTraceDialog } = useActions(traceDialogLogic)++ if (!openedFrom) {+ return null+ }++ return (+ <div+ className="flex flex-wrap items-center gap-2 rounded border border-accent bg-accent-highlight-secondary px-2 py-1 text-xs"+ data-attr="trace-dialog-opened-from-log"+ >+ <span className="font-semibold">Opened from log</span>+ <LogTag level={openedFrom.severity} />+ <span+ className="ph-replay-block ph-no-capture font-mono truncate flex-1 basis-60 min-w-0"+ translate="no"+ title={openedFrom.body}+ >+ {openedFrom.body}+ </span>+ {openedSpan && (+ <span className="flex items-center gap-1 text-muted min-w-0 max-w-full">+ <span className="shrink-0">Emitted by</span>+ <LemonButton+ size="xsmall"+ type="tertiary"+ truncate+ className="min-w-0"+ onClick={() => selectSpan(openedSpan.span_id)}+ data-attr="trace-dialog-opened-span"+ tooltip={openedSpan.name}+ >+ <span className="font-mono" translate="no">+ {openedSpan.name}+ </span>+ </LemonButton>+ {openedAtUs != null && (+ <span className="font-mono shrink-0" translate="no">+ +{formatDuration(Math.max(openedAtUs - timeline.startUs, 0) * 1_000)}+ </span>+ )}+ </span>+ )}+ <LemonButton size="xsmall" type="secondary" onClick={closeTraceDialog} data-attr="trace-dialog-back-to-log">+ Back to log+ </LemonButton>+ </div>+ )+}diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogShortcuts.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogShortcuts.tsxnew file mode 100644index 000000000000..fa490254c463--- /dev/null+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogShortcuts.tsx@@ -0,0 +1,27 @@+import { useValues } from 'kea'++import { KeyboardShortcut } from 'lib/components/KeyboardShortcut/KeyboardShortcut'++import { traceDialogLogic } from './traceDialogLogic'++export function TraceDialogShortcuts(): JSX.Element {+ const { openedFrom } = useValues(traceDialogLogic)++ return (+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted">+ <span className="flex items-center gap-1">+ <KeyboardShortcut escape />+ <span>{openedFrom ? 'Back to log' : 'Close'}</span>+ </span>+ <span className="flex items-center gap-1">+ <KeyboardShortcut j />+ <KeyboardShortcut k />+ <span>Next or previous span</span>+ </span>+ <span className="flex items-center gap-1">+ <KeyboardShortcut command />+ <span>Click Open in Tracing for a new tab</span>+ </span>+ </div>+ )+}diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsxnew file mode 100644index 000000000000..75d29f5f1be2--- /dev/null+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsx@@ -0,0 +1,75 @@+import '@testing-library/jest-dom'++import { cleanup, render, waitFor } from '@testing-library/react'+import { Provider } from 'kea'+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'++import { initKeaTests } from '~/test/init'++import type { Span } from 'products/tracing/frontend/types'++import { traceDialogLogic } from './traceDialogLogic'+import { TraceDialogSpanTree } from './TraceDialogSpanTree'++function span(spanId: string, parentSpanId: string): Span {+ return {+ uuid: spanId,+ trace_id: 'abc123',+ span_id: spanId,+ parent_span_id: parentSpanId,+ name: `${spanId} span`,+ kind: 0,+ service_name: 'agent-worker',+ status_code: 0,+ timestamp: '2026-10-14T10:00:00.000000Z',+ end_time: '2026-10-14T10:00:01.000000Z',+ duration_nano: 1_000_000_000,+ is_root_span: parentSpanId === '',+ matched_filter: true,+ attributes: {},+ resource_attributes: {},+ }+}++describe('TraceDialogSpanTree', () => {+ beforeEach(() => {+ initKeaTests()+ // jsdom lays nothing out, so the virtualized list needs a size to render rows into.+ jest.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(600)+ jest.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(1000)+ })++ afterEach(() => {+ cleanup()+ jest.restoreAllMocks()+ })++ it('renders a loaded trace and steps the selection with J', async () => {+ jest.spyOn(api.tracing, 'getTrace').mockResolvedValue({+ results: [span('ROOT', ''), span('A', 'ROOT'), span('B', 'ROOT')],+ hasMore: false,+ nextOffset: null,+ })+ const logic = traceDialogLogic()+ logic.mount()+ await expectLogic(logic, () => {+ logic.actions.openTraceDialog({ traceId: 'abc123', spanId: 'A' })+ }).toDispatchActions(['loadTraceSpansSuccess'])++ const { container } = render(+ <Provider>+ <TraceDialogSpanTree />+ </Provider>+ )+ logic.actions.selectNextSpan()++ await waitFor(() =>+ expect(container.querySelector('[data-attr="trace-dialog-span-row"][aria-pressed="true"]')).toHaveAttribute(+ 'aria-label',+ 'B span'+ )+ )+ })+})diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsxindex 34024feeb353..cd76809a5ef3 100644--- a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx@@ -1,5 +1,5 @@import { useActions, useValues } from 'kea'-import { CSSProperties, useCallback, useMemo, useRef } from 'react'+import { CSSProperties, useCallback, useEffect, useMemo, useRef } from 'react'import { List, useListRef } from 'react-window'import { AutoSizer } from 'lib/components/AutoSizer'@@ -106,6 +106,15 @@ export function TraceDialogSpanTree(): JSX.Element {},[openedIndex, listRef])+ // Keep each span J and K step to in view. While the opened span still waits for its centred reveal+ // above, this leaves it alone.+ const selectedSpanId = missingParentSpanId ?? selectedSpan?.span_id ?? null+ useEffect(() => {+ const index = spanRows.findIndex((row) => row.kind === 'span' && row.node.span.span_id === selectedSpanId)+ if (index >= 0 && (selectedSpanId !== openedSpanId || revealedIndexRef.current !== null)) {+ listRef.current?.scrollToRow({ index, align: 'smart' })+ }+ }, [spanRows, selectedSpanId, openedSpanId, listRef])return (<div className="flex flex-col h-full min-h-0">@@ -143,7 +152,7 @@ export function TraceDialogSpanTree(): JSX.Element {collapsedSpanIds,timeline,serviceColorMap,- selectedSpanId: missingParentSpanId ?? selectedSpan?.span_id ?? null,+ selectedSpanId,openedSpanId,openedAtUs,onSelect: selectSpan,diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.tsindex 7814f28bb439..93c7e691c36b 100644--- a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts@@ -238,4 +238,90 @@ describe('traceDialogLogic', () => {await expectLogic(logic, open).toMatchValues({ isOpen: false })})++ it('drops the log from a previous open, so a later open has no stale strip or marker', async () => {+ logic.actions.openTraceDialog(+ { traceId: 'abc123', ts: '2026-05-01T12:00:00.000Z' },+ { body: 'run_sql failed', severity: 'error' }+ )+ expect(logic.values.openedAtUs).not.toBeNull()++ // A metrics link passes a time near the trace, which is no point in it to mark.+ await expectLogic(logic, () => {+ logic.actions.openTraceDialog({ traceId: 'def456', ts: '2026-05-01T12:00:00.000Z' })+ }).toMatchValues({ openedFrom: null, openedAtUs: null })+ })++ describe('span keys', () => {+ let pageListener: jest.Mock++ beforeEach(async () => {+ getTraceSpy.mockResolvedValue({ results: [span('a'), span('b')], hasMore: false, nextOffset: null })+ logic.actions.openTraceDialog({ traceId: 'abc123', spanId: 'a' })+ await expectLogic(logic).toDispatchActions(['loadTraceSpansSuccess'])+ // Stands in for the logs list under the dialog, which binds J and K on window too.+ pageListener = jest.fn()+ window.addEventListener('keydown', pageListener)+ })++ afterEach(() => {+ window.removeEventListener('keydown', pageListener)+ })++ const press = (key: string, target: EventTarget = document.body): void => {+ target.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true }))+ }++ it('steps through spans and keeps the key from the page under the dialog', () => {+ press('j')+ expect(logic.values.selectedSpan?.span_id).toBe('b')+ press('k')+ expect(logic.values.selectedSpan?.span_id).toBe('a')+ expect(pageListener).not.toHaveBeenCalled()+ })++ it('steps onto a missing parent row and on past it', async () => {+ const orphan = { ...span('b'), parent_span_id: 'GONE' }+ getTraceSpy.mockResolvedValue({ results: [span('a'), orphan], hasMore: false, nextOffset: null })+ logic.actions.openTraceDialog({ traceId: 'abc123', spanId: 'a' })+ await expectLogic(logic).toDispatchActions(['loadTraceSpansSuccess'])++ press('j')+ expect(logic.values.missingParentSpanId).toBe('GONE')+ press('j')+ expect(logic.values.missingParentSpanId).toBeNull()+ expect(logic.values.selectedSpan?.span_id).toBe('b')+ press('k')+ expect(logic.values.missingParentSpanId).toBe('GONE')+ press('k')+ expect(logic.values.selectedSpan?.span_id).toBe('a')+ })++ it('leaves keys typed into an input in the dialog alone, but not one hidden behind it', () => {+ const dialog = document.createElement('div')+ dialog.setAttribute('data-attr', 'trace-dialog')+ const inDialog = document.createElement('input')+ const behind = document.createElement('textarea')+ dialog.appendChild(inDialog)+ document.body.append(dialog, behind)++ press('j', inDialog)+ expect(logic.values.selectedSpan?.span_id).toBe('a')+ expect(pageListener).toHaveBeenCalledTimes(1)++ press('j', behind)+ expect(logic.values.selectedSpan?.span_id).toBe('b')+ expect(pageListener).toHaveBeenCalledTimes(1)+ dialog.remove()+ behind.remove()+ })++ it('stops listening once the dialog closes', () => {+ logic.actions.closeTraceDialog()+ press('j')++ expect(logic.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.tsindex 5e4eb1d406bd..9b30816d1854 100644--- a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts@@ -14,6 +14,7 @@ import {sessionPlayerModalLogic,} from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'+import type { LogSeverityLevel } from '~/queries/schema/schema-general'import type { SessionRecordingType, UniversalFiltersGroup } from '~/types'import type { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'@@ -33,6 +34,10 @@ import { buildTraceDialogRows, countDescendantsById, type TraceDialogRow } from// Tracing, which pages in on scroll.const TRACE_DIALOG_MAX_PAGES = 5+// Pinned: autocapture and the span keys both match on the dialog's data-attr.+export const TRACE_DIALOG_DATA_ATTR = 'trace-dialog'+const TRACE_DIALOG_SELECTOR = `[data-attr="${TRACE_DIALOG_DATA_ATTR}"]`+// 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 {@@ -53,6 +58,12 @@ export interface TraceDialogTree {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+ severity: LogSeverityLevel+}+export interface TraceDialogTimeline {startUs: numberdurationUs: number@@ -78,6 +89,8 @@ export interface traceDialogLogicValues {isOpen: booleanmissingParentSpanId: string | nullopenedAtUs: number | null+ openedFrom: TraceDialogSource | null+ openedSpan: Span | nullselectedSpan: Span | nullselectedSpanId: string | nullserviceColorMap: Map<string, number>@@ -149,13 +162,23 @@ export interface traceDialogLogicActions {traceSpans: TraceDialogSpans | nullpayload?: TraceLinkParams}- openTraceDialog: (trace: TraceLinkParams) => {+ openTraceDialog: (+ trace: TraceLinkParams,+ openedFrom?: TraceDialogSource | null+ ) => {+ openedFrom: TraceDialogSource | nulltrace: {spanId: string | nulltraceId: stringts?: string | null | undefined}}+ selectNextSpan: () => {+ value: true+ }+ selectPreviousSpan: () => {+ value: true+ }selectSpan: (spanId: string) => {spanId: string}@@ -188,6 +211,7 @@ export interface traceDialogLogicMeta {summary: TraceDialogSummary) => Span | nullmissingParentSpanId: (traceSpans: TraceDialogSpans | null, selectedSpanId: string | null) => string | null+ openedSpan: (traceSpans: TraceDialogSpans | null, trace: TraceLinkParams | null) => Span | nullactiveInspectorTab: (chosenInspectorTab: SpanInspectorTab | null,selectedSpan: Span | null,@@ -196,7 +220,7 @@ export interface traceDialogLogicMeta {serviceColorMap: (traceSpans: TraceDialogSpans | null) => Map<string, number>timeline: (traceSpans: TraceDialogSpans | null) => TraceDialogTimelinesummary: (traceSpans: TraceDialogSpans | null) => TraceDialogSummary- openedAtUs: (trace: TraceLinkParams | null) => number | null+ openedAtUs: (trace: TraceLinkParams | null, openedFrom: TraceDialogSource | null) => number | null}}@@ -221,7 +245,12 @@ export const traceDialogLogic = kea<traceDialogLogicType>([values: [tracingCorrelationConfigLogic, ['sessionErrorBadgesEnabled'], featureFlagLogic, ['featureFlags']],})),actions({- openTraceDialog: (trace: TraceLinkParams) => ({ trace: { ...trace, spanId: inApiCase(trace.spanId) } }),+ openTraceDialog: (trace: TraceLinkParams, openedFrom?: TraceDialogSource | null) => ({+ trace: { ...trace, spanId: inApiCase(trace.spanId) },+ openedFrom: openedFrom ?? null,+ }),+ selectNextSpan: true,+ selectPreviousSpan: true,closeTraceDialog: true,selectSpan: (spanId: string) => ({ spanId }),toggleSpanCollapsed: (spanId: string) => ({ spanId }),@@ -282,6 +311,12 @@ export const traceDialogLogic = kea<traceDialogLogicType>([traceSpans: {openTraceDialog: () => null,},+ openedFrom: [+ null as TraceDialogSource | null,+ {+ openTraceDialog: (_, { openedFrom }) => openedFrom,+ },+ ],traceSpansFailed: [false,{@@ -391,6 +426,11 @@ export const traceDialogLogic = kea<traceDialogLogicType>([? selectedSpanId: 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@@ -430,14 +470,59 @@ export const traceDialogLogic = kea<traceDialogLogicType>([// 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: [- (s) => [s.trace],- (trace: TraceLinkParams | null): number | null =>- trace?.ts && dayjs(trace.ts).isValid() ? parseTimestampUs(trace.ts) : null,+ (s) => [s.trace, s.openedFrom],+ (trace: TraceLinkParams | null, openedFrom: TraceDialogSource | null): number | null =>+ // Other links pass a time near the trace, not the moment anything happened in it.+ openedFrom && trace?.ts && dayjs(trace.ts).isValid() ? parseTimestampUs(trace.ts) : null,],}),listeners(({ values, actions, cache }) => ({openTraceDialog: ({ trace }) => {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.+ cache.disposables.add(() => {+ const onKeyDown = (event: KeyboardEvent): void => {+ const target = event.target as HTMLElement | null+ // A field behind the dialog can still hold focus, such as one that autofocused+ // while the trace loaded. The person cannot see it, so the key is theirs to step with.+ const typing =+ !!target?.closest(TRACE_DIALOG_SELECTOR) &&+ (['input', 'textarea', 'select'].includes(target.tagName.toLowerCase()) ||+ target.isContentEditable)+ if (typing || event.isComposing || event.metaKey || event.ctrlKey || event.altKey) {+ return+ }+ const step = { j: actions.selectNextSpan, k: actions.selectPreviousSpan }[event.key.toLowerCase()]+ if (step) {+ event.preventDefault()+ event.stopPropagation()+ step()+ }+ }+ window.addEventListener('keydown', onKeyDown, { capture: true })+ return () => window.removeEventListener('keydown', onKeyDown, { capture: true })+ }, 'spanKeys')+ },+ closeTraceDialog: () => {+ cache.disposables.dispose('spanKeys')+ },+ selectNextSpan: () => {+ // 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: () => {+ 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)+ }},// Collapsing the span that holds the selection selects it, so the inspector shows a span on screen.toggleSpanCollapsed: ({ spanId }) => {diff --git a/products/tracing/frontend/components/TraceDialog/useOpenTraceDialog.ts b/products/tracing/frontend/components/TraceDialog/useOpenTraceDialog.tsindex 480b9072dedc..dfedb49f7023 100644--- a/products/tracing/frontend/components/TraceDialog/useOpenTraceDialog.ts+++ b/products/tracing/frontend/components/TraceDialog/useOpenTraceDialog.ts@@ -3,9 +3,18 @@ import { type MouseEvent, useCallback } from 'react'import type { TraceLinkParams } from 'lib/components/ViewTraceButton/traceUrl'-import { traceDialogLogic } from './traceDialogLogic'+import { type TraceDialogSource, traceDialogLogic } from './traceDialogLogic'-export type OpenTraceDialogHandler = (event: MouseEvent | null, trace: TraceLinkParams) => boolean+export interface OpenTraceDialogOptions {+ /** The log the link sits on, shown in the dialog as the reason the trace was opened. */+ openedFrom?: TraceDialogSource | null+}++export type OpenTraceDialogHandler = (+ event: MouseEvent | null,+ trace: TraceLinkParams,+ options?: OpenTraceDialogOptions+) => boolean/*** Opens a trace in the dialog in place of navigating to Tracing. Returns false when it did not, so@@ -18,7 +27,7 @@ export function useOpenTraceDialog(): OpenTraceDialogHandler {// Stable while the flag holds, so callers can list it in a memo's dependencies.return useCallback(- (event, trace) => {+ (event, trace, options) => {if (!dialogEnabled) {return false}@@ -26,7 +35,7 @@ export function useOpenTraceDialog(): OpenTraceDialogHandler {return false}event?.preventDefault()- openTraceDialog(trace)+ openTraceDialog(trace, options?.openedFrom)return true},[dialogEnabled, openTraceDialog]diff --git a/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.tsx b/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.tsxindex 9978a28c93fe..5ea9e3243fff 100644--- a/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.tsx+++ b/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.tsx@@ -78,6 +78,8 @@ export function SpanLogsTab({ span }: { span: Span }): JSX.Element {// Start with the facet/filter rail hidden — the drawer is narrow and the pinned// scope already covers the common case; "Show filters" re-expands it.defaultFacetRailCollapsed+ // The span view around this tab owns the keyboard, J and K included.+ autoFocusSearch={false}/></div>)