Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(trace-detail): tree view improvements (#8557)

Leo Weiganda0c876271a7f
diff --git a/web/src/components/table/peek/peek-dataset-compare-detail.tsx b/web/src/components/table/peek/peek-dataset-compare-detail.tsx
index a63c11fc6b..c474598b1f 100644
--- a/web/src/components/table/peek/peek-dataset-compare-detail.tsx
+++ b/web/src/components/table/peek/peek-dataset-compare-detail.tsx
@@ -5,7 +5,7 @@ import {
ResizableHandle,
} from "@/src/components/ui/resizable";
import { IOPreview } from "@/src/components/trace/IOPreview";
-import { ObservationTree } from "@/src/components/trace/ObservationTree";
+import { TraceTree } from "@/src/components/trace/TraceTree";
import { Skeleton } from "@/src/components/ui/skeleton";
import { type RouterOutputs } from "@/src/utils/api";
import { DatasetAggregateTableCell } from "@/src/features/datasets/components/DatasetAggregateTableCell";
@@ -17,6 +17,8 @@ import DocPopup from "@/src/components/layouts/doc-popup";
import type { DatasetCompareRunRowData } from "@/src/features/datasets/components/DatasetCompareRunsTable";
import { useRouter } from "next/router";
import { usePeekData } from "@/src/components/table/peek/hooks/usePeekData";
+import React, { useState, useCallback, useMemo } from "react";
+import { buildTraceTree } from "@/src/components/trace/lib/helpers";
export type PeekDatasetCompareDetailProps = {
projectId: string;
@@ -32,6 +34,7 @@ export const PeekDatasetCompareDetail = ({
row,
}: PeekDatasetCompareDetailProps) => {
const router = useRouter();
+ const [collapsedNodes, setCollapsedNodes] = useState<string[]>([]);
const timestamp =
router.query.timestamp && typeof router.query.timestamp === "string"
@@ -48,6 +51,37 @@ export const PeekDatasetCompareDetail = ({
timestamp,
});
+ const tree = useMemo(() => {
+ if (!trace.data) return null;
+
+ const { tree } = buildTraceTree(
+ trace.data,
+ trace.data.observations ?? [],
+ "DEFAULT",
+ );
+
+ return tree;
+ }, [trace.data]);
+
+ const toggleCollapsedNode = useCallback((id: string) => {
+ setCollapsedNodes((prevNodes) => {
+ if (prevNodes.includes(id)) {
+ return prevNodes.filter((i) => i !== id);
+ } else {
+ return [...prevNodes, id];
+ }
+ });
+ }, []);
+
+ const handleSetCurrentObservationId = (id?: string) => {
+ if (id && traceId && !id.startsWith("trace-")) {
+ // Only open observations in new tabs, not the trace root (which has trace- prefix)
+ const pathname = `/project/${projectId}/traces/${encodeURIComponent(traceId)}?observation=${encodeURIComponent(id)}`;
+ const pathnameWithBasePath = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${pathname}`;
+ window.open(pathnameWithBasePath, "_blank", "noopener noreferrer");
+ }
+ };
+
const handleToggleTrace = (
newTraceId?: string,
newRunId?: string,
@@ -63,14 +97,7 @@ export const PeekDatasetCompareDetail = ({
traceId: newTraceId,
observationId: newObservationId,
});
- }
- };
-
- const handleSetCurrentObservationId = (id?: string) => {
- if (id && traceId) {
- const pathname = `/project/${projectId}/traces/${encodeURIComponent(traceId)}?observation=${encodeURIComponent(id)}`;
- const pathnameWithBasePath = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${pathname}`;
- window.open(pathnameWithBasePath, "_blank", "noopener noreferrer");
+ setCollapsedNodes([]); // Reset collapsed state for new trace
}
};
@@ -87,26 +114,24 @@ export const PeekDatasetCompareDetail = ({
<div className="h-full overflow-y-auto border-r p-2">
{trace.data ? (
<Command>
- <h3 className="mb-3 font-semibold">{`Run: ${
- runsData?.find((r: any) => r.id === runId)?.name
- }`}</h3>
- <ObservationTree
- observations={trace.data?.observations ?? []}
- collapsedObservations={[]}
- toggleCollapsedObservation={() => {}}
- collapseAll={() => {}}
- expandAll={() => {}}
- trace={trace.data}
- scores={trace.data.scores ?? []}
- currentObservationId={undefined}
- setCurrentObservationId={handleSetCurrentObservationId}
- showComments={false}
- showMetrics={false}
- showScores={true}
- colorCodeMetrics={false}
- className="flex w-full flex-col overflow-y-auto"
- showExpandControls={false}
- />
+ <h3 className="mb-3 font-semibold">
+ Run: {runsData?.find((r) => r.id === runId)?.name}
+ </h3>
+ {tree && (
+ <TraceTree
+ tree={tree}
+ collapsedNodes={collapsedNodes}
+ toggleCollapsedNode={toggleCollapsedNode}
+ scores={trace.data?.scores ?? []}
+ currentNodeId={undefined}
+ setCurrentNodeId={handleSetCurrentObservationId}
+ showMetrics={false}
+ showScores={true}
+ colorCodeMetrics={false}
+ showComments={false}
+ className="flex w-full flex-col overflow-y-auto"
+ />
+ )}
</Command>
) : (
<Skeleton className="min-h-full w-full" />
@@ -152,7 +177,7 @@ export const PeekDatasetCompareDetail = ({
{row?.runs && (
<div className="flex h-[calc(100%-2rem)] w-full gap-4 overflow-x-auto">
{Object.entries(row.runs).map(([id, run]) => {
- const runData = runsData?.find((r: any) => r.id === id);
+ const runData = runsData?.find((r) => r.id === id);
return (
<div
key={id}
@@ -190,7 +215,6 @@ export const PeekDatasetCompareDetail = ({
>
<ListTree className="h-4 w-4" />
</Button>
-
<Button
variant="outline"
size="icon"
diff --git a/web/src/components/trace/ObservationTree.tsx b/web/src/components/trace/ObservationTree.tsx
deleted file mode 100644
index 538824afea..0000000000
--- a/web/src/components/trace/ObservationTree.tsx
+++ /dev/null
@@ -1,530 +0,0 @@
-import { type NestedObservation } from "@/src/utils/types";
-import { cn } from "@/src/utils/tailwind";
-import {
- type APIScoreV2,
- ObservationLevel,
- type ObservationLevelType,
- type TraceDomain,
-} from "@langfuse/shared";
-import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
-import { Fragment, useMemo, useRef, useEffect } from "react";
-import { type ObservationReturnType } from "@/src/server/api/routers/traces";
-import { LevelColors } from "@/src/components/level-colors";
-import { formatIntervalSeconds } from "@/src/utils/dates";
-import {
- InfoIcon,
- ChevronRight,
- ChevronDown,
- ChevronsUpDown,
- ChevronsDownUp,
-} from "lucide-react";
-import { Button } from "@/src/components/ui/button";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import {
- calculateDisplayTotalCost,
- heatMapTextColor,
- nestObservations,
- unnestObservation,
-} from "@/src/components/trace/lib/helpers";
-import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";
-import { usdFormatter } from "@/src/utils/numbers";
-import type Decimal from "decimal.js";
-import { CommandItem } from "@/src/components/ui/command";
-import { ItemBadge } from "@/src/components/ItemBadge";
-
-export const ObservationTree = ({
- showExpandControls = true,
- showComments,
- ...props
-}: {
- observations: ObservationReturnType[];
- collapsedObservations: string[];
- toggleCollapsedObservation: (id: string) => void;
- collapseAll: () => void;
- expandAll: () => void;
- trace: Omit<TraceDomain, "input" | "output" | "metadata"> & {
- latency?: number;
- input: string | null;
- output: string | null;
- metadata: string | null;
- };
- scores: APIScoreV2[];
- currentObservationId: string | undefined;
- setCurrentObservationId: (id: string | undefined) => void;
- showMetrics: boolean;
- showScores: boolean;
- colorCodeMetrics: boolean;
- observationCommentCounts?: Map<string, number>;
- traceCommentCounts?: Map<string, number>;
- className?: string;
- showExpandControls?: boolean;
- minLevel?: ObservationLevelType;
- setMinLevel?: React.Dispatch<React.SetStateAction<ObservationLevelType>>;
- showComments: boolean;
-}) => {
- const { nestedObservations, hiddenObservationsCount } = useMemo(
- () => nestObservations(props.observations, props.minLevel),
- [props.observations, props.minLevel],
- );
- const totalCost = useMemo(() => {
- return calculateDisplayTotalCost({
- allObservations: props.observations,
- });
- }, [props.observations]);
-
- return (
- <div className={props.className}>
- <ObservationTreeTraceNode
- expandAll={props.expandAll}
- collapseAll={props.collapseAll}
- trace={props.trace}
- scores={props.scores}
- comments={props.traceCommentCounts}
- currentObservationId={props.currentObservationId}
- setCurrentObservationId={props.setCurrentObservationId}
- showMetrics={props.showMetrics}
- showScores={props.showScores}
- totalCost={totalCost}
- showExpandControls={showExpandControls}
- showComments={showComments}
- />
- <ObservationTreeNode
- observations={nestedObservations}
- collapsedObservations={props.collapsedObservations}
- toggleCollapsedObservation={props.toggleCollapsedObservation}
- scores={props.scores}
- comments={props.observationCommentCounts}
- indentationLevel={1}
- currentObservationId={props.currentObservationId}
- setCurrentObservationId={props.setCurrentObservationId}
- showMetrics={props.showMetrics}
- showScores={props.showScores}
- colorCodeMetrics={props.colorCodeMetrics}
- parentTotalCost={totalCost}
- parentTotalDuration={
- props.trace.latency ? props.trace.latency * 1000 : undefined
- }
- showComments={showComments}
- />
- {props.minLevel && hiddenObservationsCount > 0 ? (
- <span className="flex items-center gap-1 p-2 py-4">
- <InfoIcon className="h-4 w-4 text-muted-foreground" />
- <p className="text-sm text-muted-foreground">
- <span>
- {hiddenObservationsCount}{" "}
- {hiddenObservationsCount === 1 ? "observation" : "observations"}{" "}
- below {props.minLevel} level are hidden.{" "}
- </span>
- <span
- className="cursor-pointer underline"
- onClick={() => props.setMinLevel?.(ObservationLevel.DEBUG)}
- >
- Show all
- </span>
- </p>
- </span>
- ) : null}
- </div>
- );
-};
-
-const ObservationTreeTraceNode = (props: {
- trace: Omit<TraceDomain, "input" | "output" | "metadata"> & {
- input: string | null;
- output: string | null;
- metadata: string | null;
- latency?: number;
- };
- expandAll: () => void;
- collapseAll: () => void;
- scores: APIScoreV2[];
- comments: Map<string, number> | undefined;
- currentObservationId: string | undefined;
- setCurrentObservationId: (id: string | undefined) => void;
- showMetrics?: boolean;
- showScores?: boolean;
- totalCost?: Decimal;
- showExpandControls?: boolean;
- showComments: boolean;
-}) => {
- return (
- <CommandItem
- value={`${props.trace.name} TRACE`}
- className={cn(
- "flex w-full rounded-md px-0 hover:rounded-lg",
- (props.currentObservationId === undefined ||
- props.currentObservationId === "") &&
- "rounded-lg bg-muted",
- "after:hover:absolute after:hover:bottom-0 after:hover:left-0 after:hover:right-0 after:hover:h-[2px] after:hover:bg-background after:hover:content-['']",
- "before:hover:absolute before:hover:left-0 before:hover:right-0 before:hover:top-0 before:hover:h-[2px] before:hover:bg-background before:hover:content-['']",
- (props.currentObservationId === undefined ||
- props.currentObservationId === "") && [
- "after:absolute after:bottom-0 after:left-0 after:right-0 after:h-[2px] after:bg-background after:content-['']",
- "before:absolute before:left-0 before:right-0 before:top-0 before:h-[2px] before:bg-background before:content-['']",
- ],
- )}
- style={{
- paddingTop: 0,
- paddingBottom: 0,
- cursor: "pointer",
- borderRadius: "0.5rem",
- }}
- onSelect={() => props.setCurrentObservationId(undefined)}
- >
- <div className="flex w-full flex-row items-start justify-between gap-1 py-1">
- <div className="flex w-full flex-col items-start gap-2 -space-y-1 py-1.5">
- <div className="flex flex-wrap items-center gap-2">
- <ItemBadge
- type="TRACE"
- isSmall={true}
- className="flex-shrink-0 scale-75"
- />
- <span className="break-all text-sm font-medium">
- {props.trace.name}
- </span>
- {props.comments && props.showComments ? (
- <CommentCountIcon count={props.comments.get(props.trace.id)} />
- ) : null}
- </div>
-
- {props.showMetrics && (
- <div className="flex gap-2">
- {props.trace.latency ? (
- <span
- className="text-xs text-muted-foreground"
- title="Aggregated duration of all observations"
- >
- {formatIntervalSeconds(props.trace.latency)}
- </span>
- ) : null}
- {props.totalCost ? (
- <span
- className="text-xs text-muted-foreground"
- title="Aggregated cost of all observations"
- >
- {usdFormatter(props.totalCost.toNumber())}
- </span>
- ) : null}
- </div>
- )}
- {props.showScores &&
- props.scores.find((s) => s.observationId === null) ? (
- <div className="flex flex-wrap gap-1">
- <GroupedScoreBadges
- scores={props.scores.filter((s) => s.observationId === null)}
- />
- </div>
- ) : null}
- </div>
- {props.showExpandControls && (
- <div className="mt-1 flex flex-1 items-center justify-end">
- <Button
- variant="ghost"
- size="icon"
- onClick={() => props.expandAll()}
- className="h-4 w-4 flex-shrink-0"
- title="Expand all"
- >
- <ChevronsUpDown className="h-4 w-4 text-foreground" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={() => props.collapseAll()}
- className="h-4 w-4 flex-shrink-0"
- title="Collapse all"
- >
- <ChevronsDownUp className="h-4 w-4 text-foreground" />
- </Button>
- </div>
- )}
- </div>
- </CommandItem>
- );
-};
-
-const ObservationTreeNode = (props: {
- observations: NestedObservation[];
- collapsedObservations: string[];
- toggleCollapsedObservation: (id: string) => void;
- scores: APIScoreV2[];
- comments?: Map<string, number> | undefined;
- indentationLevel: number;
- currentObservationId: string | undefined;
- setCurrentObservationId: (id: string | undefined) => void;
- showMetrics?: boolean;
- showScores?: boolean;
- colorCodeMetrics?: boolean;
- parentTotalCost?: Decimal;
- parentTotalDuration?: number;
- showComments: boolean;
-}) => {
- return (
- <div className="flex w-full flex-col">
- {props.observations
- .sort((a, b) => a.startTime.getTime() - b.startTime.getTime())
- .map((observation) => {
- const collapsed = props.collapsedObservations.includes(
- observation.id,
- );
-
- return (
- <Fragment key={observation.id}>
- <ObservationTreeNodeCard
- observation={observation}
- collapsed={collapsed}
- toggleCollapsedObservation={props.toggleCollapsedObservation}
- scores={props.scores}
- comments={props.comments}
- indentationLevel={props.indentationLevel}
- currentObservationId={props.currentObservationId}
- setCurrentObservationId={props.setCurrentObservationId}
- showMetrics={props.showMetrics}
- showScores={props.showScores}
- colorCodeMetrics={props.colorCodeMetrics}
- parentTotalCost={props.parentTotalCost}
- parentTotalDuration={props.parentTotalDuration}
- showComments={props.showComments}
- />
- {!collapsed && observation.children.length > 0 && (
- <ObservationTreeNode
- {...props}
- observations={observation.children}
- indentationLevel={props.indentationLevel + 1}
- showComments={props.showComments}
- />
- )}
- </Fragment>
- );
- })}
- </div>
- );
-};
-
-const ObservationTreeNodeCard = ({
- observation,
- collapsed,
- toggleCollapsedObservation,
- indentationLevel,
- currentObservationId,
- setCurrentObservationId,
- comments,
- showMetrics,
- showScores,
- scores,
- colorCodeMetrics,
- parentTotalCost,
- parentTotalDuration,
- showComments,
-}: {
- observation: NestedObservation;
- collapsed: boolean;
- toggleCollapsedObservation: (id: string) => void;
- scores: APIScoreV2[];
- comments?: Map<string, number> | undefined;
- indentationLevel: number;
- currentObservationId: string | undefined;
- setCurrentObservationId: (id: string | undefined) => void;
- showMetrics?: boolean;
- showScores?: boolean;
- colorCodeMetrics?: boolean;
- parentTotalCost?: Decimal;
- parentTotalDuration?: number;
- showComments: boolean;
-}) => {
- const capture = usePostHogClientCapture();
- const unnestedObservations = unnestObservation(observation);
- const totalCost = calculateDisplayTotalCost({
- allObservations: unnestedObservations,
- });
- const duration = observation.endTime
- ? observation.endTime.getTime() - observation.startTime.getTime()
- : undefined;
-
- const currentObservationRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (
- currentObservationId &&
- currentObservationRef.current &&
- currentObservationId === observation.id
- ) {
- currentObservationRef.current.scrollIntoView({
- behavior: "smooth",
- block: "center",
- });
- }
- }, [currentObservationId, observation.id]);
-
- return (
- <CommandItem
- value={`${observation.name} ${observation.type} ${observation.id}`}
- className={cn(
- "relative flex w-full rounded-md px-0 hover:rounded-lg",
- currentObservationId === observation.id && "bg-muted",
- "after:hover:absolute after:hover:bottom-0 after:hover:left-0 after:hover:right-0 after:hover:h-[2px] after:hover:bg-background after:hover:content-['']",
- "before:hover:absolute before:hover:left-0 before:hover:right-0 before:hover:top-0 before:hover:h-[2px] before:hover:bg-background before:hover:content-['']",
- currentObservationId === observation.id && [
- "after:absolute after:bottom-0 after:left-0 after:right-0 after:h-[2px] after:bg-background after:content-['']",
- "before:absolute before:left-0 before:right-0 before:top-0 before:h-[2px] before:bg-background before:content-['']",
- ],
- )}
- style={{
- paddingTop: 0,
- paddingBottom: 0,
- cursor: "pointer",
- borderRadius: "0.5rem",
- }}
- onSelect={() => setCurrentObservationId(observation.id)}
- >
- <div className="flex w-full">
- {/* Indentation guides */}
- {Array.from({ length: indentationLevel }, (_, i) => (
- <div className="w-6 flex-shrink-0 border-l border-border" key={i} />
- ))}
-
- {/* Node content */}
- <div
- className={cn(
- "flex w-full flex-wrap items-center gap-2 -space-y-1 py-2",
- )}
- ref={currentObservationRef}
- >
- {/* Type badge and name */}
- <div className="flex flex-shrink-0 items-center gap-2">
- <ItemBadge
- type={observation.type}
- isSmall
- className="flex-shrink-0 scale-75"
- />
- <span className="whitespace-nowrap text-sm font-medium">
- {observation.name}
- </span>
- </div>
-
- {/* Duration and Comments */}
- <div className="flex items-center gap-2">
- {comments && showComments ? (
- <CommentCountIcon count={comments.get(observation.id)} />
- ) : null}
- {/* Level badge */}
- {observation.level !== "DEFAULT" ? (
- <div className="flex">
- <span
- className={cn(
- "rounded-sm p-0.5 text-xs",
- LevelColors[observation.level].bg,
- LevelColors[observation.level].text,
- )}
- >
- {observation.level}
- </span>
- </div>
- ) : null}
- </div>
- {/* Metrics on their own line */}
- {showMetrics && (
- <>
- {(observation.inputUsage ||
- observation.outputUsage ||
- observation.totalUsage ||
- duration ||
- totalCost) && (
- <div className="flex w-full flex-wrap gap-2">
- {duration ? (
- <span
- title={
- observation.children.length > 0
- ? "Aggregated duration of all child observations"
- : undefined
- }
- className={cn(
- "text-xs text-muted-foreground",
- parentTotalDuration &&
- colorCodeMetrics &&
- heatMapTextColor({
- max: parentTotalDuration,
- value: duration,
- }),
- )}
- >
- {formatIntervalSeconds(duration / 1000)}
- </span>
- ) : null}
- {observation.inputUsage ||
- observation.outputUsage ||
- observation.totalUsage ? (
- <span className="text-xs text-muted-foreground">
- {observation.inputUsage} → {observation.outputUsage} (∑{" "}
- {observation.totalUsage})
- </span>
- ) : null}
- {totalCost ? (
- <span
- title={
- observation.children.length > 0
- ? "Aggregated cost of all child observations"
- : undefined
- }
- className={cn(
- "text-xs text-muted-foreground",
- parentTotalCost &&
- colorCodeMetrics &&
- heatMapTextColor({
- max: parentTotalCost,
- value: totalCost,
- }),
- )}
- >
- {observation.children.length > 0 ? "∑ " : ""}
- {usdFormatter(totalCost.toNumber())}
- </span>
- ) : null}
- </div>
- )}
- </>
- )}
-
- {/* Scores on their own line */}
- {showScores &&
- scores.find((s) => s.observationId === observation.id) ? (
- <div className="flex w-full flex-wrap gap-1">
- <GroupedScoreBadges
- scores={scores.filter(
- (s) => s.observationId === observation.id,
- )}
- />
- </div>
- ) : null}
- </div>
- {/* Expand/Collapse button */}
-
- {observation.children.length > 0 && (
- <div className="flex items-center justify-end">
- <Button
- size="icon"
- variant="ghost"
- onClick={(ev) => {
- ev.stopPropagation();
- toggleCollapsedObservation(observation.id);
- capture(
- collapsed
- ? "trace_detail:observation_tree_expand"
- : "trace_detail:observation_tree_collapse",
- { type: "single" },
- );
- }}
- className="h-full flex-shrink-0"
- >
- {collapsed ? (
- <ChevronRight className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- )}
- </Button>
- </div>
- )}
- </div>
- </CommandItem>
- );
-};
diff --git a/web/src/components/trace/TraceTimelineView.tsx b/web/src/components/trace/TraceTimelineView.tsx
index 0890d63d1d..84831521db 100644
--- a/web/src/components/trace/TraceTimelineView.tsx
+++ b/web/src/components/trace/TraceTimelineView.tsx
@@ -411,6 +411,7 @@ export function TraceTimelineView({
colorCodeMetrics = true,
minLevel,
setMinLevel,
+ containerWidth,
}: {
trace: Omit<TraceDomain, "input" | "output" | "metadata"> & {
latency?: number;
@@ -431,6 +432,7 @@ export function TraceTimelineView({
colorCodeMetrics?: boolean;
minLevel?: ObservationLevelType;
setMinLevel?: React.Dispatch<React.SetStateAction<ObservationLevelType>>;
+ containerWidth?: number;
}) {
const { latency, name, id } = trace;
@@ -439,6 +441,7 @@ export function TraceTimelineView({
[observations, minLevel],
);
+ // Use containerWidth from parent or fallback to ResizeObserver if not provided
const [cardWidth, setCardWidth] = useState(0);
const parentRef = useRef<HTMLDivElement>(null);
@@ -452,20 +455,33 @@ export function TraceTimelineView({
);
useEffect(() => {
- const handleResize = () => {
+ if (containerWidth) {
+ // Use passed container width from parent
+ setCardWidth(containerWidth);
+ } else {
+ // Fallback to ResizeObserver if containerWidth not provided
+ const handleResize = () => {
+ if (parentRef.current) {
+ const availableWidth = parentRef.current.offsetWidth;
+ setCardWidth(availableWidth);
+ }
+ };
+
+ handleResize();
+
if (parentRef.current) {
- const availableWidth = parentRef.current.offsetWidth;
- setCardWidth(availableWidth);
- }
- };
+ const resizeObserver = new ResizeObserver(() => {
+ handleResize();
+ });
- handleResize();
- window.addEventListener("resize", handleResize); // Recalculate on window resize
+ resizeObserver.observe(parentRef.current);
- return () => {
- window.removeEventListener("resize", handleResize);
- };
- }, []);
+ return () => {
+ resizeObserver.disconnect();
+ };
+ }
+ }
+ }, [containerWidth]);
const isAuthenticatedAndProjectMember =
useIsAuthenticatedAndProjectMember(projectId);
@@ -532,7 +548,7 @@ export function TraceTimelineView({
return (
<div ref={parentRef} className="h-full w-full px-3">
- <div className="relative flex max-h-full flex-col">
+ <div className="relative flex h-full flex-col">
{/* Sticky time index section - positioned absolutely at the top */}
<div className="sticky top-0 z-20 bg-background">
<div
@@ -594,7 +610,7 @@ export function TraceTimelineView({
{/* Main content with scrolling */}
<div
ref={outerContainerRef}
- className="overflow-x-auto"
+ className="flex-1 overflow-x-auto"
style={{ width: cardWidth }}
onScroll={(e) => {
if (timeIndexRef.current) {
@@ -602,11 +618,11 @@ export function TraceTimelineView({
}
}}
>
- <div style={{ width: `${contentWidth}px` }}>
+ <div className="h-full" style={{ width: `${contentWidth}px` }}>
{/* Main timeline content */}
<div
ref={timelineContentRef}
- className="overflow-y-auto"
+ className="h-full overflow-y-auto"
style={{ width: `${contentWidth}px` }}
>
<SimpleTreeView
diff --git a/web/src/components/trace/TraceTree.tsx b/web/src/components/trace/TraceTree.tsx
new file mode 100644
index 0000000000..186f26cd7b
--- /dev/null
+++ b/web/src/components/trace/TraceTree.tsx
@@ -0,0 +1,455 @@
+import { type TreeNode } from "./lib/types";
+import { cn } from "@/src/utils/tailwind";
+import {
+ type APIScoreV2,
+ ObservationLevel,
+ type ObservationLevelType,
+} from "@langfuse/shared";
+import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
+import { Fragment, useMemo, useRef, useEffect } from "react";
+import { LevelColors } from "@/src/components/level-colors";
+import { formatIntervalSeconds } from "@/src/utils/dates";
+import { InfoIcon, ChevronRight } from "lucide-react";
+import { Button } from "@/src/components/ui/button";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import {
+ calculateDisplayTotalCost,
+ heatMapTextColor,
+ unnestObservation,
+} from "@/src/components/trace/lib/helpers";
+import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";
+import { usdFormatter } from "@/src/utils/numbers";
+import type Decimal from "decimal.js";
+import { CommandItem } from "@/src/components/ui/command";
+import { ItemBadge } from "@/src/components/ItemBadge";
+
+export const TraceTree = ({
+ tree,
+ collapsedNodes,
+ toggleCollapsedNode,
+ scores,
+ currentNodeId,
+ setCurrentNodeId,
+ showMetrics,
+ showScores,
+ colorCodeMetrics,
+ nodeCommentCounts,
+ className,
+ showComments,
+ hiddenObservationsCount,
+ minLevel,
+ setMinLevel,
+}: {
+ tree: TreeNode;
+ collapsedNodes: string[];
+ toggleCollapsedNode: (id: string) => void;
+ scores: APIScoreV2[];
+ currentNodeId: string | undefined;
+ setCurrentNodeId: (id: string | undefined) => void;
+ showMetrics: boolean;
+ showScores: boolean;
+ colorCodeMetrics: boolean;
+ nodeCommentCounts?: Map<string, number>;
+ className?: string;
+ showComments: boolean;
+ hiddenObservationsCount?: number;
+ minLevel?: ObservationLevelType;
+ setMinLevel?: React.Dispatch<React.SetStateAction<ObservationLevelType>>;
+}) => {
+ const totalCost = useMemo(() => {
+ // For unified tree, we need to calculate total cost differently
+ // Convert TreeNode back to observation format for cost calculation
+ const convertTreeNodeToObservation = (node: TreeNode): any => ({
+ ...node,
+ children: node.children.map(convertTreeNodeToObservation),
+ });
+
+ if (tree.type === "TRACE") {
+ // For trace root, calculate from all children
+ const allObservations = tree.children.flatMap((child) =>
+ unnestObservation(convertTreeNodeToObservation(child)),
+ );
+ return calculateDisplayTotalCost({ allObservations });
+ }
+
+ return calculateDisplayTotalCost({
+ allObservations: [convertTreeNodeToObservation(tree)],
+ });
+ }, [tree]);
+
+ return (
+ <div className={className}>
+ <div className="pb-3">
+ <TreeNodeComponent
+ node={tree}
+ collapsedNodes={collapsedNodes}
+ toggleCollapsedNode={toggleCollapsedNode}
+ scores={scores}
+ comments={nodeCommentCounts}
+ indentationLevel={0}
+ currentNodeId={currentNodeId}
+ setCurrentNodeId={setCurrentNodeId}
+ showMetrics={showMetrics}
+ showScores={showScores}
+ colorCodeMetrics={colorCodeMetrics}
+ parentTotalCost={totalCost}
+ parentTotalDuration={tree.latency ? tree.latency * 1000 : undefined}
+ showComments={showComments}
+ treeLines={[]}
+ isLastSibling={true}
+ />
+
+ {minLevel && hiddenObservationsCount && hiddenObservationsCount > 0 ? (
+ <span className="flex items-center gap-1 p-2 py-4">
+ <InfoIcon className="h-4 w-4 text-muted-foreground" />
+ <p className="text-sm text-muted-foreground">
+ <span>
+ {hiddenObservationsCount}{" "}
+ {hiddenObservationsCount === 1 ? "observation" : "observations"}{" "}
+ below {minLevel} level are hidden.{" "}
+ </span>
+ <span
+ className="cursor-pointer underline"
+ onClick={() => setMinLevel?.(ObservationLevel.DEBUG)}
+ >
+ Show all
+ </span>
+ </p>
+ </span>
+ ) : null}
+ </div>
+ </div>
+ );
+};
+
+const TreeNodeComponent = ({
+ node,
+ collapsedNodes,
+ toggleCollapsedNode,
+ scores,
+ comments,
+ indentationLevel,
+ currentNodeId,
+ setCurrentNodeId,
+ showMetrics,
+ showScores,
+ colorCodeMetrics,
+ parentTotalCost,
+ parentTotalDuration,
+ showComments,
+ treeLines,
+ isLastSibling,
+}: {
+ node: TreeNode;
+ collapsedNodes: string[];
+ toggleCollapsedNode: (id: string) => void;
+ scores: APIScoreV2[];
+ comments?: Map<string, number>;
+ indentationLevel: number;
+ currentNodeId: string | undefined;
+ setCurrentNodeId: (id: string | undefined) => void;
+ showMetrics: boolean;
+ showScores: boolean;
+ colorCodeMetrics: boolean;
+ parentTotalCost?: Decimal;
+ parentTotalDuration?: number;
+ showComments: boolean;
+ treeLines: boolean[]; // Track which levels need vertical lines
+ isLastSibling: boolean;
+}) => {
+ const capture = usePostHogClientCapture();
+ const collapsed = collapsedNodes.includes(node.id);
+
+ // Convert TreeNode back to observation format for cost calculation
+ const convertTreeNodeToObservation = (treeNode: TreeNode): any => ({
+ ...treeNode,
+ children: treeNode.children.map(convertTreeNodeToObservation),
+ });
+
+ const totalCost = calculateDisplayTotalCost({
+ allObservations:
+ node.children.length > 0
+ ? node.children.flatMap((child) =>
+ unnestObservation(convertTreeNodeToObservation(child)),
+ )
+ : [convertTreeNodeToObservation(node)],
+ });
+
+ const duration =
+ node.endTime && node.startTime
+ ? node.endTime.getTime() - node.startTime.getTime()
+ : node.latency
+ ? node.latency * 1000
+ : undefined;
+
+ const currentNodeRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (currentNodeId && currentNodeRef.current && currentNodeId === node.id) {
+ currentNodeRef.current.scrollIntoView({
+ behavior: "smooth",
+ block: "center",
+ });
+ }
+ }, [currentNodeId, node.id]);
+
+ return (
+ <Fragment>
+ <CommandItem
+ value={`${node.name} ${node.type} ${node.id}`}
+ className={cn(
+ "relative flex w-full rounded-md px-0 hover:rounded-lg hover:bg-muted/50",
+ currentNodeId === node.id && "bg-muted/40",
+ )}
+ style={{
+ paddingTop: 0,
+ paddingBottom: 0,
+ cursor: "pointer",
+ borderRadius: "0.5rem",
+ }}
+ onSelect={() =>
+ setCurrentNodeId(node.type === "TRACE" ? undefined : node.id)
+ }
+ >
+ <div className="flex w-full">
+ {/* Tree structure indicators */}
+ {indentationLevel > 0 && (
+ <div className="flex flex-shrink-0">
+ {/* Vertical lines for ancestor levels */}
+ {Array.from({ length: indentationLevel - 1 }, (_, i) => (
+ <div key={i} className="relative w-6">
+ {treeLines[i] && (
+ <div className="absolute bottom-0 left-3 top-0 w-px bg-border" />
+ )}
+ </div>
+ ))}
+ {/* Branch indicator for current level */}
+ <div className="relative w-6">
+ <div
+ className="absolute left-3 z-10 w-px bg-border"
+ style={{
+ top: 0,
+ bottom: isLastSibling ? "calc(100% - 12px)" : "12px",
+ }}
+ />
+ <div className="absolute left-3 top-3 h-px w-3 bg-border" />
+ {!isLastSibling && (
+ <div className="absolute bottom-0 left-3 top-3 w-px bg-border" />
+ )}
+ {/* Downward connector for nodes with children */}
+ {node.children.length > 0 && !collapsed && (
+ <div
+ className="absolute w-px bg-border"
+ style={{ left: "36px", top: "18px", bottom: 0 }}
+ />
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Downward connector for root nodes with children */}
+ {indentationLevel === 0 && node.children.length > 0 && !collapsed && (
+ <div
+ className="absolute w-px bg-border"
+ style={{ left: "20px", top: "18px", bottom: 0 }}
+ />
+ )}
+
+ {/* Node content */}
+ <div
+ className="flex min-w-0 flex-1 items-start gap-2 py-1"
+ ref={currentNodeRef}
+ >
+ {/* Icon */}
+ <div className="relative z-20 flex-shrink-0">
+ <ItemBadge type={node.type} isSmall className="scale-75" />
+ </div>
+
+ {/* Content that can wrap */}
+ <div className="flex min-w-0 flex-1 flex-col">
+ {/* First line: name, comments, level */}
+ <div className="flex min-w-0 items-center gap-2 overflow-hidden">
+ <span
+ className="flex-shrink truncate text-xs"
+ title={node.name}
+ >
+ {node.name}
+ </span>
+
+ {/* Comments and Level */}
+ <div className="flex items-center gap-2">
+ {comments && showComments ? (
+ <CommentCountIcon count={comments.get(node.id)} />
+ ) : null}
+ {/* Level badge (only for non-trace nodes) */}
+ {node.type !== "TRACE" &&
+ node.level &&
+ node.level !== "DEFAULT" ? (
+ <div className="flex">
+ <span
+ className={cn(
+ "rounded-sm p-0.5 text-xs",
+ LevelColors[node.level as keyof typeof LevelColors]
+ ?.bg,
+ LevelColors[node.level as keyof typeof LevelColors]
+ ?.text,
+ )}
+ >
+ {node.level}
+ </span>
+ </div>
+ ) : null}
+ </div>
+ </div>
+
+ {/* Metrics line */}
+ {showMetrics &&
+ (node.inputUsage ||
+ node.outputUsage ||
+ node.totalUsage ||
+ duration ||
+ totalCost ||
+ node.latency) && (
+ <div className="flex flex-wrap gap-2">
+ {duration || node.latency ? (
+ <span
+ title={
+ node.children.length > 0 || node.type === "TRACE"
+ ? "Aggregated duration of all child observations"
+ : undefined
+ }
+ className={cn(
+ "text-xs text-muted-foreground",
+ parentTotalDuration &&
+ colorCodeMetrics &&
+ heatMapTextColor({
+ max: parentTotalDuration,
+ value:
+ duration ||
+ (node.latency ? node.latency * 1000 : 0),
+ }),
+ )}
+ >
+ {formatIntervalSeconds(
+ (duration ||
+ (node.latency ? node.latency * 1000 : 0)) / 1000,
+ )}
+ </span>
+ ) : null}
+ {node.inputUsage || node.outputUsage || node.totalUsage ? (
+ <span className="text-xs text-muted-foreground">
+ {node.inputUsage} → {node.outputUsage} (∑{" "}
+ {node.totalUsage})
+ </span>
+ ) : null}
+ {totalCost ? (
+ <span
+ title={
+ node.children.length > 0 || node.type === "TRACE"
+ ? "Aggregated cost of all child observations"
+ : undefined
+ }
+ className={cn(
+ "text-xs text-muted-foreground",
+ parentTotalCost &&
+ colorCodeMetrics &&
+ heatMapTextColor({
+ max: parentTotalCost,
+ value: totalCost,
+ }),
+ )}
+ >
+ {node.children.length > 0 || node.type === "TRACE"
+ ? "∑ "
+ : ""}
+ {usdFormatter(totalCost.toNumber())}
+ </span>
+ ) : null}
+ </div>
+ )}
+
+ {/* Scores line */}
+ {showScores &&
+ ((node.type === "TRACE" &&
+ scores.find((s) => s.observationId === null)) ||
+ scores.find((s) => s.observationId === node.id)) && (
+ <div className="flex flex-wrap gap-1">
+ <GroupedScoreBadges
+ scores={
+ node.type === "TRACE"
+ ? scores.filter((s) => s.observationId === null)
+ : scores.filter((s) => s.observationId === node.id)
+ }
+ />
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Expand/Collapse button */}
+ {node.children.length > 0 && (
+ <div className="flex items-center justify-end py-1">
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={(ev) => {
+ ev.stopPropagation();
+ toggleCollapsedNode(node.id);
+ capture(
+ collapsed
+ ? "trace_detail:observation_tree_expand"
+ : "trace_detail:observation_tree_collapse",
+ { type: "single", nodeType: node.type },
+ );
+ }}
+ className="h-6 w-6 flex-shrink-0 hover:bg-primary/10"
+ >
+ <ChevronRight
+ className={cn(
+ "h-4 w-4 transition-transform duration-200",
+ !collapsed && "rotate-90",
+ )}
+ />
+ </Button>
+ </div>
+ )}
+ </div>
+ </CommandItem>
+
+ {/* Render children */}
+ {!collapsed && node.children.length > 0 && (
+ <div className="flex w-full flex-col">
+ {node.children
+ .sort((a, b) => a.startTime.getTime() - b.startTime.getTime())
+ .map((childNode, index) => {
+ const isChildLastSibling = index === node.children.length - 1;
+ // Add to treeLines: whether there are more children after this one (determines if vertical line should continue)
+ const childTreeLines = [...treeLines, !isChildLastSibling];
+
+ return (
+ <TreeNodeComponent
+ key={childNode.id}
+ node={childNode}
+ collapsedNodes={collapsedNodes}
+ toggleCollapsedNode={toggleCollapsedNode}
+ scores={scores}
+ comments={comments}
+ indentationLevel={indentationLevel + 1}
+ currentNodeId={currentNodeId}
+ setCurrentNodeId={setCurrentNodeId}
+ showMetrics={showMetrics}
+ showScores={showScores}
+ colorCodeMetrics={colorCodeMetrics}
+ parentTotalCost={parentTotalCost}
+ parentTotalDuration={parentTotalDuration}
+ showComments={showComments}
+ treeLines={childTreeLines}
+ isLastSibling={isChildLastSibling}
+ />
+ );
+ })}
+ </div>
+ )}
+ </Fragment>
+ );
+};
diff --git a/web/src/components/trace/hooks/usePanelState.ts b/web/src/components/trace/hooks/usePanelState.ts
new file mode 100644
index 0000000000..4019289e41
--- /dev/null
+++ b/web/src/components/trace/hooks/usePanelState.ts
@@ -0,0 +1,123 @@
+import {
+ useState,
+ useCallback,
+ useLayoutEffect,
+ useEffect,
+ useRef,
+} from "react";
+import useLocalStorage from "@/src/components/useLocalStorage";
+
+interface PanelState {
+ sizes: number[]; // [leftPanelSize, rightPanelSize]
+ minSize: number;
+ maxSize: number;
+}
+
+export function usePanelState(
+ containerRef: React.RefObject<HTMLDivElement>,
+ viewType: "timeline" | "tree",
+) {
+ const previousViewTypeRef = useRef<string>(viewType);
+
+ const [timelineSizes, setTimelineSizes] = useLocalStorage(
+ "trace-detail-timeline",
+ [30, 70],
+ );
+ const [treeSizes, setTreeSizes] = useLocalStorage(
+ "trace-detail-tree",
+ [30, 70],
+ );
+
+ const [panelState, setPanelState] = useState<PanelState>(() => {
+ const savedSizes = viewType === "timeline" ? timelineSizes : treeSizes;
+
+ return {
+ sizes: savedSizes,
+ minSize: 25, // Will be updated by ResizeObserver
+ maxSize: viewType === "timeline" ? 67 : 50, // Will be updated by ResizeObserver
+ };
+ });
+
+ // Handle view switching
+ useEffect(() => {
+ if (previousViewTypeRef.current !== viewType) {
+ const newSizes = viewType === "timeline" ? timelineSizes : treeSizes;
+
+ setPanelState((prev) => ({
+ ...prev,
+ sizes: newSizes,
+ maxSize: viewType === "timeline" ? 67 : 50,
+ }));
+
+ previousViewTypeRef.current = viewType;
+ }
+ }, [viewType, timelineSizes, treeSizes]);
+
+ const updateConstraints = useCallback(
+ (containerWidth: number) => {
+ const MIN_WIDTH_PX = 380;
+ const MAX_TREE_WIDTH_PX = 500;
+
+ if (containerWidth <= 0) return;
+
+ const minSize = Math.max(
+ 10,
+ Math.min(60, (MIN_WIDTH_PX / containerWidth) * 100),
+ );
+ const maxSize =
+ viewType === "timeline"
+ ? 67
+ : Math.max(25, (MAX_TREE_WIDTH_PX / containerWidth) * 100);
+
+ setPanelState((prev) => {
+ if (prev.minSize !== minSize || prev.maxSize !== maxSize) {
+ return { ...prev, minSize, maxSize };
+ }
+ return prev;
+ });
+ },
+ [viewType],
+ );
+
+ const onLayout = useCallback(
+ (sizes: number[]) => {
+ if (viewType === "timeline") {
+ setTimelineSizes(sizes);
+ } else {
+ setTreeSizes(sizes);
+ }
+
+ setPanelState((prev) => ({ ...prev, sizes }));
+ },
+ [viewType, setTimelineSizes, setTreeSizes],
+ );
+
+ // Handle container width changes
+ useLayoutEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+
+ const resizeObserver = new ResizeObserver((entries) => {
+ const entry = entries[0];
+ if (entry) {
+ updateConstraints(entry.contentRect.width);
+ }
+ });
+
+ // Initial calculation
+ updateConstraints(container.offsetWidth);
+
+ resizeObserver.observe(container);
+
+ return () => {
+ resizeObserver.disconnect();
+ };
+ }, [updateConstraints, containerRef]);
+
+ return {
+ sizes: panelState.sizes,
+ minSize: panelState.minSize,
+ maxSize: panelState.maxSize,
+ onLayout,
+ };
+}
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index 0a6af7ddc7..8fb449ea95 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -1,5 +1,5 @@
import { type ObservationLevelType, type TraceDomain } from "@langfuse/shared";
-import { ObservationTree } from "./ObservationTree";
+import { TraceTree } from "./TraceTree";
import { ObservationPreview } from "./ObservationPreview";
import { TracePreview } from "./TracePreview";
import {
@@ -12,11 +12,12 @@ import { api } from "@/src/utils/api";
import useLocalStorage from "@/src/components/useLocalStorage";
import {
Settings2,
- ChevronsUpDown,
- ChevronsDownUp,
Download,
+ FoldVertical,
+ UnfoldVertical,
} from "lucide-react";
-import { useCallback, useState } from "react";
+import { useCallback, useState, useMemo, useRef } from "react";
+import { usePanelState } from "./hooks/usePanelState";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { TraceTimelineView } from "@/src/components/trace/TraceTimelineView";
import { type APIScoreV2, ObservationLevel } from "@langfuse/shared";
@@ -35,11 +36,16 @@ import {
DropdownMenuSubTrigger,
DropdownMenuSubContent,
DropdownMenuLabel,
- DropdownMenuGroup,
} from "@/src/components/ui/dropdown-menu";
import { cn } from "@/src/utils/tailwind";
import useSessionStorage from "@/src/components/useSessionStorage";
import { JsonExpansionProvider } from "@/src/components/trace/JsonExpansionContext";
+import { buildTraceTree } from "@/src/components/trace/lib/helpers";
+import {
+ ResizablePanelGroup,
+ ResizablePanel,
+ ResizableHandle,
+} from "@/src/components/ui/resizable";
const getNestedObservationKeys = (
observations: ObservationReturnTypeWithMetadata[],
@@ -93,15 +99,20 @@ export function Trace(props: {
] = useLocalStorage("colorCodeMetricsOnObservationTree", true);
const [showComments, setShowComments] = useLocalStorage("showComments", true);
const [showGraph, setShowGraph] = useLocalStorage("showGraph", true);
- const [collapsedObservations, setCollapsedObservations] = useState<string[]>(
- [],
- );
+ const [collapsedNodes, setCollapsedNodes] = useState<string[]>([]);
const [minObservationLevel, setMinObservationLevel] =
useState<ObservationLevelType>(
props.defaultMinObservationLevel ?? ObservationLevel.DEFAULT,
);
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ const panelState = usePanelState(
+ containerRef,
+ props.selectedTab?.includes("timeline") ? "timeline" : "tree",
+ );
+
const isAuthenticatedAndProjectMember = useIsAuthenticatedAndProjectMember(
props.projectId,
);
@@ -164,50 +175,20 @@ export function Trace(props: {
const agentGraphData = agentGraphDataQuery.data ?? [];
const isGraphViewAvailable = agentGraphData.length > 0;
- const toggleCollapsedObservation = useCallback(
+ const toggleCollapsedNode = useCallback(
(id: string) => {
- if (collapsedObservations.includes(id)) {
- setCollapsedObservations(collapsedObservations.filter((i) => i !== id));
+ if (collapsedNodes.includes(id)) {
+ setCollapsedNodes(collapsedNodes.filter((i) => i !== id));
} else {
- setCollapsedObservations([...collapsedObservations, id]);
+ setCollapsedNodes([...collapsedNodes, id]);
}
},
- [collapsedObservations],
+ [collapsedNodes],
);
- const collapseAll = useCallback(() => {
- // exclude all parents of the current observation
- let excludeParentObservations = new Set<string>();
- let newExcludeParentObservations = new Set<string>();
- do {
- excludeParentObservations = new Set<string>([
- ...excludeParentObservations,
- ...newExcludeParentObservations,
- ]);
- newExcludeParentObservations = new Set<string>(
- props.observations
- .filter(
- (o) =>
- o.parentObservationId !== null &&
- (o.id === currentObservationId ||
- excludeParentObservations.has(o.id)),
- )
- .map((o) => o.parentObservationId as string)
- .filter((id) => !excludeParentObservations.has(id)),
- );
- } while (newExcludeParentObservations.size > 0);
- capture("trace_detail:observation_tree_collapse", { type: "all" });
- setCollapsedObservations(
- props.observations
- .map((o) => o.id)
- .filter((id) => !excludeParentObservations.has(id)),
- );
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [props.observations, currentObservationId]);
-
const expandAll = useCallback(() => {
capture("trace_detail:observation_tree_expand", { type: "all" });
- setCollapsedObservations([]);
+ setCollapsedNodes([]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
@@ -237,211 +218,325 @@ export function Trace(props: {
[`trace-${props.trace.id}`],
);
+ // Build unified tree structure
+ const { tree: traceTree, hiddenObservationsCount } = useMemo(
+ () => buildTraceTree(props.trace, props.observations, minObservationLevel),
+ [props.trace, props.observations, minObservationLevel],
+ );
+
return (
<JsonExpansionProvider>
<div
- className={cn(
- "flex-1 gap-4 overflow-y-auto md:grid md:h-full md:grid-cols-5",
- props.selectedTab?.includes("timeline")
- ? "md:grid-cols-[3fr_2fr] xl:grid-cols-[4fr_2fr]"
- : "md:grid-cols-[2fr_3fr] xl:grid-cols-[2fr_4fr]",
- )}
+ ref={containerRef}
+ className="flex-1 md:h-full"
+ style={{ minWidth: "600px" }}
>
- <div className="border-r md:flex md:h-full md:flex-col md:overflow-hidden">
- <Command className="mt-2 flex h-full flex-col gap-2 overflow-hidden rounded-none border-0">
- <div className="flex flex-row justify-between px-3 pl-5">
- {props.selectedTab?.includes("timeline") ? (
- <div className="flex h-full items-center gap-1">
- <Button
- onClick={() => {
- setExpandedItems([
- `trace-${props.trace.id}`,
- ...getNestedObservationKeys(props.observations),
- ]);
- }}
- size="xs"
- variant="ghost"
- title="Expand all"
- className="px-0 text-muted-foreground"
- >
- <ChevronsUpDown className="h-4 w-4" />
- </Button>
- <Button
- onClick={() => setExpandedItems([])}
- size="xs"
- variant="ghost"
- title="Collapse all"
- className="px-0 text-muted-foreground"
- >
- <ChevronsDownUp className="h-4 w-4" />
- </Button>
- <span className="px-1 py-2 text-sm text-muted-foreground">
+ <ResizablePanelGroup
+ direction="horizontal"
+ className="flex-1 md:h-full"
+ onLayout={panelState.onLayout}
+ >
+ <ResizablePanel
+ defaultSize={panelState.sizes[0]}
+ minSize={panelState.minSize}
+ maxSize={panelState.maxSize}
+ className="md:flex md:h-full md:flex-col md:overflow-hidden"
+ >
+ <Command className="mt-2 flex h-full flex-col gap-2 overflow-hidden rounded-none border-0">
+ <div className="flex flex-row justify-between px-3 pl-5">
+ {props.selectedTab?.includes("timeline") ? (
+ <span className="whitespace-nowrap px-1 py-2 text-sm text-muted-foreground">
Node display
</span>
- </div>
- ) : (
- <CommandInput
- showBorder={false}
- placeholder="Search (type, title, id)"
- className="-ml-2 h-9 border-0 focus:ring-0"
- />
- )}
- {viewType === "detailed" && (
- <div className="flex flex-row items-center gap-2">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="icon">
- <Settings2 className="h-4 w-4" />
+ ) : (
+ <CommandInput
+ showBorder={false}
+ placeholder="Search"
+ className="-ml-2 h-9 min-w-20 border-0 focus:ring-0"
+ />
+ )}
+ {viewType === "detailed" && (
+ <div className="flex flex-row items-center gap-2">
+ {props.selectedTab?.includes("timeline") ? (
+ <Button
+ onClick={() => {
+ // Check if trace is expanded (top level element)
+ const isTraceExpanded = expandedItems.includes(
+ `trace-${props.trace.id}`,
+ );
+ if (isTraceExpanded) {
+ setExpandedItems([]);
+ } else {
+ setExpandedItems([
+ `trace-${props.trace.id}`,
+ ...getNestedObservationKeys(props.observations),
+ ]);
+ }
+ }}
+ variant="ghost"
+ size="icon"
+ title={
+ expandedItems.includes(`trace-${props.trace.id}`)
+ ? "Collapse all"
+ : "Expand all"
+ }
+ >
+ {expandedItems.includes(`trace-${props.trace.id}`) ? (
+ <FoldVertical className="h-4 w-4" />
+ ) : (
+ <UnfoldVertical className="h-4 w-4" />
+ )}
</Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuLabel>Settings</DropdownMenuLabel>
- <DropdownMenuSeparator />
+ ) : (
+ (() => {
+ // Check if anything is expanded by seeing if the trace is collapsed
+ const isEverythingCollapsed = collapsedNodes.includes(
+ props.trace.id,
+ );
+
+ return (
+ <Button
+ onClick={() => {
+ if (isEverythingCollapsed) {
+ expandAll();
+ } else {
+ // Collapse all observations AND the trace
+ const allObservationIds =
+ props.observations.map((o) => o.id);
+ setCollapsedNodes([
+ ...allObservationIds,
+ props.trace.id,
+ ]);
+ }
+ }}
+ variant="ghost"
+ size="icon"
+ title={
+ isEverythingCollapsed
+ ? "Expand all"
+ : "Collapse all"
+ }
+ >
+ {isEverythingCollapsed ? (
+ <UnfoldVertical className="h-4 w-4" />
+ ) : (
+ <FoldVertical className="h-4 w-4" />
+ )}
+ </Button>
+ );
+ })()
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ title="View Options"
+ >
+ <Settings2 className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-56">
+ <DropdownMenuLabel>View Options</DropdownMenuLabel>
+ <DropdownMenuSeparator />
- {isGraphViewAvailable && (
- <>
+ {isGraphViewAvailable && (
+ <div className="p-1">
+ <DropdownMenuItem
+ asChild
+ onSelect={(e) => e.preventDefault()}
+ >
+ <div className="flex w-full items-center justify-between">
+ <span className="mr-2">Show Graph</span>
+ <Switch
+ checked={showGraph}
+ onCheckedChange={(e) => setShowGraph(e)}
+ />
+ </div>
+ </DropdownMenuItem>
+ </div>
+ )}
+
+ <div className="space-y-1 p-1">
<DropdownMenuItem
asChild
onSelect={(e) => e.preventDefault()}
>
<div className="flex w-full items-center justify-between">
- <span className="mr-2">Show Graph</span>
+ <span className="mr-2">Show Comments</span>
<Switch
- checked={showGraph}
- onCheckedChange={(e) => setShowGraph(e)}
+ checked={showComments}
+ onCheckedChange={(e) => {
+ setShowComments(e);
+ }}
/>
</div>
</DropdownMenuItem>
- <DropdownMenuSeparator />
- </>
- )}
-
- <DropdownMenuGroup>
- <DropdownMenuItem
- asChild
- onSelect={(e) => e.preventDefault()}
- >
- <div className="flex w-full items-center justify-between">
- <span className="mr-2">Show Comments</span>
- <Switch
- checked={showComments}
- onCheckedChange={(e) => {
- setShowComments(e);
- }}
- />
- </div>
- </DropdownMenuItem>
-
- <DropdownMenuItem
- asChild
- onSelect={(e) => e.preventDefault()}
- >
- <div className="flex w-full items-center justify-between">
- <span className="mr-2">Show Scores</span>
- <Switch
- checked={scoresOnObservationTree}
- onCheckedChange={(e) => {
- capture(
- "trace_detail:observation_tree_toggle_scores",
- {
- show: e,
- },
- );
- setScoresOnObservationTree(e);
- }}
- />
- </div>
- </DropdownMenuItem>
- <DropdownMenuItem
- asChild
- onSelect={(e) => e.preventDefault()}
- >
- <div className="flex w-full items-center justify-between">
- <span className="mr-2">Show Metrics</span>
- <Switch
- checked={metricsOnObservationTree}
- onCheckedChange={(e) => {
- capture(
- "trace_detail:observation_tree_toggle_metrics",
- {
- show: e,
- },
- );
- setMetricsOnObservationTree(e);
- }}
- />
- </div>
- </DropdownMenuItem>
+ <DropdownMenuItem
+ asChild
+ onSelect={(e) => e.preventDefault()}
+ >
+ <div className="flex w-full items-center justify-between">
+ <span className="mr-2">Show Scores</span>
+ <Switch
+ checked={scoresOnObservationTree}
+ onCheckedChange={(e) => {
+ capture(
+ "trace_detail:observation_tree_toggle_scores",
+ {
+ show: e,
+ },
+ );
+ setScoresOnObservationTree(e);
+ }}
+ />
+ </div>
+ </DropdownMenuItem>
- <DropdownMenuItem
- asChild
- onSelect={(e) => e.preventDefault()}
- >
- <div className="flex w-full items-center justify-between">
- <span className="mr-2">Color Code Metrics</span>
- <Switch
- checked={colorCodeMetricsOnObservationTree}
- onCheckedChange={(e) =>
- setColorCodeMetricsOnObservationTree(e)
- }
- />
- </div>
- </DropdownMenuItem>
- </DropdownMenuGroup>
- <DropdownMenuSeparator />
+ <DropdownMenuItem
+ asChild
+ onSelect={(e) => e.preventDefault()}
+ >
+ <div className="flex w-full items-center justify-between">
+ <span className="mr-2">Show Metrics</span>
+ <Switch
+ checked={metricsOnObservationTree}
+ onCheckedChange={(e) => {
+ capture(
+ "trace_detail:observation_tree_toggle_metrics",
+ {
+ show: e,
+ },
+ );
+ setMetricsOnObservationTree(e);
+ }}
+ />
+ </div>
+ </DropdownMenuItem>
- <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);
- }}
+ <DropdownMenuItem
+ asChild
+ onSelect={(e) => e.preventDefault()}
+ disabled={!metricsOnObservationTree}
+ className={cn(
+ !metricsOnObservationTree && "cursor-not-allowed",
+ )}
+ >
+ <div
+ className={cn(
+ "flex w-full items-center justify-between",
+ !metricsOnObservationTree &&
+ "cursor-not-allowed",
+ )}
>
- {level}
- </DropdownMenuItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- </DropdownMenuContent>
- </DropdownMenu>
- <Button
- variant="ghost"
- size="icon"
- onClick={downloadTraceAsJson}
- title="Download trace as JSON"
- >
- <Download className="h-4 w-4" />
- </Button>
- <Switch
- checked={props.selectedTab?.includes("timeline")}
- onCheckedChange={(checked) =>
- props.setSelectedTab?.(checked ? "timeline" : "preview")
- }
- ></Switch>
- <span className="text-sm">Timeline</span>
- </div>
- )}
- </div>
- <div className="h-full overflow-hidden">
- {props.selectedTab?.includes("timeline") ? (
- <div className="h-full w-full flex-1 flex-col overflow-hidden">
- {isGraphViewAvailable && showGraph ? (
- <div className="flex h-full w-full flex-col overflow-hidden">
- <div className="h-1/2 w-full overflow-y-auto overflow-x-hidden">
+ <span
+ className={cn(
+ "mr-2",
+ !metricsOnObservationTree &&
+ "cursor-not-allowed",
+ )}
+ >
+ Color Code Metrics
+ </span>
+ <Switch
+ checked={colorCodeMetricsOnObservationTree}
+ onCheckedChange={(e) =>
+ setColorCodeMetricsOnObservationTree(e)
+ }
+ disabled={!metricsOnObservationTree}
+ className={cn(
+ !metricsOnObservationTree &&
+ "cursor-not-allowed",
+ )}
+ />
+ </div>
+ </DropdownMenuItem>
+ </div>
+
+ <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>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={downloadTraceAsJson}
+ title="Download trace as JSON"
+ >
+ <Download className="h-4 w-4" />
+ </Button>
+ <label className="flex cursor-pointer items-center gap-2">
+ <Switch
+ checked={props.selectedTab?.includes("timeline")}
+ onCheckedChange={(checked) =>
+ props.setSelectedTab?.(
+ checked ? "timeline" : "preview",
+ "replaceIn",
+ )
+ }
+ />
+ <span className="text-sm">Timeline</span>
+ </label>
+ </div>
+ )}
+ </div>
+ <div className="h-full overflow-hidden">
+ {props.selectedTab?.includes("timeline") ? (
+ <div className="h-full w-full flex-1 flex-col overflow-hidden">
+ {isGraphViewAvailable && showGraph ? (
+ <div className="flex h-full w-full flex-col overflow-hidden">
+ <div className="h-1/2 w-full overflow-y-auto overflow-x-hidden">
+ <TraceTimelineView
+ key={`timeline-${props.trace.id}`}
+ trace={props.trace}
+ scores={props.scores}
+ observations={props.observations}
+ projectId={props.trace.projectId}
+ currentObservationId={currentObservationId ?? null}
+ setCurrentObservationId={setCurrentObservationId}
+ expandedItems={expandedItems}
+ setExpandedItems={setExpandedItems}
+ showMetrics={metricsOnObservationTree}
+ showScores={scoresOnObservationTree}
+ showComments={showComments}
+ colorCodeMetrics={colorCodeMetricsOnObservationTree}
+ minLevel={minObservationLevel}
+ setMinLevel={setMinObservationLevel}
+ />
+ </div>
+ <div className="h-1/2 w-full overflow-hidden border-t">
+ <TraceGraphView
+ key={`graph-timeline-${props.trace.id}`}
+ agentGraphData={agentGraphData}
+ />
+ </div>
+ </div>
+ ) : (
+ <div className="flex h-full w-full overflow-y-auto overflow-x-hidden">
<TraceTimelineView
- key={`timeline-${props.trace.id}`}
+ key={props.trace.id}
trace={props.trace}
scores={props.scores}
observations={props.observations}
@@ -458,127 +553,139 @@ export function Trace(props: {
setMinLevel={setMinObservationLevel}
/>
</div>
- <div className="h-1/2 w-full overflow-hidden border-t">
- <TraceGraphView
- key={`graph-timeline-${props.trace.id}`}
- agentGraphData={agentGraphData}
- />
+ )}
+ </div>
+ ) : (
+ <div className="h-full w-full flex-1 flex-col overflow-hidden">
+ {isGraphViewAvailable && showGraph ? (
+ <div className="flex h-full w-full flex-col overflow-hidden">
+ <div className="h-1/2 w-full overflow-y-auto">
+ <TraceTree
+ tree={traceTree}
+ collapsedNodes={collapsedNodes}
+ toggleCollapsedNode={toggleCollapsedNode}
+ scores={props.scores}
+ currentNodeId={currentObservationId ?? undefined}
+ setCurrentNodeId={setCurrentObservationId}
+ showMetrics={metricsOnObservationTree}
+ showScores={scoresOnObservationTree}
+ showComments={showComments}
+ colorCodeMetrics={colorCodeMetricsOnObservationTree}
+ nodeCommentCounts={
+ new Map(
+ [
+ ...(observationCommentCounts.data
+ ? Array.from(
+ observationCommentCounts.data.entries(),
+ )
+ : []),
+ ...(traceCommentCounts.data
+ ? [
+ [
+ props.trace.id,
+ traceCommentCounts.data.get(
+ props.trace.id,
+ ),
+ ],
+ ]
+ : []),
+ ].filter(
+ ([, count]) => count !== undefined,
+ ) as [string, number][],
+ )
+ }
+ className="flex w-full flex-col px-3"
+ hiddenObservationsCount={hiddenObservationsCount}
+ minLevel={minObservationLevel}
+ setMinLevel={setMinObservationLevel}
+ />
+ </div>
+ <div className="h-1/2 w-full overflow-hidden border-t">
+ <TraceGraphView
+ key={`graph-tree-${props.trace.id}`}
+ agentGraphData={agentGraphData}
+ />
+ </div>
</div>
- </div>
- ) : (
- <div className="flex h-full w-full overflow-y-auto overflow-x-hidden">
- <TraceTimelineView
- key={props.trace.id}
- trace={props.trace}
- scores={props.scores}
- observations={props.observations}
- projectId={props.trace.projectId}
- currentObservationId={currentObservationId ?? null}
- setCurrentObservationId={setCurrentObservationId}
- expandedItems={expandedItems}
- setExpandedItems={setExpandedItems}
- showMetrics={metricsOnObservationTree}
- showScores={scoresOnObservationTree}
- showComments={showComments}
- colorCodeMetrics={colorCodeMetricsOnObservationTree}
- minLevel={minObservationLevel}
- setMinLevel={setMinObservationLevel}
- />
- </div>
- )}
- </div>
- ) : (
- <div className="h-full w-full flex-1 flex-col overflow-hidden">
- {isGraphViewAvailable && showGraph ? (
- <div className="flex h-full w-full flex-col overflow-hidden">
- <div className="h-1/2 w-full overflow-y-auto">
- <ObservationTree
- observations={props.observations}
- collapsedObservations={collapsedObservations}
- toggleCollapsedObservation={
- toggleCollapsedObservation
- }
- collapseAll={collapseAll}
- expandAll={expandAll}
- trace={props.trace}
+ ) : (
+ <div className="flex h-full w-full overflow-auto">
+ <TraceTree
+ tree={traceTree}
+ collapsedNodes={collapsedNodes}
+ toggleCollapsedNode={toggleCollapsedNode}
scores={props.scores}
- currentObservationId={
- currentObservationId ?? undefined
- }
- setCurrentObservationId={setCurrentObservationId}
+ currentNodeId={currentObservationId ?? undefined}
+ setCurrentNodeId={setCurrentObservationId}
showMetrics={metricsOnObservationTree}
showScores={scoresOnObservationTree}
showComments={showComments}
colorCodeMetrics={colorCodeMetricsOnObservationTree}
- observationCommentCounts={
- observationCommentCounts.data
+ nodeCommentCounts={
+ new Map(
+ [
+ ...(observationCommentCounts.data
+ ? Array.from(
+ observationCommentCounts.data.entries(),
+ )
+ : []),
+ ...(traceCommentCounts.data
+ ? [
+ [
+ props.trace.id,
+ traceCommentCounts.data.get(
+ props.trace.id,
+ ),
+ ],
+ ]
+ : []),
+ ].filter(([, count]) => count !== undefined) as [
+ string,
+ number,
+ ][],
+ )
}
- traceCommentCounts={traceCommentCounts.data}
className="flex w-full flex-col px-3"
+ hiddenObservationsCount={hiddenObservationsCount}
minLevel={minObservationLevel}
setMinLevel={setMinObservationLevel}
/>
</div>
- <div className="h-1/2 w-full overflow-hidden border-t">
- <TraceGraphView
- key={`graph-tree-${props.trace.id}`}
- agentGraphData={agentGraphData}
- />
- </div>
- </div>
- ) : (
- <div className="flex h-full w-full overflow-auto">
- <ObservationTree
- observations={props.observations}
- collapsedObservations={collapsedObservations}
- toggleCollapsedObservation={toggleCollapsedObservation}
- collapseAll={collapseAll}
- expandAll={expandAll}
- trace={props.trace}
- scores={props.scores}
- currentObservationId={currentObservationId ?? undefined}
- setCurrentObservationId={setCurrentObservationId}
- showMetrics={metricsOnObservationTree}
- showScores={scoresOnObservationTree}
- showComments={showComments}
- colorCodeMetrics={colorCodeMetricsOnObservationTree}
- observationCommentCounts={observationCommentCounts.data}
- traceCommentCounts={traceCommentCounts.data}
- className="flex w-full flex-col px-3"
- minLevel={minObservationLevel}
- setMinLevel={setMinObservationLevel}
- />
- </div>
- )}
- </div>
- )}
+ )}
+ </div>
+ )}
+ </div>
+ </Command>
+ </ResizablePanel>
+
+ <ResizableHandle className="relative w-px bg-border transition-colors duration-200 after:absolute after:inset-y-0 after:left-0 after:w-1 after:-translate-x-px after:bg-blue-200 after:opacity-0 after:transition-opacity after:duration-200 hover:after:opacity-100 data-[resize-handle-state='drag']:after:opacity-100" />
+
+ <ResizablePanel className="min-w-56 overflow-hidden md:h-full">
+ <div className="h-full pl-3">
+ {currentObservationId === undefined ||
+ currentObservationId === "" ||
+ currentObservationId === null ? (
+ <TracePreview
+ trace={props.trace}
+ observations={props.observations}
+ scores={props.scores}
+ commentCounts={traceCommentCounts.data}
+ viewType={viewType}
+ />
+ ) : isValidObservationId ? (
+ <ObservationPreview
+ observations={props.observations}
+ scores={props.scores}
+ projectId={props.projectId}
+ currentObservationId={currentObservationId}
+ traceId={props.trace.id}
+ commentCounts={observationCommentCounts.data}
+ viewType={viewType}
+ isTimeline={props.selectedTab?.includes("timeline")}
+ />
+ ) : null}
</div>
- </Command>
- </div>
- <div className="overflow-hidden pl-3 md:h-full md:p-0">
- {currentObservationId === undefined ||
- currentObservationId === "" ||
- currentObservationId === null ? (
- <TracePreview
- trace={props.trace}
- observations={props.observations}
- scores={props.scores}
- commentCounts={traceCommentCounts.data}
- viewType={viewType}
- />
- ) : isValidObservationId ? (
- <ObservationPreview
- observations={props.observations}
- scores={props.scores}
- projectId={props.projectId}
- currentObservationId={currentObservationId}
- traceId={props.trace.id}
- commentCounts={observationCommentCounts.data}
- viewType={viewType}
- isTimeline={props.selectedTab?.includes("timeline")}
- />
- ) : null}
- </div>
+ </ResizablePanel>
+ </ResizablePanelGroup>
</div>
</JsonExpansionProvider>
);
diff --git a/web/src/components/trace/lib/helpers.ts b/web/src/components/trace/lib/helpers.ts
index 444f77f17c..f3430fe442 100644
--- a/web/src/components/trace/lib/helpers.ts
+++ b/web/src/components/trace/lib/helpers.ts
@@ -1,10 +1,12 @@
import { type NestedObservation } from "@/src/utils/types";
+import { type TreeNode } from "./types";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import Decimal from "decimal.js";
import {
type ObservationType,
type ObservationLevelType,
ObservationLevel,
+ type TraceDomain,
} from "@langfuse/shared";
export type TreeItemType = ObservationType | "TRACE";
@@ -191,3 +193,60 @@ export const unnestObservation = (nestedObservation: NestedObservation) => {
});
return unnestedObservations;
};
+
+// Transform trace + observations into unified tree structure
+export function buildTraceTree(
+ trace: Omit<TraceDomain, "input" | "output" | "metadata"> & {
+ input: string | null;
+ output: string | null;
+ metadata: string | null;
+ latency?: number;
+ },
+ observations: ObservationReturnType[],
+ minLevel?: ObservationLevelType,
+): {
+ tree: TreeNode;
+ hiddenObservationsCount: number;
+} {
+ // First, nest the observations as before
+ const { nestedObservations, hiddenObservationsCount } = nestObservations(
+ observations,
+ minLevel,
+ );
+
+ // Convert observations to TreeNodes
+ const convertObservationToTreeNode = (obs: NestedObservation): TreeNode => ({
+ id: obs.id,
+ type: obs.type,
+ name: obs.name ?? "",
+ startTime: obs.startTime,
+ endTime: obs.endTime,
+ level: obs.level,
+ children: obs.children.map(convertObservationToTreeNode),
+ inputUsage: obs.inputUsage,
+ outputUsage: obs.outputUsage,
+ totalUsage: obs.totalUsage,
+ calculatedInputCost:
+ "calculatedInputCost" in obs ? obs.calculatedInputCost : undefined,
+ calculatedOutputCost:
+ "calculatedOutputCost" in obs ? obs.calculatedOutputCost : undefined,
+ calculatedTotalCost:
+ "calculatedTotalCost" in obs ? obs.calculatedTotalCost : undefined,
+ parentObservationId: obs.parentObservationId,
+ traceId: obs.traceId,
+ });
+
+ // Create the root tree node (trace)
+ // Use a unique ID for the trace root to avoid conflicts with observations that might have the same ID
+ const tree: TreeNode = {
+ id: `trace-${trace.id}`,
+ type: "TRACE",
+ name: trace.name ?? "",
+ startTime: trace.timestamp,
+ endTime: null, // traces don't have explicit end times
+ children: nestedObservations.map(convertObservationToTreeNode),
+ latency: trace.latency,
+ };
+
+ return { tree, hiddenObservationsCount };
+}
diff --git a/web/src/components/trace/lib/types.ts b/web/src/components/trace/lib/types.ts
new file mode 100644
index 0000000000..beae64bb52
--- /dev/null
+++ b/web/src/components/trace/lib/types.ts
@@ -0,0 +1,24 @@
+import { type ObservationType } from "@langfuse/shared";
+
+// Unified tree node type for trace tree component
+export type TreeNode = {
+ id: string;
+ type: "TRACE" | ObservationType;
+ name: string;
+ startTime: Date;
+ endTime?: Date | null;
+ level?: string;
+ children: TreeNode[];
+ // Common properties
+ inputUsage?: number | null;
+ outputUsage?: number | null;
+ totalUsage?: number | null;
+ calculatedInputCost?: any;
+ calculatedOutputCost?: any;
+ calculatedTotalCost?: any;
+ // Trace-specific properties (when type === 'TRACE')
+ latency?: number;
+ // Observation-specific properties (when type !== 'TRACE')
+ parentObservationId?: string | null;
+ traceId?: string;
+};