🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(trace): rebuild Timeline as a two-pane waterfall (LFE-10527) (#14572)
Nikita Kabardin4080d4d60d36
diff --git a/web/src/components/trace/components/TraceSearchList.tsx b/web/src/components/trace/components/TraceSearchList.tsxindex 774aebe777..78970355b9 100644--- a/web/src/components/trace/components/TraceSearchList.tsx+++ b/web/src/components/trace/components/TraceSearchList.tsx@@ -11,6 +11,7 @@ import { useTraceData } from "../contexts/TraceDataContext";import { useSearch } from "../contexts/SearchContext";import { useSelection } from "../contexts/SelectionContext";import { useHandlePrefetchObservation } from "../hooks/useHandlePrefetchObservation";+import { useDesktopLayoutContextOptional } from "./_layout/TraceLayoutDesktop";import { VirtualizedList } from "./_shared/VirtualizedList";import { TraceSearchListItem } from "./TraceSearchListItem";import { Button } from "@/src/components/ui/button";@@ -21,6 +22,13 @@ export function TraceSearchList() {const { searchQuery, setSearchInputValue } = useSearch();const { selectedNodeId, setSelectedNodeId } = useSelection();const { handleHover } = useHandlePrefetchObservation();+ // Optional (null on mobile): reopen the detail panel on select, including+ // re-selecting the already-selected result.+ const layout = useDesktopLayoutContextOptional();+ const handleSelectItem = (id: string | null) => {+ setSelectedNodeId(id);+ layout?.expandDetailPanel();+ };// Co-located filtering - only this component re-renders on search query changeconst searchResults = useMemo(() => {@@ -63,7 +71,7 @@ export function TraceSearchList() {<VirtualizedListitems={searchResults}selectedItemId={selectedNodeId}- onSelectItem={setSelectedNodeId}+ onSelectItem={handleSelectItem}getItemId={(item) => item.node.id}estimatedItemSize={48}overscan={500}diff --git a/web/src/components/trace/components/TraceSettingsDropdown.tsx b/web/src/components/trace/components/TraceSettingsDropdown.tsxindex 5a1f17e299..bd0fedc4b0 100644--- a/web/src/components/trace/components/TraceSettingsDropdown.tsx+++ b/web/src/components/trace/components/TraceSettingsDropdown.tsx@@ -21,7 +21,6 @@ import {DropdownMenuContent,DropdownMenuItem,DropdownMenuTrigger,- DropdownMenuSeparator,DropdownMenuSub,DropdownMenuSubTrigger,DropdownMenuSubContent,@@ -38,6 +37,38 @@ export interface TraceSettingsDropdownProps {export function TraceSettingsDropdown({isGraphViewAvailable,+}: TraceSettingsDropdownProps) {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ title="View Options"+ className="h-7 w-7"+ >+ <Settings2 className="h-3.5 w-3.5" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="center"+ className="w-64 space-y-0 space-x-0 p-0 px-0"+ >+ <TraceViewOptionsMenuItems+ isGraphViewAvailable={isGraphViewAvailable}+ />+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++/**+ * The view-option menu items (toggles + min-level submenu) without the+ * dropdown shell, so they can be reused inside the navigation header's overflow+ * "⋯" menu when the panel is too narrow for inline toolbar icons.+ */+export function TraceViewOptionsMenuItems({+ isGraphViewAvailable,}: TraceSettingsDropdownProps) {const capture = usePostHogClientCapture();@@ -63,172 +94,154 @@ export function TraceSettingsDropdown({const isColorCodeEnabled = showDuration || showCostTokens;return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- variant="ghost"- size="icon"- title="View Options"- className="h-7 w-7"- >- <Settings2 className="h-3.5 w-3.5" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent- align="end"- className="w-64 space-y-0 space-x-0 p-0 px-0"- >- <DropdownMenuLabel>View Options</DropdownMenuLabel>- <DropdownMenuSeparator />-- <div className="space-y-0 p-0 py-1">- {/* Show Graph Toggle (only when available) */}- {isGraphViewAvailable && (- <DropdownMenuItem- asChild- onSelect={(e) => e.preventDefault()}- className="space-y-0 px-2 py-1"- >- <div className="flex w-full items-center justify-between">- <span className="mr-2">Show Graph</span>- <Switch- size="sm"- checked={showGraph}- onCheckedChange={setShowGraph}- />- </div>- </DropdownMenuItem>- )}-- {/* Show Comments Toggle */}+ <>+ <div className="space-y-0 p-0 py-1">+ {/* Show Graph Toggle (only when available) */}+ {isGraphViewAvailable && (<DropdownMenuItemasChildonSelect={(e) => e.preventDefault()}- className="px-2 py-1"+ className="space-y-0 px-2 py-1"><div className="flex w-full items-center justify-between">- <span className="mr-2">Show Comments</span>+ <span className="mr-2">Show Graph</span><Switchsize="sm"- checked={showComments}- onCheckedChange={setShowComments}+ checked={showGraph}+ onCheckedChange={setShowGraph}/></div></DropdownMenuItem>+ )}- {/* Show Scores Toggle */}- <DropdownMenuItem- asChild- onSelect={(e) => e.preventDefault()}- className="px-2 py-1"- >- <div className="flex w-full items-center justify-between">- <span className="mr-2">Show Scores</span>- <Switch- size="sm"- checked={showScores}- onCheckedChange={(checked) => {- capture("trace_detail:observation_tree_toggle_scores", {- show: checked,- });- setShowScores(checked);- }}- />- </div>- </DropdownMenuItem>+ {/* Show Comments Toggle */}+ <DropdownMenuItem+ asChild+ onSelect={(e) => e.preventDefault()}+ className="px-2 py-1"+ >+ <div className="flex w-full items-center justify-between">+ <span className="mr-2">Show Comments</span>+ <Switch+ size="sm"+ checked={showComments}+ onCheckedChange={setShowComments}+ />+ </div>+ </DropdownMenuItem>- {/* Show Duration Toggle */}- <DropdownMenuItem- asChild- onSelect={(e) => e.preventDefault()}- className="px-2 py-1"- >- <div className="flex w-full items-center justify-between">- <span className="mr-2">Show Duration</span>- <Switch- size="sm"- checked={showDuration}- onCheckedChange={setShowDuration}- />- </div>- </DropdownMenuItem>+ {/* Show Scores Toggle */}+ <DropdownMenuItem+ asChild+ onSelect={(e) => e.preventDefault()}+ className="px-2 py-1"+ >+ <div className="flex w-full items-center justify-between">+ <span className="mr-2">Show Scores</span>+ <Switch+ size="sm"+ checked={showScores}+ onCheckedChange={(checked) => {+ capture("trace_detail:observation_tree_toggle_scores", {+ show: checked,+ });+ setShowScores(checked);+ }}+ />+ </div>+ </DropdownMenuItem>- {/* Show Cost/Tokens Toggle */}- <DropdownMenuItem- asChild- onSelect={(e) => e.preventDefault()}- className="px-2 py-1"- >- <div className="flex w-full items-center justify-between">- <span className="mr-2">Show Cost/Tokens</span>- <Switch- size="sm"- checked={showCostTokens}- onCheckedChange={setShowCostTokens}- />- </div>- </DropdownMenuItem>+ {/* Show Duration Toggle */}+ <DropdownMenuItem+ asChild+ onSelect={(e) => e.preventDefault()}+ className="px-2 py-1"+ >+ <div className="flex w-full items-center justify-between">+ <span className="mr-2">Show Duration</span>+ <Switch+ size="sm"+ checked={showDuration}+ onCheckedChange={setShowDuration}+ />+ </div>+ </DropdownMenuItem>- {/* Color Code Metrics Toggle (disabled when no metrics shown) */}- <DropdownMenuItem- asChild- onSelect={(e) => e.preventDefault()}- disabled={!isColorCodeEnabled}- className={cn([- "px-2 py-1",- isColorCodeEnabled ? "" : "cursor-not-allowed",- ])}+ {/* Show Cost/Tokens Toggle */}+ <DropdownMenuItem+ asChild+ onSelect={(e) => e.preventDefault()}+ className="px-2 py-1"+ >+ <div className="flex w-full items-center justify-between">+ <span className="mr-2">Show Cost/Tokens</span>+ <Switch+ size="sm"+ checked={showCostTokens}+ onCheckedChange={setShowCostTokens}+ />+ </div>+ </DropdownMenuItem>++ {/* Color Code Metrics Toggle (disabled when no metrics shown) */}+ <DropdownMenuItem+ asChild+ onSelect={(e) => e.preventDefault()}+ disabled={!isColorCodeEnabled}+ className={cn([+ "px-2 py-1",+ isColorCodeEnabled ? "" : "cursor-not-allowed",+ ])}+ >+ <div+ className={cn(+ "flex w-full items-center justify-between",+ !isColorCodeEnabled && "cursor-not-allowed",+ )}>- <div+ <spanclassName={cn(- "flex w-full items-center justify-between",+ "mr-2",!isColorCodeEnabled && "cursor-not-allowed",)}>- <span- className={cn(- "mr-2",- !isColorCodeEnabled && "cursor-not-allowed",- )}- >- Show Color Code Metrics- </span>- <Switch- size="sm"- checked={colorCodeMetrics}- onCheckedChange={setColorCodeMetrics}- disabled={!isColorCodeEnabled}- className={cn(!isColorCodeEnabled && "cursor-not-allowed")}- />- </div>- </DropdownMenuItem>- </div>-- {/* Minimum Observation Level Submenu */}- <DropdownMenuSub>- <DropdownMenuSubTrigger>- <span className="flex items-center">- Min Level: {minObservationLevel}+ Show Color Code Metrics</span>- </DropdownMenuSubTrigger>- <DropdownMenuSubContent>- <DropdownMenuLabel className="font-semibold">- Minimum Level- </DropdownMenuLabel>- {Object.values(ObservationLevel).map((level) => (- <DropdownMenuItem- key={level}- onSelect={(e) => {- e.preventDefault();- setMinObservationLevel(level);- }}- >- {level}- </DropdownMenuItem>- ))}- </DropdownMenuSubContent>- </DropdownMenuSub>- </DropdownMenuContent>- </DropdownMenu>+ <Switch+ size="sm"+ checked={colorCodeMetrics}+ onCheckedChange={setColorCodeMetrics}+ disabled={!isColorCodeEnabled}+ className={cn(!isColorCodeEnabled && "cursor-not-allowed")}+ />+ </div>+ </DropdownMenuItem>+ </div>++ {/* Minimum Observation Level Submenu */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex items-center">+ Min Level: {minObservationLevel}+ </span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ <DropdownMenuLabel className="font-semibold">+ Minimum Level+ </DropdownMenuLabel>+ {Object.values(ObservationLevel).map((level) => (+ <DropdownMenuItem+ key={level}+ onSelect={(e) => {+ e.preventDefault();+ setMinObservationLevel(level);+ }}+ >+ {level}+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ </>);}diff --git a/web/src/components/trace/components/TraceTimeline/TimelineBar.stories.tsx b/web/src/components/trace/components/TraceTimeline/TimelineBar.stories.tsxnew file mode 100644index 0000000000..1b6a62e488--- /dev/null+++ b/web/src/components/trace/components/TraceTimeline/TimelineBar.stories.tsx@@ -0,0 +1,68 @@+import preview from "../../../../../.storybook/preview";+import { TimelineBar } from "./TimelineBar";+import { makeTreeNode, makeMetrics, cost } from "./timeline.fixtures";++const meta = preview.meta({+ component: TimelineBar,+ args: {+ node: makeTreeNode(),+ metrics: makeMetrics(),+ isSelected: false,+ showDuration: true,+ showCostTokens: false,+ showScores: false,+ showComments: false,+ colorCodeMetrics: false,+ },+ // The bar positions itself absolutely on the time axis; host it in a+ // row-height relative track so its left offset renders in context.+ decorators: [+ (Story) => (+ <div className="bg-background relative h-[42px] w-[640px] rounded border">+ <Story />+ </div>+ ),+ ],+});++export const Default = meta.story({});++export const Selected = meta.story({+ args: { isSelected: true },+});++export const ZeroDuration = meta.story({+ args: {+ node: makeTreeNode({+ endTime: new Date("2024-01-01T00:00:00.000Z"),+ latency: 0,+ }),+ metrics: makeMetrics({ itemWidth: 0, latency: 0 }),+ },+});++export const Streaming = meta.story({+ args: {+ metrics: makeMetrics({+ startOffset: 60,+ itemWidth: 260,+ firstTokenTimeOffset: 150,+ }),+ },+});++export const WithCostAndTokens = meta.story({+ args: {+ showCostTokens: true,+ node: makeTreeNode({+ totalCost: cost(0.0021),+ inputUsage: 320,+ outputUsage: 140,+ totalUsage: 460,+ }),+ },+});++export const WithComments = meta.story({+ args: { showComments: true, commentCount: 3 },+});diff --git a/web/src/components/trace/components/TraceTimeline/TimelineBar.tsx b/web/src/components/trace/components/TraceTimeline/TimelineBar.tsxindex 32543c877d..d0f4a34fc9 100644--- a/web/src/components/trace/components/TraceTimeline/TimelineBar.tsx+++ b/web/src/components/trace/components/TraceTimeline/TimelineBar.tsx@@ -1,11 +1,14 @@/**- * TimelineBar - Renders individual Gantt bar for a node- * Shows duration visually with colored box, displays name, badges, and metrics+ * TimelineBar - Renders the gantt bar for a node on the time track.+ *+ * Pure time-coordinate concern: a colored duration box positioned at the node's+ * start offset, followed by a trailing metric label. Identity (badge, name) and+ * hierarchy (tree connectors) live in the gutter (TimelineGutterRow) — not here — so+ * the bar can sit at its true time position without dragging the tree with it.*/import { type TimelineBarProps } from "./types";import { cn } from "@/src/utils/tailwind";-import { ItemBadge } from "@/src/components/ItemBadge";import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";import { formatIntervalSeconds } from "@/src/utils/dates";@@ -19,12 +22,14 @@ import { isPresent } from "@langfuse/shared";const SUBTREE_DURATION_TITLE ="Subtree wall-clock duration (first start → last end)";+// Keep zero/near-zero-duration spans visible as a small marker.+const MIN_BAR_WIDTH = 4;+export function TimelineBar({node,metrics,isSelected,- onSelect,- onHover,+ isHovered,showDuration,showCostTokens,showScores,@@ -37,12 +42,11 @@ export function TimelineBar({}: TimelineBarProps) {const { startOffset, itemWidth, firstTokenTimeOffset, latency } = metrics;const duration = latency ? latency * 1000 : undefined;- const hasChildren = node.children.length > 0;- // Wall-clock duration of the whole subtree, surfaced only when async- // descendants outlive this node's own span (LFE-10475). Own-span basis- // mirrors SpanContent: fall back to node.latency when there's no endTime- // (e.g. the synthetic v4 trace-root span) so the tree and timeline agree.+ // Own-span basis mirrors SpanContent: fall back to node.latency when there's+ // no endTime (e.g. the synthetic v4 trace-root span) so tree and timeline+ // agree. Wall-clock subtree duration is surfaced only when async descendants+ // outlive this node's own span (LFE-10475).const ownDurationMs =duration ?? (node.latency ? node.latency * 1000 : undefined);const subtreeWallClockOverflowMs = showDuration@@ -52,182 +56,113 @@ export function TimelineBar({): null;- // Render split bar for streaming LLMs (first token time)+ // Ring driven by shared row state (not group-hover) so it lights up whether+ // the chart bar or the caption is hovered.+ const ringClass = isSelected+ ? "ring-primary-accent ring-2"+ : isHovered+ ? "ring-tertiary ring-2"+ : "";++ // Trailing label: rides just after the bar so metrics stay readable no matter+ // how thin the bar is. Respects the same view toggles as the tree.+ const label = (+ <div className="text-muted-foreground flex items-center gap-2 text-xs whitespace-nowrap">+ {showComments && commentCount ? (+ <CommentCountIcon count={commentCount} />+ ) : null}+ {showDuration && isPresent(ownDurationMs) && (+ <span+ className={cn(+ parentTotalDuration &&+ colorCodeMetrics &&+ heatMapTextColor({+ max: parentTotalDuration,+ value: ownDurationMs,+ }),+ )}+ >+ {formatIntervalSeconds(ownDurationMs / 1000)}+ </span>+ )}+ {isPresent(ownDurationMs) && subtreeWallClockOverflowMs != null && (+ <span title={SUBTREE_DURATION_TITLE}>+ {"∑ "}+ {formatIntervalSeconds(subtreeWallClockOverflowMs / 1000)}+ </span>+ )}+ {showCostTokens && node.totalCost && (+ <span+ className={cn(+ parentTotalCost &&+ colorCodeMetrics &&+ heatMapTextColor({+ max: parentTotalCost,+ value: node.totalCost,+ }),+ )}+ >+ {usdFormatter(node.totalCost.toNumber())}+ </span>+ )}+ {showScores && scores && scores.length > 0 && (+ <div className="flex max-h-5 gap-1">+ <GroupedScoreBadges scores={scores} maxVisible={3} />+ </div>+ )}+ </div>+ );++ // Split bar for streaming LLMs (first token time): waiting segment + completion.if (firstTokenTimeOffset) {- const firstTokenWidth = firstTokenTimeOffset - startOffset;- const completionWidth = itemWidth - firstTokenWidth;+ const firstTokenWidth = Math.max(firstTokenTimeOffset - startOffset, 0);+ const completionWidth = Math.max(+ itemWidth - firstTokenWidth,+ MIN_BAR_WIDTH,+ );return (<div- className="group my-0.5 flex w-full min-w-fit cursor-pointer flex-row items-center"- onClick={onSelect}- onMouseEnter={onHover}+ className="absolute top-1/2 flex -translate-y-1/2 items-center gap-2"+ style={{ left: `${startOffset}px` }}><divclassName={cn(- "border-border flex rounded-sm border",- isSelected- ? "ring-primary-accent ring-3"- : "group-hover:ring-tertiary group-hover:ring-3",+ "border-border flex h-5 overflow-hidden rounded-sm border",+ // Dashed when in-flight (no width yet), matching the non-streaming bar.+ itemWidth ? "" : "border-dashed",+ ringClass,)}- style={{ marginLeft: `${startOffset}px` }}>- {/* First token time bar (waiting period) */}<div- className={cn(- "bg-muted flex h-8 items-center justify-start rounded-l-sm border-r border-gray-400 opacity-60",- itemWidth ? "" : "border border-dashed",- )}+ className="bg-muted h-full border-r border-gray-400 opacity-60"style={{ width: `${firstTokenWidth}px` }}+ title="Time to first token"/>-- {/* Completion time bar */}<div- className={cn(- "bg-muted flex h-8 items-center justify-start rounded-r-sm",- itemWidth ? "" : "border border-dashed",- )}+ className="bg-muted h-full"style={{ width: `${completionWidth}px` }}- >- <div className="text-muted-foreground -ml-8 flex flex-row items-center justify-start gap-2 text-xs">- <span className="text-primary">First token</span>- <ItemBadge type={node.type} isSmall />- <span className="text-primary text-sm font-medium whitespace-nowrap">- {node.name}- </span>- {showComments && commentCount ? (- <CommentCountIcon count={commentCount} />- ) : null}- {showDuration && isPresent(ownDurationMs) && (- <span- className={cn(- "text-muted-foreground text-xs",- parentTotalDuration &&- colorCodeMetrics &&- heatMapTextColor({- max: parentTotalDuration,- value: ownDurationMs,- }),- )}- >- {formatIntervalSeconds(ownDurationMs / 1000)}- </span>- )}- {isPresent(ownDurationMs) &&- subtreeWallClockOverflowMs != null && (- <span- title={SUBTREE_DURATION_TITLE}- className="text-muted-foreground text-xs whitespace-nowrap"- >- {"∑ "}- {formatIntervalSeconds(subtreeWallClockOverflowMs / 1000)}- </span>- )}- {showCostTokens && node.totalCost && (- <span- className={cn(- "text-muted-foreground text-xs",- parentTotalCost &&- colorCodeMetrics &&- heatMapTextColor({- max: parentTotalCost,- value: node.totalCost,- }),- )}- >- {usdFormatter(node.totalCost.toNumber())}- </span>- )}- {showScores && scores && scores.length > 0 && (- <div className="flex max-h-8 gap-1">- <GroupedScoreBadges scores={scores} maxVisible={3} />- </div>- )}- </div>- </div>+ /></div>+ {label}</div>);}- // Regular bar (no first token time)return (<div- className="group my-0.5 flex w-full min-w-fit cursor-pointer flex-row items-center"- onClick={onSelect}- onMouseEnter={onHover}+ className="absolute top-1/2 flex -translate-y-1/2 items-center gap-2"+ style={{ left: `${startOffset}px` }}>- <div className="relative" style={{ marginLeft: `${startOffset}px` }}>- <div- className={cn(- "border-border bg-muted flex h-8 items-center justify-start rounded-sm border",- itemWidth ? "" : "border-dashed",- isSelected- ? "ring-primary-accent ring-3"- : "group-hover:ring-tertiary group-hover:ring-3",- )}- style={{ width: `${itemWidth || 10}px` }}- >- <div- className={cn(- "text-muted-foreground flex flex-row items-center justify-start gap-2 text-xs",- hasChildren ? "ml-6" : "ml-1",- )}- >- <ItemBadge type={node.type} isSmall />- <span className="text-primary text-sm font-medium whitespace-nowrap">- {node.name}- </span>- {showComments && commentCount ? (- <CommentCountIcon count={commentCount} />- ) : null}- {showDuration && isPresent(ownDurationMs) && (- <span- className={cn(- "text-muted-foreground text-xs",- parentTotalDuration &&- colorCodeMetrics &&- heatMapTextColor({- max: parentTotalDuration,- value: ownDurationMs,- }),- )}- >- {formatIntervalSeconds(ownDurationMs / 1000)}- </span>- )}- {isPresent(ownDurationMs) && subtreeWallClockOverflowMs != null && (- <span- title={SUBTREE_DURATION_TITLE}- className="text-muted-foreground text-xs whitespace-nowrap"- >- {"∑ "}- {formatIntervalSeconds(subtreeWallClockOverflowMs / 1000)}- </span>- )}- {showCostTokens && node.totalCost && (- <span- className={cn(- "text-muted-foreground text-xs",- parentTotalCost &&- colorCodeMetrics &&- heatMapTextColor({- max: parentTotalCost,- value: node.totalCost,- }),- )}- >- {usdFormatter(node.totalCost.toNumber())}- </span>- )}- {showScores && scores && scores.length > 0 && (- <div className="flex max-h-8 gap-1">- <GroupedScoreBadges scores={scores} maxVisible={3} />- </div>- )}- </div>- </div>- </div>+ <div+ className={cn(+ "border-border bg-muted h-5 rounded-sm border",+ itemWidth ? "" : "border-dashed",+ ringClass,+ )}+ style={{ width: `${Math.max(itemWidth, MIN_BAR_WIDTH)}px` }}+ />+ {label}</div>);}diff --git a/web/src/components/trace/components/TraceTimeline/TimelineGutterRow.stories.tsx b/web/src/components/trace/components/TraceTimeline/TimelineGutterRow.stories.tsxnew file mode 100644index 0000000000..ce7937e611--- /dev/null+++ b/web/src/components/trace/components/TraceTimeline/TimelineGutterRow.stories.tsx@@ -0,0 +1,227 @@+import { fn } from "storybook/test";+import preview from "../../../../../.storybook/preview";+import { TimelineGutterRow } from "./TimelineGutterRow";+import { flattenTreeWithTimelineMetrics } from "./timeline-flattening";+import { makeItem, makeTreeNode } from "./timeline.fixtures";++const ROW_BOX =+ "bg-background relative h-[42px] w-[320px] overflow-hidden rounded border";+const PANEL_BOX = "bg-background w-[320px] overflow-hidden rounded border";++// fn() gives Storybook actions; cast to the prop type so meta args and the+// per-story decorators agree (story-level decorators are typed against the+// component props, not the Mock-widened meta args).+const meta = preview.meta({+ component: TimelineGutterRow,+ args: {+ item: makeItem({+ depth: 1,+ treeLines: [false],+ isLastSibling: true,+ node: makeTreeNode({ name: "compose-context-window", type: "SPAN" }),+ }),+ isSelected: false,+ onSelect: fn() as () => void,+ onHover: fn() as () => void,+ onToggleCollapse: fn() as () => void,+ hasChildren: false,+ isCollapsed: false,+ },+});++export const Default = meta.story({+ decorators: [+ (Story) => (+ <div className={ROW_BOX}>+ <Story />+ </div>+ ),+ ],+});++export const RootWithChildren = meta.story({+ args: {+ item: makeItem({+ depth: 0,+ treeLines: [],+ isLastSibling: true,+ node: makeTreeNode({ name: "orchestrator-agent", type: "AGENT" }),+ }),+ hasChildren: true,+ },+ decorators: [+ (Story) => (+ <div className={ROW_BOX}>+ <Story />+ </div>+ ),+ ],+});++export const NestedWithSiblingBelow = meta.story({+ args: {+ item: makeItem({+ depth: 2,+ treeLines: [true, true],+ isLastSibling: false,+ node: makeTreeNode({ name: "rerank-candidate-passages", type: "SPAN" }),+ }),+ hasChildren: true,+ },+ decorators: [+ (Story) => (+ <div className={ROW_BOX}>+ <Story />+ </div>+ ),+ ],+});++export const NestedLastChild = meta.story({+ args: {+ item: makeItem({+ depth: 2,+ treeLines: [true, false],+ isLastSibling: true,+ node: makeTreeNode({ name: "vector-search-shard-3", type: "SPAN" }),+ }),+ },+ decorators: [+ (Story) => (+ <div className={ROW_BOX}>+ <Story />+ </div>+ ),+ ],+});++export const Selected = meta.story({+ args: { isSelected: true },+ decorators: [+ (Story) => (+ <div className={ROW_BOX}>+ <Story />+ </div>+ ),+ ],+});++export const Collapsed = meta.story({+ args: {+ item: makeItem({+ depth: 1,+ treeLines: [false],+ isLastSibling: true,+ node: makeTreeNode({ name: "retrieve-relevant-documents", type: "SPAN" }),+ }),+ hasChildren: true,+ isCollapsed: true,+ },+ decorators: [+ (Story) => (+ <div className={ROW_BOX}>+ <Story />+ </div>+ ),+ ],+});++// Design showcase: a stacked mini-tree from the real flattening logic, so the+// connectors connect parent→child across rows exactly as in the app.+export const TreeShowcase = meta.story({+ decorators: [+ (Story) => (+ <div className={PANEL_BOX}>+ <Story />+ </div>+ ),+ ],+ render: (args) => {+ const t = (ms: number) =>+ new Date(Date.parse("2024-01-01T00:00:00.000Z") + ms);+ const tree = makeTreeNode({+ id: "orch",+ name: "orchestrator-agent",+ type: "AGENT",+ startTime: t(0),+ endTime: t(8000),+ latency: 8,+ children: [+ makeTreeNode({+ id: "retr",+ name: "retrieve-relevant-documents",+ type: "SPAN",+ startTime: t(200),+ endTime: t(6000),+ children: [+ makeTreeNode({+ id: "rerank",+ name: "rerank-candidate-passages",+ type: "SPAN",+ startTime: t(500),+ endTime: t(5500),+ children: [+ makeTreeNode({+ id: "compose",+ name: "compose-context-window",+ type: "SPAN",+ startTime: t(1000),+ endTime: t(5000),+ children: [+ makeTreeNode({+ id: "llm",+ name: "call-large-language-model",+ type: "GENERATION",+ startTime: t(1200),+ endTime: t(4800),+ }),+ ],+ }),+ ],+ }),+ ],+ }),+ makeTreeNode({+ id: "e0",+ name: "vector-search-shard-0",+ type: "SPAN",+ startTime: t(6000),+ endTime: t(6900),+ }),+ makeTreeNode({+ id: "e1",+ name: "vector-search-shard-1",+ type: "SPAN",+ startTime: t(6900),+ endTime: t(7800),+ }),+ ],+ });++ const items = flattenTreeWithTimelineMetrics(+ [tree],+ new Set(),+ tree.startTime,+ 8,+ 900,+ );++ return (+ <>+ {items.map((item) => (+ <div key={item.node.id} className="h-[42px]">+ <TimelineGutterRow+ item={item}+ isSelected={false}+ onSelect={args.onSelect}+ onHover={args.onHover}+ onToggleCollapse={args.onToggleCollapse}+ hasChildren={item.node.children.length > 0}+ isCollapsed={false}+ />+ </div>+ ))}+ </>+ );+ },+});diff --git a/web/src/components/trace/components/TraceTimeline/TimelineGutterRow.tsx b/web/src/components/trace/components/TraceTimeline/TimelineGutterRow.tsxnew file mode 100644index 0000000000..7b241338ed--- /dev/null+++ b/web/src/components/trace/components/TraceTimeline/TimelineGutterRow.tsx@@ -0,0 +1,141 @@+/**+ * TimelineGutterRow - the left, fixed gutter cell for one waterfall row.+ *+ * Pure depth coordinate: tree connectors + icon + name. It lives in the gutter+ * pane (which never scrolls horizontally), so hover/selection highlighting is+ * scoped to this narrow cell — the wide chart never gets a full-width band.+ *+ * Connectors are absolute lines at computed rail x's. Each parent→child line is+ * two segments (parent draws center→bottom, child draws top→center) meeting at+ * the shared row boundary, so the line is continuous at every depth. The rail+ * sits a gap to the LEFT of the icon (it never crosses it), and the elbow stops+ * at the icon.+ */++import { type TimelineGutterRowProps } from "./types";+import { ItemBadge } from "@/src/components/ItemBadge";+import { ChevronRight } from "lucide-react";+import { cn } from "@/src/utils/tailwind";++const INDENT = 14; // px per depth level+const RAIL = 7; // x of a level's vertical rail within its indent step+const ICON_GAP = 6; // gap from a node's rail to its icon++export function TimelineGutterRow({+ item,+ isSelected,+ isHovered,+ onSelect,+ onHover,+ onToggleCollapse,+ hasChildren,+ isCollapsed,+}: TimelineGutterRowProps) {+ const { node, depth, treeLines, isLastSibling } = item;++ const ownRailX = depth * INDENT + RAIL;+ const parentRailX = (depth - 1) * INDENT + RAIL;+ const showsChildSpine = hasChildren && !isCollapsed;+ const contentLeft = ownRailX + ICON_GAP;++ return (+ <div+ className={cn(+ "relative flex h-full w-full cursor-pointer items-center pr-2",+ // Whole-row highlight is driven by shared state (so hovering the chart+ // highlights the caption too). Selected uses an accent tint so it stays+ // distinct from the neutral bar (bg-muted) — otherwise the bar vanishes+ // into the selected row; hover stays neutral.+ isSelected ? "bg-primary-accent/10" : isHovered ? "bg-muted" : "",+ )}+ onClick={onSelect}+ onMouseEnter={onHover}+ >+ {/* Selected accent bar (no layout shift). */}+ {isSelected && (+ <div className="bg-primary-accent absolute inset-y-0 left-0 w-0.5" />+ )}+ {/* Ancestor rails: continue through this row for ancestors with a sibling below. */}+ {treeLines+ .slice(0, Math.max(0, depth - 1))+ .map((continues, level) =>+ continues ? (+ <div+ key={level}+ className="bg-border absolute inset-y-0 w-px"+ style={{ left: `${level * INDENT + RAIL}px` }}+ />+ ) : null,+ )}++ {depth > 0 && (+ <>+ {/* This node's vertical off the parent rail: top→center (last) or full. */}+ <div+ className={cn(+ "bg-border absolute top-0 w-px",+ isLastSibling ? "h-1/2" : "bottom-0",+ )}+ style={{ left: `${parentRailX}px` }}+ />+ {/* Elbow: parent rail → icon, at the row's vertical center. */}+ <div+ className="bg-border absolute top-1/2 h-px"+ style={{+ left: `${parentRailX}px`,+ width: `${INDENT + ICON_GAP}px`,+ }}+ />+ </>+ )}++ {/* Downward stub to this node's children, on its own rail (left of the icon). */}+ {showsChildSpine && (+ <div+ className="bg-border absolute top-1/2 bottom-0 w-px"+ style={{ left: `${ownRailX}px` }}+ />+ )}++ {/* Icon + name. The icon is offset to a node's rail; the rail sits a gap+ to its left so it never crosses the chip. */}+ <div+ className="flex min-w-0 flex-1 items-center gap-2"+ style={{ paddingLeft: `${contentLeft}px` }}+ >+ {/* Wrap to keep the badge from flex-shrinking (ItemBadge's className+ only reaches the inner icon, not the Badge wrapper). */}+ <div className="shrink-0">+ <ItemBadge type={node.type} isSmall />+ </div>+ <span+ className="text-primary min-w-0 flex-1 truncate text-xs font-medium"+ title={node.name}+ >+ {node.name || `Unnamed ${node.type.toLowerCase()}`}+ </span>+ </div>++ {/* Expand/collapse caret, pinned right (as in the tree view). */}+ {hasChildren && (+ <button+ type="button"+ aria-label={isCollapsed ? "Expand" : "Collapse"}+ aria-expanded={!isCollapsed}+ onClick={(e) => {+ e.stopPropagation();+ onToggleCollapse();+ }}+ className="hover:bg-muted-foreground/10 ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded"+ >+ <ChevronRight+ className={cn(+ "h-4 w-4 transition-transform duration-200",+ !isCollapsed && "rotate-90",+ )}+ />+ </button>+ )}+ </div>+ );+}diff --git a/web/src/components/trace/components/TraceTimeline/TimelineRow.tsx b/web/src/components/trace/components/TraceTimeline/TimelineRow.tsxdeleted file mode 100644index 05d3c77737..0000000000--- a/web/src/components/trace/components/TraceTimeline/TimelineRow.tsx+++ /dev/null@@ -1,112 +0,0 @@-/**- * TimelineRow - Combines tree structure with timeline bar- * Renders tree lines, expand button, and timeline bar positioned horizontally by time- */--import { type TimelineRowProps } from "./types";-import { TimelineBar } from "./TimelineBar";-import { ChevronRight } from "lucide-react";-import { cn } from "@/src/utils/tailwind";--const TREE_INDENTATION = 12; // pixels per depth level--export function TimelineRow({- item,- isSelected,- onSelect,- onHover,- onToggleCollapse,- hasChildren,- isCollapsed,- showDuration,- showCostTokens,- showScores,- showComments,- colorCodeMetrics,- parentTotalCost,- parentTotalDuration,- commentCount,- scores,-}: TimelineRowProps) {- const { node, depth, treeLines, isLastSibling, metrics } = item;-- return (- <div className="group my-0.5 flex w-full min-w-fit cursor-pointer flex-row items-center">- {/* Tree lines for ancestor levels (depth - 1) */}- {depth > 0 && (- <div className="flex shrink-0">- {Array.from({ length: depth - 1 }, (_, i) => (- <div- key={i}- className="relative"- style={{ width: `${TREE_INDENTATION}px` }}- >- {treeLines[i] && (- <div className="bg-border absolute top-0 bottom-0 left-1.5 w-px" />- )}- </div>- ))}- </div>- )}-- {/* Current level tree connector */}- {depth > 0 && (- <div- className="relative shrink-0"- style={{ width: `${TREE_INDENTATION}px` }}- >- {/* Vertical line up */}- <div- className={cn(- "bg-border absolute top-0 left-1.5 w-px",- isLastSibling ? "h-3" : "bottom-0",- )}- />- {/* Horizontal line to content */}- <div className="bg-border absolute top-3 left-1.5 h-px w-2" />- </div>- )}-- {/* Expand/collapse button (if has children) */}- {hasChildren && (- <button- onClick={(e) => {- e.stopPropagation();- onToggleCollapse();- }}- className="hover:bg-muted absolute z-10 rounded"- style={{- left: `${depth * TREE_INDENTATION + (metrics.startOffset > 0 ? metrics.startOffset + 4 : 4)}px`,- top: "50%",- transform: "translateY(-50%)",- }}- >- <ChevronRight- className={cn(- "h-4 w-4 transition-transform duration-200",- !isCollapsed && "rotate-90",- )}- />- </button>- )}-- {/* Timeline bar */}- <TimelineBar- node={node}- metrics={metrics}- isSelected={isSelected}- onSelect={onSelect}- onHover={onHover}- showDuration={showDuration}- showCostTokens={showCostTokens}- showScores={showScores}- showComments={showComments}- colorCodeMetrics={colorCodeMetrics}- parentTotalCost={parentTotalCost}- parentTotalDuration={parentTotalDuration}- commentCount={commentCount}- scores={scores}- />- </div>- );-}diff --git a/web/src/components/trace/components/TraceTimeline/TimelineScale.stories.tsx b/web/src/components/trace/components/TraceTimeline/TimelineScale.stories.tsxnew file mode 100644index 0000000000..caf3a743ca--- /dev/null+++ b/web/src/components/trace/components/TraceTimeline/TimelineScale.stories.tsx@@ -0,0 +1,25 @@+import preview from "../../../../../.storybook/preview";+import { TimelineScale } from "./TimelineScale";++const meta = preview.meta({+ component: TimelineScale,+ args: { traceDuration: 8, scaleWidth: 900, stepSize: 1 },+ // The scale is wider than most viewports; host it in a scrollable box.+ decorators: [+ (Story) => (+ <div className="bg-background w-[700px] overflow-x-auto rounded border p-2">+ <Story />+ </div>+ ),+ ],+});++export const Default = meta.story({});++export const SubSecond = meta.story({+ args: { traceDuration: 0.8, stepSize: 0.1 },+});++export const LongTrace = meta.story({+ args: { traceDuration: 300, stepSize: 50 },+});diff --git a/web/src/components/trace/components/TraceTimeline/TimelineScale.tsx b/web/src/components/trace/components/TraceTimeline/TimelineScale.tsxindex e38f6d4ae9..6a9717c35f 100644--- a/web/src/components/trace/components/TraceTimeline/TimelineScale.tsx+++ b/web/src/components/trace/components/TraceTimeline/TimelineScale.tsx@@ -15,8 +15,10 @@ export function TimelineScale({const numMarkers = Math.ceil(scaleWidth / STEP_SIZE) + 1;return (- <div className="mb-2 ml-2">- <div className="relative mr-2 h-8" style={{ width: `${scaleWidth}px` }}>+ // No left margin: the 0s tick must sit exactly at the track origin so the+ // ticks line up with the bars (which start at startOffset = 0 there).+ <div className="mb-2">+ <div className="relative h-8" style={{ width: `${scaleWidth}px` }}>{Array.from({ length: numMarkers }).map((_, index) => {const timeValue = stepSize * index;diff --git a/web/src/components/trace/components/TraceTimeline/index.tsx b/web/src/components/trace/components/TraceTimeline/index.tsxindex f17a23509e..95945a4633 100644--- a/web/src/components/trace/components/TraceTimeline/index.tsx+++ b/web/src/components/trace/components/TraceTimeline/index.tsx@@ -1,9 +1,18 @@/**- * TraceTimeline - Main timeline view component- * Renders Gantt chart visualization with virtualized rows+ * TraceTimeline - Gantt waterfall: a fixed name-gutter + a scrollable chart.+ *+ * Two panes, side by side, sharing the virtualized rows:+ * - Gutter pane (fixed, resizable): the indented name tree. Never scrolls+ * horizontally; its vertical scroll is mirrored from the chart.+ * - Chart pane (flex-1): the gantt bars. Owns the only horizontal scrollbar+ * (and the vertical one). It is the virtualizer's scroll element.+ *+ * The time scale sits in an overflow-hidden header strip whose inner is+ * transform-synced to the chart's horizontal scroll, so the scale stays aligned+ * with the bars without a scrollbar of its own.*/-import { useMemo, useRef, useLayoutEffect } from "react";+import { useCallback, useMemo, useRef, useState, useLayoutEffect } from "react";import { useVirtualizer } from "@tanstack/react-virtual";import { useTraceData } from "../../contexts/TraceDataContext";import { useSelection } from "../../contexts/SelectionContext";@@ -17,7 +26,16 @@ import {SCALE_WIDTH,} from "./timeline-calculations";import { TimelineScale } from "./TimelineScale";-import { TimelineRow } from "./TimelineRow";+import { TimelineGutterRow } from "./TimelineGutterRow";+import { TimelineBar } from "./TimelineBar";+import { useDesktopLayoutContextOptional } from "../_layout/TraceLayoutDesktop";+import { cn } from "@/src/utils/tailwind";++// Width of the left name gutter. Resizable; these bound it.+const GUTTER_WIDTH_DEFAULT = 240;+const GUTTER_WIDTH_MIN = 160;+const GUTTER_WIDTH_MAX = 560;+const ROW_HEIGHT = 42;export function TraceTimeline() {const { roots, serverScores: scores, comments } = useTraceData();@@ -31,36 +49,61 @@ export function TraceTimeline() {colorCodeMetrics,} = useViewPreferences();const { handleHover } = useHandlePrefetchObservation();+ // Optional (null in the mobile layout): reopen the detail panel on select.+ const layout = useDesktopLayoutContextOptional();++ const gutterRef = useRef<HTMLDivElement>(null);+ const chartRef = useRef<HTMLDivElement>(null);+ const scaleInnerRef = useRef<HTMLDivElement>(null);++ // Hovered row, lifted to shared state so hovering either pane highlights the+ // whole row (caption + chart), which CSS :hover can't do across two panes.+ const [hoveredNodeId, setHoveredNodeId] = useState<string | null>(null);- const timeIndexRef = useRef<HTMLDivElement>(null);- const contentRef = useRef<HTMLDivElement>(null);+ // Resizable name gutter so users can trade name space for chart space.+ const [gutterWidth, setGutterWidth] = useState(GUTTER_WIDTH_DEFAULT);+ const startGutterResize = useCallback(+ (e: React.PointerEvent) => {+ e.preventDefault();+ const startX = e.clientX;+ const startWidth = gutterWidth;+ const onMove = (ev: PointerEvent) => {+ const next = startWidth + (ev.clientX - startX);+ setGutterWidth(+ Math.min(GUTTER_WIDTH_MAX, Math.max(GUTTER_WIDTH_MIN, next)),+ );+ };+ const onUp = () => {+ window.removeEventListener("pointermove", onMove);+ window.removeEventListener("pointerup", onUp);+ window.removeEventListener("pointercancel", onUp);+ };+ window.addEventListener("pointermove", onMove);+ window.addEventListener("pointerup", onUp);+ // pointercancel (OS gesture, contextmenu, touch interruption) must also+ // tear down the move listener, else the gutter ghost-resizes afterwards.+ window.addEventListener("pointercancel", onUp);+ },+ [gutterWidth],+ );// Timeline origin (the 0s mark): the earliest start time across the WHOLE- // tree, not just the roots. A child can start before its root (the TRACE- // wrapper's start is the trace timestamp, which may be later than the first- // observation), so anchoring to roots alone misplaces the origin past early- // children. See findEarliestStartTime.+ // tree, not just the roots. See findEarliestStartTime.const traceStartTime = useMemo(() => {return findEarliestStartTime(roots) ?? new Date();}, [roots]);// TODO: Extract aggregation logic to shared utility - duplicated in tree-building.ts and TraceTree.tsx- // Total span of the scale, in seconds, measured from the timeline origin- // (earliest start) to the latest end across the tree, so every bar fits- // within the scale even when the origin sits before a root's start. The- // latency fallback (for traces without end times) is anchored to the origin,- // so a root that starts after an earlier child still fits. See+ // Total span of the scale, in seconds, from origin to latest end. See// calculateTraceDuration.const traceDuration = useMemo(() => {return calculateTraceDuration(roots, traceStartTime);}, [roots, traceStartTime]);- // Calculate step size for time axisconst stepSize = useMemo(() => {return calculateStepSize(traceDuration, SCALE_WIDTH);}, [traceDuration]);- // Flatten tree with pre-computed timeline metricsconst flattenedItems = useMemo(() => {return flattenTreeWithTimelineMetrics(roots,@@ -71,8 +114,9 @@ export function TraceTimeline() {);}, [roots, collapsedNodes, traceStartTime, traceDuration]);- // Calculate content width (max offset + max width)- const contentWidth = useMemo(() => {+ // Width of the chart content (gantt area). Padding leaves room for the+ // trailing metric label that rides after each bar.+ const chartContentWidth = useMemo(() => {if (flattenedItems.length === 0) return SCALE_WIDTH;const maxEnd = Math.max(@@ -81,18 +125,18 @@ export function TraceTimeline() {),);- return Math.max(SCALE_WIDTH, maxEnd + 50); // Add padding+ return Math.max(SCALE_WIDTH, maxEnd + 300);}, [flattenedItems]);- // Set up virtualizer for rows+ // Virtualizer drives off the chart pane; the gutter mirrors its vertical scroll.const rowVirtualizer = useVirtualizer({count: flattenedItems.length,- getScrollElement: () => contentRef.current,- estimateSize: () => 42, // Row height in pixels- overscan: 500, // Large overscan for smooth scrolling with complex items+ getScrollElement: () => chartRef.current,+ estimateSize: () => ROW_HEIGHT,+ overscan: 500,});- // Auto-scroll to selected node on initial load (URL-based navigation only)+ // Auto-scroll to selected node on initial load (URL-based navigation only).const initialNodeIdRef = useRef(selectedNodeId);const hasScrolledRef = useRef(false);@@ -107,9 +151,6 @@ export function TraceTimeline() {);if (index !== -1) {- // Use behavior: "auto" for instant scroll on initial load to prevent- // visible scroll animation after page render. The synchronous scroll- // completes within useLayoutEffect, before browser paint.rowVirtualizer.scrollToIndex(index, {align: "center",behavior: "auto",@@ -119,116 +160,228 @@ export function TraceTimeline() {}}, [selectedNodeId, flattenedItems, rowVirtualizer]);- // Scroll sync handlers- const handleTimeIndexScroll = (e: React.UIEvent<HTMLDivElement>) => {- if (contentRef.current) {- contentRef.current.scrollLeft = e.currentTarget.scrollLeft;+ // Vertical scroll sync (chart ⇄ gutter) + horizontal sync (chart → scale).+ // Guard with !== so mirroring doesn't loop (setting an equal value is a no-op).+ const handleChartScroll = useCallback(() => {+ const chart = chartRef.current;+ if (!chart) return;+ if (gutterRef.current && gutterRef.current.scrollTop !== chart.scrollTop) {+ gutterRef.current.scrollTop = chart.scrollTop;}- };+ if (scaleInnerRef.current) {+ scaleInnerRef.current.style.transform = `translateX(${-chart.scrollLeft}px)`;+ }+ }, []);- const handleContentScroll = (e: React.UIEvent<HTMLDivElement>) => {- if (timeIndexRef.current) {- timeIndexRef.current.scrollLeft = e.currentTarget.scrollLeft;+ const handleGutterScroll = useCallback(() => {+ const gutter = gutterRef.current;+ if (!gutter) return;+ if (chartRef.current && chartRef.current.scrollTop !== gutter.scrollTop) {+ chartRef.current.scrollTop = gutter.scrollTop;}- };+ }, []);- // Get parent totals for heatmap coloring (aggregate across all roots)+ // Parent totals for heatmap coloring (aggregate across all roots).const parentTotalCost = useMemo(() => {return roots.reduce((acc, r) => {if (!r.totalCost) return acc;return acc ? acc.plus(r.totalCost) : r.totalCost;},- // TODO: make it niceundefined as (typeof roots)[0]["totalCost"],);}, [roots]);const parentTotalDuration = traceDuration;- return (- <div className="flex h-full w-full flex-col overflow-hidden">- {/* Sticky time scale header */}+ const totalSize = rowVirtualizer.getTotalSize();+ const virtualItems = rowVirtualizer.getVirtualItems();++ // Classic scrollbars (Windows/Linux) on the chart pane consume client area+ // the gutter/scale don't: its horizontal scrollbar eats ~15px of height, its+ // vertical scrollbar ~15px of width. We reserve the matching amount on the+ // gutter (bottom) and the scale strip (right) so the three panes share the+ // same scrollable extent — otherwise mirrored scroll clamps at the bottom and+ // a right-edge tick floats over the chart's scrollbar. Both are 0 with macOS+ // overlay bars.+ const [chartScrollbar, setChartScrollbar] = useState({ x: 0, y: 0 });+ useLayoutEffect(() => {+ const el = chartRef.current;+ if (!el) return;+ const measure = () =>+ setChartScrollbar({+ x: el.offsetWidth - el.clientWidth,+ y: el.offsetHeight - el.clientHeight,+ });+ measure();+ const ro = new ResizeObserver(measure);+ ro.observe(el);+ return () => ro.disconnect();+ }, [chartContentWidth, totalSize, gutterWidth]);++ const renderRow = (+ virtualRow: (typeof virtualItems)[number],+ pane: "gutter" | "chart",+ ) => {+ const item = flattenedItems[virtualRow.index];+ if (!item) return null;++ const nodeId = item.node.id;+ const isSelected = selectedNodeId === nodeId;+ const isHovered = hoveredNodeId === nodeId;+ const hasChildren = item.node.children.length > 0;+ const isCollapsed = collapsedNodes.has(nodeId);++ const onEnter = () => {+ setHoveredNodeId(nodeId);+ handleHover(item.node);+ };+ // Reopen the detail panel on any select — including re-clicking the+ // already-selected row, where the URL param (and the effect) wouldn't fire.+ const onSelectNode = () => {+ setSelectedNodeId(nodeId);+ layout?.expandDetailPanel();+ };++ const baseStyle = {+ position: "absolute" as const,+ top: 0,+ left: 0,+ height: `${virtualRow.size}px`,+ transform: `translateY(${virtualRow.start}px)`,+ };++ if (pane === "gutter") {+ return (+ <div key={nodeId} style={{ ...baseStyle, width: "100%" }}>+ <TimelineGutterRow+ item={item}+ isSelected={isSelected}+ isHovered={isHovered}+ onSelect={onSelectNode}+ onHover={onEnter}+ onToggleCollapse={() => toggleCollapsed(nodeId)}+ hasChildren={hasChildren}+ isCollapsed={isCollapsed}+ />+ </div>+ );+ }++ const nodeScores = scores.filter((score) =>+ item.node.type === "TRACE"+ ? score.traceId === item.node.id+ : score.observationId === item.node.id,+ );+ const commentCount = comments.get(nodeId) ?? 0;++ return (<div- ref={timeIndexRef}- className="overflow-x-auto overflow-y-hidden"- onScroll={handleTimeIndexScroll}+ key={nodeId}+ style={{ ...baseStyle, width: `${chartContentWidth}px` }}+ className={cn(+ "cursor-pointer",+ // Selected = accent tint so the neutral bar (bg-muted) stays visible+ // against the row; hover stays neutral.+ isSelected ? "bg-primary-accent/10" : isHovered ? "bg-muted" : "",+ )}+ onClick={onSelectNode}+ onMouseEnter={onEnter}>- <div style={{ width: `${contentWidth}px` }}>- <TimelineScale- traceDuration={traceDuration}- scaleWidth={SCALE_WIDTH}- stepSize={stepSize}- />+ <TimelineBar+ node={item.node}+ metrics={item.metrics}+ isSelected={isSelected}+ isHovered={isHovered}+ showDuration={showDuration}+ showCostTokens={showCostTokens}+ showScores={showScores}+ showComments={showComments}+ colorCodeMetrics={colorCodeMetrics}+ parentTotalCost={parentTotalCost}+ parentTotalDuration={parentTotalDuration}+ commentCount={commentCount}+ scores={nodeScores}+ />+ </div>+ );+ };++ return (+ <div className="flex h-full w-full flex-col overflow-hidden">+ {/* Header: name label + time scale (scale transform-synced, no scrollbar). */}+ <div className="flex shrink-0">+ <div+ className="bg-background text-muted-foreground flex shrink-0 items-start pt-0.5 pl-2 text-xs font-medium"+ style={{ width: `${gutterWidth}px` }}+ >+ Name+ </div>+ <div className="bg-border/60 w-px shrink-0" />+ <div+ className="flex-1 overflow-hidden"+ style={{ marginRight: `${chartScrollbar.x}px` }}+ >+ <div ref={scaleInnerRef} style={{ width: `${chartContentWidth}px` }}>+ <TimelineScale+ traceDuration={traceDuration}+ scaleWidth={SCALE_WIDTH}+ stepSize={stepSize}+ />+ </div></div></div>- {/* Main scrollable content with virtualized rows */}+ {/* Body: gutter pane | resizer | chart pane. */}<div- ref={contentRef}- className="flex-1 overflow-auto"- onScroll={handleContentScroll}+ className="flex min-h-0 flex-1"+ onMouseLeave={() => setHoveredNodeId(null)}>+ {/* Gutter pane — vertical scroll mirrored from the chart; scrollbar hidden. */}+ <div+ ref={gutterRef}+ onScroll={handleGutterScroll}+ className="shrink-0 overflow-x-hidden overflow-y-auto [&::-webkit-scrollbar]:hidden"+ style={{ width: `${gutterWidth}px`, scrollbarWidth: "none" }}+ >+ <div+ style={{+ height: `${totalSize + chartScrollbar.y}px`,+ position: "relative",+ }}+ >+ {virtualItems.map((vr) => renderRow(vr, "gutter"))}+ </div>+ </div>++ {/* Resizer: structural 1px divider with a wider invisible drag grip. */}+ <div className="bg-border/60 relative w-px shrink-0">+ <div+ role="separator"+ aria-orientation="vertical"+ aria-label="Resize name column"+ onPointerDown={startGutterResize}+ className={cn(+ "hover:bg-primary/40 active:bg-primary/40 absolute inset-y-0 left-1/2 z-20 w-2",+ "-translate-x-1/2 cursor-col-resize",+ )}+ />+ </div>++ {/* Chart pane — the only horizontal scrollbar lives here. */}<div- style={{- height: `${rowVirtualizer.getTotalSize()}px`,- width: `${contentWidth}px`,- position: "relative",- }}+ ref={chartRef}+ onScroll={handleChartScroll}+ className="flex-1 overflow-auto">- {rowVirtualizer.getVirtualItems().map((virtualRow) => {- const item = flattenedItems[virtualRow.index];- if (!item) return null;-- const nodeId = item.node.id;- const isSelected = selectedNodeId === nodeId;- const hasChildren = item.node.children.length > 0;- const isCollapsed = collapsedNodes.has(nodeId);-- // Get scores for this node- const nodeScores = scores.filter((score) => {- // Match based on observation ID or trace ID- if (item.node.type === "TRACE") {- return score.traceId === item.node.id;- }- return score.observationId === item.node.id;- });-- // Get comment count for this node- const commentCount = comments.get(nodeId) ?? 0;-- return (- <div- key={nodeId}- style={{- position: "absolute",- top: 0,- left: 0,- width: "100%",- height: `${virtualRow.size}px`,- transform: `translateY(${virtualRow.start}px)`,- }}- >- <TimelineRow- item={item}- isSelected={isSelected}- onSelect={() => setSelectedNodeId(nodeId)}- onHover={() => handleHover(item.node)}- onToggleCollapse={() => toggleCollapsed(nodeId)}- hasChildren={hasChildren}- isCollapsed={isCollapsed}- showDuration={showDuration}- showCostTokens={showCostTokens}- showScores={showScores}- showComments={showComments}- colorCodeMetrics={colorCodeMetrics}- parentTotalCost={parentTotalCost}- parentTotalDuration={parentTotalDuration}- commentCount={commentCount}- scores={nodeScores}- />- </div>- );- })}+ <div+ style={{+ height: `${totalSize}px`,+ width: `${chartContentWidth}px`,+ position: "relative",+ }}+ >+ {virtualItems.map((vr) => renderRow(vr, "chart"))}+ </div></div></div></div>diff --git a/web/src/components/trace/components/TraceTimeline/timeline.fixtures.ts b/web/src/components/trace/components/TraceTimeline/timeline.fixtures.tsnew file mode 100644index 0000000000..d04799369a--- /dev/null+++ b/web/src/components/trace/components/TraceTimeline/timeline.fixtures.ts@@ -0,0 +1,50 @@+/**+ * Small fixtures for TraceTimeline stories. Kept minimal — the smallest shape+ * that renders each state — and shared across the TimelineBar / TimelineGutterRow+ * stories so node construction lives in one place.+ */++import Decimal from "decimal.js";+import { type TreeNode } from "../../lib/types";+import { type FlatTimelineItem, type TimelineMetrics } from "./types";++const BASE_START = new Date("2024-01-01T00:00:00.000Z");++export function makeTreeNode(overrides: Partial<TreeNode> = {}): TreeNode {+ const startTime = overrides.startTime ?? BASE_START;+ return {+ id: "node",+ type: "GENERATION",+ name: "llm-call",+ startTime,+ endTime: new Date(startTime.getTime() + 2000),+ latency: 2,+ children: [],+ startTimeSinceTrace: 0,+ startTimeSinceParentStart: 0,+ depth: 0,+ childrenDepth: 0,+ ...overrides,+ };+}++export function makeMetrics(+ overrides: Partial<TimelineMetrics> = {},+): TimelineMetrics {+ return { startOffset: 60, itemWidth: 220, latency: 2, ...overrides };+}++export function makeItem(+ overrides: Partial<FlatTimelineItem> = {},+): FlatTimelineItem {+ return {+ node: overrides.node ?? makeTreeNode(),+ depth: 0,+ treeLines: [],+ isLastSibling: true,+ metrics: overrides.metrics ?? makeMetrics(),+ ...overrides,+ };+}++export const cost = (value: number) => new Decimal(value);diff --git a/web/src/components/trace/components/TraceTimeline/types.ts b/web/src/components/trace/components/TraceTimeline/types.tsindex 131017c276..6f65ffa746 100644--- a/web/src/components/trace/components/TraceTimeline/types.ts+++ b/web/src/components/trace/components/TraceTimeline/types.ts@@ -24,14 +24,16 @@ export interface TimelineMetrics {/*** Props for TimelineBar component- * Renders individual Gantt bar with metrics and badges+ * Renders the gantt bar (duration) plus a trailing metric label, positioned on+ * the time axis. Hierarchy/identity (badge, name, connectors) lives in the+ * gutter (TimelineGutterRow), not here.*/export interface TimelineBarProps {node: TreeNode;metrics: TimelineMetrics;isSelected: boolean;- onSelect: () => void;- onHover?: () => void;+ /** Row is hovered (driven by shared state so the whole row highlights). */+ isHovered?: boolean;// View preferencesshowDuration: boolean;showCostTokens: boolean;@@ -61,29 +63,20 @@ export interface FlatTimelineItem {}/**- * Props for TimelineRow component- * Renders tree structure + timeline bar+ * Props for TimelineGutterRow component+ * Renders the left gutter: tree connectors + icon + name (the depth coordinate).+ * Identity only — time/metrics live on the bar (TimelineBar) in the chart pane.*/-export interface TimelineRowProps {+export interface TimelineGutterRowProps {item: FlatTimelineItem;isSelected: boolean;+ /** Row is hovered (shared state so the gutter + chart highlight together). */+ isHovered?: boolean;onSelect: () => void;onHover?: () => void;onToggleCollapse: () => void;hasChildren: boolean;isCollapsed: boolean;- // View preferences- showDuration: boolean;- showCostTokens: boolean;- showScores: boolean;- showComments: boolean;- colorCodeMetrics: boolean;- // Heatmap context- parentTotalCost?: Decimal;- parentTotalDuration?: number;- // Optional data- commentCount?: number;- scores?: WithStringifiedMetadata<ScoreDomain>[];}/**diff --git a/web/src/components/trace/components/TraceTree.tsx b/web/src/components/trace/components/TraceTree.tsxindex ae0c786cea..0f0fa46ca1 100644--- a/web/src/components/trace/components/TraceTree.tsx+++ b/web/src/components/trace/components/TraceTree.tsx@@ -15,6 +15,7 @@ import { SpanContent } from "./SpanContent";import { useTraceData } from "../contexts/TraceDataContext";import { useSelection } from "../contexts/SelectionContext";import { useHandlePrefetchObservation } from "../hooks/useHandlePrefetchObservation";+import { useDesktopLayoutContextOptional } from "./_layout/TraceLayoutDesktop";import { type TreeNode } from "../lib/types";export function TraceTree() {@@ -22,6 +23,13 @@ export function TraceTree() {const { selectedNodeId, setSelectedNodeId, collapsedNodes, toggleCollapsed } =useSelection();const { handleHover } = useHandlePrefetchObservation();+ // Optional (null on mobile): reopen the detail panel on select, including+ // re-selecting the already-selected node.+ const layout = useDesktopLayoutContextOptional();+ const handleSelectNode = (id: string | null) => {+ setSelectedNodeId(id);+ layout?.expandDetailPanel();+ };// TODO: Extract aggregation logic to shared utility - duplicated in tree-building.ts and TraceTimeline/index.tsx// Calculate aggregated totals across all roots for heatmap color scaling@@ -46,7 +54,7 @@ export function TraceTree() {collapsedNodes={collapsedNodes}selectedNodeId={selectedNodeId}onToggleCollapse={toggleCollapsed}- onSelectNode={setSelectedNodeId}+ onSelectNode={handleSelectNode}renderNode={({node,treeMetadata,diff --git a/web/src/components/trace/components/_layout/TraceLayoutDesktop.tsx b/web/src/components/trace/components/_layout/TraceLayoutDesktop.tsxindex aa0f0f17e1..ab47ce1054 100644--- a/web/src/components/trace/components/_layout/TraceLayoutDesktop.tsx+++ b/web/src/components/trace/components/_layout/TraceLayoutDesktop.tsx@@ -14,7 +14,10 @@ import {useContext,type ReactNode,} from "react";+import { PanelRightOpen } from "lucide-react";+import { Button } from "@/src/components/ui/button";import { useViewPreferences } from "@/src/components/trace/contexts/ViewPreferencesContext";+import { useSelection } from "@/src/components/trace/contexts/SelectionContext";const RESIZABLE_PANEL_GROUP_ID = "trace-layout";const RESIZABLE_PANEL_HANDLE_ID = "trace-layout-handle";@@ -28,6 +31,11 @@ interface TraceLayoutDesktopContext {panelRef: React.RefObject<PanelImperativeHandle | null>;handleTogglePanel: () => void;shouldPulseToggle: boolean;+ // Detail (info/preview) panel — collapsible like the navigation panel.+ detailPanelRef: React.RefObject<PanelImperativeHandle | null>;+ isDetailPanelCollapsed: boolean;+ setIsDetailPanelCollapsed: (collapsed: boolean) => void;+ expandDetailPanel: () => void;}const LayoutContext = createContext<TraceLayoutDesktopContext | null>(null);@@ -47,6 +55,12 @@ export function useDesktopLayoutContext() {return useLayoutContext();}+// Safe variant for components rendered in both desktop and mobile layouts+// (mobile has no provider): returns null instead of throwing.+export function useDesktopLayoutContextOptional() {+ return useContext(LayoutContext);+}+export function TraceLayoutDesktop({ children }: { children: ReactNode }) {// Get current view mode from URLconst [viewMode] = useQueryParam("view", StringParam);@@ -61,6 +75,27 @@ export function TraceLayoutDesktop({ children }: { children: ReactNode }) {// Ref to programmatically control the panelconst panelRef = usePanelRef();+ // Detail (info/preview) panel collapse state + control.+ const detailPanelRef = usePanelRef();+ const [isDetailPanelCollapsed, setIsDetailPanelCollapsed] = useState(false);+ // Guarded so it's a no-op (not a resize) when already open — safe to call on+ // every row click, which is how re-selecting the same node reopens it.+ const expandDetailPanel = () => {+ if (detailPanelRef.current?.isCollapsed()) detailPanelRef.current.expand();+ };++ // Selecting another node (timeline/tree) while the detail panel is collapsed+ // reopens it. This covers selection CHANGES (incl. the search list); re-+ // selecting the same node is handled at the row click via expandDetailPanel,+ // since the URL param — and thus this effect — doesn't change on re-click.+ const { selectedNodeId } = useSelection();+ useEffect(() => {+ // Guard on selectedNodeId so a deliberately-collapsed panel isn't reopened+ // on mount/refresh when there's no selection (effects always run once).+ if (selectedNodeId) expandDetailPanel();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [selectedNodeId]);+// Collapse panel on initial mount if in annotation modeuseEffect(() => {if (@@ -112,11 +147,15 @@ export function TraceLayoutDesktop({ children }: { children: ReactNode }) {panelRef,handleTogglePanel,shouldPulseToggle,+ detailPanelRef,+ isDetailPanelCollapsed,+ setIsDetailPanelCollapsed,+ expandDetailPanel,};return (<LayoutContext.Provider value={contextValue}>- <div className="h-full w-full">+ <div className="relative h-full w-full"><Grouporientation="horizontal"id={RESIZABLE_PANEL_GROUP_ID}@@ -125,6 +164,21 @@ export function TraceLayoutDesktop({ children }: { children: ReactNode }) {>{children}</Group>++ {/* When the detail panel is fully collapsed, a tab on the right edge+ brings it back (the drag handle alone isn't discoverable). */}+ {isDetailPanelCollapsed && (+ <Button+ variant="outline"+ size="icon"+ title="Show detail panel"+ aria-label="Show detail panel"+ onClick={expandDetailPanel}+ className="bg-background absolute top-1/2 right-0 z-30 h-9 w-6 -translate-y-1/2 rounded-l-md rounded-r-none border-r-0 shadow-sm"+ >+ <PanelRightOpen className="h-4 w-4" />+ </Button>+ )}</div></LayoutContext.Provider>);@@ -174,8 +228,26 @@ TraceLayoutDesktop.DetailPanel = function Detail({}: {children: ReactNode;}) {+ const { detailPanelRef, setIsDetailPanelCollapsed } = useLayoutContext();+return (- <Panel id={RESIZABLE_PANEL_PREVIEW_ID} defaultSize="70%" minSize="50%">+ // Collapsible like the navigation panel: dragging it below the 360px floor+ // snaps it shut (collapsedSize 0) so the timeline/tree can take the full+ // width. A tab on the right edge (rendered by TraceLayoutDesktop) brings it+ // back. 360px is the readable minimum the narrow peek already renders at.+ <Panel+ id={RESIZABLE_PANEL_PREVIEW_ID}+ panelRef={detailPanelRef}+ defaultSize="70%"+ collapsible={true}+ collapsedSize="0px"+ minSize="360px"+ onResize={() => {+ setIsDetailPanelCollapsed(+ detailPanelRef.current?.isCollapsed() ?? false,+ );+ }}+ >{children}</Panel>);diff --git a/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx b/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsxindex 65463de358..cdceaa9b0d 100644--- a/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx+++ b/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx@@ -16,11 +16,30 @@ import { useTraceGraphData } from "../../contexts/TraceGraphDataContext";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import { Command, CommandInput } from "@/src/components/ui/command";import { Button } from "@/src/components/ui/button";-import { FoldVertical, UnfoldVertical, Download, Loader2 } from "lucide-react";+import {+ FoldVertical,+ UnfoldVertical,+ Download,+ Loader2,+ ListTree,+ GanttChartSquare,+ MoreHorizontal,+ type LucideIcon,+} from "lucide-react";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";import { StringParam, useQueryParam } from "use-query-params";import { cn } from "@/src/utils/tailwind";import { useCallback } from "react";-import { TraceSettingsDropdown } from "../TraceSettingsDropdown";+import {+ TraceSettingsDropdown,+ TraceViewOptionsMenuItems,+} from "../TraceSettingsDropdown";import {downloadLegacyTraceAsJson,downloadServerTraceAsJson,@@ -136,8 +155,8 @@ function TracePanelNavigationHeaderExpanded({const isTimelineView = viewMode === "timeline";return (- <Command className="mt-1 flex h-auto shrink-0 flex-col gap-1 overflow-hidden rounded-none border-b">- <div className="flex flex-row justify-between pr-2 pl-1">+ <Command className="flex h-auto shrink-0 flex-col gap-1 overflow-hidden rounded-none border-b">+ <div className="@container/navheader flex flex-row items-center justify-between pr-2 pl-1">{/* Panel Toggle Button; special p-0.5 offset to pixel align with closed version */}<div className="flex flex-row items-center p-0.5"><TracePanelNavigationButton@@ -158,54 +177,141 @@ function TracePanelNavigationHeaderExpanded({/></div><div className="flex shrink-0 flex-row items-center gap-0.5">- {/* Expand/Collapse All Button */}- <Button- onClick={handleToggleTreeNodes}- variant="ghost"- size="icon"- title={isEverythingCollapsed ? "Expand all" : "Collapse all"}- className="h-7 w-7"- >- {isEverythingCollapsed ? (- <UnfoldVertical className="h-3.5 w-3.5" />- ) : (- <FoldVertical className="h-3.5 w-3.5" />- )}- </Button>-- {/* Settings Dropdown */}- <TraceSettingsDropdown isGraphViewAvailable={isGraphViewAvailable} />-- {/* Download Button */}- <Button- variant="ghost"- size="icon"- onClick={handleDownload}- disabled={isDownloading}- title="Download trace as JSON"- className="h-7 w-7"- >- {isDownloading ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <Download className="h-3.5 w-3.5" />- )}- </Button>-- {/* Timeline Toggle Button */}- <Button- variant={isTimelineView ? "default" : "ghost"}- size="sm"- onClick={() => setViewMode(isTimelineView ? null : "timeline")}- className={cn(- "h-7 shrink-0 px-2 text-xs",- isTimelineView && "bg-primary text-primary-foreground",- )}- >- <span className="text-xs">Timeline</span>- </Button>+ {/* Minor tools — inline when the panel is wide enough. */}+ <div className="hidden flex-row items-center gap-0.5 @min-[380px]/navheader:flex">+ <Button+ onClick={handleToggleTreeNodes}+ variant="ghost"+ size="icon"+ title={isEverythingCollapsed ? "Expand all" : "Collapse all"}+ className="h-7 w-7"+ >+ {isEverythingCollapsed ? (+ <UnfoldVertical className="h-3.5 w-3.5" />+ ) : (+ <FoldVertical className="h-3.5 w-3.5" />+ )}+ </Button>++ <TraceSettingsDropdown+ isGraphViewAvailable={isGraphViewAvailable}+ />++ <Button+ variant="ghost"+ size="icon"+ onClick={handleDownload}+ disabled={isDownloading}+ title="Download trace as JSON"+ className="h-7 w-7"+ >+ {isDownloading ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Download className="h-3.5 w-3.5" />+ )}+ </Button>+ </div>++ {/* …and folded into an overflow menu when it's narrow. */}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ title="More"+ aria-label="More options"+ className="h-7 w-7 @min-[380px]/navheader:hidden"+ >+ <MoreHorizontal className="h-3.5 w-3.5" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="center" className="w-64">+ <DropdownMenuItem onSelect={handleToggleTreeNodes}>+ {isEverythingCollapsed ? (+ <UnfoldVertical className="mr-2 h-3.5 w-3.5" />+ ) : (+ <FoldVertical className="mr-2 h-3.5 w-3.5" />+ )}+ {isEverythingCollapsed ? "Expand all" : "Collapse all"}+ </DropdownMenuItem>+ <DropdownMenuItem+ onSelect={() => handleDownload()}+ disabled={isDownloading}+ >+ <Download className="mr-2 h-3.5 w-3.5" />+ Download trace as JSON+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <TraceViewOptionsMenuItems+ isGraphViewAvailable={isGraphViewAvailable}+ />+ </DropdownMenuContent>+ </DropdownMenu>++ {/* Tree / Timeline segmented switch (labels collapse to icons when+ the panel is narrow — see @container/navheader). */}+ <ViewModeSwitch+ isTimelineView={isTimelineView}+ onSelect={(timeline) => setViewMode(timeline ? "timeline" : null)}+ /></div></div></Command>);}++function ViewModeSwitch({+ isTimelineView,+ onSelect,+}: {+ isTimelineView: boolean;+ onSelect: (timeline: boolean) => void;+}) {+ return (+ <div className="bg-muted/60 ml-2 inline-flex h-7 shrink-0 items-center rounded-md border p-0.5">+ <ViewModeSegment+ active={!isTimelineView}+ onClick={() => onSelect(false)}+ icon={ListTree}+ label="Tree"+ />+ <ViewModeSegment+ active={isTimelineView}+ onClick={() => onSelect(true)}+ icon={GanttChartSquare}+ label="Timeline"+ />+ </div>+ );+}++function ViewModeSegment({+ active,+ onClick,+ icon: Icon,+ label,+}: {+ active: boolean;+ onClick: () => void;+ icon: LucideIcon;+ label: string;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ aria-pressed={active}+ title={label}+ className={cn(+ "flex h-6 items-center gap-1.5 rounded-md px-2 text-xs font-medium transition-colors",+ active+ ? "bg-primary text-primary-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ <Icon className="h-3.5 w-3.5 shrink-0" />+ <span className="@max-[360px]/navheader:hidden">{label}</span>+ </button>+ );+}