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.

feat(tracing): fold call chains and draw tree lines in the trace dialog (#117994)

Jon McCallum00e6aaea873f
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx
index 3b1769fab340..0a0071808045 100644
--- a/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { type CSSProperties, useCallback, useRef, useState } from 'react'
-import { IconExternal } from '@posthog/icons'
+import { IconCollapse45, IconExpand45, IconExternal, IconSidebarClose, IconSidebarOpen } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonModal, LemonTag, Spinner } from '@posthog/lemon-ui'
import { Resizer } from 'lib/components/Resizer/Resizer'
@@ -9,6 +9,7 @@ import { type ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/res
import { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'
import { traceUrl } from 'lib/components/ViewTraceButton/traceUrl'
import { FloatingContainerContext } from 'lib/hooks/useFloatingContainerContext'
+import { cn } from 'lib/utils/css-classes'
import { pluralize } from 'lib/utils/strings'
import { SpanInspector } from 'products/tracing/frontend/components/SpanInspector/SpanInspector'
@@ -50,8 +51,11 @@ export function TraceDialog(): JSX.Element | null {
sessionErrorBadgesEnabled,
traceIdentity,
traceSessionId,
+ inspectorOpen,
+ isFullscreen,
} = useValues(traceDialogLogic)
- const { closeTraceDialog, loadTraceSpans, setInspectorTab, openInTracing } = useActions(traceDialogLogic)
+ const { closeTraceDialog, loadTraceSpans, setInspectorTab, openInTracing, toggleInspector, toggleFullscreen } =
+ useActions(traceDialogLogic)
// The dialog sits above popovers, so the inspector's menus and drawers, and the person popover,
// portal inside it instead.
const [floatingContainer, setFloatingContainer] = useState<HTMLDivElement | null>(null)
@@ -89,24 +93,42 @@ export function TraceDialog(): JSX.Element | null {
data-attr={TRACE_DIALOG_DATA_ATTR}
width="90vw"
maxWidth={1600}
+ fullScreen={isFullscreen}
footer={
<div className="flex flex-wrap items-center justify-between gap-2 w-full">
<TraceDialogShortcuts />
- <LemonButton
- type="secondary"
- icon={<IconExternal />}
- to={traceUrl(trace)}
- onClick={openInTracing}
- data-attr="trace-dialog-open-in-tracing"
- >
- Open in Tracing
- </LemonButton>
+ <div className="flex items-center gap-2">
+ <LemonButton
+ type="secondary"
+ icon={inspectorOpen ? <IconSidebarClose /> : <IconSidebarOpen />}
+ tooltip={inspectorOpen ? 'Hide span details' : 'Show span details'}
+ onClick={toggleInspector}
+ data-attr="trace-dialog-toggle-inspector"
+ />
+ <LemonButton
+ type="secondary"
+ icon={isFullscreen ? <IconCollapse45 /> : <IconExpand45 />}
+ tooltip={isFullscreen ? 'Exit full screen' : 'Full screen'}
+ onClick={toggleFullscreen}
+ data-attr="trace-dialog-toggle-fullscreen"
+ />
+ <LemonButton
+ type="secondary"
+ icon={<IconExternal />}
+ to={traceUrl(trace)}
+ onClick={openInTracing}
+ data-attr="trace-dialog-open-in-tracing"
+ >
+ Open in Tracing
+ </LemonButton>
+ </div>
</div>
}
>
<FloatingContainerContext.Provider value={floatingContainer}>
- {/* The span list virtualizes, so it needs a definite height to measure against. */}
- <div className="flex flex-col gap-2 h-[65vh]">
+ {/* The span list virtualizes, so it needs a definite height to measure against. Full screen
+ leaves room for the dialog's header and footer. */}
+ <div className={cn('flex flex-col gap-2', isFullscreen ? 'h-[calc(100vh-12rem)]' : 'h-[65vh]')}>
<TraceDialogOpenedFromLog />
<TraceIdentityChips
identity={traceIdentity}
@@ -141,7 +163,7 @@ export function TraceDialog(): JSX.Element | null {
<div className="flex-1 min-w-0 min-h-0">
<TraceDialogSpanTree />
</div>
- {(missingParentSpanId || selectedSpan) && (
+ {inspectorOpen && (missingParentSpanId || selectedSpan) && (
<div
ref={inspectorRef}
// Half the body at most side by side, so the span tree keeps room for its timeline bars.
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsx
index 4750f4db8739..30b5951e18c3 100644
--- a/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsx
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsx
@@ -1,25 +1,26 @@
import { LemonButton } from '@posthog/lemon-ui'
-import type { SpanNode } from 'products/tracing/frontend/spanTree'
-
-import { INDENT_PX, MAX_INDENT_DEPTH } from './TraceDialogSpanRow'
+import type { TraceDialogRow } from './traceDialogRows'
+import { indentPx, TraceDialogTreeLines } from './TraceDialogTreeLines'
export interface TraceDialogMoreSpansRowProps {
- parent: SpanNode
- hiddenCount: number
+ row: Extract<TraceDialogRow, { kind: 'more' }>
onShowAll: (spanId: string) => void
}
-export function TraceDialogMoreSpansRow({ parent, hiddenCount, onShowAll }: TraceDialogMoreSpansRowProps): JSX.Element {
+export function TraceDialogMoreSpansRow({ row, onShowAll }: TraceDialogMoreSpansRowProps): JSX.Element {
+ const { parent, hiddenCount } = row
return (
- <div className="flex items-center w-full h-full gap-2 text-xs text-muted border-l-[3px] border-l-transparent">
+ // Same columns and no gap as the span row, so the tree lines on both line up at any width.
+ <div className="flex items-center w-full h-full text-xs text-muted border-l-[3px] border-l-transparent">
<span className="w-16 shrink-0" aria-hidden />
<span
- className="flex items-center gap-2"
+ className="relative self-stretch w-96 shrink min-w-48 flex items-center gap-2"
// eslint-disable-next-line react/forbid-dom-props
- style={{ paddingLeft: Math.min(parent.depth + 1, MAX_INDENT_DEPTH) * INDENT_PX }}
+ style={{ paddingLeft: indentPx(row.depth) + 22 }}
>
- <span>
+ <TraceDialogTreeLines row={row} />
+ <span className="relative">
{hiddenCount.toLocaleString()} more {hiddenCount === 1 ? 'span' : 'spans'}
</span>
<LemonButton
@@ -31,6 +32,8 @@ export function TraceDialogMoreSpansRow({ parent, hiddenCount, onShowAll }: Trac
Show all
</LemonButton>
</span>
+ <span className="grow min-w-16" aria-hidden />
+ <span className="w-20 shrink-0" aria-hidden />
</div>
)
}
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx
index fc00308a25c2..58f31120f1a6 100644
--- a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx
@@ -3,18 +3,17 @@ import { IconChevronRight, IconWarning } from '@posthog/icons'
import { getSeriesColor } from 'lib/colors'
import { cn } from 'lib/utils/css-classes'
-import { parseTimestampUs, type SpanNode } from 'products/tracing/frontend/spanTree'
+import { parseTimestampUs } from 'products/tracing/frontend/spanTree'
import { formatDuration } from 'products/tracing/frontend/TraceWaterfallView'
import type { TraceDialogTimeline } from './traceDialogLogic'
+import type { TraceDialogRow } from './traceDialogRows'
+import { indentPx, MAX_VISUAL_DEPTH, TraceDialogTreeLines } from './TraceDialogTreeLines'
-export const INDENT_PX = 12
-// Deeper spans stop indenting, so the name keeps room in the fixed-width span column.
-export const MAX_INDENT_DEPTH = 10
const ERROR_COLOR = 'var(--danger)'
export interface TraceDialogSpanRowProps {
- node: SpanNode
+ row: Extract<TraceDialogRow, { kind: 'span' | 'chain' }>
timeline: TraceDialogTimeline
serviceColorMap: Map<string, number>
isSelected: boolean
@@ -25,6 +24,7 @@ export interface TraceDialogSpanRowProps {
isCollapsed: boolean
onSelect: (spanId: string) => void
onToggleCollapsed: (spanId: string) => void
+ onToggleChain: (spanId: string) => void
}
function percentOfTrace(us: number, timeline: TraceDialogTimeline): number {
@@ -32,7 +32,7 @@ function percentOfTrace(us: number, timeline: TraceDialogTimeline): number {
}
export function TraceDialogSpanRow({
- node,
+ row,
timeline,
serviceColorMap,
isSelected,
@@ -41,8 +41,13 @@ export function TraceDialogSpanRow({
isCollapsed,
onSelect,
onToggleCollapsed,
+ onToggleChain,
}: TraceDialogSpanRowProps): JSX.Element {
+ const node = row.kind === 'chain' ? row.nodes[0] : row.node
+ const chainLast = row.kind === 'chain' ? row.nodes[row.nodes.length - 1] : null
+ const openChainLength = row.kind === 'span' ? row.openChainLength : undefined
const { span, isMissingParent = false } = node
+ const name = chainLast ? `${span.name} › … › ${chainLast.span.name}` : span.name
const startUs = parseTimestampUs(span.timestamp)
const leftPct = Math.max(percentOfTrace(startUs, timeline), 0)
const widthPct = Math.max(
@@ -52,7 +57,8 @@ export function TraceDialogSpanRow({
),
0.3
)
- const isError = span.status_code === 2
+ // A folded chain shows an error when any span in it errored, not only its first.
+ const isError = (row.kind === 'chain' ? row.nodes : [node]).some((member) => member.span.status_code === 2)
const serviceColor = getSeriesColor(serviceColorMap.get(span.service_name) ?? 0)
const barColor = isError ? ERROR_COLOR : serviceColor
const openedAtPct = openedAtUs != null ? Math.min(Math.max(percentOfTrace(openedAtUs, timeline), 0), 100) : null
@@ -73,7 +79,7 @@ export function TraceDialogSpanRow({
className="absolute inset-0 cursor-pointer"
aria-pressed={isSelected}
aria-label={span.name}
- title={isMissingParent ? span.name : `${span.name} · ${span.service_name}`}
+ title={isMissingParent ? name : `${name} · ${span.service_name}`}
onClick={() => onSelect(span.span_id)}
data-attr="trace-dialog-span-row"
/>
@@ -81,14 +87,27 @@ export function TraceDialogSpanRow({
+{formatDuration(Math.max(startUs - timeline.startUs, 0) * 1_000)}
</span>
<span
- className="pointer-events-none relative w-80 shrink-0 flex items-center gap-1.5 min-w-0 pr-2"
+ className="pointer-events-none relative self-stretch w-96 shrink min-w-48 flex items-center gap-1.5 pr-2"
// eslint-disable-next-line react/forbid-dom-props
- style={{ paddingLeft: Math.min(node.depth, MAX_INDENT_DEPTH) * INDENT_PX }}
+ style={{ paddingLeft: indentPx(row.depth) }}
>
- {descendantCount > 0 ? (
+ <TraceDialogTreeLines row={row} />
+ {chainLast ? (
<button
type="button"
- className="pointer-events-auto shrink-0 flex items-center gap-0.5 h-5 pl-0.5 pr-1 rounded border border-primary bg-surface-primary text-[11px] font-semibold text-secondary hover:border-secondary hover:text-primary"
+ className="pointer-events-auto relative shrink-0 flex items-center gap-0.5 h-5 pl-0.5 pr-1.5 rounded border border-dashed border-accent bg-surface-primary text-[11px] font-semibold text-accent hover:bg-accent-highlight-secondary"
+ aria-expanded={false}
+ aria-label={`Show ${row.kind === 'chain' ? row.nodes.length : 0} folded spans`}
+ onClick={() => onToggleChain(span.span_id)}
+ data-attr="trace-dialog-span-chain"
+ >
+ <IconChevronRight />
+ {row.kind === 'chain' ? row.nodes.length.toLocaleString() : null}
+ </button>
+ ) : descendantCount > 0 ? (
+ <button
+ type="button"
+ className="pointer-events-auto relative shrink-0 flex items-center gap-0.5 h-5 pl-0.5 pr-1.5 rounded border border-accent bg-accent-highlight-secondary text-[11px] font-semibold text-accent hover:bg-accent-highlight-primary"
aria-expanded={!isCollapsed}
aria-label={`${isCollapsed ? 'Show' : 'Hide'} ${descendantCount} nested ${
descendantCount === 1 ? 'span' : 'spans'
@@ -99,30 +118,55 @@ export function TraceDialogSpanRow({
<IconChevronRight className={cn('transition-transform', !isCollapsed && 'rotate-90')} />
{descendantCount.toLocaleString()}
</button>
- ) : (
- <span className="w-5 shrink-0" aria-hidden />
- )}
- {!isMissingParent && (
+ ) : null}
+ {/* A leaf's dot sits where a parent's toggle would, so the elbow ends at it. */}
+ <span
+ className={cn(
+ 'relative flex shrink-0 items-center justify-center',
+ descendantCount === 0 && !chainLast && 'w-4'
+ )}
+ aria-hidden
+ >
+ {!isMissingParent && (
+ <span
+ className="size-2 rounded-full"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ backgroundColor: serviceColor }}
+ />
+ )}
+ </span>
+ {row.depth > MAX_VISUAL_DEPTH && (
<span
- className="size-2 rounded-full shrink-0"
- // eslint-disable-next-line react/forbid-dom-props
- style={{ backgroundColor: serviceColor }}
- aria-hidden
- />
+ className="relative shrink-0 rounded border px-1 font-mono text-[10px] text-muted"
+ translate="no"
+ >
+ L{row.depth}
+ </span>
)}
{isError && <IconWarning className="shrink-0 text-danger" fontSize={14} aria-label="Error" />}
<span
className={cn(
- 'truncate font-mono',
+ 'relative truncate font-mono',
(isError || isMissingParent) && 'text-danger',
+ chainLast && 'text-secondary',
isSelected && 'font-semibold'
)}
translate="no"
>
- {span.name}
+ {name}
</span>
+ {openChainLength && (
+ <button
+ type="button"
+ className="pointer-events-auto relative ml-auto shrink-0 text-[11px] font-medium text-accent hover:underline"
+ onClick={() => onToggleChain(span.span_id)}
+ data-attr="trace-dialog-span-chain-fold"
+ >
+ Fold {openChainLength}
+ </button>
+ )}
</span>
- <span className="pointer-events-none relative grow self-stretch my-1.5" aria-hidden>
+ <span className="pointer-events-none relative grow min-w-16 self-stretch my-1.5" aria-hidden>
{!isMissingParent && (
<span
className="absolute inset-y-0"
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx
index cd76809a5ef3..f579a518c83d 100644
--- a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { CSSProperties, useCallback, useEffect, useMemo, useRef } from 'react'
+import { CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { List, useListRef } from 'react-window'
import { AutoSizer } from 'lib/components/AutoSizer'
@@ -10,7 +10,7 @@ import { formatDuration } from 'products/tracing/frontend/TraceWaterfallView'
import { traceDialogLogic, type TraceDialogTimeline } from './traceDialogLogic'
import { TraceDialogMoreSpansRow } from './TraceDialogMoreSpansRow'
-import type { TraceDialogRow } from './traceDialogRows'
+import { rowSpanNode, type TraceDialogRow } from './traceDialogRows'
import { TraceDialogSpanRow } from './TraceDialogSpanRow'
const ROW_HEIGHT = 32
@@ -26,6 +26,7 @@ interface SpanListRowData {
openedAtUs: number | null
onSelect: (spanId: string) => void
onToggleCollapsed: (spanId: string) => void
+ onToggleChain: (spanId: string) => void
onShowAll: (spanId: string) => void
}
@@ -51,21 +52,69 @@ function SpanListRow({
// eslint-disable-next-line react/forbid-dom-props
<div {...ariaAttributes} style={style}>
{row.kind === 'more' ? (
- <TraceDialogMoreSpansRow parent={row.parent} hiddenCount={row.hiddenCount} onShowAll={onShowAll} />
+ <TraceDialogMoreSpansRow row={row} onShowAll={onShowAll} />
) : (
- <TraceDialogSpanRow
- node={row.node}
- isSelected={row.node.span.span_id === selectedSpanId}
- openedAtUs={row.node.span.span_id === openedSpanId ? openedAtUs : null}
- descendantCount={descendantCounts.get(row.node.span.span_id) ?? 0}
- isCollapsed={collapsedSpanIds.has(row.node.span.span_id)}
- {...rowProps}
+ <SpanOrChainRow
+ row={row}
+ selectedSpanId={selectedSpanId}
+ openedSpanId={openedSpanId}
+ openedAtUs={openedAtUs}
+ descendantCounts={descendantCounts}
+ collapsedSpanIds={collapsedSpanIds}
+ rowProps={rowProps}
/>
)}
</div>
)
}
+function SpanOrChainRow({
+ row,
+ selectedSpanId,
+ openedSpanId,
+ openedAtUs,
+ descendantCounts,
+ collapsedSpanIds,
+ rowProps,
+}: {
+ row: Extract<TraceDialogRow, { kind: 'span' | 'chain' }>
+ selectedSpanId: string | null
+ openedSpanId: string | null
+ openedAtUs: number | null
+ descendantCounts: Map<string, number>
+ collapsedSpanIds: Set<string>
+ rowProps: Pick<SpanListRowData, 'timeline' | 'serviceColorMap' | 'onSelect' | 'onToggleCollapsed' | 'onToggleChain'>
+}): JSX.Element {
+ const spanId = (row.kind === 'chain' ? row.nodes[0] : row.node).span.span_id
+ return (
+ <TraceDialogSpanRow
+ row={row}
+ isSelected={spanId === selectedSpanId}
+ openedAtUs={spanId === openedSpanId ? openedAtUs : null}
+ descendantCount={descendantCounts.get(spanId) ?? 0}
+ isCollapsed={collapsedSpanIds.has(spanId)}
+ {...rowProps}
+ />
+ )
+}
+
+function scrolledPastAncestors(row: TraceDialogRow | undefined): TraceDialogRow[] {
+ const ancestors: TraceDialogRow[] = []
+ for (let ancestor = row?.parentRow ?? null; ancestor; ancestor = ancestor.parentRow) {
+ ancestors.push(ancestor)
+ }
+ return ancestors.reverse()
+}
+
+function rowLabel(row: TraceDialogRow): string {
+ if (row.kind === 'chain') {
+ return `${row.nodes[0].span.name} › … › ${row.nodes[row.nodes.length - 1].span.name}`
+ }
+ return row.kind === 'span' ? row.node.span.name : ''
+}
+
+const MAX_PINNED_ANCESTORS = 4
+
export function TraceDialogSpanTree(): JSX.Element {
const {
spanRows,
@@ -78,7 +127,8 @@ export function TraceDialogSpanTree(): JSX.Element {
trace,
openedAtUs,
} = useValues(traceDialogLogic)
- const { selectSpan, toggleSpanCollapsed, showAllChildren } = useActions(traceDialogLogic)
+ const { selectSpan, toggleSpanCollapsed, toggleChain, showAllChildren } = useActions(traceDialogLogic)
+ const [topIndex, setTopIndex] = useState(0)
const listRef = useListRef(null)
const openedSpanId = trace?.spanId ?? null
@@ -95,6 +145,7 @@ export function TraceDialogSpanTree(): JSX.Element {
const revealedIndexRef = useRef<number | null>(null)
const revealOpenedSpan = useCallback(
(visibleRows: { startIndex: number; stopIndex: number }): void => {
+ setTopIndex(visibleRows.startIndex)
if (openedIndex < 0 || revealedIndexRef.current === openedIndex) {
return
}
@@ -110,18 +161,21 @@ export function TraceDialogSpanTree(): JSX.Element {
// above, this leaves it alone.
const selectedSpanId = missingParentSpanId ?? selectedSpan?.span_id ?? null
useEffect(() => {
- const index = spanRows.findIndex((row) => row.kind === 'span' && row.node.span.span_id === selectedSpanId)
+ const index = spanRows.findIndex((row) => rowSpanNode(row)?.span.span_id === selectedSpanId)
if (index >= 0 && (selectedSpanId !== openedSpanId || revealedIndexRef.current !== null)) {
listRef.current?.scrollToRow({ index, align: 'smart' })
}
}, [spanRows, selectedSpanId, openedSpanId, listRef])
+ const pinnedAncestors = scrolledPastAncestors(spanRows[topIndex])
+ const hiddenAncestorCount = Math.max(pinnedAncestors.length - MAX_PINNED_ANCESTORS, 0)
+
return (
<div className="flex flex-col h-full min-h-0">
<div className="flex items-center text-[11px] text-muted border-b py-1" aria-hidden>
<span className="w-16 shrink-0 px-2">Start</span>
- <span className="w-80 shrink-0">Span</span>
- <span className="relative grow h-4">
+ <span className="w-96 shrink min-w-48">Span</span>
+ <span className="relative grow min-w-16 h-4">
{getTimelineTicks(timeline.durationUs).map((tickUs) => (
<span
key={tickUs}
@@ -136,6 +190,42 @@ export function TraceDialogSpanTree(): JSX.Element {
</span>
<span className="w-20 shrink-0 px-2 text-right">Duration</span>
</div>
+ {pinnedAncestors.length > 0 && (
+ <div
+ className="flex items-center gap-1 h-7 px-2 border-b text-xs text-muted bg-surface-secondary min-w-0 overflow-hidden"
+ data-attr="trace-dialog-pinned-ancestors"
+ >
+ <span className="shrink-0">Inside</span>
+ {hiddenAncestorCount > 0 && (
+ <span className="shrink-0">
+ <span translate="no">{hiddenAncestorCount}</span> more ›
+ </span>
+ )}
+ {pinnedAncestors.slice(hiddenAncestorCount).map((ancestor, i) => {
+ const node = rowSpanNode(ancestor)
+ return node ? (
+ <span key={node.span.span_id} className="flex items-center gap-1 min-w-0">
+ {i > 0 && <span aria-hidden>›</span>}
+ <button
+ type="button"
+ className="truncate font-mono text-primary hover:underline"
+ onClick={() => {
+ selectSpan(node.span.span_id)
+ // Selecting an already selected span changes nothing the scroll effect watches.
+ listRef.current?.scrollToRow({
+ index: spanRows.indexOf(ancestor),
+ align: 'smart',
+ })
+ }}
+ translate="no"
+ >
+ {rowLabel(ancestor)}
+ </button>
+ </span>
+ ) : null
+ })}
+ </div>
+ )}
<div className="flex-1 min-h-0">
<AutoSizer
renderProp={({ width, height }: SizeProps) => (
@@ -157,6 +247,7 @@ export function TraceDialogSpanTree(): JSX.Element {
openedAtUs,
onSelect: selectSpan,
onToggleCollapsed: toggleSpanCollapsed,
+ onToggleChain: toggleChain,
onShowAll: showAllChildren,
}}
listRef={listRef}
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogTreeLines.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogTreeLines.tsx
new file mode 100644
index 000000000000..a8ff6d95b7f0
--- /dev/null
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogTreeLines.tsx
@@ -0,0 +1,52 @@
+import { rowConnectorLines, type TraceDialogRow } from './traceDialogRows'
+
+// Indent shrinks with depth, so a deep span keeps room for its name.
+const INDENT_STEPS: [maxDepth: number, px: number][] = [
+ [4, 16],
+ [8, 12],
+ [Infinity, 8],
+]
+// Past this depth rows stop indenting and show their depth instead. Folded chains keep most traces above it.
+export const MAX_VISUAL_DEPTH = 16
+const LINE_OFFSET_PX = 8
+
+export function indentPx(depth: number): number {
+ let px = 0
+ for (let level = 0; level < Math.min(depth, MAX_VISUAL_DEPTH); level++) {
+ px += INDENT_STEPS.find(([maxDepth]) => level < maxDepth)![1]
+ }
+ return px
+}
+
+// Past MAX_VISUAL_DEPTH every level shares one position, so there is no line to draw.
+export function TraceDialogTreeLines({ row }: { row: TraceDialogRow }): JSX.Element | null {
+ if (row.depth === 0 || row.depth > MAX_VISUAL_DEPTH) {
+ return null
+ }
+ const lines = rowConnectorLines(row)
+ const parentLineX = indentPx(row.depth - 1) + LINE_OFFSET_PX
+ return (
+ <span className="absolute inset-y-0 left-0 pointer-events-none" aria-hidden>
+ {lines.map((continues, level) =>
+ continues ? (
+ <span
+ key={level}
+ className="absolute inset-y-0 w-px bg-border-secondary"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ left: indentPx(level) + LINE_OFFSET_PX }}
+ />
+ ) : null
+ )}
+ <span
+ className="absolute top-0 w-px bg-border-secondary"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ left: parentLineX, bottom: row.isLast ? '50%' : 0 }}
+ />
+ <span
+ className="absolute top-1/2 h-px bg-border-secondary"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ left: parentLineX, width: indentPx(row.depth) - parentLineX }}
+ />
+ </span>
+ )
+}
diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts
index 97848e378be1..2d67f152cc2d 100644
--- a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts
+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts
@@ -315,6 +315,36 @@ describe('traceDialogLogic', () => {
expect(pageListener).not.toHaveBeenCalled()
})
+ it('opens a folded chain with the right arrow, and keeps the selection on screen when it folds again', async () => {
+ const child = (spanId: string, parentSpanId: string): Span => ({
+ ...span(spanId),
+ parent_span_id: parentSpanId,
+ })
+ getTraceSpy.mockResolvedValue({
+ results: [
+ { ...span('ROOT'), is_root_span: true },
+ child('A', 'ROOT'),
+ child('B', 'A'),
+ child('C', 'B'),
+ child('LEAF', 'C'),
+ ],
+ hasMore: false,
+ nextOffset: null,
+ })
+ logic.actions.openTraceDialog({ traceId: 'abc123', spanId: 'ROOT' }, { entryPoint: 'log_details' })
+ await expectLogic(logic).toDispatchActions(['loadTraceSpansSuccess'])
+ const visible = (): string[] => logic.values.flatSpans.map((node) => node.span.span_id)
+ expect(visible()).toEqual(['ROOT', 'A', 'LEAF'])
+
+ logic.actions.selectSpan('A')
+ press('ArrowRight')
+ expect(visible()).toEqual(['ROOT', 'A', 'B', 'C', 'LEAF'])
+
+ logic.actions.selectSpan('C')
+ logic.actions.toggleChain('A')
+ expect(logic.values.selectedSpanId).toBe('A')
+ })
+
it('steps onto a missing parent row and on past it', async () => {
const orphan = { ...span('b'), parent_span_id: 'GONE' }
getTraceSpy.mockResolvedValue({ results: [span('a'), orphan], hasMore: false, nextOffset: null })
diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts
index e38ed5efc40d..1632f4dba586 100644
--- a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts
+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts
@@ -35,7 +35,7 @@ import { buildServiceColorMap } from 'products/tracing/frontend/TraceWaterfallVi
import { tracingCorrelationConfigLogic } from 'products/tracing/frontend/tracingCorrelationConfigLogic'
import type { Span, SpanInspectorTab } from 'products/tracing/frontend/types'
-import { buildTraceDialogRows, countDescendantsById, type TraceDialogRow } from './traceDialogRows'
+import { buildTraceDialogRows, countDescendantsById, rowSpanNode, type TraceDialogRow } from './traceDialogRows'
// The trace endpoint pages at 2,000 spans, so this caps the dialog at 10,000. Bigger traces open in
// Tracing, which pages in on scroll.
@@ -129,13 +129,20 @@ export interface traceDialogLogicValues {
correlationLinksEnabled: boolean // tracingCorrelationConfigLogic
sessionErrorBadgesEnabled: boolean // tracingCorrelationConfigLogic
activeInspectorTab: SpanInspectorTab
+ chainStartIds: {
+ folded: Set<string>
+ opened: Set<string>
+ }
chosenInspectorTab: SpanInspectorTab | null
collapsedSpanIds: Set<string>
dialogEnabled: boolean
flatSpans: SpanNode[]
fullChildListSpanIds: Set<string>
+ inspectorOpen: boolean
+ isFullscreen: boolean
isOpen: boolean
missingParentSpanId: string | null
+ openChainIds: Set<string>
openedAtUs: number | null
openedFrom: TraceDialogSource | null
openedSpan: Span | null
@@ -203,6 +210,9 @@ export interface traceDialogLogicActions {
expandSelectedSpan: () => {
value: true
}
+ keepSelectionOnScreen: () => {
+ value: true
+ }
loadTraceSpans: (trace: TraceLinkParams) => TraceLinkParams
loadTraceSpansFailure: (
error: string,
@@ -248,6 +258,15 @@ export interface traceDialogLogicActions {
showAllChildren: (spanId: string) => {
spanId: string
}
+ toggleChain: (spanId: string) => {
+ spanId: string
+ }
+ toggleFullscreen: () => {
+ value: true
+ }
+ toggleInspector: () => {
+ value: true
+ }
toggleSpanCollapsed: (spanId: string) => {
spanId: string
}
@@ -262,9 +281,14 @@ export interface traceDialogLogicMeta {
spanTree: TraceDialogTree,
collapsedSpanIds: Set<string>,
fullChildListSpanIds: Set<string>,
+ openChainIds: Set<string>,
trace: TraceLinkParams | null
) => TraceDialogRow[]
flatSpans: (spanRows: TraceDialogRow[]) => SpanNode[]
+ chainStartIds: (spanRows: TraceDialogRow[]) => {
+ folded: Set<string>
+ opened: Set<string>
+ }
selectedSpan: (
traceSpans: TraceDialogSpans | null,
selectedSpanId: string | null,
@@ -340,6 +364,10 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
selectSpan: (spanId: string) => ({ spanId }),
toggleSpanCollapsed: (spanId: string) => ({ spanId }),
showAllChildren: (spanId: string) => ({ spanId }),
+ toggleChain: (spanId: string) => ({ spanId }),
+ keepSelectionOnScreen: true,
+ toggleInspector: true,
+ toggleFullscreen: true,
setInspectorTab: (tab: SpanInspectorTab) => ({ tab }),
}),
loaders(({ values }) => ({
@@ -436,6 +464,34 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
showAllChildren: (shown, { spanId }) => new Set(shown).add(spanId),
},
],
+ // Chains fold by default, so this holds the opened ones.
+ openChainIds: [
+ new Set<string>(),
+ {
+ openTraceDialog: () => new Set<string>(),
+ toggleChain: (opened, { spanId }) => {
+ const next = new Set(opened)
+ if (!next.delete(spanId)) {
+ next.add(spanId)
+ }
+ return next
+ },
+ },
+ ],
+ inspectorOpen: [
+ true,
+ { persist: true },
+ {
+ toggleInspector: (open) => !open,
+ },
+ ],
+ isFullscreen: [
+ false,
+ { persist: true },
+ {
+ toggleFullscreen: (fullscreen) => !fullscreen,
+ },
+ ],
// A tab the person picked sticks while they move between spans. Until they pick one, the
// inspector chooses for the span in view.
chosenInspectorTab: [
@@ -468,25 +524,43 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
},
],
spanRows: [
- (s) => [s.spanTree, s.collapsedSpanIds, s.fullChildListSpanIds, s.trace],
+ (s) => [s.spanTree, s.collapsedSpanIds, s.fullChildListSpanIds, s.openChainIds, s.trace],
(
spanTree: TraceDialogTree,
collapsedSpanIds: Set<string>,
fullChildListSpanIds: Set<string>,
+ openChainIds: Set<string>,
trace: TraceLinkParams | null
): TraceDialogRow[] =>
- buildTraceDialogRows(
- spanTree.roots,
+ buildTraceDialogRows(spanTree.roots, {
collapsedSpanIds,
fullChildListSpanIds,
- (trace?.spanId && spanTree.nodesById.get(trace.spanId)) || null
- ),
+ openChainIds,
+ pinned: (trace?.spanId && spanTree.nodesById.get(trace.spanId)) || null,
+ }),
],
- // The spans on screen, in order, for stepping through them.
flatSpans: [
(s) => [s.spanRows],
(spanRows: TraceDialogRow[]): SpanNode[] =>
- spanRows.flatMap((row) => (row.kind === 'span' ? [row.node] : [])),
+ spanRows.flatMap((row) => {
+ const node = rowSpanNode(row)
+ return node ? [node] : []
+ }),
+ ],
+ 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 }
+ },
],
selectedSpan: [
(s) => [s.traceSpans, s.selectedSpanId, s.summary],
@@ -715,10 +789,21 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
if (cache.session) {
cache.session.keyboardSteps += 1
}
- if (node.children.length > 0 && !values.collapsedSpanIds.has(node.span.span_id)) {
- actions.toggleSpanCollapsed(node.span.span_id)
+ const spanId = node.span.span_id
+ if (values.chainStartIds.opened.has(spanId)) {
+ actions.toggleChain(spanId)
+ } else if (node.children.length > 0 && !values.collapsedSpanIds.has(spanId)) {
+ actions.toggleSpanCollapsed(spanId)
} else if (node.parent) {
- actions.selectSpan(node.parent.span.span_id)
+ // 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.
@@ -727,6 +812,13 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
if (!node || node.children.length === 0) {
return
}
+ if (values.chainStartIds.folded.has(node.span.span_id)) {
+ if (cache.session) {
+ cache.session.keyboardSteps += 1
+ }
+ actions.toggleChain(node.span.span_id)
+ return
+ }
if (!values.collapsedSpanIds.has(node.span.span_id)) {
actions.selectNextSpan()
return
@@ -736,20 +828,31 @@ export const traceDialogLogic = kea<traceDialogLogicType>([
}
actions.toggleSpanCollapsed(node.span.span_id)
},
- // Collapsing the span that holds the selection selects it, so the inspector shows a span on screen.
- toggleSpanCollapsed: ({ spanId }) => {
+ toggleSpanCollapsed: () => {
if (cache.session) {
cache.session.collapseToggles += 1
}
- if (!values.collapsedSpanIds.has(spanId) || !values.selectedSpanId) {
+ actions.keepSelectionOnScreen()
+ },
+ toggleChain: () => {
+ if (cache.session) {
+ cache.session.collapseToggles += 1
+ }
+ actions.keepSelectionOnScreen()
+ },
+ // The inspector must never show a span the list hides.
+ keepSelectionOnScreen: () => {
+ const selected = values.selectedSpanId ? values.spanTree.nodesById.get(values.selectedSpanId) : undefined
+ if (!selected) {
return
}
- const { nodesById } = values.spanTree
- for (let node = nodesById.get(values.selectedSpanId)?.parent; node; node = node.parent) {
- if (node.span.span_id === spanId) {
- actions.selectSpan(spanId)
- return
- }
+ const shown = new Set(values.flatSpans)
+ let node: SpanNode | null = selected
+ while (node && !shown.has(node)) {
+ node = node.parent
+ }
+ if (node && node !== selected) {
+ actions.selectSpan(node.span.span_id)
}
},
// The player and the full-screen logs viewer are global modals that can sit below this one,
diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.ts b/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.ts
index c894c82c2cd0..4e368d8371b0 100644
--- a/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.ts
+++ b/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.ts
@@ -1,7 +1,7 @@
import { buildSpanTree, type SpanNode } from 'products/tracing/frontend/spanTree'
import type { Span } from 'products/tracing/frontend/types'
-import { buildTraceDialogRows, countDescendantsById, type TraceDialogRow } from './traceDialogRows'
+import { buildTraceDialogRows, countDescendantsById, rowConnectorLines, type TraceDialogRow } from './traceDialogRows'
function span(spanId: string, parentSpanId: string, offsetMs: number): Span {
return {
@@ -24,7 +24,13 @@ function span(spanId: string, parentSpanId: string, offsetMs: number): Span {
}
function labels(rows: TraceDialogRow[]): string[] {
- return rows.map((row) => (row.kind === 'span' ? row.node.span.span_id : `+${row.hiddenCount}`))
+ return rows.map((row) =>
+ row.kind === 'span'
+ ? row.node.span.span_id
+ : row.kind === 'chain'
+ ? `[${row.nodes.map((node) => node.span.span_id).join('>')}]`
+ : `+${row.hiddenCount}`
+ )
}
function find(roots: SpanNode[], spanId: string): SpanNode {
@@ -81,6 +87,83 @@ describe('traceDialogRows', () => {
])('%s', (_name, collapsed, fullChildLists, pinnedId, expected) => {
const pinned = pinnedId ? find(roots, pinnedId) : null
- expect(labels(buildTraceDialogRows(roots, collapsed, fullChildLists, pinned))).toEqual(expected)
+ expect(
+ labels(
+ buildTraceDialogRows(roots, {
+ collapsedSpanIds: collapsed,
+ fullChildListSpanIds: fullChildLists,
+ openChainIds: new Set(),
+ pinned,
+ })
+ )
+ ).toEqual(expected)
+ })
+
+ describe('chains', () => {
+ // root > a > b > c > d, where d branches into e and f.
+ const chain = buildSpanTree([
+ span('root', '', 0),
+ span('a', 'root', 1),
+ span('b', 'a', 2),
+ span('c', 'b', 3),
+ span('d', 'c', 4),
+ span('e', 'd', 5),
+ span('f', 'd', 6),
+ ])
+ const build = (openChainIds: Set<string>, pinnedId: string | null = null): TraceDialogRow[] =>
+ buildTraceDialogRows(chain, {
+ collapsedSpanIds: new Set(),
+ fullChildListSpanIds: new Set(),
+ openChainIds,
+ pinned: pinnedId ? find(chain, pinnedId) : null,
+ })
+
+ it.each([
+ [
+ 'folds a run of single-child spans into one row',
+ new Set<string>(),
+ null,
+ ['root', '[a>b>c]', 'd', 'e', 'f'],
+ ],
+ // Opening must not fold the rest of the run again from its second span.
+ ['shows every span of an opened chain', new Set(['a']), null, ['root', 'a', 'b', 'c', 'd', 'e', 'f']],
+ [
+ 'keeps the chain open when the span a log came from is inside it',
+ new Set<string>(),
+ 'b',
+ ['root', 'a', 'b', 'c', 'd', 'e', 'f'],
+ ],
+ ])('%s', (_name, openChainIds, pinnedId, expected) => {
+ expect(labels(build(openChainIds, pinnedId))).toEqual(expected)
+ })
+
+ it('still folds the spans below the span a log came from', () => {
+ const long = buildSpanTree([
+ span('root', '', 0),
+ span('a', 'root', 1),
+ span('b', 'a', 2),
+ span('c', 'b', 3),
+ span('d', 'c', 4),
+ span('e', 'd', 5),
+ span('f', 'e', 6),
+ ])
+ const rows = buildTraceDialogRows(long, {
+ collapsedSpanIds: new Set(),
+ fullChildListSpanIds: new Set(),
+ openChainIds: new Set(),
+ pinned: find(long, 'a'),
+ })
+
+ expect(labels(rows)).toEqual(['root', 'a', '[b>c>d>e]', 'f'])
+ })
+
+ it('places rows under a folded chain one level below it, with lines only where siblings follow', () => {
+ const rows = build(new Set())
+ const [, chainRow, d, e, f] = rows
+
+ expect([chainRow.depth, d.depth, e.depth, f.depth]).toEqual([1, 2, 3, 3])
+ expect([e.isLast, f.isLast]).toEqual([false, true])
+ expect(rowConnectorLines(f)).toEqual([false, false])
+ })
})
})
diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogRows.ts b/products/tracing/frontend/components/TraceDialog/traceDialogRows.ts
index bb9078ac55f6..b34ae33bbb7b 100644
--- a/products/tracing/frontend/components/TraceDialog/traceDialogRows.ts
+++ b/products/tracing/frontend/components/TraceDialog/traceDialogRows.ts
@@ -2,8 +2,30 @@ import { parseTimestampUs, type SpanNode } from 'products/tracing/frontend/spanT
// A wide fan-out shows this many children until the person asks for the rest.
export const TRACE_DIALOG_CHILD_LIMIT = 10
+export const TRACE_DIALOG_MIN_CHAIN = 3
-export type TraceDialogRow = { kind: 'span'; node: SpanNode } | { kind: 'more'; parent: SpanNode; hiddenCount: number }
+interface TraceDialogRowBase {
+ depth: number
+ isLast: boolean
+ /** Connectors walk this up, so they are derived only for rows on screen. */
+ parentRow: TraceDialogRow | null
+}
+
+export type TraceDialogRow = TraceDialogRowBase &
+ (
+ | {
+ kind: 'span'
+ node: SpanNode
+ openChainLength?: number
+ }
+ /** The first span stands for the chain in selection and the inspector. */
+ | { kind: 'chain'; nodes: SpanNode[] }
+ | { kind: 'more'; parent: SpanNode; hiddenCount: number }
+ )
+
+export function rowSpanNode(row: TraceDialogRow): SpanNode | null {
+ return row.kind === 'span' ? row.node : row.kind === 'chain' ? row.nodes[0] : null
+}
function byStart(nodes: SpanNode[]): SpanNode[] {
return [...nodes].sort((a, b) => parseTimestampUs(a.span.timestamp) - parseTimestampUs(b.span.timestamp))
@@ -30,50 +52,107 @@ export function countDescendantsById(roots: SpanNode[]): Map<string, number> {
return counts
}
-/**
- * The rows the span list shows, depth first in start order. A collapsed span hides its subtree, and a
- * span with more than TRACE_DIALOG_CHILD_LIMIT children shows the first ones and a "more" row, unless
- * its children are shown in full. The pinned span stays visible past the limit, so the span a log came
- * from is on screen when the dialog opens.
- */
+function singleChildRun(first: SpanNode, collapsedSpanIds: Set<string>): SpanNode[] {
+ const run: SpanNode[] = []
+ let node: SpanNode | undefined = first
+ while (node && node.children.length === 1 && !collapsedSpanIds.has(node.span.span_id)) {
+ run.push(node)
+ node = node.children[0]
+ }
+ return run
+}
+
+export interface TraceDialogRowOptions {
+ collapsedSpanIds: Set<string>
+ fullChildListSpanIds: Set<string>
+ openChainIds: Set<string>
+ /** The span a log came from. It stays on screen: past the child cap, and outside folded chains. */
+ pinned: SpanNode | null
+}
+
+/** Chains fold so long call chains don't push the tree off the right edge. */
export function buildTraceDialogRows(
roots: SpanNode[],
- collapsedSpanIds: Set<string>,
- fullChildListSpanIds: Set<string>,
- pinned: SpanNode | null
+ { collapsedSpanIds, fullChildListSpanIds, openChainIds, pinned }: TraceDialogRowOptions
): TraceDialogRow[] {
const pinnedPath = new Set<SpanNode>()
for (let node = pinned; node; node = node.parent) {
pinnedPath.add(node)
}
+ type Pending = { node: SpanNode; depth: number; isLast: boolean; parentRow: TraceDialogRow | null }
const rows: TraceDialogRow[] = []
- const stack: TraceDialogRow[] = byStart(roots)
- .reverse()
- .map((node) => ({ kind: 'span', node }))
+ // Spans that must not start a fold: members of an opened chain, and spans at or above the pinned
+ // span in a run. Marking them keeps a deep pinned chain to one scan instead of one per member.
+ const noFold = new Set<SpanNode>()
+ const stack: (Pending | TraceDialogRow)[] = []
+ const pushChildren = (children: SpanNode[], owner: SpanNode, depth: number, parentRow: TraceDialogRow): void => {
+ let shown = byStart(children)
+ if (shown.length > TRACE_DIALOG_CHILD_LIMIT && !fullChildListSpanIds.has(owner.span.span_id)) {
+ shown = shown.filter((child, i) => i < TRACE_DIALOG_CHILD_LIMIT || pinnedPath.has(child))
+ }
+ const hiddenCount = children.length - shown.length
+ const next: (Pending | TraceDialogRow)[] = shown.map((child, i) => ({
+ node: child,
+ depth,
+ isLast: hiddenCount === 0 && i === shown.length - 1,
+ parentRow,
+ }))
+ if (hiddenCount > 0) {
+ next.push({ kind: 'more', parent: owner, hiddenCount, depth, isLast: true, parentRow })
+ }
+ for (let i = next.length - 1; i >= 0; i--) {
+ stack.push(next[i])
+ }
+ }
+
+ const sortedRoots = byStart(roots)
+ for (let i = sortedRoots.length - 1; i >= 0; i--) {
+ stack.push({ node: sortedRoots[i], depth: 0, isLast: i === sortedRoots.length - 1, parentRow: null })
+ }
while (stack.length > 0) {
- const row = stack.pop()!
- rows.push(row)
- if (row.kind !== 'span') {
+ const item = stack.pop()!
+ if ('kind' in item) {
+ rows.push(item)
continue
}
- const { node } = row
- const spanId = node.span.span_id
- if (node.children.length === 0 || collapsedSpanIds.has(spanId)) {
+ const { node, depth, isLast, parentRow } = item
+ const run =
+ node.parent?.children.length === 1 && !noFold.has(node) ? singleChildRun(node, collapsedSpanIds) : []
+ const pinnedAt = run.findLastIndex((member) => pinnedPath.has(member))
+ // Spans below the pinned one can still fold, so only the part down to it is ruled out.
+ run.slice(0, pinnedAt + 1).forEach((member) => noFold.add(member))
+ const foldable = run.length >= TRACE_DIALOG_MIN_CHAIN && pinnedAt < 0
+ if (foldable && !openChainIds.has(node.span.span_id)) {
+ const chainRow: TraceDialogRow = { kind: 'chain', nodes: run, depth, isLast, parentRow }
+ rows.push(chainRow)
+ const after = run[run.length - 1].children[0]
+ stack.push({ node: after, depth: depth + 1, isLast: true, parentRow: chainRow })
continue
}
- let shown = byStart(node.children)
- if (shown.length > TRACE_DIALOG_CHILD_LIMIT && !fullChildListSpanIds.has(spanId)) {
- shown = shown.filter((child, i) => i < TRACE_DIALOG_CHILD_LIMIT || pinnedPath.has(child))
+ if (foldable) {
+ run.forEach((member) => noFold.add(member))
}
- const next: TraceDialogRow[] = shown.map((child) => ({ kind: 'span', node: child }))
- const hiddenCount = node.children.length - shown.length
- if (hiddenCount > 0) {
- next.push({ kind: 'more', parent: node, hiddenCount })
+ const row: TraceDialogRow = {
+ kind: 'span',
+ node,
+ depth,
+ isLast,
+ parentRow,
+ ...(foldable ? { openChainLength: run.length } : {}),
}
- for (let i = next.length - 1; i >= 0; i--) {
- stack.push(next[i])
+ rows.push(row)
+ if (node.children.length > 0 && !collapsedSpanIds.has(node.span.span_id)) {
+ pushChildren(node.children, node, depth + 1, row)
}
}
return rows
}
+
+export function rowConnectorLines(row: TraceDialogRow): boolean[] {
+ const lines: boolean[] = []
+ for (let ancestor = row.parentRow; ancestor && ancestor.depth > 0; ancestor = ancestor.parentRow) {
+ lines.push(!ancestor.isLast)
+ }
+ return lines.reverse()
+}