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.

6.3 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router } from 'kea-router'
import type { LocationChangedPayload } from 'kea-router/lib/types'

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

import type { LogSeverityLevel } from '~/queries/schema/schema-general'

import type { TraceLinkParams } from './traceUrl'
import { usableId } from './usableId'

/** 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
}

/** Where a trace dialog was opened from. Sent with every dialog event, so keep the values stable. */
export type TraceDialogEntryPoint =
    | 'log_details'
    | 'log_expanded_row'
    | 'log_row_action'
    | 'log_trace_id_cell'
    | 'metric_sample'
    | 'metric_exemplar'
    | 'exception_card'

export type TraceDialogCloseReason = 'dismissed' | 'back_to_log' | 'open_in_tracing' | 'navigated' | 'replaced'

export interface OpenTraceDialogOptions {
    entryPoint: TraceDialogEntryPoint
    openedFrom?: TraceDialogSource | null
}

// 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 {
    if (!spanId) {
        return null
    }
    return usableId(spanId) ? spanId.toUpperCase() : spanId
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceDialogOpenLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    dialogEnabled: boolean
    entryPoint: TraceDialogEntryPoint | null
    isOpen: boolean
    openedFrom: TraceDialogSource | null
    trace: TraceLinkParams | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceDialogOpenLogicActions {
    locationChanged: ({
        method,
        pathname,
        search,
        searchParams,
        hash,
        hashParams,
        initial,
        url,
        routerState,
    }: LocationChangedPayload) => {
        hash: string
        hashParams: Record<string, any>
        initial: boolean
        method: 'POP' | 'PUSH' | 'REPLACE'
        pathname: string
        routerState: Record<string, any>
        search: string
        searchParams: Record<string, any>
        url: string
    } // router
    closeTraceDialog: (reason?: TraceDialogCloseReason) => {
        reason: TraceDialogCloseReason
    }
    openTraceDialog: (
        trace: TraceLinkParams,
        options: OpenTraceDialogOptions
    ) => {
        entryPoint: TraceDialogEntryPoint
        openedFrom: TraceDialogSource | null
        trace: {
            spanId: string | null
            traceId: string
            ts?: string | null | undefined
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceDialogOpenLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        dialogEnabled: (featureFlags: FeatureFlagsSet) => boolean
    }
}

export type traceDialogOpenLogicType = MakeLogicType<
    traceDialogOpenLogicValues,
    traceDialogOpenLogicActions,
    Record<string, any>,
    traceDialogOpenLogicMeta
>

/**
 * Whether the trace dialog is open, and which trace it shows. Every logged-in page mounts this logic,
 * so it must not import feature code. traceDialogLogic loads the trace when the dialog mounts.
 */
export const traceDialogOpenLogic = kea<traceDialogOpenLogicType>([
    path(['lib', 'components', 'ViewTraceButton', 'traceDialogOpenLogic']),
    connect(() => ({
        actions: [router, ['locationChanged']],
        values: [featureFlagLogic, ['featureFlags']],
    })),
    actions({
        openTraceDialog: (trace: TraceLinkParams, options: OpenTraceDialogOptions) => ({
            trace: { ...trace, spanId: inApiCase(trace.spanId) },
            openedFrom: options.openedFrom ?? null,
            entryPoint: options.entryPoint,
        }),
        closeTraceDialog: (reason: TraceDialogCloseReason = 'dismissed') => ({ reason }),
    }),
    reducers({
        isOpen: [
            false,
            {
                openTraceDialog: () => true,
                closeTraceDialog: () => false,
            },
        ],
        // Survives close: useKeepMountedWhileOpen keeps the dialog rendered through its exit
        // animation, and clearing the trace then would flash an empty dialog.
        trace: [
            null as TraceLinkParams | null,
            {
                openTraceDialog: (_, { trace }) => trace,
            },
        ],
        openedFrom: [
            null as TraceDialogSource | null,
            {
                openTraceDialog: (_, { openedFrom }) => openedFrom,
            },
        ],
        entryPoint: [
            null as TraceDialogEntryPoint | null,
            {
                openTraceDialog: (_, { entryPoint }) => entryPoint,
            },
        ],
    }),
    selectors({
        // Every entry point checks this one place, so the flag cannot open the dialog from some
        // links and not others.
        dialogEnabled: [
            (s) => [s.featureFlags],
            (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_TRACE_DIALOG],
        ],
    }),
    listeners(({ values, actions, cache }) => ({
        locationChanged: ({ pathname }) => {
            // Query and hash changes fire locationChanged too, so only a new pathname closes the dialog.
            if (pathname === cache.lastPathname) {
                return
            }
            cache.lastPathname = pathname
            if (values.isOpen) {
                actions.closeTraceDialog('navigated')
            }
        },
    })),
    afterMount(({ cache }) => {
        cache.lastPathname = router.values.location.pathname
    }),
])

/**
 * The session player and the full-screen logs viewer are global modals that render below the trace
 * dialog. Each one calls this when it opens, so it does not open hidden behind the dialog.
 */
export function closeTraceDialogUnderModal(): void {
    if (traceDialogOpenLogic.findMounted()?.values.isOpen) {
        traceDialogOpenLogic.actions.closeTraceDialog()
    }
}