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.

38.6 KB
Raw Blame
import {
    LogicWrapper,
    MakeLogicType,
    actions,
    connect,
    kea,
    key,
    listeners,
    path,
    props,
    reducers,
    selectors,
    sharedListeners,
} from 'kea'
import type { BreakPointFunction } from 'kea'
import posthog from 'posthog-js'

import { FEATURE_FLAGS } from 'lib/constants'
import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'

import { isAiEventSpan } from 'products/tracing/frontend/aiEventSpans'
import type { FlameTreeNode } from 'products/tracing/frontend/flameTree'
import { buildSpanTree, parseTimestampUs, type SpanNode } from 'products/tracing/frontend/spanTree'
import { buildTraceCallTree } from 'products/tracing/frontend/traceCallTree'
import { buildServiceColorMap } from 'products/tracing/frontend/TraceWaterfallView'
import { tracingConfigLogic } from 'products/tracing/frontend/tracingConfigLogic'
import { tracingCorrelationConfigLogic } from 'products/tracing/frontend/tracingCorrelationConfigLogic'
import type { Span, SpanInspectorTab, TraceViewMode } from 'products/tracing/frontend/types'

import {
    buildTraceDialogRows,
    countDescendantsById,
    firstOperationSpan,
    markOperationSubtrees,
    operationRowMatches,
    revealSpanInRows,
    rowSpanNode,
    type TraceDialogReveal,
    type TraceDialogRow,
} from '../TraceDialog/traceDialogRows'

// Views with span keys enabled, in the order they enabled them. Each listens on window, so
// only the last one acts on a key.
const spanKeyOwners: symbol[] = []

// Shallow, because the spans of a trace keep their identity when the list is rebuilt around them.
function sameSpans(a: Span[], b: Span[]): boolean {
    return a.length === b.length && a.every((span, index) => span === b[index])
}

export interface TraceViewLogicProps {
    id: string
}

/** Where the view sits. Pinned: sent as the `surface` property of analytics events, so keep the values stable. */
export type TraceViewSurface = 'drawer' | 'trace_dialog'

/**
 * What the Operations tab counts: the whole trace, or the inspected span and the spans under it.
 * Pinned: sent as the `scope` property of analytics events, so keep the values stable.
 */
export type TraceOperationsScope = 'trace' | 'span'

/**
 * How the person opened or folded a run: a click, or a key (Enter or Space on a focused run control, Left or Right).
 * Pinned: sent as the `method` property of analytics events, so keep the values stable.
 */
export type TraceRunToggleMethod = 'click' | 'key'

export interface TraceViewTree {
    roots: SpanNode[]
    nodesById: Map<string, SpanNode>
    descendantCounts: Map<string, number>
}

export interface TraceViewTimeline {
    startUs: number
    durationUs: number
}

