: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): open traces in a dialog behind a flag (#116908)
Jon McCallum4cf6a0c1a01a
diff --git a/frontend/src/layout/GlobalModals.tsx b/frontend/src/layout/GlobalModals.tsxindex 63ff71e30f82..90cdd24fd71a 100644--- a/frontend/src/layout/GlobalModals.tsx+++ b/frontend/src/layout/GlobalModals.tsx@@ -26,6 +26,7 @@ import { MaybeWelcomeDialog } from 'scenes/welcome/WelcomeDialog'import { composeTicketLogic } from 'products/conversations/frontend/components/ComposeTicket/composeTicketLogic'import { logsViewerModalLogic } from 'products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic'+import { traceDialogLogic } from 'products/tracing/frontend/components/TraceDialog/traceDialogLogic'import { globalModalsLogic } from './globalModalsLogic'import { navigationLogic } from './navigation/navigationLogic'@@ -46,6 +47,12 @@ const LogsViewerModal = lazyWithRetry(() =>})))+const TraceDialog = lazyWithRetry(() =>+ import('products/tracing/frontend/components/TraceDialog/TraceDialog').then((m) => ({+ default: m.TraceDialog,+ }))+)+// The compose ticket modal anchors the support rich text editor (tiptap and prosemirror).const ComposeTicketModal = lazyWithRetry(() =>import('products/conversations/frontend/components/ComposeTicket/ComposeTicketModal').then((m) => ({@@ -61,6 +68,8 @@ export function GlobalModals(): JSX.Element {// Grace-extended so the modals' exit animations finish before the lazy subtree unmounts.const shouldRenderSessionPlayerModal = useKeepMountedWhileOpen(!!activeSessionRecording)const shouldRenderLogsViewerModal = useKeepMountedWhileOpen(isLogsViewerModalOpen)+ const { isOpen: isTraceDialogOpen } = useValues(traceDialogLogic)+ const shouldRenderTraceDialog = useKeepMountedWhileOpen(isTraceDialogOpen)const { isOpen: isComposeTicketModalOpen } = useValues(composeTicketLogic)const shouldRenderComposeTicketModal = useKeepMountedWhileOpen(isComposeTicketModalOpen)const { isInviteModalShown } = useValues(inviteLogic)@@ -86,6 +95,11 @@ export function GlobalModals(): JSX.Element {<LogsViewerModal /></Suspense>) : null}+ {shouldRenderTraceDialog ? (+ <Suspense fallback={null}>+ <TraceDialog />+ </Suspense>+ ) : null}<PreviewingCustomCssModal /><TwoFactorSetupModal /><HedgehogMode />diff --git a/frontend/src/lib/components/ViewTraceButton/ViewTraceButton.tsx b/frontend/src/lib/components/ViewTraceButton/ViewTraceButton.tsxindex fad31703f3ec..6fa7ac00fb5d 100644--- a/frontend/src/lib/components/ViewTraceButton/ViewTraceButton.tsx+++ b/frontend/src/lib/components/ViewTraceButton/ViewTraceButton.tsx@@ -7,7 +7,10 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'import { traceUrl } from './traceUrl'-export interface ViewTraceButtonProps extends Pick<LemonButtonProps, 'size' | 'type' | 'className' | 'data-attr'> {+export interface ViewTraceButtonProps extends Pick<+ LemonButtonProps,+ 'size' | 'type' | 'className' | 'data-attr' | 'onClick'+> {/** Hex trace id, as every product's query runner returns it. */traceId: string | null | undefined/** Anchors the waterfall on one span. */diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 4e42a7cd8857..83db3a66734f 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -594,6 +594,7 @@ export const FEATURE_FLAGS = {TRACING_SETTINGS_RETENTION: 'tracing-settings-retention', // owner: #team-apm — gates the traces retention setting; mirrored by `TRACES_RETENTION_FLAG` in posthog/api/team.pyTRACING_SETTINGS_RETENTION_RULES: 'tracing-settings-retention-rules', // owner: #team-apm — gates the span retention rules in tracing settingsTRACING_SPAN_ERROR_BADGES: 'tracing-span-error-badges', // owner: #team-apm, badges span rows whose session hit errors and adds the Errors tab to the trace drawer+ TRACING_TRACE_DIALOG: 'tracing-trace-dialog', // owner: #team-apm — opens traces in a dialog over the current page instead of navigating to tracingTRACING_UI_V2: 'tracing-ui-v2',TRAFFIC_TYPE_VIRTUAL_PROPERTIES: 'traffic-type-virtual-properties', // owner: #team-web-analyticsUI_CUSTOMIZATION: 'ui-customization-enabled', // owner: @fercgomes #team-self-driving, gates sidebar/homepage UI customizationdiff --git a/products/logs/frontend/components/LogsViewer/LogContextLinks/LogContextLinks.tsx b/products/logs/frontend/components/LogsViewer/LogContextLinks/LogContextLinks.tsxindex e7adcaf67cbc..665685d5dcad 100644--- a/products/logs/frontend/components/LogsViewer/LogContextLinks/LogContextLinks.tsx+++ b/products/logs/frontend/components/LogsViewer/LogContextLinks/LogContextLinks.tsx@@ -16,6 +16,7 @@ import { logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'import { ParsedLogMessage } from 'products/logs/frontend/types'import { getDistinctIdWithKey, getSessionIdFromLogAttributes } from 'products/logs/frontend/utils'import { PersonDisplay } from 'products/persons/frontend/components/PersonDisplay'+import { useOpenTraceDialog } from 'products/tracing/frontend/components/TraceDialog/useOpenTraceDialog'import { type ErrorScope } from 'products/tracing/frontend/errorCorrelation'import { LogErrorCount } from './LogErrorCount'@@ -48,6 +49,7 @@ export function LogContextLinks({const { configuredSessionIdKeys, configuredDistinctIdKeys } = useValues(logsConfigLogic)const traceId = usableId(log.trace_id)+ const openTraceDialog = useOpenTraceDialog()const sessionId = getSessionIdFromLogAttributes(log.attributes, log.resource_attributes, configuredSessionIdKeys)const distinctId = getDistinctIdWithKey(log.attributes, log.resource_attributes, configuredDistinctIdKeys)?.value@@ -72,6 +74,7 @@ export function LogContextLinks({traceId={traceId}spanId={log.span_id}timestamp={log.timestamp}+ onClick={(event) => openTraceDialog(event, { traceId, spanId: log.span_id, ts: log.timestamp })}size="xsmall"type="secondary"data-attr={TRACE_DATA_ATTR[surface]}diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialog.tsxnew file mode 100644index 000000000000..bb6f2ae1f2f3--- /dev/null+++ b/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx@@ -0,0 +1,42 @@+import { useActions, useValues } from 'kea'++import { IconExternal } from '@posthog/icons'+import { LemonButton, LemonModal } from '@posthog/lemon-ui'++import { traceUrl } from 'lib/components/ViewTraceButton/traceUrl'++import { traceDialogLogic } from './traceDialogLogic'++export function TraceDialog(): JSX.Element | null {+ const { isOpen, trace } = useValues(traceDialogLogic)+ const { closeTraceDialog } = useActions(traceDialogLogic)++ if (!trace) {+ return null+ }++ return (+ <LemonModal+ isOpen={isOpen}+ onClose={closeTraceDialog}+ title="Trace"+ description={<span translate="no">{trace.traceId}</span>}+ forceAbovePopovers+ 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="min-h-80" />+ </LemonModal>+ )+}diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.tsnew file mode 100644index 000000000000..5b14e67247ce--- /dev/null+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts@@ -0,0 +1,41 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'++import { traceDialogLogic } from './traceDialogLogic'++describe('traceDialogLogic', () => {+ let logic: ReturnType<typeof traceDialogLogic.build>++ beforeEach(() => {+ initKeaTests()+ router.actions.push('/logs')+ logic = traceDialogLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('keeps the trace after close so the exit animation does not flash an empty dialog', async () => {+ logic.actions.openTraceDialog({ traceId: 'abc123', spanId: 'def456' })++ await expectLogic(logic, () => {+ logic.actions.closeTraceDialog()+ }).toMatchValues({ isOpen: false, trace: { traceId: 'abc123', spanId: 'def456' } })+ })++ it.each([+ ['stays open on a query-only change', '/logs?filters=abc', true],+ ['stays open on a hash-only change', '/logs#panel', true],+ ['closes on a new pathname', '/insights', false],+ ])('%s', async (_name, url, expectedOpen) => {+ logic.actions.openTraceDialog({ traceId: 'abc123' })++ await expectLogic(logic, () => {+ router.actions.push(url)+ }).toMatchValues({ isOpen: expectedOpen })+ })+})diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.tsnew file mode 100644index 000000000000..68fdd5b6bc22--- /dev/null+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts@@ -0,0 +1,112 @@+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 type { TraceLinkParams } from 'lib/components/ViewTraceButton/traceUrl'+import { FEATURE_FLAGS } from 'lib/constants'+import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface traceDialogLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ dialogEnabled: boolean+ isOpen: boolean+ trace: TraceLinkParams | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface traceDialogLogicActions {+ 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: () => {+ value: true+ }+ openTraceDialog: (trace: TraceLinkParams) => {+ trace: TraceLinkParams+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface traceDialogLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ dialogEnabled: (featureFlags: FeatureFlagsSet) => boolean+ }+}++export type traceDialogLogicType = MakeLogicType<+ traceDialogLogicValues,+ traceDialogLogicActions,+ Record<string, any>,+ traceDialogLogicMeta+>++export const traceDialogLogic = kea<traceDialogLogicType>([+ path(['products', 'tracing', 'frontend', 'components', 'TraceDialog', 'traceDialogLogic']),+ connect(() => ({+ actions: [router, ['locationChanged']],+ values: [featureFlagLogic, ['featureFlags']],+ })),+ actions({+ openTraceDialog: (trace: TraceLinkParams) => ({ trace }),+ closeTraceDialog: true,+ }),+ 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,+ },+ ],+ }),+ 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()+ }+ },+ })),+ afterMount(({ cache }) => {+ cache.lastPathname = router.values.location.pathname+ }),+])diff --git a/products/tracing/frontend/components/TraceDialog/useOpenTraceDialog.test.tsx b/products/tracing/frontend/components/TraceDialog/useOpenTraceDialog.test.tsxnew file mode 100644index 000000000000..1ca2ffeb8885--- /dev/null+++ b/products/tracing/frontend/components/TraceDialog/useOpenTraceDialog.test.tsx@@ -0,0 +1,70 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { Provider } from 'kea'+import { router } from 'kea-router'++import { ViewTraceButton } from 'lib/components/ViewTraceButton/ViewTraceButton'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { initKeaTests } from '~/test/init'+import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'++import { traceDialogLogic } from './traceDialogLogic'+import { useOpenTraceDialog } from './useOpenTraceDialog'++function DialogTraceButton(): JSX.Element | null {+ const openTraceDialog = useOpenTraceDialog()+ return (+ <ViewTraceButton+ traceId="abc123"+ spanId="def456"+ onClick={(event) => openTraceDialog(event, { traceId: 'abc123', spanId: 'def456' })}+ />+ )+}++describe('useOpenTraceDialog', () => {+ beforeEach(() => {+ window.POSTHOG_APP_CONTEXT = {+ ...window.POSTHOG_APP_CONTEXT,+ resource_access_control: {+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,+ [AccessControlResourceType.Tracing]: AccessControlLevel.Viewer,+ },+ } as AppContext+ initKeaTests()+ })++ afterEach(() => cleanup())++ it.each([+ ['a plain click with the flag on', true, {}, true],+ // Modifier clicks skip the dialog and leave the link to go to Tracing.+ ['a cmd click', true, { metaKey: true }, false],+ ['a ctrl click', true, { ctrlKey: true }, false],+ ['a shift click', true, { shiftKey: true }, false],+ ['a plain click with the flag off', false, {}, false],+ ])('%s opens the dialog: %s', (_name, flagOn, modifiers, expectDialog) => {+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TRACING_TRACE_DIALOG]: flagOn })+ traceDialogLogic.mount()+ router.actions.push('/logs')+ const pathnameBeforeClick = router.values.location.pathname++ render(+ <Provider>+ <DialogTraceButton />+ </Provider>+ )+ fireEvent.click(screen.getByText('View trace'), modifiers)++ expect(traceDialogLogic.values.isOpen).toBe(expectDialog)+ if (expectDialog) {+ expect(traceDialogLogic.values.trace).toMatchObject({ traceId: 'abc123', spanId: 'def456' })+ // A dialog click must not also follow the link.+ expect(router.values.location.pathname).toBe(pathnameBeforeClick)+ }+ })+})diff --git a/products/tracing/frontend/components/TraceDialog/useOpenTraceDialog.ts b/products/tracing/frontend/components/TraceDialog/useOpenTraceDialog.tsnew file mode 100644index 000000000000..480b9072dedc--- /dev/null+++ b/products/tracing/frontend/components/TraceDialog/useOpenTraceDialog.ts@@ -0,0 +1,34 @@+import { useActions, useValues } from 'kea'+import { type MouseEvent, useCallback } from 'react'++import type { TraceLinkParams } from 'lib/components/ViewTraceButton/traceUrl'++import { traceDialogLogic } from './traceDialogLogic'++export type OpenTraceDialogHandler = (event: MouseEvent | null, trace: TraceLinkParams) => boolean++/**+ * Opens a trace in the dialog in place of navigating to Tracing. Returns false when it did not, so+ * the caller's link or navigation goes ahead: while the dialog flag is off, and for modifier and+ * non-primary clicks. Cmd and ctrl then open Tracing in a new tab, and shift opens it in place.+ */+export function useOpenTraceDialog(): OpenTraceDialogHandler {+ const { dialogEnabled } = useValues(traceDialogLogic)+ const { openTraceDialog } = useActions(traceDialogLogic)++ // Stable while the flag holds, so callers can list it in a memo's dependencies.+ return useCallback(+ (event, trace) => {+ if (!dialogEnabled) {+ return false+ }+ if (event && (event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0)) {+ return false+ }+ event?.preventDefault()+ openTraceDialog(trace)+ return true+ },+ [dialogEnabled, openTraceDialog]+ )+}