Skip to content

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

feat(trace-detail): improved search that works well with new trace tree (#8604)

Leo Weigand8cd2b8867ef4
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 7b42f95419..26343cf6a6 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -28,5 +28,6 @@
"editor.defaultFormatter": "Prisma.prisma"
},
"eslint.lintTask.enable": true,
- "eslint.workingDirectories": ["./web", "./worker"]
+ "eslint.workingDirectories": ["./web", "./worker"],
+ "eslint.useFlatConfig": false
}
diff --git a/web/src/components/grouped-score-badge.tsx b/web/src/components/grouped-score-badge.tsx
index e1d689e2d7..34215e138c 100644
--- a/web/src/components/grouped-score-badge.tsx
+++ b/web/src/components/grouped-score-badge.tsx
@@ -38,17 +38,24 @@ const hasMetadata = (score: APIScoreV2 | LastUserScore) => {
const ScoreGroupBadge = <T extends APIScoreV2 | LastUserScore>({
name,
scores,
+ compact,
+ badgeClassName,
}: {
name: string;
scores: T[];
+ compact?: boolean;
+ badgeClassName?: string;
}) => {
return (
<Badge
variant="tertiary"
key={name}
- className="flex items-center gap-1 px-2.5 text-xs font-normal"
+ className={`flex items-center gap-1 ${compact ? "px-1.5 leading-tight" : "px-2.5"} text-xs font-normal${badgeClassName ? " " + badgeClassName : ""}`}
>
- <div className="w-fit max-w-20 truncate" title={name}>
+ <div
+ className={`w-fit max-w-20 truncate ${compact ? "leading-tight" : ""}`}
+ title={name}
+ >
{name}:
</div>
<div className="flex items-center gap-1 text-nowrap">
@@ -89,9 +96,13 @@ const ScoreGroupBadge = <T extends APIScoreV2 | LastUserScore>({
export const GroupedScoreBadges = <T extends APIScoreV2 | LastUserScore>({
scores,
maxVisible,
+ compact,
+ badgeClassName,
}: {
scores: T[];
maxVisible?: number;
+ compact?: boolean;
+ badgeClassName?: string;
}) => {
const groupedScores = scores.reduce<Record<string, T[]>>((acc, score) => {
if (!acc[score.name] || !Array.isArray(acc[score.name])) {
@@ -110,13 +121,19 @@ export const GroupedScoreBadges = <T extends APIScoreV2 | LastUserScore>({
return (
<>
{visibleScores.map(([name, scores]) => (
- <ScoreGroupBadge key={name} name={name} scores={scores} />
+ <ScoreGroupBadge
+ key={name}
+ name={name}
+ scores={scores}
+ compact={compact}
+ badgeClassName={badgeClassName}
+ />
))}
{Boolean(hiddenScores.length) && (
<HoverCard>
<HoverCardTrigger className="inline-block rounded-sm">
<Badge
- className="cursor-pointer px-1 text-xs font-medium"
+ className={`cursor-pointer ${compact ? "px-0.5 py-0 leading-tight" : "px-1"} text-xs font-medium${badgeClassName ? " " + badgeClassName : ""}`}
variant="tertiary"
>
+{hiddenScores.length}
@@ -125,7 +142,13 @@ export const GroupedScoreBadges = <T extends APIScoreV2 | LastUserScore>({
<HoverCardContent className="max-h-[300px] max-w-[200px] overflow-y-auto p-2">
<div className="flex flex-wrap gap-1">
{hiddenScores.map(([name, scores]) => (
- <ScoreGroupBadge key={name} name={name} scores={scores} />
+ <ScoreGroupBadge
+ key={name}
+ name={name}
+ scores={scores}
+ compact={compact}
+ badgeClassName={badgeClassName}
+ />
))}
</div>
</HoverCardContent>
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 b139c4f4be..799dcb0b36 100644
--- a/web/src/components/table/peek/peek-dataset-compare-detail.tsx
+++ b/web/src/components/table/peek/peek-dataset-compare-detail.tsx
@@ -18,7 +18,7 @@ import type { DatasetCompareRunRowData } from "@/src/features/datasets/component
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";
+import { buildTraceUiData } from "@/src/components/trace/lib/helpers";
export type PeekDatasetCompareDetailProps = {
projectId: string;
@@ -54,7 +54,7 @@ export const PeekDatasetCompareDetail = ({
const tree = useMemo(() => {
if (!trace.data) return null;
- const { tree } = buildTraceTree(
+ const { tree } = buildTraceUiData(
trace.data,
trace.data.observations ?? [],
"DEFAULT",
diff --git a/web/src/components/trace/SpanItem.tsx b/web/src/components/trace/SpanItem.tsx
new file mode 100644
index 0000000000..699c179563
--- /dev/null
+++ b/web/src/components/trace/SpanItem.tsx
@@ -0,0 +1,177 @@
+import { type TreeNode } from "./lib/types";
+import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
+import { ItemBadge } from "@/src/components/ItemBadge";
+import { LevelColors } from "@/src/components/level-colors";
+import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";
+import { cn } from "@/src/utils/tailwind";
+import { formatIntervalSeconds } from "@/src/utils/dates";
+import { usdFormatter } from "@/src/utils/numbers";
+import {
+ calculateDisplayTotalCost,
+ heatMapTextColor,
+ unnestObservation,
+} from "@/src/components/trace/lib/helpers";
+import { type APIScoreV2 } from "@langfuse/shared";
+import type Decimal from "decimal.js";
+import React from "react";
+
+export interface SpanItemProps {
+ node: TreeNode;
+ scores: APIScoreV2[];
+ comments?: Map<string, number>;
+ showMetrics: boolean;
+ showScores: boolean;
+ colorCodeMetrics: boolean;
+ parentTotalCost?: Decimal;
+ parentTotalDuration?: number;
+ showComments?: boolean;
+ className?: string;
+}
+
+export const SpanItem: React.FC<SpanItemProps> = ({
+ node,
+ scores,
+ comments,
+ showMetrics,
+ showScores,
+ colorCodeMetrics,
+ parentTotalCost,
+ parentTotalDuration,
+ showComments = true,
+ className,
+}) => {
+ 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;
+
+ return (
+ <div className={cn("flex min-w-0 items-start gap-2", className)}>
+ <div className="relative z-20 flex-shrink-0">
+ <ItemBadge type={node.type} isSmall className="!size-3" />
+ </div>
+
+ <div className="flex min-w-0 flex-1 flex-col">
+ <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>
+
+ <div className="flex items-center gap-2">
+ {comments && showComments ? (
+ <CommentCountIcon count={comments.get(node.id)} />
+ ) : null}
+ {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>
+
+ {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>
+ )}
+
+ {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
+ compact
+ scores={
+ node.type === "TRACE"
+ ? scores.filter((s) => s.observationId === null)
+ : scores.filter((s) => s.observationId === node.id)
+ }
+ />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/web/src/components/trace/TracePage.tsx b/web/src/components/trace/TracePage.tsx
index 1d7a10dd47..adefdc5e48 100644
--- a/web/src/components/trace/TracePage.tsx
+++ b/web/src/components/trace/TracePage.tsx
@@ -162,7 +162,6 @@ export function TracePage({
>
<div className="flex max-h-full min-h-0 flex-1 overflow-hidden">
<Trace
- key={trace.data.id}
trace={trace.data}
scores={trace.data.scores}
projectId={trace.data.projectId}
diff --git a/web/src/components/trace/TraceSearchList.tsx b/web/src/components/trace/TraceSearchList.tsx
new file mode 100644
index 0000000000..c5e191ff51
--- /dev/null
+++ b/web/src/components/trace/TraceSearchList.tsx
@@ -0,0 +1,96 @@
+import React from "react";
+import {
+ CommandEmpty,
+ CommandGroup,
+ CommandItem,
+ CommandList,
+} from "@/src/components/ui/command";
+import { SpanItem } from "@/src/components/trace/SpanItem";
+import { type APIScoreV2 } from "@langfuse/shared";
+import type Decimal from "decimal.js";
+import { type TreeNode } from "./lib/types";
+
+export interface TraceSearchListItem {
+ node: TreeNode;
+ parentTotalCost?: Decimal;
+ parentTotalDuration?: number;
+ observationId?: string; // The actual observation ID to use for navigation (undefined for TRACE nodes)
+}
+
+export interface TraceSearchListProps {
+ items: TraceSearchListItem[];
+ scores: APIScoreV2[];
+ onSelect: (observationId: string | undefined) => void;
+ comments?: Map<string, number>;
+ showMetrics: boolean;
+ showScores: boolean;
+ colorCodeMetrics: boolean;
+ showComments?: boolean;
+ onClearSearch?: () => void;
+}
+
+export const TraceSearchList: React.FC<TraceSearchListProps> = ({
+ items,
+ scores,
+ onSelect,
+ comments,
+ showMetrics,
+ showScores,
+ colorCodeMetrics,
+ showComments = true,
+ onClearSearch,
+}) => {
+ return (
+ <div className="w-full">
+ <CommandList className="max-h-none w-full overflow-x-hidden overflow-y-visible">
+ <CommandGroup className="p-0">
+ {items.map(
+ ({ node, parentTotalCost, parentTotalDuration, observationId }) => (
+ <CommandItem
+ key={node.id}
+ value={`${node.name} ${node.type} ${node.id}`}
+ className="relative flex w-full !rounded-lg !py-1.5 px-2 hover:bg-muted/40 data-[selected=true]:!text-foreground"
+ onSelect={() => onSelect(observationId)}
+ >
+ <div className="flex w-full">
+ <div className="flex min-w-0 flex-1 items-start gap-2">
+ <SpanItem
+ node={node}
+ scores={scores}
+ comments={comments}
+ showMetrics={showMetrics}
+ showScores={showScores}
+ colorCodeMetrics={colorCodeMetrics}
+ parentTotalCost={parentTotalCost}
+ parentTotalDuration={parentTotalDuration}
+ showComments={showComments}
+ />
+ </div>
+ </div>
+ </CommandItem>
+ ),
+ )}
+ </CommandGroup>
+ <CommandEmpty>
+ <div className="flex w-full justify-center">
+ <div className="flex w-48 flex-col py-4 text-muted-foreground">
+ <span className="mb-2 font-semibold">No results found</span>
+ <span className="text-xs">
+ Try searching by type, title, or id.
+ </span>
+ </div>
+ </div>
+ </CommandEmpty>
+ </CommandList>
+ {onClearSearch && items.length > 0 ? (
+ <button
+ type="button"
+ className="mt-1 inline-flex w-full items-center justify-center rounded-lg px-2 py-1 text-xs hover:bg-muted/70"
+ onClick={() => onClearSearch?.()}
+ >
+ Clear search
+ </button>
+ ) : null}
+ </div>
+ );
+};
diff --git a/web/src/components/trace/TraceTimelineView.tsx b/web/src/components/trace/TraceTimelineView.tsx
index 84831521db..c4c8f98380 100644
--- a/web/src/components/trace/TraceTimelineView.tsx
+++ b/web/src/components/trace/TraceTimelineView.tsx
@@ -24,10 +24,8 @@ import {
} from "@/src/components/trace/lib/helpers";
import { type NestedObservation } from "@/src/utils/types";
import { cn } from "@/src/utils/tailwind";
-import {
- type TreeItemType,
- calculateDisplayTotalCost,
-} from "@/src/components/trace/lib/helpers";
+import { calculateDisplayTotalCost } from "@/src/components/trace/lib/helpers";
+import type { ObservationType } from "@langfuse/shared";
import { api } from "@/src/utils/api";
import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";
import { ItemBadge } from "@/src/components/ItemBadge";
@@ -75,7 +73,7 @@ function TreeItemInner({
}: {
latency?: number;
totalScaleSpan: number;
- type: TreeItemType;
+ type: ObservationType | "TRACE";
startOffset?: number;
firstTokenTimeOffset?: number;
name?: string | null;
diff --git a/web/src/components/trace/TraceTree.tsx b/web/src/components/trace/TraceTree.tsx
index 77f6acea32..7e9b961e8e 100644
--- a/web/src/components/trace/TraceTree.tsx
+++ b/web/src/components/trace/TraceTree.tsx
@@ -5,23 +5,16 @@ import {
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";
+import { SpanItem } from "@/src/components/trace/SpanItem";
export const TraceTree = ({
tree,
@@ -79,67 +72,48 @@ export const TraceTree = ({
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}
- />
+ <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>
+ {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>
);
};
-const TreeNodeComponent = ({
- node,
- collapsedNodes,
- toggleCollapsedNode,
- scores,
- comments,
- indentationLevel,
- currentNodeId,
- setCurrentNodeId,
- showMetrics,
- showScores,
- colorCodeMetrics,
- parentTotalCost,
- parentTotalDuration,
- showComments,
- treeLines,
- isLastSibling,
-}: {
+type TreeNodeComponentProps = {
node: TreeNode;
collapsedNodes: string[];
toggleCollapsedNode: (id: string) => void;
@@ -156,33 +130,32 @@ const TreeNodeComponent = ({
showComments: boolean;
treeLines: boolean[]; // Track which levels need vertical lines
isLastSibling: boolean;
-}) => {
+};
+
+const UnmemoizedTreeNodeComponent = ({
+ node,
+ collapsedNodes,
+ toggleCollapsedNode,
+ scores,
+ comments,
+ indentationLevel,
+ currentNodeId,
+ setCurrentNodeId,
+ showMetrics,
+ showScores,
+ colorCodeMetrics,
+ parentTotalCost,
+ parentTotalDuration,
+ showComments,
+ treeLines,
+ isLastSibling,
+}: TreeNodeComponentProps) => {
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;
+ // Convert TreeNode back to observation format for cost calculation (only for root parent totals outside)
- const currentNodeRef = useRef<HTMLDivElement>(null);
+ const currentNodeRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (currentNodeId && currentNodeRef.current && currentNodeId === node.id) {
@@ -193,28 +166,26 @@ const TreeNodeComponent = ({
}
}, [currentNodeId, node.id]);
+ const isSelected =
+ currentNodeId === node.id || (!currentNodeId && node.type === "TRACE");
+
return (
<Fragment>
- <CommandItem
- value={`${node.name} ${node.type} ${node.id}`}
+ <div
className={cn(
"relative flex w-full rounded-md px-0 hover:rounded-lg",
- currentNodeId === node.id && "bg-muted/60 hover:bg-muted/60",
+ isSelected ? "bg-muted" : "hover:bg-muted/50",
)}
style={{
paddingTop: 0,
paddingBottom: 0,
- cursor: "pointer",
borderRadius: "0.5rem",
}}
- onSelect={() =>
- setCurrentNodeId(node.type === "TRACE" ? undefined : node.id)
- }
>
- <div className="flex w-full">
+ <div className="flex w-full pl-2">
{/* Tree structure indicators */}
{indentationLevel > 0 && (
- <div className="flex flex-shrink-0">
+ <div className="z-20 flex flex-shrink-0">
{/* Vertical lines for ancestor levels */}
{Array.from({ length: indentationLevel - 1 }, (_, i) => (
<div key={i} className="relative w-6">
@@ -247,151 +218,48 @@ const TreeNodeComponent = ({
</div>
)}
- {/* Downward connector for root nodes with children */}
- {indentationLevel === 0 && node.children.length > 0 && !collapsed && (
+ {/* Downward connector placeholder for root */}
+ {indentationLevel === 0 ? (
<div
- className="absolute w-px bg-border"
+ className={cn(
+ "absolute w-px",
+ node.children.length > 0 && !collapsed
+ ? "bg-border"
+ : "bg-transparent",
+ )}
style={{ left: "20px", top: "18px", bottom: 0 }}
/>
- )}
+ ) : null}
- {/* Node content */}
- <div
+ {/* Node content button */}
+ {/* eslint-disable-next-line jsx-a11y/role-supports-aria-props */}
+ <button
+ type="button"
+ aria-selected={isSelected}
+ onClick={() =>
+ setCurrentNodeId(node.type === "TRACE" ? undefined : node.id)
+ }
className={cn(
- "flex min-w-0 flex-1 items-start gap-2 py-1",
- currentNodeId !== node.id && "rounded-md hover:bg-muted/40",
+ "peer relative z-20 flex min-w-0 flex-1 items-center rounded-md py-1.5 pl-0 pr-2 text-left",
)}
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>
+ <SpanItem
+ node={node}
+ scores={scores}
+ comments={comments}
+ showMetrics={showMetrics}
+ showScores={showScores}
+ colorCodeMetrics={colorCodeMetrics}
+ parentTotalCost={parentTotalCost}
+ parentTotalDuration={parentTotalDuration}
+ showComments={showComments}
+ />
+ </button>
{/* Expand/Collapse button */}
{node.children.length > 0 && (
- <div className="flex items-center justify-end py-1">
+ <div className="z-20 flex items-center justify-end py-1 pr-2">
<Button
size="icon"
variant="ghost"
@@ -407,21 +275,25 @@ const TreeNodeComponent = ({
}}
className="h-6 w-6 flex-shrink-0 hover:bg-primary/10"
>
- <ChevronRight
+ <span
className={cn(
- "h-4 w-4 transition-transform duration-200",
- !collapsed && "rotate-90",
+ "inline-block h-4 w-4 transform transition-transform duration-200 ease-in-out",
+ collapsed ? "rotate-0" : "rotate-90",
)}
- />
+ >
+ <ChevronRight className="h-4 w-4" />
+ </span>
</Button>
</div>
)}
+
+ {/* Background handled by container hover/selected classes */}
</div>
- </CommandItem>
+ </div>
{/* Render children */}
- {!collapsed && node.children.length > 0 && (
- <div className="flex w-full flex-col">
+ {node.children.length > 0 && (
+ <div className={cn("flex w-full flex-col", collapsed && "hidden")}>
{node.children
.sort((a, b) => a.startTime.getTime() - b.startTime.getTime())
.map((childNode, index) => {
@@ -456,3 +328,5 @@ const TreeNodeComponent = ({
</Fragment>
);
};
+
+const TreeNodeComponent = UnmemoizedTreeNodeComponent;
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index 6cd6d2013d..35bdd581b4 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -24,6 +24,7 @@ import { type APIScoreV2, ObservationLevel } from "@langfuse/shared";
import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";
import { TraceGraphView } from "@/src/features/trace-graph-view/components/TraceGraphView";
import { Command, CommandInput } from "@/src/components/ui/command";
+import { TraceSearchList } from "@/src/components/trace/TraceSearchList";
import { Switch } from "@/src/components/ui/switch";
import { Button } from "@/src/components/ui/button";
import {
@@ -40,7 +41,7 @@ import {
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 { buildTraceUiData } from "@/src/components/trace/lib/helpers";
import {
ResizablePanelGroup,
ResizablePanel,
@@ -107,6 +108,7 @@ export function Trace(props: {
);
const containerRef = useRef<HTMLDivElement>(null);
+ const [searchQuery, setSearchQuery] = useState("");
const panelState = usePanelState(
containerRef,
@@ -175,16 +177,11 @@ export function Trace(props: {
const agentGraphData = agentGraphDataQuery.data ?? [];
const isGraphViewAvailable = agentGraphData.length > 0;
- const toggleCollapsedNode = useCallback(
- (id: string) => {
- if (collapsedNodes.includes(id)) {
- setCollapsedNodes(collapsedNodes.filter((i) => i !== id));
- } else {
- setCollapsedNodes([...collapsedNodes, id]);
- }
- },
- [collapsedNodes],
- );
+ const toggleCollapsedNode = useCallback((id: string) => {
+ setCollapsedNodes((prev) =>
+ prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id],
+ );
+ }, []);
const expandAll = useCallback(() => {
capture("trace_detail:observation_tree_expand", { type: "all" });
@@ -218,12 +215,66 @@ export function Trace(props: {
[`trace-${props.trace.id}`],
);
- // Build unified tree structure
- const { tree: traceTree, hiddenObservationsCount } = useMemo(
- () => buildTraceTree(props.trace, props.observations, minObservationLevel),
+ // Build UI data once
+ const {
+ tree: traceTree,
+ hiddenObservationsCount,
+ searchItems,
+ } = useMemo(
+ () =>
+ buildTraceUiData(props.trace, props.observations, minObservationLevel),
[props.trace, props.observations, minObservationLevel],
);
+ // Compute these outside the component to avoid recreation
+ const hasQuery = (searchQuery ?? "").trim().length > 0;
+ const commentsMap = new Map(
+ [
+ ...(observationCommentCounts.data
+ ? Array.from(observationCommentCounts.data.entries())
+ : []),
+ ...(traceCommentCounts.data
+ ? [
+ [
+ `trace-${props.trace.id}`,
+ traceCommentCounts.data.get(props.trace.id),
+ ],
+ ]
+ : []),
+ ].filter(([, count]) => count !== undefined) as [string, number][],
+ );
+
+ const treeOrSearchContent = hasQuery ? (
+ <TraceSearchList
+ items={searchItems}
+ scores={props.scores}
+ onSelect={setCurrentObservationId}
+ comments={commentsMap}
+ showMetrics={metricsOnObservationTree}
+ showScores={scoresOnObservationTree}
+ colorCodeMetrics={colorCodeMetricsOnObservationTree}
+ showComments={showComments}
+ onClearSearch={() => setSearchQuery("")}
+ />
+ ) : (
+ <TraceTree
+ tree={traceTree}
+ collapsedNodes={collapsedNodes}
+ toggleCollapsedNode={toggleCollapsedNode}
+ scores={props.scores}
+ currentNodeId={currentObservationId ?? undefined}
+ setCurrentNodeId={setCurrentObservationId}
+ showMetrics={metricsOnObservationTree}
+ showScores={scoresOnObservationTree}
+ showComments={showComments}
+ colorCodeMetrics={colorCodeMetricsOnObservationTree}
+ nodeCommentCounts={commentsMap}
+ hiddenObservationsCount={hiddenObservationsCount}
+ minLevel={minObservationLevel}
+ setMinLevel={setMinObservationLevel}
+ />
+ );
+
return (
<JsonExpansionProvider>
<div
@@ -253,6 +304,8 @@ export function Trace(props: {
showBorder={false}
placeholder="Search"
className="-ml-2 h-9 min-w-20 border-0 focus:ring-0"
+ value={searchQuery}
+ onValueChange={setSearchQuery}
/>
)}
{viewType === "detailed" && (
@@ -289,7 +342,7 @@ export function Trace(props: {
</Button>
) : (
(() => {
- // Use the same root id format as the tree (see buildTraceTree)
+ // Use the same root id format as the tree (see buildTraceUiData)
const traceRootId = `trace-${props.trace.id}`;
// Check if everything is collapsed by seeing if the trace root is collapsed
const isEverythingCollapsed =
@@ -560,46 +613,8 @@ export function Trace(props: {
<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 className="h-1/2 w-full overflow-y-auto overflow-x-hidden px-2">
+ <div className="pb-2">{treeOrSearchContent}</div>
</div>
<div className="h-1/2 w-full overflow-hidden border-t">
<TraceGraphView
@@ -609,47 +624,8 @@ export function Trace(props: {
</div>
</div>
) : (
- <div className="flex h-full w-full overflow-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
- ? [
- [
- `trace-${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 className="h-full w-full overflow-auto px-2">
+ <div className="pb-2">{treeOrSearchContent}</div>
</div>
)}
</div>
diff --git a/web/src/components/trace/lib/helpers.ts b/web/src/components/trace/lib/helpers.ts
index f3430fe442..bd15dd00aa 100644
--- a/web/src/components/trace/lib/helpers.ts
+++ b/web/src/components/trace/lib/helpers.ts
@@ -1,16 +1,14 @@
import { type NestedObservation } from "@/src/utils/types";
import { type TreeNode } from "./types";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
+import type { TraceSearchListItem } from "../TraceSearchList";
import Decimal from "decimal.js";
import {
- type ObservationType,
type ObservationLevelType,
ObservationLevel,
type TraceDomain,
} from "@langfuse/shared";
-export type TreeItemType = ObservationType | "TRACE";
-
export function nestObservations(
list: ObservationReturnType[],
minLevel?: ObservationLevelType,
@@ -195,7 +193,8 @@ export const unnestObservation = (nestedObservation: NestedObservation) => {
};
// Transform trace + observations into unified tree structure
-export function buildTraceTree(
+// This function is only used internally by buildTraceUiData
+function buildTraceTree(
trace: Omit<TraceDomain, "input" | "output" | "metadata"> & {
input: string | null;
output: string | null;
@@ -250,3 +249,96 @@ export function buildTraceTree(
return { tree, hiddenObservationsCount };
}
+
+// UI helper: build flat search items with per-node aggregated totals and root-level parent totals for heatmap scaling
+
+export function buildTraceUiData(
+ 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;
+ searchItems: TraceSearchListItem[];
+} {
+ const { tree, hiddenObservationsCount } = buildTraceTree(
+ trace,
+ observations,
+ minLevel,
+ );
+
+ // Calculate total cost directly from TreeNode structure
+ // This avoids unnecessary type conversions and is more straightforward
+ const calculateTreeNodeTotalCost = (node: TreeNode): Decimal | undefined => {
+ // Check if this node has cost data
+ let nodeCost: Decimal | undefined;
+
+ if (node.calculatedTotalCost != null) {
+ nodeCost = new Decimal(node.calculatedTotalCost);
+ } else if (
+ node.calculatedInputCost != null ||
+ node.calculatedOutputCost != null
+ ) {
+ const inputCost =
+ node.calculatedInputCost != null
+ ? new Decimal(node.calculatedInputCost)
+ : new Decimal(0);
+ const outputCost =
+ node.calculatedOutputCost != null
+ ? new Decimal(node.calculatedOutputCost)
+ : new Decimal(0);
+ const combinedCost = inputCost.plus(outputCost);
+ if (!combinedCost.isZero()) {
+ nodeCost = combinedCost;
+ }
+ }
+
+ // Calculate total from all children
+ const childrenCost = node.children.reduce<Decimal | undefined>(
+ (acc, child) => {
+ const childCost = calculateTreeNodeTotalCost(child);
+ if (!childCost) return acc;
+ return acc ? acc.plus(childCost) : childCost;
+ },
+ undefined,
+ );
+
+ // Return the sum of node cost and children cost
+ if (nodeCost && childrenCost) {
+ return nodeCost.plus(childrenCost);
+ }
+ return nodeCost || childrenCost;
+ };
+
+ const rootTotalCost =
+ tree.type === "TRACE"
+ ? tree.children.reduce<Decimal | undefined>((acc, child) => {
+ const childCost = calculateTreeNodeTotalCost(child);
+ if (!childCost) return acc;
+ return acc ? acc.plus(childCost) : childCost;
+ }, undefined)
+ : calculateTreeNodeTotalCost(tree);
+ const rootDuration = tree.latency ? tree.latency * 1000 : undefined;
+
+ const out: TraceSearchListItem[] = [];
+ const visit = (node: TreeNode) => {
+ // push node; SpanItem will compute its own displayed metrics, we only need parent totals for heatmap
+ out.push({
+ node,
+ parentTotalCost: rootTotalCost,
+ parentTotalDuration: rootDuration,
+ // For TRACE nodes, observationId should be undefined (shows trace overview)
+ // For actual observations, use the node ID (which is the real observation ID)
+ observationId: node.type === "TRACE" ? undefined : node.id,
+ });
+ node.children.forEach(visit);
+ };
+ visit(tree);
+
+ return { tree, hiddenObservationsCount, searchItems: out };
+}