: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
import { deepEqual as equal } from 'fast-equals'
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router, urlToAction } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/constants'
import { usableId } from 'lib/components/ViewTraceButton/usableId'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { parseTagsFilter } from 'lib/utils/url'
import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'
import { Params } from 'scenes/sceneTypes'
import { Breadcrumb } from '~/types'
import type { AggregatedSpanRow, DateRange, SpanTreeNode } from '../../../frontend/src/queries/schema/schema-general'
import type { UniversalFiltersGroup } from '../../../frontend/src/types'
import { tracingSqlEditorTrackingLogic } from './components/TracingSqlEditor/tracingSqlEditorTrackingLogic'
import type { TracingDurationHistogramData, VisibleDurationRange } from './durationBuckets'
import type { TracingLatencyHeatmapData } from './durationBuckets'
import type { ErrorScope } from './errorCorrelation'
import { spanErrorsLogic } from './spanErrorsLogic'
import type { SpanErrorBadge } from './spanErrorsLogic'
import type { TraceIdentity } from './traceIdentity'
import { tracingDataLogic } from './tracingDataLogic'
import type { TracingSparklineData, VisibleSpanTimeRange } from './tracingDataLogic'
import {
DEFAULT_CUSTOM_COMPARISON,
DEFAULT_DATE_RANGE,
DEFAULT_ORDER_BY,
DEFAULT_ORDER_DIRECTION,
DEFAULT_SERVICE_NAMES,
DEFAULT_CHART_TYPE,
DEFAULT_VIEW_MODE,
parseComparison,
serializeComparison,
TRACING_SCENE_VIEWER_ID,
type TracingComparison,
tracingFiltersLogic,
} from './tracingFiltersLogic'
import type {
OverlayWindow,
TimeComparison,
TracingFilters,
TracingOrderBy,
TracingOrderDirection,
TracingViewMode,
} from './tracingFiltersLogic'
import { tracingViewerLogic } from './tracingViewerLogic'
import type { Span, SpanInspectorTab } from './types'
/** What each result row represents: a trace (its root span), an individual span, or an operation or endpoint aggregate. */
export type TracingDisplayMode = TracingViewMode | 'operations' | 'endpoints'
export type TracingResultsTab = 'traces' | 'operations' | 'endpoints'
function resultsTabFromView(view: unknown, operationsEnabled: boolean, endpointsEnabled: boolean): TracingResultsTab {
if (operationsEnabled && view === 'operations') {
return 'operations'
}
if (endpointsEnabled && view === 'endpoints') {
return 'endpoints'
}
return 'traces'
}
/** The aggregate tables always cover the whole selected range, even while a comparison is active. */
function aggregateFetchOptions(tab: TracingResultsTab): { fullRange: boolean; groupByEndpoint: boolean } {
return { fullRange: true, groupByEndpoint: tab === 'endpoints' }
}
const TRACING_SCENE_TABS = ['viewer', 'sql'] as const
export type TracingSceneTab = (typeof TRACING_SCENE_TABS)[number]
const DEFAULT_SCENE_TAB: TracingSceneTab = 'viewer'
export const getTracingSqlEditorTabId = (id: string): string => `tracing-sql-editor-${id}`
// Uppercase, because the trace API returns ids that way and the viewer matches them exactly.
const traceIdFromUrl = (searchParams: Params): string | null =>
usableId(typeof searchParams.trace === 'string' ? searchParams.trace : null)?.toUpperCase() ?? null
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tracingSceneLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
receivedFeatureFlags: boolean // featureFlagLogic
errorBadgeByRow: Map<string, SpanErrorBadge> // spanErrorsLogic
aggregation: {
current: AggregatedSpanRow[]
previous: AggregatedSpanRow[] | null
} // tracingDataLogic
aggregationLoading: boolean // tracingDataLogic
durationHistogramData: TracingDurationHistogramData // tracingDataLogic
durationHistogramLoading: boolean // tracingDataLogic
hasMoreToLoad: boolean // tracingDataLogic
hasRunQuery: boolean // tracingDataLogic
isDurationMode: boolean // tracingDataLogic
latencyHeatmapData: TracingLatencyHeatmapData // tracingDataLogic
latencyHeatmapLoading: boolean // tracingDataLogic
listRows: Span[] // tracingDataLogic
showHeatmap: boolean // tracingDataLogic
spanTree: {
current: SpanTreeNode[]
previous: SpanTreeNode[] | null
spanName: string | null
} // tracingDataLogic
spanTreeLoading: boolean // tracingDataLogic
spans: Span[] // tracingDataLogic
spansError: string | null // tracingDataLogic
spansLoading: boolean // tracingDataLogic
sparklineData: TracingSparklineData // tracingDataLogic
sparklineError: string | null // tracingDataLogic
sparklineLoading: boolean // tracingDataLogic
totalMatchingFilters: number // tracingDataLogic
traceSpans: Span[] // tracingDataLogic
traceSpansHasMore: boolean // tracingDataLogic
traceSpansLoading: boolean // tracingDataLogic
traceSpansLoadingMore: boolean // tracingDataLogic
visibleRowDateRange: VisibleSpanTimeRange | null // tracingDataLogic
visibleRowDurationRange: VisibleDurationRange | null // tracingDataLogic
compareActive: boolean // tracingFiltersLogic
currentWindowMs: OverlayWindow // tracingFiltersLogic
filters: TracingFilters // tracingFiltersLogic
previousWindowMs: OverlayWindow // tracingFiltersLogic
sparklineWindowMs: OverlayWindow // tracingFiltersLogic
utcDateRange: {
date_from: string | null | undefined
date_to: string
} // tracingFiltersLogic
canLoadMoreTraceSpans: boolean // tracingViewerLogic
compareFlameServiceName: string | null // tracingViewerLogic
compareFlameSpanName: string | null // tracingViewerLogic
errorsScope: ErrorScope | null // tracingViewerLogic
inspectorOpen: boolean // tracingViewerLogic
inspectorTab: SpanInspectorTab // tracingViewerLogic
isFullscreen: boolean // tracingViewerLogic
isLoadingFullTrace: boolean // tracingViewerLogic
isTraceOpen: boolean // tracingViewerLogic
openTraceSpans: Span[] // tracingViewerLogic
selectedSpanId: string | null // tracingViewerLogic
selectedTraceId: string | null // tracingViewerLogic
selectedTraceLoadFailed: boolean // tracingViewerLogic
selectedTraceTs: string | null // tracingViewerLogic
sessionErrorBadgesEnabled: boolean // tracingViewerLogic
traceIdentity: TraceIdentity // tracingViewerLogic
traceSessionId: string | null // tracingViewerLogic
activeSceneTab: TracingSceneTab
activeTracingTab: TracingResultsTab
breadcrumbs: Breadcrumb[]
displayMode: TracingDisplayMode
endpointsViewEnabled: boolean
operationsViewEnabled: boolean
sceneTab: TracingSceneTab
sceneTabsEnabled: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tracingSceneLogicActions {
setFeatureFlags: (
flags: string[],
variants: Record<string, boolean | string>
) => {
flags: string[]
variants: Record<string, boolean | string>
} // featureFlagLogic
applyHeatmapBrush: (selection: import('./heatmapBrush').HeatmapBrushSelection) => {
selection: import('./heatmapBrush').HeatmapBrushSelection
} // tracingDataLogic
fetchAggregation: (
options?:
| {
fullRange?: boolean
groupByEndpoint?: boolean
}
| null
| undefined
) => {
fullRange?: boolean
groupByEndpoint?: boolean
} | null // tracingDataLogic
fetchNextPage: () => {
value: true
} // tracingDataLogic
fetchSpanTree: (params: { serviceName: string; spanName: string }) => {
serviceName: string
spanName: string
} // tracingDataLogic
fetchSpans: () => any // tracingDataLogic
fetchSparkline: () => any // tracingDataLogic
handleFilterChange: (
filterType: string,
extraProps?: Record<string, unknown> | undefined
) => {
extraProps: Record<string, unknown> | undefined
filterType: string
} // tracingDataLogic
loadMoreTraceSpans: () => {
value: true
} // tracingDataLogic
loadTraceSpans: (args_0: { traceId: string; ts?: string | null }) => {
traceId: string
ts?: string | null
} // tracingDataLogic
refreshQuery: () => {
value: true
} // tracingDataLogic
runQuery: () => {
value: true
} // tracingDataLogic
setVisibleRowRange: (
startIndex: number,
stopIndex: number
) => {
startIndex: number
stopIndex: number
} // tracingDataLogic
setChartType: (chartType: import('./tracingFiltersLogic').TracingChartType) => {
chartType: import('./tracingFiltersLogic').TracingChartType
} // tracingFiltersLogic
setComparison: (comparison: TimeComparison | null) => {
comparison: TimeComparison | null
} // tracingFiltersLogic
setDateRange: (
dateRange: DateRange,
source?: import('./sparklineSelection').TracingDateRangeSource | undefined
) => {
dateRange: DateRange
source: import('./sparklineSelection').TracingDateRangeSource | undefined
} // tracingFiltersLogic
setFilterGroup: (
filterGroup: UniversalFiltersGroup,
skipQuery?: boolean | undefined
) => {
filterGroup: UniversalFiltersGroup
skipQuery: boolean
} // tracingFiltersLogic
setFilters: (filters: Partial<TracingFilters>) => {
filters: Partial<TracingFilters>
} // tracingFiltersLogic
setServiceNames: (serviceNames: string[]) => {
serviceNames: string[]
} // tracingFiltersLogic
setSort: (
orderBy: TracingOrderBy,
orderDirection: TracingOrderDirection
) => {
orderBy: TracingOrderBy
orderDirection: TracingOrderDirection
} // tracingFiltersLogic
setViewMode: (viewMode: TracingViewMode) => {
viewMode: TracingViewMode
} // tracingFiltersLogic
updateComparisonWindows: (
current: OverlayWindow,
previous: OverlayWindow
) => {
current: OverlayWindow
previous: OverlayWindow
} // tracingFiltersLogic
closeCompareFlame: () => {
value: true
} // tracingViewerLogic
closeTrace: () => {
value: true
} // tracingViewerLogic
openCompareFlame: (
spanName: string,
serviceName: string
) => {
serviceName: string
spanName: string
} // tracingViewerLogic
openTrace: (
traceId: string,
options?:
| {
errorsScope?: ErrorScope | null
spanId?: string | null
tab?: SpanInspectorTab | null
ts?: string | null
}
| undefined
) => {
errorsScope: ErrorScope | null
spanId: string | null
tab: SpanInspectorTab | null
traceId: string
ts: string | null
} // tracingViewerLogic
selectInspectorTab: (tab: SpanInspectorTab) => {
tab: SpanInspectorTab
} // tracingViewerLogic
selectSpan: (spanId: string | null) => {
spanId: string | null
} // tracingViewerLogic
toggleFullscreen: () => {
value: true
} // tracingViewerLogic
toggleInspector: () => {
value: true
} // tracingViewerLogic
keepSqlEditorMounted: (editorTabId: string) => {
editorTabId: string
}
selectSceneTab: (tab: TracingSceneTab) => {
tab: 'sql' | 'viewer'
}
setActiveTracingTab: (tab: TracingResultsTab) => {
tab: TracingResultsTab
}
setDisplayMode: (mode: TracingDisplayMode) => {
mode: TracingDisplayMode
}
setSceneTab: (tab: TracingSceneTab) => {
tab: 'sql' | 'viewer'
}
syncUrl: () => {
value: true
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tracingSceneLogicMeta {
__keaTypeGenInternalSelectorTypes: {
operationsViewEnabled: (featureFlags: FeatureFlagsSet) => boolean
endpointsViewEnabled: (featureFlags: FeatureFlagsSet) => boolean
displayMode: (
operationsViewEnabled: boolean,
endpointsViewEnabled: boolean,
activeTracingTab: TracingResultsTab,
filters: TracingFilters
) => TracingDisplayMode
sceneTabsEnabled: (featureFlags: FeatureFlagsSet) => boolean
activeSceneTab: (sceneTabsEnabled: boolean, sceneTab: 'sql' | 'viewer') => TracingSceneTab
}
}
export type tracingSceneLogicType = MakeLogicType<
tracingSceneLogicValues,
tracingSceneLogicActions,
Record<string, any>,
tracingSceneLogicMeta
>
export const tracingSceneLogic = kea<tracingSceneLogicType>([
path(['products', 'tracing', 'frontend', 'tracingSceneLogic']),
// The scene binds to the viewer-default instances of the keyed filter/data/viewer logics.
// It owns ALL URL sync — the keyed logics are URL-free so they can be embedded anywhere;
// this logic translates URL params to their actions and their actions back to URL writes.
// Mirrors the logsSceneLogic / logsViewerLogic boundary.
connect(() => ({
values: [
featureFlagLogic,
['featureFlags', 'receivedFeatureFlags'],
tracingDataLogic({ id: TRACING_SCENE_VIEWER_ID }),
[
'spans',
'spansLoading',
'spansError',
'listRows',
'sparklineData',
'sparklineLoading',
'sparklineError',
'hasMoreToLoad',
'hasRunQuery',
'totalMatchingFilters',
'traceSpans',
'traceSpansLoading',
'traceSpansLoadingMore',
'traceSpansHasMore',
'aggregation',
'aggregationLoading',
'spanTree',
'spanTreeLoading',
'visibleRowDateRange',
'durationHistogramData',
'durationHistogramLoading',
'visibleRowDurationRange',
'isDurationMode',
'latencyHeatmapData',
'latencyHeatmapLoading',
'showHeatmap',
],
tracingFiltersLogic({ id: TRACING_SCENE_VIEWER_ID }),
['filters', 'utcDateRange', 'sparklineWindowMs', 'currentWindowMs', 'previousWindowMs', 'compareActive'],
spanErrorsLogic({ id: TRACING_SCENE_VIEWER_ID }),
['errorBadgeByRow'],
tracingViewerLogic({ id: TRACING_SCENE_VIEWER_ID }),
[
'selectedTraceId',
'selectedSpanId',
'selectedTraceTs',
'isTraceOpen',
'openTraceSpans',
'traceIdentity',
'traceSessionId',
'sessionErrorBadgesEnabled',
'inspectorTab',
'errorsScope',
'isLoadingFullTrace',
'canLoadMoreTraceSpans',
'inspectorOpen',
'isFullscreen',
'compareFlameSpanName',
'compareFlameServiceName',
'selectedTraceLoadFailed',
],
],
actions: [
tracingDataLogic({ id: TRACING_SCENE_VIEWER_ID }),
[
'runQuery',
'fetchNextPage',
'fetchSpans',
'fetchSparkline',
'loadTraceSpans',
'loadMoreTraceSpans',
'fetchAggregation',
'fetchSpanTree',
'setVisibleRowRange',
'handleFilterChange',
'applyHeatmapBrush',
'refreshQuery',
],
tracingFiltersLogic({ id: TRACING_SCENE_VIEWER_ID }),
[
'setDateRange',
'setServiceNames',
'setFilterGroup',
'setSort',
'setViewMode',
'setChartType',
'setComparison',
'updateComparisonWindows',
'setFilters',
],
tracingViewerLogic({ id: TRACING_SCENE_VIEWER_ID }),
[
'openTrace',
'selectSpan',
'selectInspectorTab',
'closeTrace',
'toggleInspector',
'toggleFullscreen',
'openCompareFlame',
'closeCompareFlame',
],
featureFlagLogic,
['setFeatureFlags'],
],
})),
actions({
syncUrl: true,
setActiveTracingTab: (tab: TracingResultsTab) => ({ tab }),
setDisplayMode: (mode: TracingDisplayMode) => ({ mode }),
setSceneTab: (tab: TracingSceneTab) => ({ tab }),
selectSceneTab: (tab: TracingSceneTab) => ({ tab }),
keepSqlEditorMounted: (editorTabId: string) => ({ editorTabId }),
}),
reducers({
activeTracingTab: [
'traces' as TracingResultsTab,
{
setActiveTracingTab: (_, { tab }) => tab,
},
],
sceneTab: [
DEFAULT_SCENE_TAB as TracingSceneTab,
{
setSceneTab: (_, { tab }) => tab,
},
],
}),
selectors({
breadcrumbs: [
() => [],
(): Breadcrumb[] => [
{
key: 'tracing',
name: 'Tracing',
iconType: 'tracing',
},
],
],
operationsViewEnabled: [
(s) => [s.featureFlags],
(featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_OPERATIONS_VIEW],
],
endpointsViewEnabled: [
(s) => [s.featureFlags],
(featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_ENDPOINTS_VIEW],
],
// The one user-facing mode: what each result row represents. Spans two states —
// traces/spans is the viewMode filter, operations/endpoints is the scene tab.
displayMode: [
(s) => [s.operationsViewEnabled, s.endpointsViewEnabled, s.activeTracingTab, s.filters],
(
operationsViewEnabled: boolean,
endpointsViewEnabled: boolean,
activeTracingTab: TracingResultsTab,
filters: TracingFilters
): TracingDisplayMode => {
const tab = resultsTabFromView(activeTracingTab, operationsViewEnabled, endpointsViewEnabled)
return tab === 'traces' ? filters.viewMode : tab
},
],
sceneTabsEnabled: [
(s) => [s.featureFlags],
(featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_SCENE_TABS],
],
activeSceneTab: [
(s) => [s.sceneTabsEnabled, s.sceneTab],
(sceneTabsEnabled: boolean, sceneTab: TracingSceneTab): TracingSceneTab =>
sceneTabsEnabled ? sceneTab : DEFAULT_SCENE_TAB,
],
}),
listeners(({ actions, values, cache }) => ({
keepSqlEditorMounted: ({ editorTabId }) => {
if (cache.sqlEditorTabId === editorTabId) {
return
}
cache.unmountSqlEditor?.()
cache.sqlEditorTabId = editorTabId
// Never unmounted, so the user's query survives leaving and re-entering /tracing.
const unmountEditor = sqlEditorLogic({ tabId: editorTabId, mode: SQLEditorMode.Embedded }).mount()
// Mounted with the editor, so its skip of the one auto-run survives tab switches.
const unmountTracking = tracingSqlEditorTrackingLogic({ sqlEditorTabId: editorTabId }).mount()
cache.unmountSqlEditor = () => {
unmountTracking()
unmountEditor()
}
},
selectSceneTab: ({ tab }) => {
if (tab === 'sql' && values.sceneTab !== 'sql') {
posthog.capture('tracing sql tab opened')
}
actions.setSceneTab(tab)
actions.syncUrl()
},
// The keyed data logic already captured the interaction and re-ran the query;
// the scene's jobs are the URL write and scene-tab side effects.
handleFilterChange: () => {
actions.syncUrl()
// Keep the Operations aggregate in sync with filters/date while that tab is active.
// Full range: the Operations view always covers the whole selected range, even while
// a (traces-tab) comparison is active.
//
// This MUST run after the data logic's handleFilterChange listener. When a comparison
// is active, that listener synchronously runs runQuery, whose listener fires a windowed
// fetchAggregation(); every fetchAggregation aborts the previous one, so the last
// dispatched wins. The data logic mounts before this scene logic, so its listener runs
// first and the full-range fetch here beats the windowed one deterministically —
// otherwise the Operations table would divide by the narrow compare sub-window.
if (values.activeTracingTab !== 'traces') {
actions.fetchAggregation(aggregateFetchOptions(values.activeTracingTab))
}
},
setFilters: () => {
actions.syncUrl()
// Bulk restores (URL params, back/forward) route through the data logic's setFilters
// listener → runQuery, which fires a windowed fetchAggregation when a comparison is
// active. Mirror handleFilterChange so the Operations tab keeps its full-range aggregate
// instead of the narrow compare sub-window (same mount-order guarantee applies).
if (values.activeTracingTab !== 'traces') {
actions.fetchAggregation(aggregateFetchOptions(values.activeTracingTab))
}
},
// Flags resolve asynchronously, so one that arrives after the Operations fetch would show
// the Sessions and Users columns over rows fetched without them. Mirrors the heatmap's
// late-flag refetch in tracingDataLogic.
setFeatureFlags: () => {
if (
values.activeTracingTab !== 'traces' &&
values.featureFlags[FEATURE_FLAGS.TRACING_IMPACT_STRIP] &&
values.aggregation.current.length > 0 &&
values.aggregation.current[0].sessions == null &&
!values.aggregationLoading
) {
actions.fetchAggregation(aggregateFetchOptions(values.activeTracingTab))
}
// Flags can arrive after the URL parse, so a tab=sql deep link waits here for the verdict.
if (!values.sceneTabsEnabled && values.sceneTab !== DEFAULT_SCENE_TAB) {
actions.setSceneTab(DEFAULT_SCENE_TAB)
actions.syncUrl()
}
},
// The data logic refetches a windowed aggregate on these, so restore the tab's own query after it.
updateComparisonWindows: () => {
if (values.activeTracingTab !== 'traces') {
actions.fetchAggregation(aggregateFetchOptions(values.activeTracingTab))
}
},
refreshQuery: () => {
if (values.activeTracingTab !== 'traces') {
actions.fetchAggregation(aggregateFetchOptions(values.activeTracingTab))
}
},
setActiveTracingTab: ({ tab }) => {
if (tab !== 'traces') {
actions.fetchAggregation(aggregateFetchOptions(tab))
} else if (values.compareActive) {
// Returning to the traces tab with a comparison active: the aggregation state
// holds the operations full-range data — refetch the windowed compare version.
actions.fetchAggregation()
}
},
// Maps the one display-mode control onto the two underlying states, with exactly one
// URL write per interaction: setViewMode cascades its own syncUrl (via the data logic's
// handleFilterChange), so this only writes directly when that cascade won't run.
setDisplayMode: ({ mode }) => {
// pinned: analytics event name and property — renaming breaks dashboards
posthog.capture('tracing display mode changed', { mode })
if (mode === 'operations' || mode === 'endpoints') {
if (values.activeTracingTab !== mode) {
actions.setActiveTracingTab(mode)
}
actions.syncUrl()
return
}
if (values.activeTracingTab !== 'traces') {
actions.setActiveTracingTab('traces')
}
if (mode !== values.filters.viewMode) {
actions.setViewMode(mode)
} else {
actions.syncUrl()
}
},
})),
subscriptions(({ actions, values }) => {
// Feature flags can resolve AFTER the initial URL parse, and urlToAction only re-runs on
// URL changes. Without this, a late-arriving flag leaves the tab and the URL disagreeing:
// enabling it on a ?view=operations page keeps the tab stuck on traces, and disabling it
// mid-session strands the tab on operations. Re-reconcile the tab against the current URL
// whenever a flag flips, then write the URL back through the flag-aware displayMode.
const reconcileTab = (): void => {
const tab = resultsTabFromView(
router.values.searchParams.view,
values.operationsViewEnabled,
values.endpointsViewEnabled
)
if (tab === values.activeTracingTab) {
return
}
actions.setActiveTracingTab(tab)
actions.syncUrl()
}
return { operationsViewEnabled: reconcileTab, endpointsViewEnabled: reconcileTab }
}),
urlToAction(({ actions, values, cache }) => ({
'/tracing': (_, searchParams) => {
const filtersFromUrl: Record<string, any> = {}
let hasChanges = false
if (searchParams.dateRange) {
try {
const dateRange =
typeof searchParams.dateRange === 'string'
? JSON.parse(searchParams.dateRange)
: searchParams.dateRange
if (!equal(dateRange, values.filters.dateRange)) {
filtersFromUrl.dateRange = dateRange
hasChanges = true
}
} catch {
// Ignore malformed JSON
}
}
if (searchParams.serviceNames) {
const names = parseTagsFilter(searchParams.serviceNames)
if (names && !equal(names, values.filters.serviceNames)) {
filtersFromUrl.serviceNames = names
hasChanges = true
}
} else if (!equal(DEFAULT_SERVICE_NAMES, values.filters.serviceNames)) {
filtersFromUrl.serviceNames = DEFAULT_SERVICE_NAMES
hasChanges = true
}
if (searchParams.filterGroup) {
try {
const filterGroup =
typeof searchParams.filterGroup === 'string'
? JSON.parse(searchParams.filterGroup)
: searchParams.filterGroup
if (!equal(filterGroup, values.filters.filterGroup)) {
filtersFromUrl.filterGroup = filterGroup
hasChanges = true
}
} catch {
// Ignore malformed JSON
}
} else if (!equal(DEFAULT_UNIVERSAL_GROUP_FILTER, values.filters.filterGroup)) {
filtersFromUrl.filterGroup = DEFAULT_UNIVERSAL_GROUP_FILTER
hasChanges = true
}
if (searchParams.orderBy) {
if (searchParams.orderBy !== values.filters.orderBy) {
filtersFromUrl.orderBy = searchParams.orderBy
hasChanges = true
}
}
if (searchParams.orderDirection) {
if (searchParams.orderDirection !== values.filters.orderDirection) {
filtersFromUrl.orderDirection = searchParams.orderDirection
hasChanges = true
}
}
// Legacy `compare=true` links map to the custom-windows preset; everything else
// round-trips through parse/serializeComparison so future modes don't touch this file.
const legacyComparisonFromUrl: TracingComparison | null =
searchParams.compare === 'true' || searchParams.compare === true ? DEFAULT_CUSTOM_COMPARISON : null
let comparisonFromUrl = legacyComparisonFromUrl
// A malformed (or unknown future-mode) comparison param falls back to the legacy
// param, and failing that is ignored rather than clearing an active comparison —
// matching how the dateRange/filterGroup handlers treat malformed JSON.
let comparisonParamInvalid = false
if (searchParams.comparison) {
const parsed = parseComparison(searchParams.comparison)
if (parsed) {
comparisonFromUrl = parsed
} else if (!legacyComparisonFromUrl) {
comparisonParamInvalid = true
}
}
if (
!comparisonParamInvalid &&
serializeComparison(comparisonFromUrl) !== serializeComparison(values.filters.comparison)
) {
filtersFromUrl.comparison = comparisonFromUrl
hasChanges = true
}
// `view` spans two states: 'operations'/'endpoints' round-trips the scene tab, 'spans'/'traces'/absent
// round-trips the viewMode filter. While the URL names an aggregate tab the viewMode filter
// is left untouched — it has no effect on that view and shouldn't be reset under it.
// Each aggregate leg is flag-gated on BOTH the read side (here) and the write
// side (buildUrl, via the flag-aware displayMode selector): gating only one of them
// would make them fight over the tab state.
const tabFromUrl = resultsTabFromView(
searchParams.view,
values.operationsViewEnabled,
values.endpointsViewEnabled
)
if (tabFromUrl !== values.activeTracingTab) {
actions.setActiveTracingTab(tabFromUrl)
}
if (tabFromUrl === 'traces') {
const viewModeFromUrl: TracingViewMode =
searchParams.view === 'spans' || searchParams.view === 'traces'
? searchParams.view
: DEFAULT_VIEW_MODE
if (viewModeFromUrl !== values.filters.viewMode) {
filtersFromUrl.viewMode = viewModeFromUrl
hasChanges = true
}
}
const chartTypeFromUrl = searchParams.chart === 'heatmap' ? 'heatmap' : DEFAULT_CHART_TYPE
if (chartTypeFromUrl !== values.filters.chartType) {
filtersFromUrl.chartType = chartTypeFromUrl
hasChanges = true
}
const sceneTabsDisabled = values.receivedFeatureFlags && !values.sceneTabsEnabled
const sceneTabFromUrl = sceneTabsDisabled
? DEFAULT_SCENE_TAB
: (TRACING_SCENE_TABS.find((tab) => tab === searchParams.tab) ?? DEFAULT_SCENE_TAB)
if (sceneTabFromUrl !== values.sceneTab) {
actions.setSceneTab(sceneTabFromUrl)
}
if (hasChanges) {
actions.setFilters(filtersFromUrl)
} 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 = traceIdFromUrl(searchParams)
const spanFromUrl = typeof searchParams.span === 'string' ? searchParams.span : null
cache.drawerChangeFromUrl = true
try {
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()
}
} finally {
cache.drawerChangeFromUrl = false
}
if (sceneTabsDisabled && searchParams.tab !== undefined) {
actions.syncUrl()
}
},
})),
trackedActionToUrl(({ values, cache }) => {
// 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 = { ...drawerParams() }
if (!equal(values.filters.dateRange, DEFAULT_DATE_RANGE)) {
searchParams.dateRange = JSON.stringify(values.filters.dateRange)
}
if (!equal(values.filters.serviceNames, DEFAULT_SERVICE_NAMES)) {
searchParams.serviceNames = values.filters.serviceNames
}
if (!equal(values.filters.filterGroup, DEFAULT_UNIVERSAL_GROUP_FILTER)) {
searchParams.filterGroup = JSON.stringify(values.filters.filterGroup)
}
if (values.filters.orderBy !== DEFAULT_ORDER_BY) {
searchParams.orderBy = values.filters.orderBy
}
if (values.filters.orderDirection !== DEFAULT_ORDER_DIRECTION) {
searchParams.orderDirection = values.filters.orderDirection
}
const comparisonParam = serializeComparison(values.filters.comparison)
if (comparisonParam) {
searchParams.comparison = comparisonParam
}
// displayMode already folds in the flag gates and resolves to viewMode off the aggregate tabs.
if (values.displayMode !== DEFAULT_VIEW_MODE) {
searchParams.view = values.displayMode
}
if (values.filters.chartType !== DEFAULT_CHART_TYPE) {
searchParams.chart = values.filters.chartType
}
if (values.activeSceneTab !== DEFAULT_SCENE_TAB) {
searchParams.tab = values.activeSceneTab
}
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 },
]
}
// A drawer change that the URL started only cleans up the trace param, so it replaces: Back must
// not stop on a lowercase or malformed spelling, or on a URL a filter restore already rewrote.
const drawerChangeUrl = (): ReturnType<typeof drawerUrl> => drawerUrl(!!cache.drawerChangeFromUrl)
return {
syncUrl: () => buildUrl(),
openTrace: () => drawerChangeUrl(),
selectSpan: () => drawerUrl(true),
closeTrace: () => drawerChangeUrl(),
}
}),
])