export interface TraceViewSummary {
    rootSpan: Span | null
    spanCount: number
    serviceCount: number
    errorCount: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceViewLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    callTreeEnabled: boolean // tracingConfigLogic
    traceViewMode: TraceViewMode // tracingConfigLogic
    sessionErrorBadgesEnabled: boolean // tracingCorrelationConfigLogic
    activeInspectorTab: SpanInspectorTab
    callTree: FlameTreeNode
    chainStartIds: {
        folded: Set<string>
        opened: Set<string>
    }
    chosenInspectorTab: SpanInspectorTab | null
    collapsedSpanIds: Set<string>
    firstOperationRowIndex: number
    flatSpans: SpanNode[]
    foldedRunStartIds: Set<string>
    foldedRunsEnabled: boolean
    fullChildListSpanIds: Set<string>
    highlightedOperationKey: string | null
    missingParentSpanId: string | null
    openChainIds: Set<string>
    openRunIds: Set<string>
    operationRowMatches: boolean[] | null
    operationSpans: Span[]
    operationSubtreeMarks: Set<SpanNode> | null
    operationsTabEnabled: boolean
    pinnedSpan: Span | null
    pinnedSpanId: string | null
    selectedSpan: Span | null
    selectedSpanId: string | null
    serviceColorMap: Map<string, number>
    shownTraceCount: number
    spanRows: TraceDialogRow[]
    spanTree: TraceViewTree
    spans: Span[]
    summary: TraceViewSummary
    timeline: TraceViewTimeline
    visibleSpanIds: Set<string>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceViewLogicActions {
    setTraceViewMode: (
        traceViewMode: 'calltree' | 'waterfall',
        surface: TraceViewSurface
    ) => {
        surface: TraceViewSurface
        traceViewMode: 'calltree' | 'waterfall'
    } // tracingConfigLogic
    collapseSelectedSpan: (surface: TraceViewSurface) => {
        surface: TraceViewSurface
    }
    disableSpanKeys: () => {
        value: true
    }
    enableSpanKeys: (
        containerSelector: string,
        surface: TraceViewSurface
    ) => {
        containerSelector: string
        surface: TraceViewSurface
    }
    expandSelectedSpan: (surface: TraceViewSurface) => {
        surface: TraceViewSurface
    }
    highlightOperation: (
        operationKey: string | null,
        surface?: TraceViewSurface,
        scope?: TraceOperationsScope
    ) => {
        operationKey: string | null
        scope: TraceOperationsScope | null
        surface: TraceViewSurface | null
    }
    keepSelectionOnScreen: () => {
        value: true
    }
    revealSpans: (reveal: TraceDialogReveal) => {
        reveal: TraceDialogReveal
    }
    runsShown: (surface: TraceViewSurface) => {
        surface: TraceViewSurface
    }
    selectNextSpan: () => {
        value: true
    }
    selectPreviousSpan: () => {
        value: true
    }
    selectSpan: (spanId: string | null) => {
        spanId: string | null
    }
    setInspectorTab: (
        tab: SpanInspectorTab,
        surface?: TraceViewSurface
    ) => {
        surface: TraceViewSurface | null
        tab: SpanInspectorTab
    }
    setSpans: (spans: Span[]) => {
        spans: Span[]
    }
    showAllChildren: (spanId: string) => {
        spanId: string
    }
    showFewerChildren: (spanId: string) => {
        spanId: string
    }
    showTrace: (
        pinnedSpanId: string | null,
        tab: SpanInspectorTab | null
    ) => {
        pinnedSpanId: string | null
        tab: SpanInspectorTab | null
    }
    spanStepped: () => {
        value: true
    }
    toggleChain: (spanId: string) => {
        spanId: string
    }
    toggleRun: (
        spanId: string,
        method?: TraceRunToggleMethod,
        surface?: TraceViewSurface
    ) => {
        method: TraceRunToggleMethod | null
        spanId: string
        surface: TraceViewSurface | null
    }
    toggleSpanCollapsed: (spanId: string) => {
        spanId: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceViewLogicMeta {
    key: string
    sharedListeners: {
        revealSelectedSpan: (
            payload: any,
            breakpoint: BreakPointFunction,
            action: {
                type: string
                payload: any
            },
            previousState: any
        ) => void | Promise<void>
    }
    __keaTypeGenInternalSelectorTypes: {
        spanTree: (spans: Span[]) => TraceViewTree
        spanRows: (
            spanTree: TraceViewTree,
            collapsedSpanIds: Set<string>,
            fullChildListSpanIds: Set<string>,
            openChainIds: Set<string>,
            foldedRunsEnabled: boolean,
            openRunIds: Set<string>,
            pinnedSpanId: string | null
        ) => TraceDialogRow[]
        flatSpans: (spanRows: TraceDialogRow[]) => SpanNode[]
        visibleSpanIds: (flatSpans: SpanNode[]) => Set<string>
        chainStartIds: (spanRows: TraceDialogRow[]) => {
            folded: Set<string>
            opened: Set<string>
        }
        foldedRunStartIds: (spanRows: TraceDialogRow[]) => Set<string>
        selectedSpan: (spans: Span[], selectedSpanId: string | null, summary: TraceViewSummary) => Span | null
        missingParentSpanId: (spanTree: TraceViewTree, selectedSpanId: string | null) => string | null
        pinnedSpan: (spans: Span[], pinnedSpanId: string | null) => Span | null
        activeInspectorTab: (
            chosenInspectorTab: SpanInspectorTab | null,
            selectedSpan: Span | null,
            sessionErrorBadgesEnabled: boolean
        ) => SpanInspectorTab
        operationsTabEnabled: (featureFlags: FeatureFlagsSet) => boolean
        foldedRunsEnabled: (featureFlags: FeatureFlagsSet) => boolean
        operationSubtreeMarks: (
            spanTree: TraceViewTree,
            highlightedOperationKey: string | null,
            operationsTabEnabled: boolean
        ) => Set<SpanNode> | null
        operationRowMatches: (
            spanRows: TraceDialogRow[],
            highlightedOperationKey: string | null,
            operationSubtreeMarks: Set<SpanNode> | null,
            collapsedSpanIds: Set<string>
        ) => boolean[] | null
        firstOperationRowIndex: (operationRowMatches: boolean[] | null) => number
        operationSpans: (spans: Span[]) => Span[]
        callTree: (operationSpans: Span[]) => FlameTreeNode
        serviceColorMap: (spans: Span[]) => Map<string, number>
        timeline: (spans: Span[]) => TraceViewTimeline
        summary: (spans: Span[]) => TraceViewSummary
    }
}

export type traceViewLogicType = MakeLogicType<
    traceViewLogicValues,
    traceViewLogicActions,
    TraceViewLogicProps,
    traceViewLogicMeta
>

export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLogicType>([
    props({} as TraceViewLogicProps),
    key((props) => props.id),
    path((key) => ['products', 'tracing', 'frontend', 'components', 'TraceView', 'traceViewLogic', key]),
    connect(() => ({
        values: [
            tracingCorrelationConfigLogic,
            ['sessionErrorBadgesEnabled'],
            featureFlagLogic,
            ['featureFlags'],
            tracingConfigLogic,
            ['traceViewMode', 'callTreeEnabled'],
        ],
        actions: [tracingConfigLogic, ['setTraceViewMode']],
    })),
    actions({
        showTrace: (pinnedSpanId: string | null, tab: SpanInspectorTab | null) => ({ pinnedSpanId, tab }),
        setSpans: (spans: Span[]) => ({ spans }),
        selectSpan: (spanId: string | null) => ({ spanId }),
        selectNextSpan: true,
        selectPreviousSpan: true,
        collapseSelectedSpan: (surface: TraceViewSurface) => ({ surface }),
        expandSelectedSpan: (surface: TraceViewSurface) => ({ surface }),
        spanStepped: true,
        toggleSpanCollapsed: (spanId: string) => ({ spanId }),
        showAllChildren: (spanId: string) => ({ spanId }),
        showFewerChildren: (spanId: string) => ({ spanId }),
        toggleChain: (spanId: string) => ({ spanId }),
        // Only the person's own toggles pass a method, so only they send the toggle event.
        toggleRun: (spanId: string, method?: TraceRunToggleMethod, surface?: TraceViewSurface) => ({
            spanId,
            method: method ?? null,
            surface: surface ?? null,
        }),
        runsShown: (surface: TraceViewSurface) => ({ surface }),
        keepSelectionOnScreen: true,
        setInspectorTab: (tab: SpanInspectorTab, surface?: TraceViewSurface) => ({ tab, surface: surface ?? null }),
        enableSpanKeys: (containerSelector: string, surface: TraceViewSurface) => ({ containerSelector, surface }),
        disableSpanKeys: true,
        highlightOperation: (
            operationKey: string | null,
            surface?: TraceViewSurface,
            scope?: TraceOperationsScope
        ) => ({
            operationKey,
            surface: surface ?? null,
            scope: scope ?? null,
        }),
        revealSpans: (reveal: TraceDialogReveal) => ({ reveal }),
    }),
    reducers({
        spans: [
            [] as Span[],
            {
                showTrace: () => [],
                setSpans: (_, { spans }) => spans,
            },
        ],
        // Counts the traces shown, so the span tree can tell one trace from the next even when the next trace's
        // spans arrive before a render of the empty list.
        shownTraceCount: [
            0,
            {
                showTrace: (count) => count + 1,
            },
        ],
        // The span the trace was opened on: it stays listed even inside a folded branch.
        pinnedSpanId: [
            null as string | null,
            {
                showTrace: (_, { pinnedSpanId }) => pinnedSpanId,
            },
        ],
        selectedSpanId: [
            null as string | null,
            {
                showTrace: (_, { pinnedSpanId }) => pinnedSpanId,
                selectSpan: (_, { spanId }) => spanId,
            },
        ],
        collapsedSpanIds: [
            new Set<string>(),
            {
                showTrace: () => new Set<string>(),
                toggleSpanCollapsed: (collapsed, { spanId }) => {
                    const next = new Set(collapsed)
                    if (!next.delete(spanId)) {
                        next.add(spanId)
                    }
                    return next
                },
                revealSpans: (collapsed, { reveal }) => {
                    const next = new Set(collapsed)
                    reveal.collapsedSpanIds.forEach((spanId) => next.delete(spanId))
                    return next
                },
            },
        ],
        fullChildListSpanIds: [
            new Set<string>(),
            {
                showTrace: () => new Set<string>(),
                showAllChildren: (shown, { spanId }) => new Set(shown).add(spanId),
                showFewerChildren: (shown, { spanId }) => {
                    const next = new Set(shown)
                    next.delete(spanId)
                    return next
                },
                revealSpans: (shown, { reveal }) => new Set([...shown, ...reveal.fullChildListSpanIds]),
            },
        ],
        // Chains fold by default, so this holds the opened ones.
        openChainIds: [
            new Set<string>(),
            {
                showTrace: () => new Set<string>(),
                toggleChain: (opened, { spanId }) => {
                    const next = new Set(opened)
                    if (!next.delete(spanId)) {
                        next.add(spanId)
                    }
                    return next
                },
                revealSpans: (opened, { reveal }) => new Set([...opened, ...reveal.chainIds]),
            },
        ],
        // Runs fold by default too, so this holds the opened ones, by the id of their first span.
        openRunIds: [
            new Set<string>(),
            {
                showTrace: () => new Set<string>(),
                toggleRun: (opened, { spanId }) => {
                    const next = new Set(opened)
                    if (!next.delete(spanId)) {
                        next.add(spanId)
                    }
                    return next
                },
                revealSpans: (opened, { reveal }) => new Set([...opened, ...reveal.runIds]),
            },
        ],
        // A tab the person picked sticks while they move between spans. Until they pick one, the
        // inspector chooses for the span in view.
        chosenInspectorTab: [
            null as SpanInspectorTab | null,
            {
                showTrace: (_, { tab }) => tab,
                setInspectorTab: (_, { tab }) => tab,
            },
        ],
        // The `compareRowKey` of the operation whose spans the tree highlights. The key only has a meaning
        // against the spans of one trace, so opening a trace clears it. The Operations tab is the only place
        // that explains the dimmed rows, so a switch to another tab clears it too. A switch to the Operations
        // tab itself keeps it, so that a caller can select the tab after the highlight.
        highlightedOperationKey: [
            null as string | null,
            {
                highlightOperation: (_, { operationKey }) => operationKey,
                showTrace: () => null,
                setInspectorTab: (key, { tab }) => (tab === 'operations' ? key : null),
            },
        ],
    }),
    selectors({
        spanTree: [
            (s) => [s.spans],
            (spans: Span[]): TraceViewTree => {
                const roots = buildSpanTree(spans)
                const nodesById = new Map<string, SpanNode>()
                const stack = [...roots]
                while (stack.length > 0) {
                    const node = stack.pop()!
                    nodesById.set(node.span.span_id, node)
                    stack.push(...node.children)
                }
                return { roots, nodesById, descendantCounts: countDescendantsById(roots) }
            },
        ],
        spanRows: [
            (s) => [
                s.spanTree,
                s.collapsedSpanIds,
                s.fullChildListSpanIds,
                s.openChainIds,
                s.foldedRunsEnabled,
                s.openRunIds,
                s.pinnedSpanId,
            ],
            (
                spanTree: TraceViewTree,
                collapsedSpanIds: Set<string>,
                fullChildListSpanIds: Set<string>,
                openChainIds: Set<string>,
                foldedRunsEnabled: boolean,
                openRunIds: Set<string>,
                pinnedSpanId: string | null
            ): TraceDialogRow[] =>
                buildTraceDialogRows(spanTree.roots, {
                    collapsedSpanIds,
                    fullChildListSpanIds,
                    openChainIds,
                    foldRuns: foldedRunsEnabled,
                    openRunIds,
                    pinned: (pinnedSpanId && spanTree.nodesById.get(pinnedSpanId)) || null,
                }),
        ],
        flatSpans: [
            (s) => [s.spanRows],
            (spanRows: TraceDialogRow[]): SpanNode[] =>
                spanRows.flatMap((row) => {
                    const node = rowSpanNode(row)
                    return node ? [node] : []
                }),
        ],
        // The spans that have a row, or head a folded chain or run, so a selection can check in one lookup that it
        // has something on screen.
        visibleSpanIds: [
            (s) => [s.flatSpans],
            (flatSpans: SpanNode[]): Set<string> => new Set(flatSpans.map((node) => node.span.span_id)),
        ],
        chainStartIds: [
            (s) => [s.spanRows],
            (spanRows: TraceDialogRow[]): { folded: Set<string>; opened: Set<string> } => {
                const folded = new Set<string>()
                const opened = new Set<string>()
                for (const row of spanRows) {
                    if (row.kind === 'chain') {
                        folded.add(row.nodes[0].span.span_id)
                    } else if (row.kind === 'span' && row.openChainLength) {
                        opened.add(row.node.span.span_id)
                    }
                }
                return { folded, opened }
            },
        ],
        foldedRunStartIds: [
            (s) => [s.spanRows],
            (spanRows: TraceDialogRow[]): Set<string> =>
                new Set(spanRows.flatMap((row) => (row.kind === 'run' ? [row.nodes[0].span.span_id] : []))),
        ],
        selectedSpan: [
            (s) => [s.spans, s.selectedSpanId, s.summary],
            (spans: Span[], selectedSpanId: string | null, summary: TraceViewSummary): Span | null =>
                spans.find((span) => span.span_id === selectedSpanId) ?? summary.rootSpan ?? spans[0] ?? null,
        ],
        // The tree's "<parent span missing>" row selects an id that only appears as a parent id.
        missingParentSpanId: [
            (s) => [s.spanTree, s.selectedSpanId],
            (spanTree: TraceViewTree, selectedSpanId: string | null): string | null =>
                selectedSpanId && spanTree.nodesById.get(selectedSpanId)?.isMissingParent ? selectedSpanId : null,
        ],
        pinnedSpan: [
            (s) => [s.spans, s.pinnedSpanId],
            (spans: Span[], pinnedSpanId: string | null): Span | null =>
                pinnedSpanId ? (spans.find((span) => span.span_id === pinnedSpanId) ?? null) : null,
        ],
        activeInspectorTab: [
            (s) => [s.chosenInspectorTab, s.selectedSpan, s.sessionErrorBadgesEnabled],
            // An error span leads with its exceptions. Otherwise the logs lead.
            (chosen: SpanInspectorTab | null, selectedSpan: Span | null, errorsTabEnabled: boolean): SpanInspectorTab =>
                chosen ?? (errorsTabEnabled && selectedSpan?.status_code === 2 ? 'errors' : 'logs'),
        ],
        operationsTabEnabled: [
            (s) => [s.featureFlags],
            (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_TRACE_OPERATIONS_TAB],
        ],
        foldedRunsEnabled: [
            (s) => [s.featureFlags],
            (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_TRACE_FOLDED_RUNS],
        ],
        // The spans of the highlighted operation and their ancestors, so that a row that hides a match stays bright.
        // With the flag off nothing dims, because no Operations tab is on screen to explain the dimmed rows.
        operationSubtreeMarks: [
            (s) => [s.spanTree, s.highlightedOperationKey, s.operationsTabEnabled],
            (
                spanTree: TraceViewTree,
                operationKey: string | null,
                operationsTabEnabled: boolean
            ): Set<SpanNode> | null =>
                operationsTabEnabled && operationKey ? markOperationSubtrees(spanTree.roots, operationKey) : null,
        ],
        // Worked out once per change of rows or key, not per rendered row, because a "more" row stands for
        // whole subtrees and J and K re-render the rows on screen.
        operationRowMatches: [
            (s) => [s.spanRows, s.highlightedOperationKey, s.operationSubtreeMarks, s.collapsedSpanIds],
            (
                spanRows: TraceDialogRow[],
                operationKey: string | null,
                subtreeMarks: Set<SpanNode> | null,
                collapsedSpanIds: Set<string>
            ): boolean[] | null =>
                operationKey && subtreeMarks
                    ? operationRowMatches(spanRows, operationKey, subtreeMarks, collapsedSpanIds)
                    : null,
        ],
        firstOperationRowIndex: [
            (s) => [s.operationRowMatches],
            (matches: boolean[] | null): number => matches?.indexOf(true) ?? -1,
        ],
        // AI event rows are synthetic and have no operation of their own. AI events load after the spans, and a new
        // list of the same spans must keep this one, or the call tree rebuilds and drops the person's drill-down.
        operationSpans: [
            (s) => [s.spans],
            (spans: Span[]): Span[] => spans.filter((span) => !isAiEventSpan(span)),
            { resultEqualityCheck: sameSpans },
        ],
        // Kea computes a selector only when something reads it. Only the call tree pane reads this one, so the
        // waterfall never builds it, and a new selection or a resize does not rebuild it.
        callTree: [
            (s) => [s.operationSpans],
            (operationSpans: Span[]): FlameTreeNode => buildTraceCallTree(operationSpans),
        ],
        serviceColorMap: [(s) => [s.spans], (spans: Span[]): Map<string, number> => buildServiceColorMap(spans)],
        timeline: [
            (s) => [s.spans],
            (spans: Span[]): TraceViewTimeline => {
                if (spans.length === 0) {
                    return { startUs: 0, durationUs: 0 }
                }
                const starts = spans.map((span) => parseTimestampUs(span.timestamp))
                const ends = spans.map((span, i) => starts[i] + span.duration_nano / 1_000)
                const startUs = Math.min(...starts)
                return { startUs, durationUs: Math.max(...ends) - startUs }
            },
        ],
        summary: [
            (s) => [s.spans],
            (spans: Span[]): TraceViewSummary => ({
                rootSpan: spans.find((span) => span.is_root_span) ?? null,
                spanCount: spans.length,
                serviceCount: new Set(spans.map((span) => span.service_name)).size,
                errorCount: spans.filter((span) => span.status_code === 2).length,
            }),
        ],
    }),
    sharedListeners(({ values, actions }) => ({
        // J, K and clicks select spans on screen. The URL, or back and forward, can select a span that a folded run
        // hides, and a later page can fold the selected span into a run with the spans it adds. Open those runs.
        // Only runs: chains and collapsed spans stay as the person left them. One action that only opens, so the
        // trace dialog does not count it as the person's own toggle. A cleared selection has nothing to open.
        revealSelectedSpan: () => {
            const spanId = values.selectedSpanId
            const target =
                spanId && values.foldedRunsEnabled && !values.visibleSpanIds.has(spanId)
                    ? values.spanTree.nodesById.get(spanId)
                    : undefined
            if (!target) {
                return
            }
            const { roots, nodesById } = values.spanTree
            const { runIds } = revealSpanInRows(roots, target, {
                collapsedSpanIds: values.collapsedSpanIds,
                fullChildListSpanIds: values.fullChildListSpanIds,
                openChainIds: values.openChainIds,
                foldRuns: values.foldedRunsEnabled,
                openRunIds: values.openRunIds,
                pinned: (values.pinnedSpanId && nodesById.get(values.pinnedSpanId)) || null,
            })
            if (runIds.length > 0) {
                actions.revealSpans({ collapsedSpanIds: [], fullChildListSpanIds: [], chainIds: [], runIds })
            }
        },
    })),
    listeners(({ values, actions, cache, selectors, sharedListeners }) => ({
        enableSpanKeys: ({ containerSelector, surface }) => {
            // Capture phase, and stopped there, so the page under the view 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 owner = Symbol('spanKeys')
                spanKeyOwners.push(owner)
                const onKeyDown = (event: KeyboardEvent): void => {
                    const target = event.target as HTMLElement | null
                    // A field behind the view 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(containerSelector) &&
                        (['input', 'textarea', 'select'].includes(target.tagName.toLowerCase()) ||
                            target.isContentEditable)
                    // Only the most recently opened view steps, so a drawer opened over another
                    // does not move the selection underneath it too.
                    if (spanKeyOwners[spanKeyOwners.length - 1] !== owner) {
                        return
                    }
                    if (typing || event.isComposing || event.metaKey || event.ctrlKey || event.altKey) {
                        return
                    }
                    const step = {
                        j: actions.selectNextSpan,
                        k: actions.selectPreviousSpan,
                        arrowleft: () => actions.collapseSelectedSpan(surface),
                        arrowright: () => actions.expandSelectedSpan(surface),
                    }[event.key.toLowerCase()]
                    if (step) {
                        event.preventDefault()
                        event.stopPropagation()
                        // The call tree hides the span tree, so a step would move a selection that nobody can see.
                        if (values.traceViewMode === 'calltree') {
                            return
                        }
                        step()
                    }
                }
                window.addEventListener('keydown', onKeyDown, { capture: true })
                return () => {
                    window.removeEventListener('keydown', onKeyDown, { capture: true })
                    const index = spanKeyOwners.indexOf(owner)
                    if (index >= 0) {
                        spanKeyOwners.splice(index, 1)
                    }
                }
            }, 'spanKeys')
        },
        disableSpanKeys: () => {
            cache.disposables.dispose('spanKeys')
        },
        // The inspector's tab bar passes a surface only for a click that changes the tab on screen, so a tab that
        // another logic sets, or a click on the tab already shown, sends nothing. The check against the previous
        // tab also stops a caller that passes a surface for the tab already active.
        setInspectorTab: ({ tab, surface }, _, __, previousState) => {
            if (surface && tab !== selectors.activeInspectorTab(previousState)) {
                // pinned: analytics event name, so renaming it breaks the insights built on it
                posthog.capture('tracing trace inspector tab changed', { tab, surface })
            }
        },
        highlightOperation: ({ operationKey, surface, scope }) => {
            if (!operationKey) {
                return
            }
            // pinned: analytics event name, so renaming it breaks the insights built on it
            posthog.capture('tracing trace operation highlighted', { surface, scope })
            // The first span of a large operation often sits past a child cap, in a folded chain, or under
            // a collapsed span. Open what hides it, so that the tree has a row to scroll to. The selection
            // stays where it is, because the inspector shows the Operations tab the person is using.
            const { roots, nodesById } = values.spanTree
            const target = firstOperationSpan(roots, operationKey)
            if (!target) {
                return
            }
            const reveal = revealSpanInRows(roots, target, {
                collapsedSpanIds: values.collapsedSpanIds,
                fullChildListSpanIds: values.fullChildListSpanIds,
                openChainIds: values.openChainIds,
                foldRuns: values.foldedRunsEnabled,
                openRunIds: values.openRunIds,
                pinned: (values.pinnedSpanId && nodesById.get(values.pinnedSpanId)) || null,
            })
            // One action that only opens. The toggle actions flip state, and the trace dialog counts them as the
            // person's own collapse toggles.
            if (
                reveal.collapsedSpanIds.length +
                    reveal.fullChildListSpanIds.length +
                    reveal.chainIds.length +
                    reveal.runIds.length >
                0
            ) {
                actions.revealSpans(reveal)
            }
        },
        selectSpan: [
            // The missing-parent notice replaces the whole inspector, Operations tab included, so a highlight
            // left in place would dim rows with nothing on screen to explain it.
            () => {
                if (values.missingParentSpanId && values.highlightedOperationKey) {
                    actions.highlightOperation(null)
                }
            },
            sharedListeners.revealSelectedSpan,
        ],
        setSpans: sharedListeners.revealSelectedSpan,
        selectNextSpan: () => {
            actions.spanStepped()
            // A missing-parent row is selectable too, so step from it rather than from the root fallback.
            const currentId = values.missingParentSpanId ?? values.selectedSpan?.span_id
            const index = values.flatSpans.findIndex((node) => node.span.span_id === currentId)
            const next = values.flatSpans[Math.min(index + 1, values.flatSpans.length - 1)]
            if (next) {
                actions.selectSpan(next.span.span_id)
            }
        },
        selectPreviousSpan: () => {
            actions.spanStepped()
            const currentId = values.missingParentSpanId ?? values.selectedSpan?.span_id
            const index = values.flatSpans.findIndex((node) => node.span.span_id === currentId)
            const previous = values.flatSpans[Math.max(index - 1, 0)]
            if (previous) {
                actions.selectSpan(previous.span.span_id)
            }
        },
        // Left collapses the selected span, or moves up to its parent once there is nothing to collapse.
        collapseSelectedSpan: ({ surface }) => {
            const node = values.spanTree.nodesById.get(values.missingParentSpanId ?? values.selectedSpan?.span_id ?? '')
            if (!node) {
                return
            }
            actions.spanStepped()
            const spanId = node.span.span_id
            const spanRow = values.spanRows.find((row) => row.kind === 'span' && row.node === node)
            const openRunStart = spanRow?.kind === 'span' ? spanRow.openRunStart : undefined
            if (values.chainStartIds.opened.has(spanId)) {
                actions.toggleChain(spanId)
            } else if (
                // A folded run already hides the spans under its first span, so Left moves on to the parent.
                node.children.length > 0 &&
                !values.collapsedSpanIds.has(spanId) &&
                !values.foldedRunStartIds.has(spanId)
            ) {
                actions.toggleSpanCollapsed(spanId)
            } else if (openRunStart) {
                // Any span of an opened run folds it once its own children are collapsed, the first span included,
                // so a person deep in a long run can close it from where they are. The fold leaves the selection on
                // the run's row.
                actions.toggleRun(openRunStart.span.span_id, 'key', surface)
            } else if (node.parent) {
                // The parent can sit inside a folded chain, which stands for it on screen.
                const shown = new Set(values.flatSpans)
                let parent: SpanNode | null = node.parent
                while (parent && !shown.has(parent)) {
                    parent = parent.parent
                }
                if (parent) {
                    actions.selectSpan(parent.span.span_id)
                }
            }
        },
        // Right expands the selected span, or steps into its first child once it is open.
        expandSelectedSpan: ({ surface }) => {
            const node = values.spanTree.nodesById.get(values.missingParentSpanId ?? values.selectedSpan?.span_id ?? '')
            // A folded run opens before the children check, because its first span can be a leaf.
            if (node && values.foldedRunStartIds.has(node.span.span_id)) {
                actions.spanStepped()
                actions.toggleRun(node.span.span_id, 'key', surface)
                return
            }
            if (!node || node.children.length === 0) {
                return
            }
            if (values.chainStartIds.folded.has(node.span.span_id)) {
                actions.spanStepped()
                actions.toggleChain(node.span.span_id)
                return
            }
            if (!values.collapsedSpanIds.has(node.span.span_id)) {
                actions.selectNextSpan()
                return
            }
            actions.spanStepped()
            actions.toggleSpanCollapsed(node.span.span_id)
        },
        toggleSpanCollapsed: () => {
            actions.keepSelectionOnScreen()
        },
        toggleChain: () => {
            actions.keepSelectionOnScreen()
        },
        showFewerChildren: () => {
            actions.keepSelectionOnScreen()
        },
        toggleRun: ({ spanId, method, surface }) => {
            if (method) {
                // Listeners run after the reducers, so the rows already show the toggled run: an opened run's first
                // span row carries the run's length, and a folded run is a run row.
                const row = values.spanRows.find((row) => rowSpanNode(row)?.span.span_id === spanId)
                const spanCount =
                    row?.kind === 'run' ? row.nodes.length : row?.kind === 'span' ? row.openRunLength : undefined
                // pinned: analytics event name, so renaming it breaks the insights built on it
                posthog.capture('tracing trace run toggled', {
                    action: values.openRunIds.has(spanId) ? 'open' : 'fold',
                    span_count: spanCount ?? null,
                    method,
                    surface,
                })
            }
            actions.keepSelectionOnScreen()
        },
        // The span tree reports each change of the folded runs it shows. The event marks that a trace showed runs,
        // so it goes out once per trace, and later pages and toggles of the same trace send nothing.
        runsShown: ({ surface }) => {
            if (cache.runsShownSent) {
                return
            }
            const runLengths = values.spanRows.flatMap((row) => (row.kind === 'run' ? [row.nodes.length] : []))
            if (runLengths.length === 0) {
                return
            }
            cache.runsShownSent = true
            // pinned: analytics event name, so renaming it breaks the insights built on it
            posthog.capture('tracing trace runs shown', {
                run_count: runLengths.length,
                largest_run: runLengths.reduce((largest, length) => Math.max(largest, length), 0),
                surface,
            })
        },
        showTrace: () => {
            cache.runsShownSent = false
        },
        // The inspector must never show a span the list hides.
        keepSelectionOnScreen: () => {
            const selected = values.selectedSpanId ? values.spanTree.nodesById.get(values.selectedSpanId) : undefined
            const shown = new Set(values.flatSpans)
            if (!selected || shown.has(selected)) {
                return
            }
            // A folded run has one row, which stands for its first span, so a span that the fold hides moves to that
            // span. J and K stop there too. Otherwise the selection moves up to the nearest span on screen.
            const runFirstSpans = new Map<SpanNode, SpanNode>()
            for (const row of values.spanRows) {
                if (row.kind === 'run') {
                    row.nodes.forEach((member) => runFirstSpans.set(member, row.nodes[0]))
                }
            }
            let node: SpanNode | null = selected
            while (node && !shown.has(node) && !runFirstSpans.has(node)) {
                node = node.parent
            }
            const target = node ? (runFirstSpans.get(node) ?? node) : null
            if (target && target !== selected) {
                actions.selectSpan(target.span.span_id)
            }
        },
    })),
])