Skip to content

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

chore: remove trace-old (#11001)

Nimar2ce9c98004a9
diff --git a/web/src/__tests__/nestObservations.clienttest.ts b/web/src/__tests__/nestObservations.clienttest.ts
index 64fcfe9f3c..6d25be2b88 100644
--- a/web/src/__tests__/nestObservations.clienttest.ts
+++ b/web/src/__tests__/nestObservations.clienttest.ts
@@ -8,7 +8,7 @@ jest.mock("@langfuse/shared", () => ({
},
}));
-import { nestObservations } from "@/src/components/trace/lib/helpers";
+import { nestObservations } from "@/src/components/trace2/lib/helpers";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
describe("nestObservations", () => {
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index 579cb6c708..1bd2b74d60 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -2,7 +2,7 @@ import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
import { ErrorPage } from "@/src/components/error-page";
import { PublishSessionSwitch } from "@/src/components/publish-object-switch";
import { StarSessionToggle } from "@/src/components/star-toggle";
-import { IOPreview } from "@/src/components/trace/IOPreview";
+import { IOPreview } from "@/src/components/trace2/components/IOPreview/IOPreview";
import { JsonSkeleton } from "@/src/components/ui/CodeJsonViewer";
import { Badge } from "@/src/components/ui/badge";
import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
diff --git a/web/src/components/table/peek/peek-observation-detail.tsx b/web/src/components/table/peek/peek-observation-detail.tsx
index 57c8c58726..0962ea6335 100644
--- a/web/src/components/table/peek/peek-observation-detail.tsx
+++ b/web/src/components/table/peek/peek-observation-detail.tsx
@@ -1,6 +1,6 @@
import { useRouter } from "next/router";
import { usePeekData } from "@/src/components/table/peek/hooks/usePeekData";
-import { Trace } from "@/src/components/trace";
+import { Trace } from "@/src/components/trace2/Trace";
import { Skeleton } from "@/src/components/ui/skeleton";
import { StringParam, useQueryParam, withDefault } from "use-query-params";
diff --git a/web/src/components/table/peek/peek-trace-detail.tsx b/web/src/components/table/peek/peek-trace-detail.tsx
index a75e7b8a85..dc7795b100 100644
--- a/web/src/components/table/peek/peek-trace-detail.tsx
+++ b/web/src/components/table/peek/peek-trace-detail.tsx
@@ -1,6 +1,6 @@
import { usePeekData } from "@/src/components/table/peek/hooks/usePeekData";
import { useRouter } from "next/router";
-import { Trace } from "@/src/components/trace";
+import { Trace } from "@/src/components/trace2/Trace";
import { Skeleton } from "@/src/components/ui/skeleton";
import { StringParam, useQueryParam, withDefault } from "use-query-params";
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index 9b4219d926..8fa60e043b 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -44,7 +44,7 @@ import { BatchExportTableButton } from "@/src/components/BatchExportTableButton"
import {
BreakdownTooltip,
calculateAggregatedUsage,
-} from "@/src/components/trace/BreakdownToolTip";
+} from "@/src/components/trace2/components/_shared/BreakdownToolTip";
import { InfoIcon, PlusCircle } from "lucide-react";
import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";
import { LocalIsoDate } from "@/src/components/LocalIsoDate";
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index f112680ff0..2045d75fc6 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -49,7 +49,7 @@ import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableC
import { Skeleton } from "@/src/components/ui/skeleton";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";
-import { BreakdownTooltip } from "@/src/components/trace/BreakdownToolTip";
+import { BreakdownTooltip } from "@/src/components/trace2/components/_shared/BreakdownToolTip";
import { InfoIcon, MoreVertical } from "lucide-react";
import { useHasEntitlement } from "@/src/features/entitlements/hooks";
import React from "react";
diff --git a/web/src/components/trace/BreakdownToolTip.tsx b/web/src/components/trace/BreakdownToolTip.tsx
deleted file mode 100644
index 96b88f135b..0000000000
--- a/web/src/components/trace/BreakdownToolTip.tsx
+++ /dev/null
@@ -1,259 +0,0 @@
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/src/components/ui/tooltip";
-import { useState } from "react";
-import Decimal from "decimal.js";
-import { getMaxDecimals } from "@/src/features/models/utils";
-
-interface Details {
- [key: string]: number | undefined;
-}
-
-/**
- * Aggregates an array of detail objects into a single object by summing matching keys.
- * If a single object is provided, returns it as-is.
- */
-const aggregateDetailsArray = (details: Details | Details[]): Details => {
- return Array.isArray(details)
- ? details.reduce<Details>((acc, curr) => {
- Object.entries(curr).forEach(([key, value]) => {
- acc[key] = new Decimal(acc[key] || 0)
- .plus(new Decimal(value || 0))
- .toNumber();
- });
- return acc;
- }, {})
- : details;
-};
-
-/**
- * Aggregates usage or cost details by summing values based on key patterns.
- * Used to calculate input/output/total values from detailed breakdowns.
- */
-export const calculateAggregatedUsage = (
- details: Details | Details[],
-): {
- input: number;
- output: number;
- total: number;
-} => {
- const aggregatedDetails = aggregateDetailsArray(details);
-
- // Sum all keys containing "input"
- const input = Object.entries(aggregatedDetails)
- .filter(([key]) => key.includes("input"))
- .reduce(
- (sum, [_, value]) =>
- new Decimal(sum).plus(new Decimal(value ?? 0)).toNumber(),
- 0,
- );
-
- // Sum all keys containing "output"
- const output = Object.entries(aggregatedDetails)
- .filter(([key]) => key.includes("output"))
- .reduce(
- (sum, [_, value]) =>
- new Decimal(sum).plus(new Decimal(value ?? 0)).toNumber(),
- 0,
- );
-
- // Get total or calculate from input + output
- const total = aggregatedDetails.total ?? input + output;
-
- return { input, output, total };
-};
-
-interface BreakdownTooltipProps {
- details: Details | Details[];
- children: React.ReactNode;
- isCost?: boolean;
- pricingTierName?: string;
-}
-
-export const BreakdownTooltip = ({
- details,
- children,
- isCost = false,
- pricingTierName,
-}: BreakdownTooltipProps) => {
- const [isOpen, setIsOpen] = useState(false);
-
- // Aggregate details if array is provided
- const aggregatedDetails = aggregateDetailsArray(details);
-
- const formatValueWithPadding = (value: number, maxDecimals: number) => {
- return !value
- ? "0"
- : isCost
- ? `$${value.toFixed(maxDecimals)}`
- : value.toLocaleString();
- };
-
- const maxDecimals = isCost
- ? Math.max(
- ...Object.values(aggregatedDetails).map((v) => getMaxDecimals(v)),
- )
- : 0;
-
- return (
- <TooltipProvider>
- <Tooltip open={isOpen} onOpenChange={setIsOpen}>
- <TooltipTrigger
- className="flex cursor-pointer"
- onClick={() => setIsOpen(!isOpen)}
- >
- {children}
- </TooltipTrigger>
- <TooltipContent className="w-64 p-4">
- <div className="flex flex-col gap-4">
- <div className="flex flex-col gap-1">
- <span className="font-semibold">
- {isCost ? "Cost breakdown" : "Usage breakdown"}
- </span>
- {Array.isArray(details) && details.length > 0 && (
- <span className="text-xs italic text-muted-foreground">
- Aggregate across {details.length}{" "}
- {details.length === 1 ? "generation" : "generations"}
- </span>
- )}
- {/* Pricing Tier Section */}
- {pricingTierName && (
- <div className="flex flex-row items-center gap-1 border-b pb-2">
- <span className="text-xs text-muted-foreground">
- Pricing Tier:
- </span>
- <span className="text-xs font-medium text-muted-foreground">
- {pricingTierName}
- </span>
- </div>
- )}
- </div>
-
- {/* Input Section */}
- <Section
- title={isCost ? "Input cost" : "Input usage"}
- details={aggregatedDetails}
- filterFn={(key) => key.includes("input")}
- formatValue={(v) => formatValueWithPadding(v, maxDecimals)}
- />
-
- {/* Output Section */}
- <Section
- title={isCost ? "Output cost" : "Output usage"}
- details={aggregatedDetails}
- filterFn={(key) => key.includes("output")}
- formatValue={(v) => formatValueWithPadding(v, maxDecimals)}
- />
-
- {/* Other Section */}
- <OtherSection
- details={aggregatedDetails}
- isCost={isCost}
- formatValue={(v) => formatValueWithPadding(v, maxDecimals)}
- />
-
- {/* Total */}
- <div className="flex justify-between border-b-4 border-t border-double py-1">
- <span className="text-xs font-semibold">
- {isCost ? "Total cost" : "Total usage"}
- </span>
- <span className="font-mono text-xs font-semibold">
- {formatValueWithPadding(
- aggregatedDetails.total ?? 0,
- maxDecimals,
- )}
- </span>
- </div>
- </div>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- );
-};
-
-interface SectionProps {
- title: string;
- details: Details;
- filterFn: (key: string) => boolean;
- formatValue: (value: number) => string;
-}
-
-const Section = ({ title, details, filterFn, formatValue }: SectionProps) => {
- const filteredEntries = Object.entries(details)
- .filter(([key]) => filterFn(key))
- .sort(([, a], [, b]) => (b ?? 0) - (a ?? 0));
-
- const sectionTotal = filteredEntries.reduce(
- (sum, [_, value]) =>
- new Decimal(sum).plus(new Decimal(value ?? 0)).toNumber(),
- 0,
- );
-
- return (
- <div className="flex flex-col gap-2">
- <div className="flex justify-between border-b pb-1">
- <span className="text-xs font-semibold">{title}</span>
- <span className="text-right font-mono text-xs font-semibold">
- {formatValue(sectionTotal)}
- </span>
- </div>
- {filteredEntries.map(([key, value]) => (
- <div
- key={key}
- className="flex justify-between gap-4 text-xs text-muted-foreground"
- >
- <span className="break-words">{key}</span>
- <span className="shrink-0 font-mono">{formatValue(value ?? 0)}</span>
- </div>
- ))}
- </div>
- );
-};
-
-interface OtherSectionProps {
- details: Details;
- isCost: boolean;
- formatValue: (value: number) => string;
-}
-
-const OtherSection = ({ details, isCost, formatValue }: OtherSectionProps) => {
- const otherEntries = Object.entries(details)
- .filter(
- ([key]) =>
- !key.includes("input") && !key.includes("output") && key !== "total",
- )
- .sort(([, a], [, b]) => (b ?? 0) - (a ?? 0));
-
- if (otherEntries.length === 0) return null;
-
- const otherTotal = otherEntries.reduce((acc, val) => {
- if (typeof val[1] !== "number") return acc;
-
- return acc + (val[1] ?? 0);
- }, 0);
-
- return (
- <div className="flex flex-col gap-2">
- <div className="flex justify-between border-b pb-2">
- <span className="text-xs font-medium">
- {isCost ? "Other cost" : "Other usage"}
- </span>
- <span className="text-right font-mono text-xs font-medium">
- {formatValue(otherTotal)}
- </span>
- </div>
- {otherEntries.map(([key, value]) => (
- <div
- key={key}
- className="flex justify-between gap-4 text-xs text-muted-foreground"
- >
- <span className="break-words">{key}</span>
- <span className="shrink-0 font-mono">{formatValue(value ?? 0)}</span>
- </div>
- ))}
- </div>
- );
-};
diff --git a/web/src/components/trace/CopyIdsPopover.tsx b/web/src/components/trace/CopyIdsPopover.tsx
deleted file mode 100644
index a82b7a1a00..0000000000
--- a/web/src/components/trace/CopyIdsPopover.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-import { Button } from "@/src/components/ui/button";
-import { CopyIcon, CheckIcon } from "lucide-react";
-import { useState } from "react";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/src/components/ui/popover";
-import { cn } from "@/src/utils/tailwind";
-import { copyTextToClipboard } from "@/src/utils/clipboard";
-
-interface IdItem {
- name: string;
- id: string;
-}
-
-export const CopyIdsPopover = ({
- idItems,
- className,
-}: {
- idItems: IdItem[];
- className?: string;
-}) => {
- const [copiedId, setCopiedId] = useState<string | null>(null);
-
- const handleCopy = (textToCopy: string) => {
- copyTextToClipboard(textToCopy);
- setCopiedId(textToCopy);
- setTimeout(() => setCopiedId(null), 1500);
- };
-
- // If only one idItem provided, use simple button with only one ID
- if (idItems.length === 1) {
- return (
- <Button
- variant="ghost"
- title="Copy ID"
- className={cn("h-fit p-1", className)}
- onClick={() => handleCopy(idItems[0].id)}
- >
- {copiedId === idItems[0].id ? (
- <CheckIcon className="h-3 w-3 text-muted-green" />
- ) : (
- <CopyIcon className="h-3 w-3" />
- )}
- <span className="ml-1 text-xs">ID</span>
- </Button>
- );
- }
-
- return (
- <Popover>
- <PopoverTrigger asChild>
- <Button
- variant="ghost"
- title="Copy ID"
- className={cn("h-fit px-1", className)}
- >
- <CopyIcon className="h-3 w-3" />
- <span className="ml-1 text-xs">ID</span>
- </Button>
- </PopoverTrigger>
- <PopoverContent
- className="max-h-[50vh] w-auto min-w-[280px] overflow-y-auto p-1"
- align="start"
- >
- <div className="flex flex-col gap-0.5">
- {idItems.map((item) => (
- <div
- key={item.id}
- className="group flex items-center justify-between gap-2 rounded-sm px-2 py-1.5 transition-colors hover:bg-muted/50"
- >
- <div className="flex min-w-0 flex-col gap-0.5">
- <span className="text-xs font-medium text-muted-foreground">
- {item.name}
- </span>
- <span
- className="max-w-[220px] truncate font-mono text-xs"
- title={item.id}
- >
- {item.id}
- </span>
- </div>
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6 shrink-0 opacity-70 transition-opacity group-hover:opacity-100"
- onClick={() => handleCopy(item.id)}
- >
- {copiedId === item.id ? (
- <CheckIcon className="h-3 w-3 text-muted-green" />
- ) : (
- <CopyIcon className="h-3 w-3" />
- )}
- </Button>
- </div>
- ))}
- </div>
- </PopoverContent>
- </Popover>
- );
-};
diff --git a/web/src/components/trace/IOPreview.tsx b/web/src/components/trace/IOPreview.tsx
deleted file mode 100644
index 2b44744229..0000000000
--- a/web/src/components/trace/IOPreview.tsx
+++ /dev/null
@@ -1,791 +0,0 @@
-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
-import { type Prisma, deepParseJson } from "@langfuse/shared";
-import { cn } from "@/src/utils/tailwind";
-import { useEffect, useMemo, useState } from "react";
-import { Button } from "@/src/components/ui/button";
-import { ActionButton } from "@/src/components/ActionButton";
-import { Fragment } from "react";
-import type { z } from "zod/v4";
-import type {
- ChatMlArraySchema,
- ChatMlMessageSchema,
-} from "@/src/components/schemas/ChatMlSchema";
-import { type MediaReturnType } from "@/src/features/media/validation";
-import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";
-import {
- MarkdownJsonView,
- MarkdownJsonViewHeader,
-} from "@/src/components/ui/MarkdownJsonView";
-import { SubHeaderLabel } from "@/src/components/layouts/header";
-import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import useLocalStorage from "@/src/components/useLocalStorage";
-import usePreserveRelativeScroll from "@/src/hooks/usePreserveRelativeScroll";
-import { MARKDOWN_RENDER_CHARACTER_LIMIT } from "@/src/utils/constants";
-import {
- normalizeInput,
- normalizeOutput,
- combineInputOutputMessages,
- cleanLegacyOutput,
- extractAdditionalInput,
-} from "@/src/utils/chatml";
-import { ToolCallDefinitionCard } from "@/src/components/trace/ToolCallDefinitionCard";
-import { ToolCallInvocationsView } from "@/src/components/trace/ToolCallInvocationsView";
-import {
- ListChevronsDownUp,
- ListChevronsUpDown,
- BookOpen,
- X,
-} from "lucide-react";
-import { copyTextToClipboard } from "@/src/utils/clipboard";
-
-const EMPTY_IO_ALERT_ID = "empty-io";
-const STORAGE_KEY = "dismissed-trace-view-notifications";
-
-export const IOPreview: React.FC<{
- input?: Prisma.JsonValue;
- output?: Prisma.JsonValue;
- metadata?: Prisma.JsonValue;
- observationName?: string;
- isLoading?: boolean;
- hideIfNull?: boolean;
- media?: MediaReturnType[];
- hideOutput?: boolean;
- hideInput?: boolean;
- currentView?: "pretty" | "json";
- setIsPrettyViewAvailable?: (value: boolean) => void;
- inputExpansionState?: Record<string, boolean> | boolean;
- outputExpansionState?: Record<string, boolean> | boolean;
- onInputExpansionChange?: (
- expansion: Record<string, boolean> | boolean,
- ) => void;
- onOutputExpansionChange?: (
- expansion: Record<string, boolean> | boolean,
- ) => void;
-}> = ({
- isLoading = false,
- hideIfNull = false,
- hideOutput = false,
- hideInput = false,
- media,
- currentView,
- inputExpansionState,
- outputExpansionState,
- onInputExpansionChange,
- onOutputExpansionChange,
- setIsPrettyViewAvailable,
- ...props
-}) => {
- const [localCurrentView, setLocalCurrentView] = useLocalStorage<
- "pretty" | "json"
- >("jsonViewPreference", "pretty");
- const selectedView = currentView ?? localCurrentView;
- const capture = usePostHogClientCapture();
- const [dismissedTraceViewNotifications, setDismissedTraceViewNotifications] =
- useLocalStorage<string[]>(STORAGE_KEY, []);
- const input = deepParseJson(props.input);
- const output = deepParseJson(props.output);
- const metadata = deepParseJson(props.metadata);
- const [compensateScrollRef, startPreserveScroll] =
- usePreserveRelativeScroll<HTMLDivElement>([selectedView]);
-
- const {
- canDisplayAsChat,
- allMessages,
- additionalInput,
- allTools,
- toolCallCounts,
- messageToToolCallNumbers,
- toolNameToDefinitionNumber,
- } = useMemo(() => {
- const ctx = { metadata, observationName: props.observationName };
- const inResult = normalizeInput(input, ctx);
- const outResult = normalizeOutput(output, ctx);
- const outputClean = cleanLegacyOutput(output, output);
- const messages = combineInputOutputMessages(
- inResult,
- outResult,
- outputClean,
- );
-
- // extract all unique tools from messages (no numbering yet)
- const toolsMap = new Map<
- string,
- { name: string; description?: string; parameters?: Record<string, any> }
- >();
-
- for (const message of messages) {
- if (message.tools && Array.isArray(message.tools)) {
- for (const tool of message.tools) {
- if (!toolsMap.has(tool.name)) {
- toolsMap.set(tool.name, tool);
- }
- }
- }
- }
-
- // count tool call invocations and tool calls
- // Only number tool calls from OUTPUT messages (current invocation), not input (history)
- const inputMessageCount = inResult.success ? inResult.data.length : 0;
- let toolCallCounter = 0;
- const messageToToolCallNumbers = new Map<number, number[]>();
- const toolCallCounts = new Map<string, number>();
-
- for (let i = 0; i < messages.length; i++) {
- const message = messages[i];
- const isOutputMessage = i >= inputMessageCount; // Only output messages get numbered
-
- const toolCallList = parseToolCallsFromMessage(message);
-
- if (toolCallList.length > 0) {
- const messageToolNumbers: number[] = [];
-
- for (const toolCall of toolCallList) {
- const calledToolName =
- toolCall.name && typeof toolCall.name === "string"
- ? toolCall.name
- : // AI SDK has 'toolName'
- toolCall.toolName && typeof toolCall.toolName === "string"
- ? toolCall.toolName
- : undefined;
-
- if (calledToolName) {
- // count tool calls from OUTPUT messages only, only those were called
- // in this generation
- if (isOutputMessage) {
- toolCallCounts.set(
- calledToolName,
- (toolCallCounts.get(calledToolName) || 0) + 1,
- );
- toolCallCounter++;
- messageToolNumbers.push(toolCallCounter);
- }
- }
- }
-
- if (messageToolNumbers.length > 0) {
- messageToToolCallNumbers.set(i, messageToolNumbers);
- }
- }
- }
-
- // sort tools by display order (called first, then by call count)
- const sortedTools = Array.from(toolsMap.values()).sort((a, b) => {
- const callCountA = toolCallCounts.get(a.name) || 0;
- const callCountB = toolCallCounts.get(b.name) || 0;
- // Sort by called status (called first), then by call count descending
- if (callCountA > 0 && callCountB === 0) return -1;
- if (callCountA === 0 && callCountB > 0) return 1;
- return callCountB - callCountA;
- });
-
- // assign definition numbers based on sorted display order
- const toolNameToDefinitionNumber = new Map<string, number>();
- sortedTools.forEach((tool, index) => {
- toolNameToDefinitionNumber.set(tool.name, index + 1);
- });
-
- return {
- canDisplayAsChat:
- (inResult.success || outResult.success) && messages.length > 0,
- allMessages: messages,
- additionalInput: extractAdditionalInput(input),
- allTools: sortedTools,
- toolCallCounts,
- messageToToolCallNumbers,
- toolNameToDefinitionNumber,
- };
- }, [input, output, metadata, props.observationName]);
-
- // Pretty view is available for ChatML content OR any JSON content
- const isPrettyViewAvailable = true; // Always show the toggle, let individual components decide how to render
-
- useEffect(() => {
- setIsPrettyViewAvailable?.(isPrettyViewAvailable);
- }, [isPrettyViewAvailable, setIsPrettyViewAvailable]);
-
- // Don't render markdown if total content size exceeds limit
- const inputSize = JSON.stringify(input || {}).length;
- const outputSize = JSON.stringify(output || {}).length;
- const messagesSize = JSON.stringify(allMessages).length;
- const totalContentSize = inputSize + outputSize + messagesSize;
-
- const shouldRenderMarkdownSafely =
- totalContentSize <= MARKDOWN_RENDER_CHARACTER_LIMIT;
-
- const showEmptyState =
- (input === null || input === undefined) &&
- (output === null || output === undefined) &&
- !isLoading &&
- !hideIfNull &&
- !dismissedTraceViewNotifications.includes(EMPTY_IO_ALERT_ID);
-
- // default I/O
- return (
- <>
- {/* Show tools at the top if available */}
- {allTools.length > 0 && (
- <div className="[&_.io-message-content]:px-2 [&_.io-message-header]:px-2">
- <div className="mb-4 border-b border-border pb-4">
- <div className="io-message-header px-1 py-1 text-sm font-medium capitalize">
- Tools
- </div>
- <ToolCallDefinitionCard
- tools={allTools}
- toolCallCounts={toolCallCounts}
- toolNameToDefinitionNumber={toolNameToDefinitionNumber}
- className="px-2"
- />
- </div>
- </div>
- )}
-
- {isPrettyViewAvailable && !currentView ? (
- <div className="flex w-full flex-row justify-start">
- <Tabs
- ref={compensateScrollRef}
- className="h-fit py-0.5"
- value={selectedView}
- onValueChange={(value) => {
- startPreserveScroll();
- capture("trace_detail:io_mode_switch", { view: value });
- setLocalCurrentView(value as "pretty" | "json");
- }}
- >
- <TabsList className="h-fit p-0.5">
- <TabsTrigger value="pretty" className="h-fit px-1 text-xs">
- Formatted
- </TabsTrigger>
- <TabsTrigger value="json" className="h-fit px-1 text-xs">
- JSON
- </TabsTrigger>
- </TabsList>
- </Tabs>
- </div>
- ) : null}
- {/* Always render components to preserve state, just hide via CSS*/}
- {isPrettyViewAvailable ? (
- <>
- {/* Pretty view content */}
- <div
- style={{ display: selectedView === "pretty" ? "block" : "none" }}
- >
- {canDisplayAsChat ? (
- <div className="[&_.io-message-content]:px-2 [&_.io-message-header]:px-2">
- <OpenAiMessageView
- messages={allMessages}
- shouldRenderMarkdown={shouldRenderMarkdownSafely}
- additionalInput={
- Object.keys(additionalInput ?? {}).length > 0
- ? additionalInput
- : undefined
- }
- media={media ?? []}
- currentView={selectedView}
- messageToToolCallNumbers={messageToToolCallNumbers}
- />
- </div>
- ) : (
- <div className="[&_.io-message-content]:px-2 [&_.io-message-header]:px-2">
- {!(hideIfNull && !input) && !hideInput ? (
- <PrettyJsonView
- title="Input"
- json={input ?? null}
- isLoading={isLoading}
- media={media?.filter((m) => m.field === "input") ?? []}
- currentView={selectedView}
- externalExpansionState={inputExpansionState}
- onExternalExpansionChange={onInputExpansionChange}
- />
- ) : null}
- {!(hideIfNull && !output) && !hideOutput ? (
- <PrettyJsonView
- title="Output"
- json={output}
- isLoading={isLoading}
- media={media?.filter((m) => m.field === "output") ?? []}
- currentView={selectedView}
- externalExpansionState={outputExpansionState}
- onExternalExpansionChange={onOutputExpansionChange}
- />
- ) : null}
- </div>
- )}
- </div>
-
- {/* JSON view content */}
- <div style={{ display: selectedView === "json" ? "block" : "none" }}>
- <div className="[&_.io-message-content]:px-2 [&_.io-message-header]:px-2">
- {!(hideIfNull && !input) && !hideInput ? (
- <PrettyJsonView
- title="Input"
- json={input ?? null}
- isLoading={isLoading}
- media={media?.filter((m) => m.field === "input") ?? []}
- currentView={selectedView}
- externalExpansionState={inputExpansionState}
- onExternalExpansionChange={onInputExpansionChange}
- />
- ) : null}
- {!(hideIfNull && !output) && !hideOutput ? (
- <PrettyJsonView
- title="Output"
- json={output}
- isLoading={isLoading}
- media={media?.filter((m) => m.field === "output") ?? []}
- currentView={selectedView}
- externalExpansionState={outputExpansionState}
- onExternalExpansionChange={onOutputExpansionChange}
- />
- ) : null}
- </div>
- </div>
- </>
- ) : (
- <div className="[&_.io-message-content]:px-2 [&_.io-message-header]:px-2">
- {!(hideIfNull && !input) && !hideInput ? (
- <PrettyJsonView
- title="Input"
- json={input ?? null}
- isLoading={isLoading}
- media={media?.filter((m) => m.field === "input") ?? []}
- currentView={selectedView}
- externalExpansionState={inputExpansionState}
- onExternalExpansionChange={onInputExpansionChange}
- />
- ) : null}
- {!(hideIfNull && !output) && !hideOutput ? (
- <PrettyJsonView
- title="Output"
- json={output}
- isLoading={isLoading}
- media={media?.filter((m) => m.field === "output") ?? []}
- currentView={selectedView}
- externalExpansionState={outputExpansionState}
- onExternalExpansionChange={onOutputExpansionChange}
- />
- ) : null}
- </div>
- )}
- {showEmptyState && (
- <div className="relative mx-2 flex flex-col items-start gap-2 rounded-lg border border-dashed p-4">
- <Button
- variant="ghost"
- size="sm"
- className="absolute right-1.5 top-1.5 h-5 w-5 p-0"
- onClick={() => {
- capture("notification:dismiss_notification", {
- notification_id: EMPTY_IO_ALERT_ID,
- });
- setDismissedTraceViewNotifications((prev) =>
- prev.includes(EMPTY_IO_ALERT_ID)
- ? prev
- : [...prev, EMPTY_IO_ALERT_ID],
- );
- }}
- title="Dismiss"
- >
- <X className="h-3.5 w-3.5" />
- </Button>
- <div className="flex w-full flex-row items-center gap-2 pr-6">
- <div className="flex h-8 w-8 items-center justify-center rounded-full bg-accent">
- <BookOpen className="h-4 w-4 text-muted-foreground" />
- </div>
- <h3 className="text-sm font-semibold">
- Looks like this trace didn&apos;t receive an input or output.
- </h3>
- </div>
- <p className="max-w-sm text-sm text-muted-foreground">
- Add it in your code to make debugging a lot easier.
- </p>
- <ActionButton
- variant="outline"
- size="sm"
- href="https://langfuse.com/faq/all/empty-trace-input-and-output"
- trackingEventName="notification:click_link"
- trackingProps={{ notification_id: EMPTY_IO_ALERT_ID }}
- >
- View Documentation
- </ActionButton>
- </div>
- )}
- </>
- );
-};
-
-// create message title
-const getMessageTitle = (
- message: z.infer<typeof ChatMlMessageSchema>,
-): string => {
- return message.name ?? message.role ?? "";
-};
-
-export const OpenAiMessageView: React.FC<{
- messages: z.infer<typeof ChatMlArraySchema>;
- title?: string;
- shouldRenderMarkdown?: boolean;
- collapseLongHistory?: boolean;
- media?: MediaReturnType[];
- additionalInput?: Record<string, unknown>;
- projectIdForPromptButtons?: string;
- currentView?: "pretty" | "json";
- messageToToolCallNumbers?: Map<number, number[]>;
-}> = ({
- title,
- messages,
- shouldRenderMarkdown = false,
- media,
- collapseLongHistory = true,
- additionalInput,
- projectIdForPromptButtons,
- currentView = "json",
- messageToToolCallNumbers,
-}) => {
- const COLLAPSE_THRESHOLD = 3;
-
- // stores which messages should show table view (json) instead of pretty view
- const [showTableView, setShowTableView] = useState<Set<number>>(new Set());
-
- const toggleTableView = (index: number) => {
- setShowTableView((prev) => {
- const next = new Set(prev);
- if (next.has(index)) {
- next.delete(index);
- } else {
- next.add(index);
- }
- return next;
- });
- };
-
- const shouldRenderContent = (message: ChatMlMessageSchema) => {
- // Don't render if content is empty string or null/undefined in ChatML view
- // happens e.g. if an LLM only uses a tool
- const hasContent = message.content != null && message.content !== "";
- return hasContent || !!message.audio;
- };
-
- // TODO: removed for now, we never show additional JSON alongside the ChatML content
- // because we now have a switch to display it. We re-add this depending on user feedback.
- // const shouldRenderJson = (message: ChatMlMessageSchema) => {
- // return !!message.json;
- // };
- const hasAdditionalData = (message: ChatMlMessageSchema) => {
- // if anything more than role & content exists, we show the button
- const messageKeys = Object.keys(message).filter(
- (key) => key !== "role" && key !== "content",
- );
- return messageKeys.length > 0;
- };
-
- const hasPassthroughJson = (message: ChatMlMessageSchema) => {
- return message.json != null;
- };
-
- const isPlaceholderMessage = (message: ChatMlMessageSchema) => {
- return message.type === "placeholder";
- };
-
- const isOnlyJsonMessage = (message: ChatMlMessageSchema) => {
- // Message parsed as ChatML but only has json field (non-ChatML object)
- // Valid ChatML needs content OR tool_calls OR audio (role alone is insufficient)
- const hasValidChatMlContent =
- message.content != null ||
- message.tool_calls != null ||
- message.audio != null;
-
- return !hasValidChatMlContent && message.json != null;
- };
-
- const messagesToRender = useMemo(
- () =>
- messages.filter(
- (message) =>
- shouldRenderContent(message) ||
- // shouldRenderJson(message) ||
- hasAdditionalData(message) ||
- isPlaceholderMessage(message),
- ),
- [messages],
- );
-
- // Initialize collapsed state based on filtered messages, we only want to show
- // "Show X more..." if there actually are more messages to show
- const [isCollapsed, setCollapsed] = useState(
- collapseLongHistory && messagesToRender.length > COLLAPSE_THRESHOLD
- ? true
- : null,
- );
-
- return (
- <div className="flex max-h-full min-h-0 flex-col gap-2">
- {title && <SubHeaderLabel title={title} className="mt-1" />}
- <div className="flex max-h-full min-h-0 flex-col gap-2">
- <div className="flex flex-col gap-2">
- {messagesToRender
- .map((message, originalIndex) => ({ message, originalIndex }))
- .filter(
- ({ originalIndex }) =>
- // show all if not collapsed or null; show first and last n if collapsed
- !isCollapsed ||
- originalIndex == 0 ||
- originalIndex > messagesToRender.length - COLLAPSE_THRESHOLD,
- )
- .map(({ message, originalIndex }) => {
- // Check if user toggled to table view
- const isShowingTable = showTableView.has(originalIndex);
- return (
- <>
- <div
- key={originalIndex}
- className={cn("transition-colors hover:bg-muted")}
- >
- {isPlaceholderMessage(message) ? (
- <>
- <div
- style={{
- display: shouldRenderMarkdown ? "block" : "none",
- }}
- >
- <MarkdownJsonView
- title="Placeholder"
- content={message.name || "Unnamed placeholder"}
- customCodeHeaderClassName={cn(
- "bg-primary-foreground",
- )}
- />
- </div>
- <div
- style={{
- display: shouldRenderMarkdown ? "none" : "block",
- }}
- >
- <PrettyJsonView
- title="Placeholder"
- json={message.name || "Unnamed placeholder"}
- projectIdForPromptButtons={
- projectIdForPromptButtons
- }
- currentView={currentView}
- />
- </div>
- </>
- ) : isOnlyJsonMessage(message) ? (
- // Non-ChatML object that parsed via passthrough - render as JSON
- <PrettyJsonView
- title={getMessageTitle(message) || "Output"}
- json={message.json}
- projectIdForPromptButtons={projectIdForPromptButtons}
- currentView={currentView}
- />
- ) : (
- <>
- {shouldRenderContent(message) &&
- !showTableView.has(originalIndex) && (
- <>
- <div
- style={{
- display: shouldRenderMarkdown
- ? "block"
- : "none",
- }}
- >
- <MarkdownJsonView
- title={getMessageTitle(message)}
- content={message.content || '""'}
- customCodeHeaderClassName={cn(
- message.role === "assistant" &&
- "bg-secondary",
- message.role === "system" &&
- "bg-primary-foreground",
- )}
- audio={message.audio}
- controlButtons={
- hasPassthroughJson(message) ? (
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={() =>
- toggleTableView(originalIndex)
- }
- title="Show passthrough JSON data"
- className="-mr-2 hover:bg-border"
- >
- <ListChevronsUpDown className="h-3 w-3" />
- </Button>
- ) : undefined
- }
- />
- {parseToolCallsFromMessage(message).length >
- 0 && (
- <div className="mt-2">
- <ToolCallInvocationsView
- message={message}
- toolCallNumbers={messageToToolCallNumbers?.get(
- originalIndex,
- )}
- />
- </div>
- )}
- </div>
- <div
- style={{
- display: shouldRenderMarkdown
- ? "none"
- : "block",
- }}
- >
- <PrettyJsonView
- title={getMessageTitle(message)}
- json={message.content}
- projectIdForPromptButtons={
- projectIdForPromptButtons
- }
- currentView={currentView}
- controlButtons={
- hasPassthroughJson(message) ? (
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={() =>
- toggleTableView(originalIndex)
- }
- title="Show passthrough JSON data"
- className="-mr-2 hover:bg-border"
- >
- <ListChevronsUpDown className="h-3 w-3" />
- </Button>
- ) : undefined
- }
- />
- {parseToolCallsFromMessage(message).length >
- 0 && (
- <div className="mt-2">
- <ToolCallInvocationsView
- message={message}
- toolCallNumbers={messageToToolCallNumbers?.get(
- originalIndex,
- )}
- />
- </div>
- )}
- </div>
- </>
- )}
- {isShowingTable ? (
- // User clicked toggle - show passthrough JSON
- <PrettyJsonView
- title={getMessageTitle(message)}
- json={message.json}
- projectIdForPromptButtons={
- projectIdForPromptButtons
- }
- currentView="pretty"
- controlButtons={
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={() => toggleTableView(originalIndex)}
- title="Show formatted view"
- className="-mr-2 hover:bg-border"
- >
- <ListChevronsDownUp className="h-3 w-3 text-primary" />
- </Button>
- }
- />
- ) : !shouldRenderContent(message) &&
- parseToolCallsFromMessage(message).length > 0 ? (
- // No content but has tool_calls - show tool invocations
- <div>
- <MarkdownJsonViewHeader
- title={getMessageTitle(message)}
- handleOnValueChange={() => {}}
- handleOnCopy={() => {
- const rawText = JSON.stringify(
- message,
- null,
- 2,
- );
- void copyTextToClipboard(rawText);
- }}
- controlButtons={
- hasPassthroughJson(message) ? (
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={() =>
- toggleTableView(originalIndex)
- }
- title="Show passthrough JSON data"
- className="-mr-2 hover:bg-border"
- >
- <ListChevronsUpDown className="h-3 w-3" />
- </Button>
- ) : undefined
- }
- />
- <ToolCallInvocationsView
- message={message}
- toolCallNumbers={messageToToolCallNumbers?.get(
- originalIndex,
- )}
- />
- </div>
- ) : null}
- </>
- )}
- </div>
- {isCollapsed !== null && originalIndex === 0 ? (
- <Button
- variant="ghost"
- size="xs"
- onClick={() => setCollapsed((v) => !v)}
- className="underline"
- >
- {isCollapsed
- ? `Show ${messagesToRender.length - COLLAPSE_THRESHOLD} more ...`
- : "Hide history"}
- </Button>
- ) : null}
- </>
- );
- })}
- </div>
- {additionalInput && (
- <PrettyJsonView
- title="Additional Input"
- json={additionalInput}
- projectIdForPromptButtons={projectIdForPromptButtons}
- currentView={shouldRenderMarkdown ? "pretty" : "json"}
- />
- )}
- {media && media.length > 0 && (
- <>
- <div className="mx-3 border-t px-2 py-1 text-xs text-muted-foreground">
- Media
- </div>
- <div className="flex flex-wrap gap-2 p-4 pt-1">
- {media.map((m) => (
- <LangfuseMediaView
- mediaAPIReturnValue={m}
- asFileIcon={true}
- key={m.mediaId}
- />
- ))}
- </div>
- </>
- )}
- </div>
- </div>
- );
-};
-
-function parseToolCallsFromMessage(
- message: ReturnType<typeof combineInputOutputMessages>[0],
-) {
- return message.tool_calls && Array.isArray(message.tool_calls)
- ? message.tool_calls
- : message.json?.tool_calls && Array.isArray(message.json?.tool_calls)
- ? message.json.tool_calls
- : [];
-}
diff --git a/web/src/components/trace/JsonExpansionContext.tsx b/web/src/components/trace/JsonExpansionContext.tsx
deleted file mode 100644
index cb2d4eb97c..0000000000
--- a/web/src/components/trace/JsonExpansionContext.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import { createContext, useContext, useCallback } from "react";
-import useSessionStorage from "@/src/components/useSessionStorage";
-
-// Context Provider to store expanded/collapsed state of JSONs across different JSONs with similar structure
-// Used for traces (input/output/metadata) but can be reused at other places.
-
-type ExpandedState = Record<string, boolean> | boolean;
-// Stored then like this:
-// {"key1.key2":true} -> key1 and key2 expanded
-// true - expand all
-// false - collapse all (user action)
-// {} - empty state, use default actions
-
-type JsonExpansionState = {
- input: ExpandedState;
- output: ExpandedState;
- metadata: ExpandedState;
- log: ExpandedState; // for the Trace Log View
-};
-
-type JsonExpansionContextType = {
- expansionState: JsonExpansionState;
- setFieldExpansion: (
- field: keyof JsonExpansionState,
- expansion: Record<string, boolean> | boolean,
- ) => void;
-};
-
-const JsonExpansionContext = createContext<JsonExpansionContextType>({
- expansionState: { input: {}, output: {}, metadata: {}, log: {} },
- setFieldExpansion: () => {},
-});
-
-export const useJsonExpansion = () => useContext(JsonExpansionContext);
-
-export function JsonExpansionProvider({
- children,
-}: {
- children: React.ReactNode;
-}) {
- const [expansionState, setExpansionState] =
- useSessionStorage<JsonExpansionState>("jsonExpansionState", {
- input: {},
- output: {},
- metadata: {},
- log: {},
- });
-
- const setFieldExpansion = useCallback(
- (
- field: keyof JsonExpansionState,
- expansion: Record<string, boolean> | boolean,
- ) => {
- setExpansionState((prev) => ({
- ...prev,
- [field]: expansion,
- }));
- },
- [setExpansionState],
- );
-
- return (
- <JsonExpansionContext.Provider
- value={{ expansionState, setFieldExpansion }}
- >
- {children}
- </JsonExpansionContext.Provider>
- );
-}
diff --git a/web/src/components/trace/SpanItem.tsx b/web/src/components/trace/SpanItem.tsx
deleted file mode 100644
index cda306453d..0000000000
--- a/web/src/components/trace/SpanItem.tsx
+++ /dev/null
@@ -1,176 +0,0 @@
-import { type TreeNode } from "./lib/types";
-import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
-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, formatTokenCounts } from "@/src/utils/numbers";
-import { heatMapTextColor } from "@/src/components/trace/lib/helpers";
-import { type ScoreDomain } from "@langfuse/shared";
-import type Decimal from "decimal.js";
-import React from "react";
-import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
-import { calculateAggregatedUsage } from "@/src/components/trace/BreakdownToolTip";
-
-export interface SpanItemProps {
- node: TreeNode;
- scores: WithStringifiedMetadata<ScoreDomain>[];
- comments?: Map<string, number>;
- showDuration: boolean;
- showCostTokens: boolean;
- showScores: boolean;
- colorCodeMetrics: boolean;
- parentTotalCost?: Decimal;
- parentTotalDuration?: number;
- showComments?: boolean;
- className?: string;
-}
-
-export const SpanItem: React.FC<SpanItemProps> = ({
- node,
- scores,
- comments,
- showDuration,
- showCostTokens,
- showScores,
- colorCodeMetrics,
- parentTotalCost,
- parentTotalDuration,
- showComments = true,
- className,
-}) => {
- // Use pre-computed cost from the TreeNode (computed during tree building)
- const totalCost = node.totalCost;
-
- // Calculate aggregated usage from usageDetails when available
- const aggregatedUsage = node.usageDetails
- ? calculateAggregatedUsage(node.usageDetails)
- : {
- input: node.inputUsage ?? 0,
- output: node.outputUsage ?? 0,
- total: node.totalUsage ?? 0,
- };
-
- const duration =
- node.endTime && node.startTime
- ? node.endTime.getTime() - node.startTime.getTime()
- : node.latency
- ? node.latency * 1000
- : undefined;
-
- const shouldRenderDuration =
- showDuration && Boolean(duration || node.latency);
-
- const shouldRenderCostTokens =
- showCostTokens &&
- Boolean(
- node.inputUsage || node.outputUsage || node.totalUsage || totalCost,
- );
-
- const shouldRenderAnyMetrics = shouldRenderDuration || shouldRenderCostTokens;
-
- return (
- <div className={cn("flex min-w-0 flex-col", className)}>
- <div className="flex min-w-0 items-center gap-2 overflow-hidden">
- <span className="flex-shrink truncate text-xs">
- {node.name || `Unnamed ${node.type.toLowerCase()}`}
- </span>
-
- <div className="flex items-center gap-x-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>
-
- {shouldRenderAnyMetrics && (
- <div className="flex flex-wrap gap-x-2">
- {shouldRenderDuration && (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}
- {shouldRenderCostTokens &&
- (aggregatedUsage.input ||
- aggregatedUsage.output ||
- aggregatedUsage.total) ? (
- <span className="text-xs text-muted-foreground">
- {formatTokenCounts(
- aggregatedUsage.input,
- aggregatedUsage.output,
- aggregatedUsage.total,
- )}
- </span>
- ) : null}
- {shouldRenderCostTokens && 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>
- );
-};
diff --git a/web/src/components/trace/ToolCallDefinitionCard.tsx b/web/src/components/trace/ToolCallDefinitionCard.tsx
deleted file mode 100644
index 22aa56c850..0000000000
--- a/web/src/components/trace/ToolCallDefinitionCard.tsx
+++ /dev/null
@@ -1,176 +0,0 @@
-import { ChevronRight, ChevronDown, Wrench } from "lucide-react";
-import { Badge } from "@/src/components/ui/badge";
-import { cn } from "@/src/utils/tailwind";
-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
-import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
-import useLocalStorage from "@/src/components/useLocalStorage";
-import { useState } from "react";
-
-interface ToolDefinition {
- name: string;
- description?: string;
- parameters?: Record<string, any>;
-}
-
-interface ToolCallDefinitionCardProps {
- tools: ToolDefinition[];
- toolCallCounts: Map<string, number>;
- toolNameToDefinitionNumber?: Map<string, number>;
- className?: string;
-}
-
-export function ToolCallDefinitionCard({
- tools,
- toolCallCounts,
- toolNameToDefinitionNumber,
- className,
-}: ToolCallDefinitionCardProps) {
- const [expandedIndex, setExpandedIndex] = useState<number | null>(null);
- const [currentView, setCurrentView] = useLocalStorage<"formatted" | "json">(
- "toolCallPillViewPreference",
- "formatted",
- );
-
- if (!tools || tools.length === 0) {
- return null;
- }
-
- return (
- <div className={cn("flex flex-col gap-2", className)}>
- {tools.map((tool, index) => {
- const isExpanded = expandedIndex === index;
- const callCount = toolCallCounts.get(tool.name) || 0;
- const isCalled = callCount > 0;
- const toolDefinitionNumber = toolNameToDefinitionNumber?.get(tool.name);
- const statusText =
- callCount === 0
- ? "not called"
- : callCount === 1
- ? "called"
- : `called ${callCount}x`;
-
- return (
- <div
- key={`${tool.name}-${index}`}
- className="w-full overflow-hidden rounded-sm border"
- >
- {/* Card header */}
- <div
- className="flex w-full cursor-pointer items-center justify-between gap-2 px-3 py-1.5 hover:bg-muted/20"
- onClick={() => {
- setExpandedIndex(isExpanded ? null : index);
- }}
- >
- {/* Left: Tool icon + definition number + name */}
- <div className="flex items-center gap-2">
- <Wrench className="h-3.5 w-3.5 text-muted-foreground" />
- <span className="font-mono text-xs font-medium text-foreground">
- {toolDefinitionNumber !== undefined && (
- <span className="mr-1">{toolDefinitionNumber}.</span>
- )}
- {tool.name}
- </span>
- </div>
-
- {/* Right: Status badge + chevron indicator */}
- <div className="flex items-center gap-1.5">
- <Badge
- variant={isCalled ? undefined : "secondary"}
- className={cn(
- "text-xs font-medium",
- isCalled &&
- "select-none border-transparent bg-light-green text-dark-green hover:bg-light-green",
- )}
- >
- {statusText}
- </Badge>
-
- {/* Chevron indicator */}
- {isExpanded ? (
- <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" />
- ) : (
- <ChevronRight className="h-3.5 w-3.5 text-muted-foreground" />
- )}
- </div>
- </div>
-
- {/* Expanded details view */}
- {isExpanded && (
- <div className="relative border-t border-border bg-muted/30 px-4 py-3">
- {/* View toggle tabs - positioned top right */}
- <div className="absolute right-4 top-1">
- <Tabs
- className="h-fit py-0.5"
- value={currentView}
- onValueChange={(value) =>
- setCurrentView(value as "formatted" | "json")
- }
- >
- <TabsList className="h-fit p-0.5">
- <TabsTrigger
- value="formatted"
- className="h-fit px-1 text-xs"
- >
- Formatted
- </TabsTrigger>
- <TabsTrigger value="json" className="h-fit px-1 text-xs">
- JSON
- </TabsTrigger>
- </TabsList>
- </Tabs>
- </div>
-
- {/* Formatted view */}
- {currentView === "formatted" && (
- <div className="space-y-4">
- {/* Description */}
- {tool.description && (
- <div>
- <div className="mb-1.5 text-xs font-medium text-muted-foreground">
- Description
- </div>
- <div className="text-sm text-foreground">
- {tool.description}
- </div>
- </div>
- )}
-
- {/* Parameters */}
- {tool.parameters && (
- <div>
- <div className="mb-1.5 text-xs font-medium text-muted-foreground">
- Parameters
- </div>
- <PrettyJsonView
- json={tool.parameters}
- currentView="pretty"
- codeClassName="text-xs"
- />
- </div>
- )}
-
- {/* Show message if no additional details */}
- {!tool.description && !tool.parameters && (
- <div className="text-sm text-muted-foreground">
- No additional details available
- </div>
- )}
- </div>
- )}
-
- {/* JSON view - full tool object */}
- {currentView === "json" && (
- <PrettyJsonView
- json={tool}
- currentView="json"
- codeClassName="text-xs"
- />
- )}
- </div>
- )}
- </div>
- );
- })}
- </div>
- );
-}
diff --git a/web/src/components/trace/ToolCallInvocationsView.tsx b/web/src/components/trace/ToolCallInvocationsView.tsx
deleted file mode 100644
index 11e8114319..0000000000
--- a/web/src/components/trace/ToolCallInvocationsView.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import { Wrench } from "lucide-react";
-import { cn } from "@/src/utils/tailwind";
-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
-import type { z } from "zod/v4";
-import type { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";
-
-interface ToolCallInvocationsViewProps {
- message: z.infer<typeof ChatMlMessageSchema>;
- toolCallNumbers?: number[];
- className?: string;
-}
-
-export function ToolCallInvocationsView({
- message,
- toolCallNumbers,
- className,
-}: ToolCallInvocationsViewProps) {
- const toolCalls = message.tool_calls;
-
- if (!toolCalls || !Array.isArray(toolCalls) || toolCalls.length === 0) {
- return null;
- }
-
- return (
- <div className={cn("flex flex-col gap-2", className)}>
- {toolCalls.map((toolCall, index) => {
- const invocationNumber = toolCallNumbers?.[index];
- // Parse arguments if they're a JSON string
- let parsedArguments = toolCall.arguments;
- if (typeof toolCall.arguments === "string") {
- try {
- parsedArguments = JSON.parse(toolCall.arguments);
- } catch {
- // Keep as string if parsing fails
- parsedArguments = toolCall.arguments;
- }
- }
-
- return (
- <div
- key={`${toolCall.id}-${index}`}
- className={cn(
- "w-full border-t px-2 py-2",
- (message.role === "assistant" ||
- message.name === "Output" ||
- message.name === "Model") &&
- "bg-accent-light-green",
- )}
- >
- {/* Card header */}
- <div className="flex w-full items-center justify-between gap-2 py-1">
- {/* Left: Tool icon + number + name */}
- <div className="flex items-center gap-2">
- <Wrench className="h-3.5 w-3.5 text-muted-foreground" />
- <span className="font-mono text-xs font-medium text-foreground">
- {invocationNumber !== undefined && (
- <span className="mr-1">{invocationNumber}.</span>
- )}
- {toolCall.name}
- </span>
- </div>
-
- {/* Right: Call ID if available */}
- {toolCall.id && (
- <span className="font-mono text-xs text-muted-foreground">
- {toolCall.id}
- </span>
- )}
- </div>
-
- {/* Arguments view */}
- <div className="py-2 [&_.io-message-content]:px-0">
- <div className="mb-1.5 text-xs font-medium text-muted-foreground">
- Arguments
- </div>
- <PrettyJsonView
- json={parsedArguments}
- currentView="pretty"
- codeClassName="text-xs"
- />
- </div>
- </div>
- );
- })}
- </div>
- );
-}
diff --git a/web/src/components/trace/TraceLogView.tsx b/web/src/components/trace/TraceLogView.tsx
deleted file mode 100644
index 6a106744c9..0000000000
--- a/web/src/components/trace/TraceLogView.tsx
+++ /dev/null
@@ -1,291 +0,0 @@
-import { useMemo, useEffect, useCallback } from "react";
-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
-import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";
-import { api } from "@/src/utils/api";
-import { StringParam, useQueryParam } from "use-query-params";
-import { useQueries } from "@tanstack/react-query";
-import { type JsonNested } from "@langfuse/shared";
-import { useJsonExpansion } from "@/src/components/trace/JsonExpansionContext";
-import { Download } from "lucide-react";
-import { Button } from "@/src/components/ui/button";
-import { downloadTraceAsJson as downloadTraceUtil } from "@/src/components/trace/lib/helpers";
-
-// for Json Expansion Context State (keeps expanded/collapsed state across traces)
-
-// Remove observation ID from keys for persistent expansion state and convert hyphens to dots (PrettyJsonView internal format)
-// Example: "natural-language-filter (abc12345)" -> "natural.language.filter"
-const normalizeKey = (key: string): string => {
- return key.replace(/-/g, ".").replace(/\s*\([a-f0-9]{8}\)/, "");
-};
-
-// Convert normalized expansion state to actual state with observation IDs
-const denormalizeExpansionState = (
- normalizedState: Record<string, boolean> | boolean,
- observationKeys: string[],
-): Record<string, boolean> | boolean => {
- if (typeof normalizedState === "boolean") return normalizedState;
-
- // Build mapping: normalized observation name -> actual observation name(s)
- const normalizedToActual = new Map<string, string[]>();
- observationKeys.forEach((actualKey) => {
- const normalized = normalizeKey(actualKey);
- if (!normalizedToActual.has(normalized)) {
- normalizedToActual.set(normalized, []);
- }
- // store the normalized
- normalizedToActual.get(normalized)!.push(actualKey.replace(/-/g, "."));
- });
-
- const denormalized: Record<string, boolean> = {};
-
- Object.entries(normalizedState).forEach(([normalizedKey, value]) => {
- // First check if this is a top-level observation key (no nested path)
- if (normalizedToActual.has(normalizedKey)) {
- const actualKeys = normalizedToActual.get(normalizedKey)!;
- actualKeys.forEach((actualKey) => {
- denormalized[actualKey] = value;
- });
- return;
- }
-
- // Otherwise split key into top-level observation and nested path
- const parts = normalizedKey.split(".");
- const topLevelNormalized = parts[0];
- const restOfPath = parts.slice(1).join(".");
-
- // Find all actual observation keys that match this normalized key
- const actualTopLevelKeys = normalizedToActual.get(topLevelNormalized) || [];
-
- actualTopLevelKeys.forEach((actualTopLevel) => {
- const actualKey = restOfPath
- ? `${actualTopLevel}.${restOfPath}`
- : actualTopLevel;
- denormalized[actualKey] = value;
- });
- });
-
- return denormalized;
-};
-
-// for session storage, convert current expansion state to normalized state
-const normalizeExpansionState = (
- actualState: Record<string, boolean> | boolean,
-): Record<string, boolean> | boolean => {
- if (typeof actualState === "boolean") return actualState;
-
- const normalized: Record<string, boolean> = {};
-
- Object.entries(actualState).forEach(([key, value]) => {
- const normalizedKey = normalizeKey(key);
- normalized[normalizedKey] = value;
- });
-
- return normalized;
-};
-
-export const TraceLogView = ({
- observations,
- traceId,
- projectId,
- currentView,
- trace,
-}: {
- observations: ObservationReturnTypeWithMetadata[];
- traceId: string;
- projectId: string;
- currentView: "pretty" | "json";
- trace: {
- id: string;
- [key: string]: unknown;
- };
-}) => {
- const [currentObservationId] = useQueryParam("observation", StringParam);
- const [selectedTab] = useQueryParam("view", StringParam);
- const utils = api.useUtils();
- const { expansionState, setFieldExpansion } = useJsonExpansion();
-
- // Load all observations with their input/output for the log view
- const observationsWithIO = useQueries({
- queries: observations.map((obs) =>
- utils.observations.byId.queryOptions({
- observationId: obs.id,
- startTime: obs.startTime,
- traceId: traceId,
- projectId: projectId,
- }),
- ),
- });
-
- const logData = useMemo(() => {
- // Sort observations by start time
- const sortedObservations = [...observations].sort(
- (a, b) => a.startTime.getTime() - b.startTime.getTime(),
- );
-
- const allObsData: Record<
- string,
- {
- id: string;
- type: string;
- name: string | null;
- startTime: string;
- endTime: string | null;
- latency: number | null;
- level: string;
- parentObservationId: string | null;
- model: string | null;
- modelParameters:
- | string
- | number
- | boolean
- | JsonNested[]
- | { [key: string]: JsonNested }
- | null;
- promptName: string | null;
- promptVersion: number | null;
- input: unknown;
- output: unknown;
- metadata: unknown;
- statusMessage: string | null;
- inputUsage: number;
- outputUsage: number;
- totalUsage: number;
- totalCost: number | null;
- }
- > = {};
-
- const idToDisplayName = new Map<string, string>();
-
- sortedObservations.forEach((obs) => {
- const index = observations.findIndex((o) => o.id === obs.id);
- const obsWithIO = observationsWithIO[index]?.data;
-
- const displayName = `${obs.name || obs.type} (${obs.id.substring(0, 8)})`;
- idToDisplayName.set(obs.id, displayName);
-
- allObsData[displayName] = {
- id: obs.id,
- type: obs.type,
- name: obs.name,
- startTime: obs.startTime.toISOString(),
- endTime: obs.endTime?.toISOString() || null,
- latency: obs.latency,
- level: obs.level,
- parentObservationId: obs.parentObservationId,
- model: obs.model,
- modelParameters: obs.modelParameters,
- promptName: obs.promptName,
- promptVersion: obs.promptVersion,
- input: obsWithIO?.input,
- output: obsWithIO?.output,
- metadata: obsWithIO?.metadata,
- statusMessage: obs.statusMessage,
- inputUsage: obs.inputUsage,
- outputUsage: obs.outputUsage,
- totalUsage: obs.totalUsage,
- totalCost: obs.totalCost,
- };
- });
-
- return { data: allObsData, idToDisplayName };
- }, [observations, observationsWithIO]);
-
- // Check if any data is still loading
- const isLoading = observationsWithIO.some((query) => query.isPending);
-
- // Scroll to observation when clicked in trace tree
- useEffect(() => {
- if (currentObservationId && selectedTab === "log") {
- const displayName = logData.idToDisplayName.get(currentObservationId);
- if (displayName) {
- // Convert display name format: hyphens to dots to match convertRowIdToKeyPath
- const keyPathFormat = displayName.replace(/-/g, ".");
- const element = document.querySelector(
- `[data-observation-id="${keyPathFormat}"]`,
- );
- if (element) {
- element.scrollIntoView({ behavior: "smooth", block: "start" });
- }
- }
- }
- }, [currentObservationId, selectedTab, logData]);
-
- // Get top-level observation keys for denormalization
- const observationKeys = useMemo(
- () => Object.keys(logData.data),
- [logData.data],
- );
-
- // Convert normalized state from context to actual state with observation IDs
- const denormalizedState = useMemo(
- () => denormalizeExpansionState(expansionState.log, observationKeys),
- [expansionState.log, observationKeys],
- );
-
- // download includes trace + observations with full I/O
- const downloadLogAsJson = useCallback(() => {
- const observationsWithFullData = observations.map((obs, index) => {
- const obsWithIO = observationsWithIO[index]?.data;
- return {
- ...obs,
- input: obsWithIO?.input,
- output: obsWithIO?.output,
- metadata: obsWithIO?.metadata,
- };
- });
-
- downloadTraceUtil({
- trace,
- observations: observationsWithFullData,
- filename: `trace-with-observations-${traceId}.json`,
- });
- }, [trace, observations, observationsWithIO, traceId]);
-
- // Only render the actual log view when all data is loaded
- // prevents partial rendering and improves performance
- if (isLoading) {
- return (
- <div className="flex h-full w-full flex-col overflow-hidden px-2">
- <div className="mb-2 flex max-h-full min-h-0 w-full flex-col gap-2 overflow-y-auto">
- <div className="rounded-md border p-4">
- <div className="text-sm text-muted-foreground">
- Loading {observations.length} observations...
- </div>
- </div>
- </div>
- </div>
- );
- }
-
- return (
- <div className="flex h-full w-full flex-col overflow-hidden pr-2">
- <div className="mb-2 flex max-h-full min-h-0 w-full flex-col gap-2 overflow-y-auto px-2">
- <PrettyJsonView
- key="trace-log-view"
- title="Concatenated Observation Log"
- json={logData.data}
- currentView={currentView}
- isLoading={false}
- showNullValues={false}
- externalExpansionState={denormalizedState}
- onExternalExpansionChange={(expansion) =>
- setFieldExpansion("log", normalizeExpansionState(expansion))
- }
- stickyTopLevelKey={true}
- showObservationTypeBadge={true}
- controlButtons={
- <Button
- variant="ghost"
- size="sm"
- onClick={downloadLogAsJson}
- title="Download trace log as JSON"
- className="-mr-2"
- >
- <Download className="h-3 w-3" />
- </Button>
- }
- />
- </div>
- </div>
- );
-};
diff --git a/web/src/components/trace/TracePage.tsx b/web/src/components/trace/TracePage.tsx
deleted file mode 100644
index 0dd5020870..0000000000
--- a/web/src/components/trace/TracePage.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-import { StringParam, useQueryParam, withDefault } from "use-query-params";
-import { PublishTraceSwitch } from "@/src/components/publish-object-switch";
-import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
-import { useRouter } from "next/router";
-import { api } from "@/src/utils/api";
-import { StarTraceDetailsToggle } from "@/src/components/star-toggle";
-import { ErrorPage } from "@/src/components/error-page";
-import { DeleteTraceButton } from "@/src/components/deleteButton";
-import Page from "@/src/components/layouts/page";
-import { Trace } from "@/src/components/trace";
-
-export function TracePage({
- traceId,
- timestamp,
-}: {
- traceId: string;
- timestamp?: Date;
-}) {
- const router = useRouter();
-
- const trace = api.traces.byIdWithObservationsAndScores.useQuery(
- {
- traceId,
- timestamp,
- projectId: router.query.projectId as string,
- },
- {
- retry(failureCount, error) {
- if (
- error.data?.code === "UNAUTHORIZED" ||
- error.data?.code === "NOT_FOUND"
- )
- return false;
- return failureCount < 3;
- },
- },
- );
-
- const [selectedTab, setSelectedTab] = useQueryParam(
- "display",
- withDefault(StringParam, "details"),
- );
-
- if (trace.error?.data?.code === "UNAUTHORIZED")
- return <ErrorPage message="You do not have access to this trace." />;
-
- if (trace.error?.data?.code === "NOT_FOUND")
- return (
- <ErrorPage
- title="Trace not found"
- message="The trace is either still being processed or has been deleted."
- additionalButton={{
- label: "Retry",
- onClick: () => void window.location.reload(),
- }}
- />
- );
-
- if (!trace.data) return <div className="p-3">Loading...</div>;
-
- return (
- <Page
- headerProps={{
- title: trace.data.name
- ? `${trace.data.name}: ${trace.data.id}`
- : trace.data.id,
- itemType: "TRACE",
- breadcrumb: [
- {
- name: "Traces",
- href: `/project/${router.query.projectId as string}/traces`,
- },
- ],
- actionButtonsLeft: (
- <div className="ml-1 flex items-center gap-1">
- <div className="flex items-center gap-0">
- <StarTraceDetailsToggle
- traceId={trace.data.id}
- projectId={trace.data.projectId}
- value={trace.data.bookmarked}
- size="icon-xs"
- />
- <PublishTraceSwitch
- traceId={trace.data.id}
- projectId={trace.data.projectId}
- isPublic={trace.data.public}
- size="icon-xs"
- />
- </div>
- </div>
- ),
- actionButtonsRight: (
- <>
- <DetailPageNav
- currentId={traceId}
- path={(entry) => {
- const { view, display, projectId } = router.query;
- const queryParams = new URLSearchParams({
- ...(typeof view === "string" ? { view } : {}),
- ...(typeof display === "string" ? { display } : {}),
- });
- const queryParamString = Boolean(queryParams.size)
- ? `?${queryParams.toString()}`
- : "";
-
- const timestamp =
- entry.params && entry.params.timestamp
- ? encodeURIComponent(entry.params.timestamp)
- : undefined;
-
- return `/project/${projectId as string}/traces/${entry.id}${queryParamString}${timestamp ? `?timestamp=${timestamp}` : ""}`;
- }}
- listKey="traces"
- />
- <DeleteTraceButton
- itemId={traceId}
- projectId={trace.data.projectId}
- redirectUrl={`/project/${router.query.projectId as string}/traces`}
- deleteConfirmation={trace.data.name ?? ""}
- icon
- />
- </>
- ),
- }}
- >
- <div className="flex max-h-full min-h-0 flex-1 overflow-hidden">
- <Trace
- trace={trace.data}
- scores={trace.data.scores}
- projectId={trace.data.projectId}
- observations={trace.data.observations}
- selectedTab={selectedTab}
- setSelectedTab={setSelectedTab}
- />
- </div>
- </Page>
- );
-}
diff --git a/web/src/components/trace/TraceSearchList.tsx b/web/src/components/trace/TraceSearchList.tsx
deleted file mode 100644
index 946bbd8fe4..0000000000
--- a/web/src/components/trace/TraceSearchList.tsx
+++ /dev/null
@@ -1,178 +0,0 @@
-import React, { useRef } from "react";
-import { SpanItem } from "@/src/components/trace/SpanItem";
-import { ItemBadge } from "@/src/components/ItemBadge";
-import { type ScoreDomain } from "@langfuse/shared";
-import type Decimal from "decimal.js";
-import { type TreeNode } from "./lib/types";
-import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
-import { useVirtualizer } from "@tanstack/react-virtual";
-
-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[];
- displayScores: WithStringifiedMetadata<ScoreDomain>[];
- onSelect: (observationId: string | undefined) => void;
- comments?: Map<string, number>;
- showDuration: boolean;
- showCostTokens: boolean;
- showScores: boolean;
- colorCodeMetrics: boolean;
- showComments?: boolean;
- onClearSearch?: () => void;
-}
-
-// Individual search list row component for virtualization
-type SearchListRowProps = {
- item: TraceSearchListItem;
- scores: WithStringifiedMetadata<ScoreDomain>[];
- onSelect: (observationId: string | undefined) => void;
- comments?: Map<string, number>;
- showDuration: boolean;
- showCostTokens: boolean;
- showScores: boolean;
- colorCodeMetrics: boolean;
- showComments: boolean;
-};
-
-const SearchListRow: React.FC<SearchListRowProps> = ({
- item,
- scores,
- onSelect,
- comments,
- showDuration,
- showCostTokens,
- showScores,
- colorCodeMetrics,
- showComments,
-}) => {
- const { node, parentTotalCost, parentTotalDuration, observationId } = item;
-
- return (
- <div
- className="relative flex w-full cursor-pointer !rounded-lg !py-1.5 px-2 hover:bg-muted/40"
- onClick={() => onSelect(observationId)}
- >
- <div className="flex w-full">
- <div className="flex min-w-0 flex-1 items-start gap-2">
- <div className="relative z-20 flex-shrink-0">
- <ItemBadge type={node.type} isSmall className="!size-3" />
- </div>
- <SpanItem
- node={node}
- scores={scores}
- comments={comments}
- showDuration={showDuration}
- showCostTokens={showCostTokens}
- showScores={showScores}
- colorCodeMetrics={colorCodeMetrics}
- parentTotalCost={parentTotalCost}
- parentTotalDuration={parentTotalDuration}
- showComments={showComments}
- />
- </div>
- </div>
- </div>
- );
-};
-
-export const TraceSearchList: React.FC<TraceSearchListProps> = ({
- items,
- // Note: displayScores are merged with client-side score cache; handling optimistic updates
- displayScores: scores,
- onSelect,
- comments,
- showDuration,
- showCostTokens,
- showScores,
- colorCodeMetrics,
- showComments = true,
- onClearSearch,
-}) => {
- const parentRef = useRef<HTMLDivElement>(null);
-
- // Set up virtualizer
- const rowVirtualizer = useVirtualizer({
- count: items.length,
- getScrollElement: () => parentRef.current,
- estimateSize: () => 48, // Approximate height of a search result row
- overscan: 500, // Render 500 extra rows above/below viewport for smooth scrolling
- });
-
- // Handle empty state
- if (items.length === 0) {
- return (
- <div className="w-full">
- <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>
- </div>
- );
- }
-
- return (
- <div className="flex h-full w-full flex-col">
- {/* Virtualized search results */}
- <div ref={parentRef} className="flex-1 overflow-y-auto">
- <div
- style={{
- height: `${rowVirtualizer.getTotalSize()}px`,
- width: "100%",
- position: "relative",
- }}
- >
- {rowVirtualizer.getVirtualItems().map((virtualRow) => {
- const item = items[virtualRow.index];
- return (
- <div
- key={item.node.id}
- data-index={virtualRow.index}
- style={{
- position: "absolute",
- top: 0,
- left: 0,
- width: "100%",
- height: `${virtualRow.size}px`,
- transform: `translateY(${virtualRow.start}px)`,
- }}
- >
- <SearchListRow
- item={item}
- scores={scores}
- onSelect={onSelect}
- comments={comments}
- showDuration={showDuration}
- showCostTokens={showCostTokens}
- showScores={showScores}
- colorCodeMetrics={colorCodeMetrics}
- showComments={showComments}
- />
- </div>
- );
- })}
- </div>
- </div>
-
- {/* Clear search button */}
- {onClearSearch ? (
- <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/TraceSettingsDropdown.tsx b/web/src/components/trace/TraceSettingsDropdown.tsx
deleted file mode 100644
index 6be686252c..0000000000
--- a/web/src/components/trace/TraceSettingsDropdown.tsx
+++ /dev/null
@@ -1,200 +0,0 @@
-import { type ObservationLevelType, ObservationLevel } from "@langfuse/shared";
-import { Settings2 } from "lucide-react";
-import { Button } from "@/src/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
- DropdownMenuSeparator,
- DropdownMenuSub,
- DropdownMenuSubTrigger,
- DropdownMenuSubContent,
- DropdownMenuLabel,
-} from "@/src/components/ui/dropdown-menu";
-import { Switch } from "@/src/components/ui/switch";
-import { cn } from "@/src/utils/tailwind";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-
-export interface TraceSettingsDropdownProps {
- isGraphViewAvailable: boolean;
- showGraph: boolean;
- setShowGraph: (value: boolean) => void;
- showComments: boolean;
- setShowComments: (value: boolean) => void;
- scoresOnObservationTree: boolean;
- setScoresOnObservationTree: (value: boolean) => void;
- durationOnObservationTree: boolean;
- setDurationOnObservationTree: (value: boolean) => void;
- costTokensOnObservationTree: boolean;
- setCostTokensOnObservationTree: (value: boolean) => void;
- colorCodeMetricsOnObservationTree: boolean;
- setColorCodeMetricsOnObservationTree: (value: boolean) => void;
- minObservationLevel: ObservationLevelType;
- setMinObservationLevel: (level: ObservationLevelType) => void;
-}
-
-export const TraceSettingsDropdown = ({
- isGraphViewAvailable,
- showGraph,
- setShowGraph,
- showComments,
- setShowComments,
- scoresOnObservationTree,
- setScoresOnObservationTree,
- durationOnObservationTree,
- setDurationOnObservationTree,
- costTokensOnObservationTree,
- setCostTokensOnObservationTree,
- colorCodeMetricsOnObservationTree,
- setColorCodeMetricsOnObservationTree,
- minObservationLevel,
- setMinObservationLevel,
-}: TraceSettingsDropdownProps) => {
- const capture = usePostHogClientCapture();
- return (
- <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 && (
- <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 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 Duration</span>
- <Switch
- checked={durationOnObservationTree}
- onCheckedChange={setDurationOnObservationTree}
- />
- </div>
- </DropdownMenuItem>
-
- <DropdownMenuItem asChild onSelect={(e) => e.preventDefault()}>
- <div className="flex w-full items-center justify-between">
- <span className="mr-2">Show Cost/Tokens</span>
- <Switch
- checked={costTokensOnObservationTree}
- onCheckedChange={setCostTokensOnObservationTree}
- />
- </div>
- </DropdownMenuItem>
-
- <DropdownMenuItem
- asChild
- onSelect={(e) => e.preventDefault()}
- disabled={
- !durationOnObservationTree && !costTokensOnObservationTree
- }
- className={cn(
- !durationOnObservationTree &&
- !costTokensOnObservationTree &&
- "cursor-not-allowed",
- )}
- >
- <div
- className={cn(
- "flex w-full items-center justify-between",
- !durationOnObservationTree &&
- !costTokensOnObservationTree &&
- "cursor-not-allowed",
- )}
- >
- <span
- className={cn(
- "mr-2",
- !durationOnObservationTree &&
- !costTokensOnObservationTree &&
- "cursor-not-allowed",
- )}
- >
- Color Code Metrics
- </span>
- <Switch
- checked={colorCodeMetricsOnObservationTree}
- onCheckedChange={(e) => setColorCodeMetricsOnObservationTree(e)}
- disabled={
- !durationOnObservationTree && !costTokensOnObservationTree
- }
- className={cn(
- !durationOnObservationTree &&
- !costTokensOnObservationTree &&
- "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>
- );
-};
diff --git a/web/src/components/trace/TraceTimelineView.tsx b/web/src/components/trace/TraceTimelineView.tsx
deleted file mode 100644
index 9740123ebd..0000000000
--- a/web/src/components/trace/TraceTimelineView.tsx
+++ /dev/null
@@ -1,1074 +0,0 @@
-import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";
-import {
- isPresent,
- type ScoreDomain,
- type TraceDomain,
- ObservationLevel,
- type ObservationLevelType,
-} from "@langfuse/shared";
-import React, {
- useEffect,
- useMemo,
- useRef,
- useState,
- useLayoutEffect,
-} from "react";
-import { TreeItem } from "@mui/x-tree-view";
-import type Decimal from "decimal.js";
-import { type TreeNode } from "./lib/types";
-import { InfoIcon, ChevronRight } from "lucide-react";
-import {
- heatMapTextColor,
- nestObservations,
- unnestObservation,
-} from "@/src/components/trace/lib/helpers";
-import { type NestedObservation } from "@/src/utils/types";
-import { cn } from "@/src/utils/tailwind";
-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";
-import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";
-import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
-import { formatIntervalSeconds } from "@/src/utils/dates";
-import { usdFormatter } from "@/src/utils/numbers";
-import { getNumberFromMap, castToNumberMap } from "@/src/utils/map-utils";
-import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
-import { useVirtualizer } from "@tanstack/react-virtual";
-
-// Fixed widths for styling for v1
-const SCALE_WIDTH = 900;
-const STEP_SIZE = 100;
-const TREE_INDENTATION = 12; // default in MUI X TreeView
-
-const PREDEFINED_STEP_SIZES = [
- 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 2.5, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25,
- 35, 40, 45, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500,
-];
-
-// Virtualized timeline data structure
-type FlatTimelineItem = {
- observation:
- | NestedObservation
- | {
- id: string;
- name: string;
- type: "TRACE";
- startTime: Date;
- children: NestedObservation[];
- };
- depth: number;
- treeLines: boolean[];
- isLastSibling: boolean;
- // Pre-computed timeline metrics
- startOffset: number;
- itemWidth: number;
- firstTokenTimeOffset?: number;
- latency?: number;
- isTraceRoot?: boolean;
- // Pre-computed cost for this observation + all descendants
- totalCost?: Decimal;
-};
-
-/**
- * Build a map of observation ID to pre-computed totalCost from the TreeNode structure
- */
-function buildCostMap(tree: TreeNode): Map<string, Decimal> {
- const costMap = new Map<string, Decimal>();
-
- const traverse = (node: TreeNode) => {
- if (node.totalCost) {
- costMap.set(node.id, node.totalCost);
- }
- node.children.forEach(traverse);
- };
-
- traverse(tree);
- return costMap;
-}
-
-/**
- * Flatten nested observations into a flat array with pre-computed timeline metrics.
- * Only includes expanded nodes based on expandedItems.
- * This enables virtualization by converting the tree to a flat list.
- */
-function flattenTimelineTree(
- observations: NestedObservation[],
- expandedItems: string[],
- traceStartTime: Date,
- totalScaleSpan: number,
- costMap?: Map<string, Decimal>,
-): FlatTimelineItem[] {
- const result: FlatTimelineItem[] = [];
-
- const flatten = (
- obs: NestedObservation,
- depth: number,
- treeLines: boolean[],
- isLastSibling: boolean,
- ) => {
- // Calculate timeline metrics ONCE during flattening
- const latency = obs.endTime
- ? (obs.endTime.getTime() - obs.startTime.getTime()) / 1000
- : undefined;
- const startOffset =
- ((obs.startTime.getTime() - traceStartTime.getTime()) /
- totalScaleSpan /
- 1000) *
- SCALE_WIDTH;
- const itemWidth = ((latency ?? 0) / totalScaleSpan) * SCALE_WIDTH;
- const firstTokenTimeOffset = obs.completionStartTime
- ? ((obs.completionStartTime.getTime() - traceStartTime.getTime()) /
- totalScaleSpan /
- 1000) *
- SCALE_WIDTH
- : undefined;
-
- // Get pre-computed cost from the cost map
- const totalCost = costMap?.get(obs.id);
-
- result.push({
- observation: obs,
- depth,
- treeLines,
- isLastSibling,
- startOffset,
- itemWidth,
- firstTokenTimeOffset,
- latency,
- totalCost,
- });
-
- // Only include children if this observation is expanded
- const observationId = `observation-${obs.id}`;
- if (obs.children.length > 0 && expandedItems.includes(observationId)) {
- obs.children.forEach((child, index) => {
- const isChildLast = index === obs.children.length - 1;
- flatten(child, depth + 1, [...treeLines, !isChildLast], isChildLast);
- });
- }
- };
-
- observations.forEach((obs, index) => {
- flatten(obs, 0, [], index === observations.length - 1);
- });
-
- return result;
-}
-
-const calculateStepSize = (latency: number, scaleWidth: number) => {
- const calculatedStepSize = latency / (scaleWidth / STEP_SIZE);
- return (
- PREDEFINED_STEP_SIZES.find((step) => step >= calculatedStepSize) ||
- PREDEFINED_STEP_SIZES[PREDEFINED_STEP_SIZES.length - 1]
- );
-};
-
-function TreeItemInner({
- latency,
- totalScaleSpan,
- type,
- startOffset = 0,
- firstTokenTimeOffset,
- name,
- hasChildren,
- isSelected,
- showDuration = true,
- showCostTokens = true,
- showScores = true,
- showComments = true,
- colorCodeMetrics = false,
- scores,
- commentCount,
- parentTotalDuration,
- totalCost,
- parentTotalCost,
-}: {
- latency?: number;
- totalScaleSpan: number;
- type: ObservationType | "TRACE";
- startOffset?: number;
- firstTokenTimeOffset?: number;
- name?: string | null;
- hasChildren: boolean;
- isSelected: boolean;
- showDuration?: boolean;
- showCostTokens?: boolean;
- showScores?: boolean;
- showComments?: boolean;
- colorCodeMetrics?: boolean;
- scores?: WithStringifiedMetadata<ScoreDomain>[];
- commentCount?: number;
- parentTotalDuration?: number;
- totalCost?: Decimal;
- parentTotalCost?: Decimal;
-}) {
- const itemWidth = ((latency ?? 0) / totalScaleSpan) * SCALE_WIDTH;
- const duration = latency ? latency * 1000 : undefined;
-
- return (
- <div
- className={cn("group my-0.5 flex w-full min-w-fit flex-row items-center")}
- >
- <div className="flex items-center" style={{ width: `${SCALE_WIDTH}px` }}>
- <div
- className={`relative flex flex-row`}
- style={{ width: `${SCALE_WIDTH}px` }}
- >
- {firstTokenTimeOffset ? (
- <div
- className={cn(
- "flex rounded-sm border border-border",
- isSelected
- ? "ring ring-primary-accent"
- : "group-hover:ring group-hover:ring-tertiary",
- )}
- style={{ marginLeft: `${startOffset}px` }}
- >
- <div
- className={cn(
- "flex h-8 items-center justify-start rounded-l-sm border-r border-gray-400 bg-muted opacity-60",
- itemWidth ? "" : "border border-dashed",
- )}
- style={{
- width: `${firstTokenTimeOffset - startOffset}px`,
- }}
- ></div>
- <div
- className={cn(
- "flex h-8 items-center justify-start rounded-r-sm bg-muted",
- itemWidth ? "" : "border border-dashed",
- )}
- style={{
- width: `${itemWidth - (firstTokenTimeOffset - startOffset)}px`,
- }}
- >
- <div
- className={cn(
- "-ml-8 flex flex-row items-center justify-start gap-2 text-xs text-muted-foreground",
- )}
- >
- <span className="text-xxs text-primary">First token</span>
- <ItemBadge type={type} isSmall />
- <span className="whitespace-nowrap text-sm font-medium text-primary">
- {name}
- </span>
- {showComments && commentCount ? (
- <CommentCountIcon count={commentCount} />
- ) : null}
- {showDuration && isPresent(latency) && (
- <span
- className={cn(
- "text-xs text-muted-foreground",
- parentTotalDuration &&
- colorCodeMetrics &&
- duration &&
- heatMapTextColor({
- max: parentTotalDuration,
- value: duration,
- }),
- )}
- >
- {formatIntervalSeconds(latency)}
- </span>
- )}
- {showCostTokens && totalCost && (
- <span
- className={cn(
- "text-xs text-muted-foreground",
- parentTotalCost &&
- colorCodeMetrics &&
- heatMapTextColor({
- max: parentTotalCost,
- value: totalCost,
- }),
- )}
- >
- {usdFormatter(totalCost.toNumber())}
- </span>
- )}
- {showScores && scores && scores.length > 0 && (
- <div className="flex max-h-8 gap-1">
- <GroupedScoreBadges scores={scores} maxVisible={3} />
- </div>
- )}
- </div>
- </div>
- </div>
- ) : (
- <div
- className="relative"
- style={{ marginLeft: `${startOffset}px` }}
- >
- <div
- className={cn(
- "flex h-8 items-center justify-start rounded-sm border border-border bg-muted",
- itemWidth ? "" : "border-dashed",
- isSelected
- ? "ring ring-primary-accent"
- : "group-hover:ring group-hover:ring-tertiary",
- )}
- style={{
- width: `${itemWidth || 10}px`,
- }}
- >
- <div
- className={cn(
- "flex flex-row items-center justify-start gap-2 text-xs text-muted-foreground",
- hasChildren ? "ml-6" : "ml-1",
- )}
- >
- <ItemBadge type={type} isSmall />
- <span className="whitespace-nowrap text-sm font-medium text-primary">
- {name}
- </span>
- {showComments && commentCount ? (
- <CommentCountIcon count={commentCount} />
- ) : null}
- {showDuration && isPresent(latency) && (
- <span
- className={cn(
- "text-xs text-muted-foreground",
- parentTotalDuration &&
- colorCodeMetrics &&
- duration &&
- heatMapTextColor({
- max: parentTotalDuration,
- value: duration,
- }),
- )}
- >
- {formatIntervalSeconds(latency)}
- </span>
- )}
- {showCostTokens && totalCost && (
- <span
- className={cn(
- "text-xs text-muted-foreground",
- parentTotalCost &&
- colorCodeMetrics &&
- heatMapTextColor({
- max: parentTotalCost,
- value: totalCost,
- }),
- )}
- >
- {usdFormatter(totalCost.toNumber())}
- </span>
- )}
- {showScores && scores && scores.length > 0 && (
- <div className="flex max-h-8 gap-1">
- <GroupedScoreBadges scores={scores} maxVisible={3} />
- </div>
- )}
- </div>
- </div>
- </div>
- )}
- </div>
- </div>
- </div>
- );
-}
-
-/**
- * Virtualized timeline row component - replaces recursive TraceTreeItem.
- * Renders a single timeline item with tree lines, expand/collapse button, and Gantt bar.
- */
-function VirtualizedTimelineRow({
- item,
- totalScaleSpan,
- isSelected,
- onClick,
- onToggleExpand,
- hasChildren,
- isExpanded,
- scores,
- commentCount,
- parentTotalCost,
- parentTotalDuration,
- showDuration = true,
- showCostTokens = true,
- showScores = true,
- showComments = true,
- colorCodeMetrics = false,
-}: {
- item: FlatTimelineItem;
- totalScaleSpan: number;
- isSelected: boolean;
- onClick: () => void;
- onToggleExpand: () => void;
- hasChildren: boolean;
- isExpanded: boolean;
- scores?: WithStringifiedMetadata<ScoreDomain>[];
- commentCount?: number;
- parentTotalCost?: Decimal;
- parentTotalDuration?: number;
- showDuration?: boolean;
- showCostTokens?: boolean;
- showScores?: boolean;
- showComments?: boolean;
- colorCodeMetrics?: boolean;
-}) {
- const {
- observation,
- depth,
- treeLines,
- isLastSibling,
- startOffset,
- firstTokenTimeOffset,
- latency,
- isTraceRoot,
- } = item;
-
- // Use pre-computed cost from the item (computed during tree building)
- // For trace root, use the parent total cost passed from props
- const totalCost = isTraceRoot ? parentTotalCost : item.totalCost;
-
- return (
- <div
- className={cn(
- "group my-0.5 flex w-full min-w-fit cursor-pointer flex-row items-center",
- )}
- onClick={onClick}
- >
- {/* Tree lines for ancestor levels (depth - 1) */}
- {depth > 0 && (
- <div className="flex flex-shrink-0">
- {Array.from({ length: depth - 1 }, (_, i) => (
- <div
- key={i}
- className="relative"
- style={{ width: `${TREE_INDENTATION}px` }}
- >
- {treeLines[i] && (
- <div className="absolute bottom-0 left-1.5 top-0 w-px bg-border" />
- )}
- </div>
- ))}
- </div>
- )}
-
- {/* Current level tree connector */}
- {depth > 0 && (
- <div
- className="relative flex-shrink-0"
- style={{ width: `${TREE_INDENTATION}px` }}
- >
- {/* Vertical line up */}
- <div
- className={cn(
- "absolute left-1.5 top-0 w-px bg-border",
- isLastSibling ? "h-3" : "bottom-0",
- )}
- />
- {/* Horizontal line to content */}
- <div className="absolute left-1.5 top-3 h-px w-2 bg-border" />
- </div>
- )}
-
- {/* Expand/collapse button (if has children) */}
- {hasChildren && (
- <button
- onClick={(e) => {
- e.stopPropagation();
- onToggleExpand();
- }}
- className="absolute z-10 rounded hover:bg-muted"
- style={{
- left: `${depth * TREE_INDENTATION + (startOffset > 0 ? startOffset + 4 : 4)}px`,
- top: "50%",
- transform: "translateY(-50%)",
- }}
- >
- <ChevronRight
- className={cn(
- "h-4 w-4 transition-transform duration-200",
- isExpanded && "rotate-90",
- )}
- />
- </button>
- )}
-
- {/* Reuse existing TreeItemInner component */}
- <TreeItemInner
- latency={latency}
- type={observation.type}
- name={observation.name}
- startOffset={startOffset}
- firstTokenTimeOffset={firstTokenTimeOffset}
- totalScaleSpan={totalScaleSpan}
- hasChildren={hasChildren}
- isSelected={isSelected}
- showDuration={showDuration}
- showCostTokens={showCostTokens}
- showScores={showScores}
- showComments={showComments}
- colorCodeMetrics={colorCodeMetrics}
- scores={scores}
- commentCount={commentCount}
- parentTotalDuration={parentTotalDuration}
- totalCost={totalCost}
- parentTotalCost={parentTotalCost}
- />
- </div>
- );
-}
-
-function TraceTreeItem({
- observation,
- level = 0,
- traceStartTime,
- totalScaleSpan,
- projectId,
- scores,
- observations,
- cardWidth,
- commentCounts,
- currentObservationId,
- setCurrentObservationId,
- showDuration,
- showCostTokens,
- showScores,
- showComments,
- colorCodeMetrics,
- parentTotalDuration,
- parentTotalCost,
-}: {
- observation: NestedObservation;
- level: number;
- traceStartTime: Date;
- totalScaleSpan: number;
- projectId: string;
- scores: WithStringifiedMetadata<ScoreDomain>[];
- observations: Array<ObservationReturnTypeWithMetadata>;
- cardWidth: number;
- commentCounts?: Map<string, number>;
- currentObservationId: string | null;
- setCurrentObservationId: (id: string | null) => void;
- showDuration?: boolean;
- showCostTokens?: boolean;
- showScores?: boolean;
- showComments?: boolean;
- colorCodeMetrics?: boolean;
- parentTotalDuration?: number;
- parentTotalCost?: Decimal;
-}) {
- const { startTime, completionStartTime, endTime } = observation || {};
-
- const latency = endTime
- ? (endTime.getTime() - startTime.getTime()) / 1000
- : undefined;
- const startOffset =
- ((startTime.getTime() - traceStartTime.getTime()) / totalScaleSpan / 1000) *
- SCALE_WIDTH;
- const firstTokenTimeOffset = completionStartTime
- ? ((completionStartTime.getTime() - traceStartTime.getTime()) /
- totalScaleSpan /
- 1000) *
- SCALE_WIDTH
- : undefined;
-
- const observationScores = scores.filter(
- (s) => s.observationId === observation.id,
- );
-
- // Calculate total cost for this observation and its children
- const unnestedObservations = unnestObservation(observation);
- const totalCost = calculateDisplayTotalCost({
- allObservations: unnestedObservations,
- });
-
- return (
- <TreeItem
- key={`observation-${observation.id}`}
- itemId={`observation-${observation.id}`}
- onClick={(e) => {
- e.stopPropagation();
- const isIconClick = (e.target as HTMLElement).closest(
- "svg.MuiSvgIcon-root",
- );
- if (!isIconClick) {
- setCurrentObservationId(observation.id);
- }
- }}
- classes={{
- content: `!rounded-none !min-w-fit !px-0 hover:!bg-background ${
- observation.id === currentObservationId ? "!bg-background" : ""
- }`,
- selected: "!bg-background !important",
- label: "!min-w-fit",
- iconContainer: `absolute top-1/2 z-10 -translate-y-1/2`,
- }}
- sx={{
- "& .MuiTreeItem-iconContainer": {
- left: startOffset > 0 ? `${startOffset + 4}px` : "4px",
- },
- }}
- label={
- <TreeItemInner
- latency={latency}
- type={observation.type}
- name={observation.name}
- startOffset={startOffset}
- firstTokenTimeOffset={firstTokenTimeOffset}
- totalScaleSpan={totalScaleSpan}
- hasChildren={!!observation.children?.length}
- isSelected={observation.id === currentObservationId}
- showDuration={showDuration}
- showCostTokens={showCostTokens}
- showScores={showScores}
- showComments={showComments}
- colorCodeMetrics={colorCodeMetrics}
- scores={observationScores}
- commentCount={commentCounts?.get(observation.id)}
- parentTotalDuration={parentTotalDuration}
- totalCost={totalCost}
- parentTotalCost={parentTotalCost}
- />
- }
- >
- {Array.isArray(observation.children)
- ? observation.children.map((child) => (
- <TraceTreeItem
- key={`observation-${child.id}`}
- observation={child}
- level={level + 1}
- traceStartTime={traceStartTime}
- totalScaleSpan={totalScaleSpan}
- projectId={projectId}
- scores={scores}
- observations={observations}
- cardWidth={cardWidth}
- commentCounts={commentCounts}
- currentObservationId={currentObservationId}
- setCurrentObservationId={setCurrentObservationId}
- showDuration={showDuration}
- showCostTokens={showCostTokens}
- showScores={showScores}
- showComments={showComments}
- colorCodeMetrics={colorCodeMetrics}
- parentTotalDuration={parentTotalDuration}
- parentTotalCost={parentTotalCost}
- />
- ))
- : null}
- </TreeItem>
- );
-}
-
-export function TraceTimelineView({
- trace,
- observations,
- projectId,
- // Note: displayScores are merged with client-side score cache; handling optimistic updates
- displayScores: scores,
- currentObservationId,
- setCurrentObservationId,
- expandedItems,
- setExpandedItems,
- showDuration = true,
- showCostTokens = true,
- showScores = true,
- showComments = true,
- colorCodeMetrics = true,
- minLevel,
- setMinLevel,
- containerWidth,
- tree,
-}: {
- trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {
- latency?: number;
- input: string | null;
- output: string | null;
- };
- observations: Array<ObservationReturnTypeWithMetadata>;
- projectId: string;
- displayScores: WithStringifiedMetadata<ScoreDomain>[];
- currentObservationId: string | null;
- setCurrentObservationId: (id: string | null) => void;
- expandedItems: string[];
- setExpandedItems: (items: string[]) => void;
- showDuration?: boolean;
- showCostTokens?: boolean;
- showScores?: boolean;
- showComments?: boolean;
- colorCodeMetrics?: boolean;
- minLevel?: ObservationLevelType;
- setMinLevel?: React.Dispatch<React.SetStateAction<ObservationLevelType>>;
- containerWidth?: number;
- tree: TreeNode;
-}) {
- const { latency } = trace;
-
- const { nestedObservations, hiddenObservationsCount } = useMemo(
- () => nestObservations(observations, minLevel),
- [observations, minLevel],
- );
-
- // Build cost map from tree
- const costMap = useMemo(() => buildCostMap(tree), [tree]);
-
- // Use containerWidth from parent or fallback to ResizeObserver if not provided
- const [cardWidth, setCardWidth] = useState(0);
- const parentRef = useRef<HTMLDivElement>(null);
-
- // Use pre-computed cost from tree, or calculate if not available
- const totalCost = useMemo(
- () =>
- tree?.totalCost ??
- calculateDisplayTotalCost({
- allObservations: observations,
- }),
- [tree?.totalCost, observations],
- );
-
- useEffect(() => {
- 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 resizeObserver = new ResizeObserver(() => {
- handleResize();
- });
-
- resizeObserver.observe(parentRef.current);
-
- return () => {
- resizeObserver.disconnect();
- };
- }
- }
- }, [containerWidth]);
-
- const isAuthenticatedAndProjectMember =
- useIsAuthenticatedAndProjectMember(projectId);
-
- const observationCommentCounts = api.comments.getCountByObjectType.useQuery(
- {
- projectId: trace.projectId,
- objectType: "OBSERVATION",
- },
- {
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- refetchOnMount: false, // prevents refetching loops
- enabled: isAuthenticatedAndProjectMember && showComments,
- },
- );
-
- const traceCommentCounts = api.comments.getCountByObjectId.useQuery(
- {
- projectId: trace.projectId,
- objectId: trace.id,
- objectType: "TRACE",
- },
- {
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- refetchOnMount: false, // prevents refetching loops
- enabled: isAuthenticatedAndProjectMember && showComments,
- },
- );
-
- const timeIndexRef = useRef<HTMLDivElement>(null);
- const timelineContentRef = useRef<HTMLDivElement>(null);
- const outerContainerRef = useRef<HTMLDivElement>(null);
-
- const [contentWidth, setContentWidth] = useState(SCALE_WIDTH);
-
- // Use a useLayoutEffect to measure the actual content width after rendering
- useLayoutEffect(() => {
- if (!timelineContentRef.current) return;
-
- // Use scrollWidth which accounts for all content, including overflow
- const scrollWidth = timelineContentRef.current.scrollWidth;
-
- // Add 20px to account for scrollbar padding
- const newWidth = Math.max(SCALE_WIDTH, scrollWidth);
- if (newWidth !== contentWidth) {
- setContentWidth(newWidth);
- }
- }, [observations, expandedItems, contentWidth]);
-
- // Calculate step size and scale span
- const stepSize = latency ? calculateStepSize(latency, SCALE_WIDTH) : 1;
- const totalScaleSpan = stepSize * (SCALE_WIDTH / STEP_SIZE);
-
- const traceScores = scores.filter((s) => s.observationId === null);
- const totalDuration = latency ? latency * 1000 : 0; // Convert to milliseconds for consistency
-
- // Flatten the tree for virtualization
- const flattenedItems = useMemo(() => {
- if (!latency) return [];
-
- const traceStartTime = nestedObservations[0]?.startTime ?? trace.timestamp;
-
- // Create trace root item
- const traceRootItem: FlatTimelineItem = {
- observation: {
- id: trace.id,
- name: trace.name ?? "",
- type: "TRACE",
- startTime: trace.timestamp,
- children: nestedObservations,
- },
- depth: 0,
- treeLines: [],
- isLastSibling: true,
- startOffset: 0,
- itemWidth: (latency / totalScaleSpan) * SCALE_WIDTH,
- latency,
- isTraceRoot: true,
- };
-
- // Flatten all observations with pre-computed costs
- const flatObservations = flattenTimelineTree(
- nestedObservations,
- expandedItems,
- traceStartTime,
- totalScaleSpan,
- costMap,
- );
-
- return [traceRootItem, ...flatObservations];
- }, [
- nestedObservations,
- expandedItems,
- totalScaleSpan,
- trace,
- latency,
- costMap,
- ]);
-
- // Calculate dynamic content width from flattened items
- const dynamicContentWidth = useMemo(() => {
- const maxEndOffset = flattenedItems.reduce((max, item) => {
- const endOffset = item.startOffset + item.itemWidth;
- return Math.max(max, endOffset);
- }, SCALE_WIDTH);
-
- return Math.max(SCALE_WIDTH, maxEndOffset + 100); // +100px padding
- }, [flattenedItems]);
-
- // Use dynamic content width instead of measured scrollWidth
- const finalContentWidth = dynamicContentWidth;
-
- // Set up virtualizer
- const rowVirtualizer = useVirtualizer({
- count: flattenedItems.length,
- getScrollElement: () => timelineContentRef.current,
- estimateSize: () => 42, // Approximate row height
- overscan: 500,
- });
-
- // Early return after all hooks
- if (!latency) return null;
-
- return (
- <div ref={parentRef} className="h-full w-full px-3">
- <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
- ref={timeIndexRef}
- className="overflow-x-auto"
- style={{
- width: cardWidth,
- scrollbarWidth: "none" /* Firefox */,
- msOverflowStyle: "none" /* IE and Edge */,
- WebkitOverflowScrolling: "touch",
- }}
- onScroll={(e) => {
- if (outerContainerRef.current) {
- outerContainerRef.current.scrollLeft =
- e.currentTarget.scrollLeft;
- }
- }}
- >
- <div style={{ width: `${finalContentWidth}px` }}>
- <div className="mb-2 ml-2">
- <div
- className="relative mr-2 h-8"
- style={{ width: `${SCALE_WIDTH}px` }}
- >
- {Array.from({
- length: Math.ceil(SCALE_WIDTH / STEP_SIZE) + 1,
- }).map((_, index) => {
- const step = stepSize * index;
-
- return (
- <div
- key={index}
- className="absolute h-full border border-l text-xs"
- style={{ left: `${index * STEP_SIZE}px` }}
- >
- <span
- className="absolute left-2 text-xs text-muted-foreground"
- title={`${step.toFixed(2)}s`}
- >
- {step.toFixed(2)}s
- </span>
- </div>
- );
- })}
-
- {/* Add end marker if content exceeds scale */}
- {contentWidth > SCALE_WIDTH && (
- <div
- className="absolute h-full border-r border-dashed"
- style={{ left: `${SCALE_WIDTH}px` }}
- />
- )}
- </div>
- </div>
- </div>
- </div>
- </div>
-
- {/* Main content with scrolling */}
- <div
- ref={outerContainerRef}
- className="flex-1 overflow-x-auto"
- style={{ width: cardWidth }}
- onScroll={(e) => {
- if (timeIndexRef.current) {
- timeIndexRef.current.scrollLeft = e.currentTarget.scrollLeft;
- }
- }}
- >
- <div className="h-full" style={{ width: `${finalContentWidth}px` }}>
- {/* Main timeline content - virtualized */}
- <div
- ref={timelineContentRef}
- className="h-full overflow-y-auto"
- style={{ width: `${finalContentWidth}px` }}
- >
- <div
- style={{
- height: `${rowVirtualizer.getTotalSize()}px`,
- width: "100%",
- position: "relative",
- }}
- >
- {rowVirtualizer.getVirtualItems().map((virtualRow) => {
- const item = flattenedItems[virtualRow.index];
- const observationId =
- item.observation.type === "TRACE"
- ? `trace-${item.observation.id}`
- : `observation-${item.observation.id}`;
- const isExpanded = expandedItems.includes(observationId);
- const isSelected =
- item.observation.type === "TRACE"
- ? currentObservationId === null
- : item.observation.id === currentObservationId;
-
- // Get scores for this observation
- const itemScores =
- item.observation.type === "TRACE"
- ? traceScores
- : scores.filter(
- (s) => s.observationId === item.observation.id,
- );
-
- // Get comment count
- const commentCount =
- item.observation.type === "TRACE"
- ? getNumberFromMap(
- traceCommentCounts.data,
- item.observation.id,
- )
- : castToNumberMap(observationCommentCounts.data)?.get(
- item.observation.id,
- );
-
- return (
- <div
- key={item.observation.id}
- data-index={virtualRow.index}
- style={{
- position: "absolute",
- top: 0,
- left: 0,
- width: "100%",
- transform: `translateY(${virtualRow.start}px)`,
- }}
- >
- <VirtualizedTimelineRow
- item={item}
- totalScaleSpan={totalScaleSpan}
- isSelected={isSelected}
- onClick={() => {
- if (item.observation.type === "TRACE") {
- setCurrentObservationId(null);
- } else {
- setCurrentObservationId(item.observation.id);
- }
- }}
- onToggleExpand={() => {
- const newItems = expandedItems.includes(observationId)
- ? expandedItems.filter((id) => id !== observationId)
- : [...expandedItems, observationId];
- setExpandedItems(newItems);
- }}
- hasChildren={item.observation.children?.length > 0}
- isExpanded={isExpanded}
- scores={itemScores}
- commentCount={commentCount}
- parentTotalCost={totalCost}
- parentTotalDuration={totalDuration}
- showDuration={showDuration}
- showCostTokens={showCostTokens}
- showScores={showScores}
- showComments={showComments}
- colorCodeMetrics={colorCodeMetrics}
- />
- </div>
- );
- })}
- </div>
-
- {minLevel && hiddenObservationsCount > 0 ? (
- <div className="flex items-center gap-1 p-2 py-4">
- <InfoIcon className="h-4 w-4 text-muted-foreground" />
- <span className="flex flex-row gap-1 text-sm text-muted-foreground">
- <p>
- {hiddenObservationsCount} observations below {minLevel}
- level are hidden.
- </p>
- {setMinLevel && (
- <p
- className="cursor-pointer underline"
- onClick={() => setMinLevel(ObservationLevel.DEBUG)}
- >
- Show all
- </p>
- )}
- </span>
- </div>
- ) : null}
- </div>
- </div>
- </div>
- </div>
- </div>
- );
-}
diff --git a/web/src/components/trace/TraceTree.tsx b/web/src/components/trace/TraceTree.tsx
deleted file mode 100644
index a168c62799..0000000000
--- a/web/src/components/trace/TraceTree.tsx
+++ /dev/null
@@ -1,479 +0,0 @@
-import { type TreeNode } from "./lib/types";
-import { cn } from "@/src/utils/tailwind";
-import {
- type ScoreDomain,
- ObservationLevel,
- type ObservationLevelType,
-} from "@langfuse/shared";
-import { useMemo, useRef, useLayoutEffect, useCallback } from "react";
-import { InfoIcon, ChevronRight } from "lucide-react";
-import { Button } from "@/src/components/ui/button";
-import { ItemBadge } from "@/src/components/ItemBadge";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import {
- calculateDisplayTotalCost,
- unnestObservation,
-} from "@/src/components/trace/lib/helpers";
-import type Decimal from "decimal.js";
-import { SpanItem } from "@/src/components/trace/SpanItem";
-import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
-import { api } from "@/src/utils/api";
-import { useVirtualizer } from "@tanstack/react-virtual";
-
-type FlatNode = {
- node: TreeNode;
- depth: number;
- treeLines: boolean[];
- isLastSibling: boolean;
-};
-
-const flattenTree = (
- node: TreeNode,
- collapsedNodes: string[],
- depth = 0,
- treeLines: boolean[] = [],
- isLastSibling = true,
-): FlatNode[] => {
- const flatList: FlatNode[] = [{ node, depth, treeLines, isLastSibling }];
-
- if (node.children.length > 0 && !collapsedNodes.includes(node.id)) {
- const sortedChildren = node.children.sort(
- (a, b) => a.startTime.getTime() - b.startTime.getTime(),
- );
- sortedChildren.forEach((child, index) => {
- const isChildLast = index === sortedChildren.length - 1;
-
- flatList.push(
- ...flattenTree(
- child,
- collapsedNodes,
- depth + 1,
- [...treeLines, !isChildLast],
- isChildLast,
- ),
- );
- });
- }
- return flatList;
-};
-
-export const TraceTree = ({
- tree,
- collapsedNodes,
- toggleCollapsedNode,
- displayScores: scores,
- currentNodeId,
- setCurrentNodeId,
- showDuration,
- showCostTokens,
- showScores,
- colorCodeMetrics,
- nodeCommentCounts,
- className,
- showComments,
- hiddenObservationsCount,
- minLevel,
- setMinLevel,
- projectId,
- traceId,
-}: {
- tree: TreeNode;
- collapsedNodes: string[];
- toggleCollapsedNode: (id: string) => void;
- displayScores: WithStringifiedMetadata<ScoreDomain>[];
- currentNodeId: string | undefined;
- setCurrentNodeId: (id: string | undefined) => void;
- showDuration: boolean;
- showCostTokens: boolean;
- showScores: boolean;
- colorCodeMetrics: boolean;
- nodeCommentCounts?: Map<string, number>;
- className?: string;
- showComments: boolean;
- hiddenObservationsCount?: number;
- minLevel?: ObservationLevelType;
- setMinLevel?: React.Dispatch<React.SetStateAction<ObservationLevelType>>;
- projectId: string;
- traceId: string;
-}) => {
- const utils = api.useUtils();
- const parentRef = useRef<HTMLDivElement>(null);
-
- const handleObservationHover = useCallback(
- (node: TreeNode) => {
- if (node.type !== "TRACE") {
- void utils.observations.byId.prefetch(
- {
- observationId: node.id,
- startTime: node.startTime,
- traceId,
- projectId,
- },
- {
- staleTime: 5 * 60 * 1000,
- },
- );
- }
- },
- [utils, traceId, projectId],
- );
-
- const totalCost = useMemo(() => {
- const convertTreeNodeToObservation = (node: TreeNode): any => ({
- ...node,
- children: node.children.map(convertTreeNodeToObservation),
- });
-
- if (tree.type === "TRACE") {
- const allObservations = tree.children.flatMap((child) =>
- unnestObservation(convertTreeNodeToObservation(child)),
- );
- return calculateDisplayTotalCost({ allObservations });
- }
-
- return calculateDisplayTotalCost({
- allObservations: [convertTreeNodeToObservation(tree)],
- });
- }, [tree]);
-
- const flattenedItems = useMemo(() => {
- // The root node has depth 0, empty treeLines, and isLastSibling=true (it's the only root)
- return flattenTree(tree, collapsedNodes, 0, [], true);
- }, [tree, collapsedNodes]);
-
- // Calculate dynamic row height based on node content
- const estimateSize = useCallback(
- (index: number) => {
- const item = flattenedItems[index];
- if (!item) return 37;
-
- // Base height for node row
- let height = 37;
-
- // Add height for metrics line if visible
- const hasMetrics =
- (showDuration && (item.node.endTime || item.node.latency !== null)) ||
- (showCostTokens &&
- (item.node.inputUsage ||
- item.node.outputUsage ||
- item.node.totalUsage ||
- item.node.totalCost));
- if (hasMetrics) {
- height += 16; // One line of metrics
- }
-
- // Add height for scores if visible
- if (showScores) {
- const nodeScores = scores.filter((s) =>
- item.node.type === "TRACE"
- ? s.observationId === null
- : s.observationId === item.node.id,
- );
-
- if (nodeScores.length > 0) {
- // Estimate 3 score groups per line, each line ~20px
- const estimatedLines = Math.min(Math.ceil(nodeScores.length / 3), 3);
- height += estimatedLines * 20;
- }
- }
-
- return height;
- },
- [flattenedItems, showDuration, showCostTokens, showScores, scores],
- );
-
- const rowVirtualizer = useVirtualizer({
- count: flattenedItems.length,
- getScrollElement: () => parentRef.current,
- estimateSize,
- overscan: 500,
- measureElement:
- typeof window !== "undefined"
- ? (element) => element.getBoundingClientRect().height
- : undefined,
- });
-
- // Track initial currentNodeId to detect URL-based navigation vs user clicks
- const initialCurrentNodeIdRef = useRef(currentNodeId);
- const hasScrolledOnInitialLoadRef = useRef(false);
-
- // Handle scrolling to selected observation on initial page load only
- useLayoutEffect(() => {
- // Only scroll if:
- // 1. We have a currentNodeId
- // 2. We haven't scrolled yet
- // 3. The currentNodeId matches the initial one (meaning it came from URL, not user click)
- if (
- currentNodeId &&
- !hasScrolledOnInitialLoadRef.current &&
- currentNodeId === initialCurrentNodeIdRef.current
- ) {
- // Find the index of the item with the matching node ID
- const index = flattenedItems.findIndex(
- (item) => item.node.id === currentNodeId,
- );
-
- if (index !== -1) {
- // Use virtualizer's scrollToIndex to scroll to the item
- // This works even if the item isn't rendered yet
- rowVirtualizer.scrollToIndex(index, {
- align: "center",
- behavior: "smooth",
- });
- hasScrolledOnInitialLoadRef.current = true;
- }
- }
- }, [currentNodeId, flattenedItems, rowVirtualizer]);
-
- return (
- <div
- ref={parentRef}
- className={cn("h-full overflow-y-auto", className)}
- id="trace-tree"
- >
- <div
- style={{
- height: `${rowVirtualizer.getTotalSize()}px`,
- width: "100%",
- position: "relative",
- }}
- >
- {rowVirtualizer.getVirtualItems().map((virtualRow) => {
- const item = flattenedItems[virtualRow.index];
- return (
- <div
- key={item.node.id}
- data-index={virtualRow.index}
- ref={rowVirtualizer.measureElement}
- style={{
- position: "absolute",
- top: 0,
- left: 0,
- width: "100%",
- transform: `translateY(${virtualRow.start}px)`,
- }}
- >
- <TraceTreeRow
- node={item.node}
- depth={item.depth}
- treeLines={item.treeLines}
- isLastSibling={item.isLastSibling}
- collapsedNodes={collapsedNodes}
- toggleCollapsedNode={toggleCollapsedNode}
- scores={scores}
- comments={nodeCommentCounts}
- currentNodeId={currentNodeId}
- setCurrentNodeId={setCurrentNodeId}
- showDuration={showDuration}
- showCostTokens={showCostTokens}
- showScores={showScores}
- colorCodeMetrics={colorCodeMetrics}
- parentTotalCost={totalCost}
- parentTotalDuration={
- tree.latency ? tree.latency * 1000 : undefined
- }
- showComments={showComments}
- onObservationHover={handleObservationHover}
- />
- </div>
- );
- })}
- </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>
- );
-};
-
-type TraceTreeRowProps = {
- node: TreeNode;
- depth: number;
- treeLines: boolean[];
- isLastSibling: boolean;
- collapsedNodes: string[];
- toggleCollapsedNode: (id: string) => void;
- scores: WithStringifiedMetadata<ScoreDomain>[];
- comments?: Map<string, number>;
- currentNodeId: string | undefined;
- setCurrentNodeId: (id: string | undefined) => void;
- showDuration: boolean;
- showCostTokens: boolean;
- showScores: boolean;
- colorCodeMetrics: boolean;
- parentTotalCost?: Decimal;
- parentTotalDuration?: number;
- showComments: boolean;
- onObservationHover: (node: TreeNode) => void;
-};
-
-const TraceTreeRow = ({
- node,
- depth,
- treeLines,
- isLastSibling,
- collapsedNodes,
- toggleCollapsedNode,
- scores,
- comments,
- currentNodeId,
- setCurrentNodeId,
- showDuration,
- showCostTokens,
- showScores,
- colorCodeMetrics,
- parentTotalCost,
- parentTotalDuration,
- showComments,
- onObservationHover,
-}: TraceTreeRowProps) => {
- const capture = usePostHogClientCapture();
- const collapsed = collapsedNodes.includes(node.id);
-
- const isSelected =
- currentNodeId === node.id || (!currentNodeId && node.type === "TRACE");
-
- return (
- <div
- className={cn(
- "relative flex w-full cursor-pointer rounded-md px-0",
- isSelected ? "bg-muted" : "hover:bg-muted/50",
- )}
- style={{
- paddingTop: 0,
- paddingBottom: 0,
- borderRadius: "0.5rem",
- }}
- onClick={(e) => {
- if (!e.currentTarget?.closest("[data-expand-button]")) {
- setCurrentNodeId(node.type === "TRACE" ? undefined : node.id);
- }
- }}
- >
- <div className="flex w-full pl-2">
- {/* 1. Indents: ancestor level indicators */}
- {depth > 0 && (
- <div className="flex flex-shrink-0">
- {Array.from({ length: depth - 1 }, (_, i) => (
- <div key={i} className="relative w-5">
- {treeLines[i] && (
- <div className="absolute bottom-0 left-3 top-0 w-px bg-border" />
- )}
- </div>
- ))}
- </div>
- )}
-
- {/* 2. Current element bars: up/down/horizontal connectors */}
- {depth > 0 && (
- <div className="relative w-5 flex-shrink-0">
- <>
- {/* Vertical bar connecting upwards */}
- <div
- className={cn(
- "absolute left-3 top-0 w-px bg-border",
- isLastSibling ? "h-3" : "bottom-3",
- )}
- />
- {/* Vertical bar connecting downwards if not last sibling */}
- {!isLastSibling && (
- <div className="absolute bottom-0 left-3 top-3 w-px bg-border" />
- )}
- {/* Horizontal bar connecting to icon */}
- <div className="absolute left-3 top-3 h-px w-2 bg-border" />
- </>
- </div>
- )}
-
- {/* 3. Icon + child connector: fixed width container */}
- <div className="relative flex w-6 flex-shrink-0 flex-col py-1.5">
- <div className="relative z-10 flex h-4 items-center justify-center">
- <ItemBadge type={node.type} isSmall className="!size-3" />
- </div>
- {/* Vertical bar downwards if there are expanded children */}
- {node.children.length > 0 && !collapsed && (
- <div className="absolute bottom-0 left-1/2 top-3 w-px bg-border" />
- )}
- {/* Root node downward connector */}
- {depth === 0 && node.children.length > 0 && !collapsed && (
- <div className="absolute bottom-0 left-1/2 top-3 w-px bg-border" />
- )}
- </div>
-
- {/* 4. Content button: just the text/metrics content */}
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- setCurrentNodeId(node.type === "TRACE" ? undefined : node.id);
- }}
- onMouseEnter={() => onObservationHover(node)}
- title={node.name}
- className={cn(
- "peer relative flex min-w-0 flex-1 items-start rounded-md py-0.5 pl-1 pr-2 text-left",
- )}
- >
- <SpanItem
- node={node}
- scores={scores}
- comments={comments}
- showDuration={showDuration}
- showCostTokens={showCostTokens}
- showScores={showScores}
- colorCodeMetrics={colorCodeMetrics}
- parentTotalCost={parentTotalCost}
- parentTotalDuration={parentTotalDuration}
- showComments={showComments}
- />
- </button>
-
- {/* 5. Expand/Collapse button */}
- {node.children.length > 0 && (
- <div className="flex items-center justify-end py-1 pr-1">
- <Button
- data-expand-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"
- >
- <span
- className={cn(
- "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>
- )}
- </div>
- </div>
- );
-};
diff --git a/web/src/components/trace/hooks/usePanelState.ts b/web/src/components/trace/hooks/usePanelState.ts
deleted file mode 100644
index 3193664b43..0000000000
--- a/web/src/components/trace/hooks/usePanelState.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { useState, useLayoutEffect } from "react";
-
-interface PanelState {
- minSize: number;
- maxSize: number;
-}
-
-export function usePanelState(
- panelGroupId: string,
- viewType: "timeline" | "tree",
-) {
- const MIN_WIDTH_PX = 255;
- const MAX_TREE_WIDTH_PX = 700;
-
- const [panelState, setPanelState] = useState<PanelState>({
- minSize: 10, // Start with low default, will be updated by ResizeObserver
- maxSize: viewType === "timeline" ? 80 : 70,
- });
-
- // Handle PanelGroup width changes
- useLayoutEffect(() => {
- const panelGroup = document.querySelector(
- `[data-panel-group-id="${panelGroupId}"]`,
- );
- if (!panelGroup) return;
-
- const resizeObserver = new ResizeObserver(() => {
- const width = panelGroup.getBoundingClientRect().width;
-
- if (width <= 0) return;
-
- const minSize = Math.max(10, Math.min(60, (MIN_WIDTH_PX / width) * 100));
- const maxSize =
- viewType === "timeline"
- ? 80
- : Math.max(25, Math.min(70, (MAX_TREE_WIDTH_PX / width) * 100));
-
- setPanelState((prev) => {
- if (prev.minSize !== minSize || prev.maxSize !== maxSize) {
- return { minSize, maxSize };
- }
- return prev;
- });
- });
-
- resizeObserver.observe(panelGroup);
-
- return () => {
- resizeObserver.disconnect();
- };
- }, [panelGroupId, viewType]);
-
- return {
- minSize: panelState.minSize,
- maxSize: panelState.maxSize,
- };
-}
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
deleted file mode 100644
index 2288f12e50..0000000000
--- a/web/src/components/trace/index.tsx
+++ /dev/null
@@ -1,1112 +0,0 @@
-import { type ObservationLevelType, type TraceDomain } from "@langfuse/shared";
-import { TraceTree } from "./TraceTree";
-import { ObservationPreview } from "./ObservationPreview";
-import { TracePreview } from "./TracePreview";
-import { TraceSettingsDropdown } from "./TraceSettingsDropdown";
-import {
- StringParam,
- type UrlUpdateType,
- useQueryParam,
-} from "use-query-params";
-import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";
-import { api } from "@/src/utils/api";
-import { castToNumberMap } from "@/src/utils/map-utils";
-import useLocalStorage from "@/src/components/useLocalStorage";
-import {
- Download,
- FoldVertical,
- UnfoldVertical,
- PanelLeftClose,
- PanelLeftOpen,
- Info,
- X,
-} from "lucide-react";
-import { useCallback, useState, useMemo, useRef, useEffect } from "react";
-import { usePanelState } from "./hooks/usePanelState";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { TraceTimelineView } from "@/src/components/trace/TraceTimelineView";
-import { type ScoreDomain, ObservationLevel } from "@langfuse/shared";
-import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";
-import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
-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 { useDebounce } from "@/src/hooks/useDebounce";
-import { Button } from "@/src/components/ui/button";
-import { ActionButton } from "@/src/components/ActionButton";
-import { cn } from "@/src/utils/tailwind";
-import useSessionStorage from "@/src/components/useSessionStorage";
-import { JsonExpansionProvider } from "@/src/components/trace/JsonExpansionContext";
-import { buildTraceUiData } from "@/src/components/trace/lib/helpers";
-import {
- ResizablePanelGroup,
- ResizablePanel,
- ResizableHandle,
- type ImperativePanelHandle,
-} from "@/src/components/ui/resizable";
-import { useMergedScores } from "@/src/features/scores/lib/useMergedScores";
-import { useIsMobile } from "@/src/hooks/use-mobile";
-
-const getNestedObservationKeys = (
- observations: ObservationReturnTypeWithMetadata[],
-): string[] => {
- const keys: string[] = [];
-
- const collectKeys = (obs: ObservationReturnTypeWithMetadata[]) => {
- obs.forEach((observation) => {
- keys.push(`observation-${observation.id}`);
- });
- };
-
- collectKeys(observations);
- return keys;
-};
-
-const OBSERVATION_TYPE_ALERT_ID = "observation-types";
-const STORAGE_KEY = "dismissed-trace-view-notifications";
-
-export function Trace(props: {
- observations: Array<ObservationReturnTypeWithMetadata>;
- trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {
- input: string | null;
- output: string | null;
- };
- scores: WithStringifiedMetadata<ScoreDomain>[];
- projectId: string;
- viewType?: "detailed" | "focused";
- context?: "peek" | "fullscreen"; // are we in peek or fullscreen mode?
- isValidObservationId?: boolean;
- defaultMinObservationLevel?: ObservationLevelType;
- selectedTab?: string;
- setSelectedTab?: (
- newValue?: string | null,
- updateType?: UrlUpdateType,
- ) => void;
-}) {
- const viewType = props.viewType ?? "detailed";
- const context = props.context ?? "fullscreen";
- const isValidObservationId = props.isValidObservationId ?? true;
- const capture = usePostHogClientCapture();
- const isMobile = useIsMobile();
- const [currentObservationId, setCurrentObservationId] = useQueryParam(
- "observation",
- StringParam,
- );
- const [viewTab] = useQueryParam("view", StringParam);
- const [durationOnObservationTree, setDurationOnObservationTree] =
- useLocalStorage("durationOnObservationTree", true);
- const [costTokensOnObservationTree, setCostTokensOnObservationTree] =
- useLocalStorage("costTokensOnObservationTree", true);
- const [scoresOnObservationTree, setScoresOnObservationTree] = useLocalStorage(
- "scoresOnObservationTree",
- true,
- );
- const [
- colorCodeMetricsOnObservationTree,
- setColorCodeMetricsOnObservationTree,
- ] = useLocalStorage("colorCodeMetricsOnObservationTree", true);
- const [showComments, setShowComments] = useLocalStorage("showComments", true);
- const [showGraph, setShowGraph] = useLocalStorage("showGraph", true);
- const [dismissedTraceViewNotifications, setDismissedTraceViewNotifications] =
- useLocalStorage<string[]>(STORAGE_KEY, []);
- const [collapsedNodes, setCollapsedNodes] = useState<string[]>([]);
-
- // Use imperative panel API for collapse/expand
- const treePanelRef = useRef<ImperativePanelHandle>(null);
-
- // TODO: remove, kinda hacky
- // when user clicks Log View, we want to show them that you can collapse the tree panel
- const [shouldPulseToggle, setShouldPulseToggle] = useState(false);
- useEffect(() => {
- if (viewTab === "log") {
- setShouldPulseToggle(true);
- const timeout = setTimeout(() => {
- setShouldPulseToggle(false);
- }, 2000); // Pulse for 2 seconds
- return () => clearTimeout(timeout);
- }
- }, [viewTab]);
-
- // initial panel sizes for graph resizing
- const [timelineGraphSizes, setTimelineGraphSizes] = useLocalStorage(
- "trace-detail-timeline-graph-vertical",
- [60, 40],
- );
- const [treeGraphSizes, setTreeGraphSizes] = useLocalStorage(
- "trace-detail-tree-graph-vertical",
- [60, 40],
- );
-
- const [minObservationLevel, setMinObservationLevel] =
- useState<ObservationLevelType>(
- props.defaultMinObservationLevel ?? ObservationLevel.DEFAULT,
- );
-
- const containerRef = useRef<HTMLDivElement>(null);
- const [searchInputValue, setSearchInputValue] = useState("");
- const [searchQuery, setSearchQuery] = useState("");
-
- // debounce search query text input by 500ms to ensure smooth UI updates.
- // otherwise, it's very laggy to type.
- // can be skipped by pressing ENTER, then search immediately.
- const debouncedSetSearchQuery = useDebounce(setSearchQuery, 500, false);
-
- const handleSearchInputChange = useCallback(
- (value: string) => {
- setSearchInputValue(value);
- debouncedSetSearchQuery(value);
- },
- [debouncedSetSearchQuery],
- );
-
- const handleSearchKeyDown = useCallback(
- (e: React.KeyboardEvent<HTMLInputElement>) => {
- if (e.key === "Enter") {
- setSearchQuery(searchInputValue);
- }
- },
- [searchInputValue],
- );
-
- const panelGroupId = `trace-panel-group-${context}`;
- const panelState = usePanelState(
- panelGroupId,
- props.selectedTab?.includes("timeline") ? "timeline" : "tree",
- );
-
- const TREE_DEFAULT_WIDTH = 30;
-
- // Derive collapsed state from actual panel size (single source of truth = autoSaveId)
- // This avoids cross-tab sync issues from storing collapsed state separately
- const [isTreePanelCollapsed, setIsTreePanelCollapsed] = useState(false);
-
- // Sync initial collapsed state from actual panel size on mount
- useEffect(() => {
- if (treePanelRef.current) {
- const currentSize = treePanelRef.current.getSize();
- const collapsed = currentSize <= 5;
- if (collapsed !== isTreePanelCollapsed) {
- setIsTreePanelCollapsed(collapsed);
- }
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- const isAuthenticatedAndProjectMember = useIsAuthenticatedAndProjectMember(
- props.projectId,
- );
-
- const observationCommentCounts = api.comments.getCountByObjectType.useQuery(
- {
- projectId: props.trace.projectId,
- objectType: "OBSERVATION",
- },
- {
- refetchOnMount: false, // prevents refetching loops
- enabled: isAuthenticatedAndProjectMember,
- },
- );
-
- const traceCommentCounts = api.comments.getCountByObjectId.useQuery(
- {
- projectId: props.trace.projectId,
- objectId: props.trace.id,
- objectType: "TRACE",
- },
- {
- refetchOnMount: false, // prevents refetching loops
- enabled: isAuthenticatedAndProjectMember,
- },
- );
-
- const observationStartTimes = props.observations.map((o) =>
- o.startTime.getTime(),
- );
- const minStartTime = new Date(
- Math.min(...observationStartTimes, Date.now()), // the Date now is a guard for empty obs list
- ).toISOString();
- const maxStartTime = new Date(
- Math.max(...observationStartTimes, 0), // the zero is a guard for empty obs list
- ).toISOString();
-
- const agentGraphDataQuery = api.traces.getAgentGraphData.useQuery(
- {
- projectId: props.trace.projectId,
- traceId: props.trace.id,
- minStartTime,
- maxStartTime,
- },
- {
- enabled: props.observations.length > 0,
- },
- );
-
- const agentGraphData = useMemo(() => {
- return agentGraphDataQuery.data ?? [];
- }, [agentGraphDataQuery.data]);
-
- const isGraphViewAvailable = useMemo(() => {
- if (agentGraphData.length === 0) {
- return false;
- }
-
- // don't show graph UI at all for extremely large traces
- const MAX_NODES_FOR_GRAPH_UI = 5000;
- if (agentGraphData.length >= MAX_NODES_FOR_GRAPH_UI) {
- return false;
- }
-
- // Check if there are observations that would be included in the graph (not SPAN, EVENT, or GENERATION)
- const hasGraphableObservations = agentGraphData.some((obs) => {
- return (
- obs.observationType !== "SPAN" &&
- obs.observationType !== "EVENT" &&
- obs.observationType !== "GENERATION"
- );
- });
-
- const hasLangGraphData = agentGraphData.some(
- (obs) => obs.step != null && obs.step !== 0,
- );
-
- return hasGraphableObservations || hasLangGraphData;
- }, [agentGraphData]);
-
- 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" });
- setCollapsedNodes([]);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- const traceComments = api.comments.getByObjectId.useQuery({
- projectId: props.projectId,
- objectId: props.trace.id,
- objectType: "TRACE",
- });
-
- const downloadTraceAsJson = useCallback(async () => {
- // Fetch fresh comments data
- const comments = await traceComments.refetch();
-
- const exportData = {
- trace: props.trace,
- observations: props.observations,
- comments: comments.data ?? [],
- };
-
- const jsonString = JSON.stringify(exportData, null, 2);
- const blob = new Blob([jsonString], {
- type: "application/json; charset=utf-8",
- });
- const url = URL.createObjectURL(blob);
-
- const link = document.createElement("a");
- link.href = url;
- link.download = `trace-${props.trace.id}.json`;
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- URL.revokeObjectURL(url);
-
- capture("trace_detail:download_button_click");
- }, [props.trace, props.observations, capture, traceComments]);
-
- const [expandedItems, setExpandedItems] = useSessionStorage<string[]>(
- `${props.trace.id}-expanded`,
- [
- `trace-${props.trace.id}`,
- ...getNestedObservationKeys(props.observations),
- ],
- );
-
- // Merge server scores with score cache for optimistic updates in the tree view
- const displayScores = useMergedScores(
- props.scores,
- {
- type: "trace",
- traceId: props.trace.id,
- },
- "target-and-child-scores",
- );
-
- // Build UI data once
- const {
- tree: traceTree,
- hiddenObservationsCount,
- searchItems,
- nodeMap,
- } = useMemo(() => {
- return 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}
- displayScores={displayScores}
- onSelect={setCurrentObservationId}
- comments={commentsMap}
- showDuration={durationOnObservationTree}
- showCostTokens={costTokensOnObservationTree}
- showScores={scoresOnObservationTree}
- colorCodeMetrics={colorCodeMetricsOnObservationTree}
- showComments={showComments}
- onClearSearch={() => {
- setSearchInputValue("");
- setSearchQuery("");
- }}
- />
- ) : (
- <TraceTree
- tree={traceTree}
- collapsedNodes={collapsedNodes}
- toggleCollapsedNode={toggleCollapsedNode}
- displayScores={displayScores}
- currentNodeId={currentObservationId ?? undefined}
- setCurrentNodeId={setCurrentObservationId}
- showDuration={durationOnObservationTree}
- showCostTokens={costTokensOnObservationTree}
- showScores={scoresOnObservationTree}
- showComments={showComments}
- colorCodeMetrics={colorCodeMetricsOnObservationTree}
- nodeCommentCounts={commentsMap}
- hiddenObservationsCount={hiddenObservationsCount}
- minLevel={minObservationLevel}
- setMinLevel={setMinObservationLevel}
- projectId={props.projectId}
- traceId={props.trace.id}
- />
- );
-
- // Find the selected node to pass pre-computed cost to preview
- const selectedNode = useMemo(() => {
- if (!currentObservationId) return null;
- return nodeMap.get(currentObservationId) ?? null;
- }, [nodeMap, currentObservationId]);
-
- const previewContent =
- currentObservationId === undefined ||
- currentObservationId === "" ||
- currentObservationId === null ||
- viewTab === "log" ? (
- <TracePreview
- trace={props.trace}
- observations={props.observations}
- serverScores={props.scores}
- commentCounts={castToNumberMap(traceCommentCounts.data)}
- viewType={viewType}
- precomputedCost={traceTree.totalCost}
- />
- ) : isValidObservationId ? (
- <ObservationPreview
- observations={props.observations}
- serverScores={props.scores}
- projectId={props.projectId}
- currentObservationId={currentObservationId}
- traceId={props.trace.id}
- commentCounts={castToNumberMap(observationCommentCounts.data)}
- viewType={viewType}
- isTimeline={props.selectedTab?.includes("timeline")}
- precomputedCost={selectedNode?.totalCost}
- />
- ) : null;
-
- const observationTypeAlert = useMemo(() => {
- if (
- context === "peek" &&
- props.observations.length > 0 &&
- props.observations.every((o) => o.type === "SPAN") &&
- !dismissedTraceViewNotifications.includes(OBSERVATION_TYPE_ALERT_ID)
- ) {
- return (
- <div className="relative mx-2 mb-2 flex flex-col items-start justify-center gap-2 rounded-lg border border-dashed p-4">
- <Button
- variant="ghost"
- size="sm"
- className="absolute right-1.5 top-1.5 h-5 w-5 p-0"
- onClick={() => {
- capture("notification:dismiss_notification", {
- notification_id: OBSERVATION_TYPE_ALERT_ID,
- });
- setDismissedTraceViewNotifications((prev) =>
- prev.includes(OBSERVATION_TYPE_ALERT_ID)
- ? prev
- : [...prev, OBSERVATION_TYPE_ALERT_ID],
- );
- }}
- title="Dismiss"
- >
- <X className="h-3.5 w-3.5" />
- </Button>
- <div className="flex w-full flex-row items-center gap-2 pr-6">
- <div className="flex h-8 w-8 items-center justify-center rounded-full bg-accent">
- <Info className="h-4 w-4 text-muted-foreground" />
- </div>
- <h3 className="text-sm font-semibold">
- You&apos;re only using spans here.
- </h3>
- </div>
- <p className="text-sm text-muted-foreground">
- You&apos;ll get much richer insights by using specific observation
- types.
- </p>
- <ActionButton
- variant="outline"
- size="sm"
- className="h-auto whitespace-normal py-0.5 text-left"
- href="https://langfuse.com/docs/observability/features/observation-types"
- trackingEventName="notification:click_link"
- trackingProps={{ notification_id: OBSERVATION_TYPE_ALERT_ID }}
- >
- Learn how to use observation types
- </ActionButton>
- </div>
- );
- }
- return null;
- }, [
- context,
- props.observations,
- dismissedTraceViewNotifications,
- setDismissedTraceViewNotifications,
- capture,
- ]);
-
- return (
- <JsonExpansionProvider>
- <div
- ref={containerRef}
- className="relative flex-1 md:h-full md:min-w-[600px]"
- >
- {/* Mobile: Vertical stack without resizing */}
- {isMobile && (
- <div className="flex w-full flex-1 flex-col overflow-y-auto md:hidden">
- {/* Tree Panel - Mobile */}
- <div className="flex-shrink-0 border-b pb-2">
- <Command className="mt-1 flex flex-col gap-1 overflow-hidden rounded-none border-0">
- <div className="flex flex-row justify-between pl-1 pr-2">
- {props.selectedTab?.includes("timeline") ? (
- <span className="whitespace-nowrap px-1 py-1.5 text-sm text-muted-foreground">
- Node display
- </span>
- ) : (
- <div className="relative flex-1">
- <CommandInput
- showBorder={false}
- placeholder="Search"
- className="-ml-2 h-9 min-w-20 border-0 focus:ring-0"
- value={searchInputValue}
- onValueChange={handleSearchInputChange}
- onKeyDown={handleSearchKeyDown}
- />
- </div>
- )}
- {viewType === "detailed" && (
- <div className="flex flex-row items-center gap-0.5">
- {/* Expand/Collapse All Button */}
- {props.selectedTab?.includes("timeline") ? (
- <Button
- onClick={() => {
- 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"
- }
- className="h-7 w-7"
- >
- {expandedItems.includes(`trace-${props.trace.id}`) ? (
- <FoldVertical className="h-3.5 w-3.5" />
- ) : (
- <UnfoldVertical className="h-3.5 w-3.5" />
- )}
- </Button>
- ) : (
- <Button
- onClick={() => {
- const traceRootId = `trace-${props.trace.id}`;
- const isEverythingCollapsed =
- collapsedNodes.includes(traceRootId);
- if (isEverythingCollapsed) {
- expandAll();
- } else {
- const allObservationIds = props.observations.map(
- (o) => o.id,
- );
- setCollapsedNodes([
- ...allObservationIds,
- traceRootId,
- ]);
- }
- }}
- variant="ghost"
- size="icon"
- title={
- collapsedNodes.includes(`trace-${props.trace.id}`)
- ? "Expand all"
- : "Collapse all"
- }
- className="h-7 w-7"
- >
- {collapsedNodes.includes(
- `trace-${props.trace.id}`,
- ) ? (
- <UnfoldVertical className="h-3.5 w-3.5" />
- ) : (
- <FoldVertical className="h-3.5 w-3.5" />
- )}
- </Button>
- )}
-
- {/* Settings Dropdown */}
- <TraceSettingsDropdown
- isGraphViewAvailable={isGraphViewAvailable}
- showGraph={showGraph}
- setShowGraph={setShowGraph}
- showComments={showComments}
- setShowComments={setShowComments}
- scoresOnObservationTree={scoresOnObservationTree}
- setScoresOnObservationTree={setScoresOnObservationTree}
- durationOnObservationTree={durationOnObservationTree}
- setDurationOnObservationTree={
- setDurationOnObservationTree
- }
- costTokensOnObservationTree={
- costTokensOnObservationTree
- }
- setCostTokensOnObservationTree={
- setCostTokensOnObservationTree
- }
- colorCodeMetricsOnObservationTree={
- colorCodeMetricsOnObservationTree
- }
- setColorCodeMetricsOnObservationTree={
- setColorCodeMetricsOnObservationTree
- }
- minObservationLevel={minObservationLevel}
- setMinObservationLevel={setMinObservationLevel}
- />
-
- {/* Download Button */}
- <Button
- variant="ghost"
- size="icon"
- onClick={downloadTraceAsJson}
- title="Download trace as JSON"
- className="h-7 w-7"
- >
- <Download className="h-3.5 w-3.5" />
- </Button>
-
- {/* Timeline Toggle Button */}
- <Button
- variant={
- props.selectedTab?.includes("timeline")
- ? "default"
- : "ghost"
- }
- size="sm"
- onClick={() =>
- props.setSelectedTab?.(
- props.selectedTab?.includes("timeline")
- ? "preview"
- : "timeline",
- "replaceIn",
- )
- }
- className={cn(
- "h-7 px-2 text-xs",
- props.selectedTab?.includes("timeline") &&
- "bg-primary text-primary-foreground",
- )}
- >
- <span className="text-xs">Timeline</span>
- </Button>
- {/* Note: No panel collapse button on mobile */}
- </div>
- )}
- </div>
- <div className="px-2">
- {props.selectedTab?.includes("timeline") ? (
- <div className="w-full">
- <TraceTimelineView
- key={props.trace.id}
- trace={props.trace}
- displayScores={displayScores}
- observations={props.observations}
- projectId={props.trace.projectId}
- currentObservationId={currentObservationId ?? null}
- setCurrentObservationId={setCurrentObservationId}
- expandedItems={expandedItems}
- setExpandedItems={setExpandedItems}
- showDuration={durationOnObservationTree}
- showCostTokens={costTokensOnObservationTree}
- showScores={scoresOnObservationTree}
- showComments={showComments}
- colorCodeMetrics={colorCodeMetricsOnObservationTree}
- minLevel={minObservationLevel}
- setMinLevel={setMinObservationLevel}
- tree={traceTree}
- />
- </div>
- ) : (
- <div className="w-full">
- {treeOrSearchContent}
- {observationTypeAlert}
- </div>
- )}
- </div>
- </Command>
- </div>
-
- {/* Preview Panel - Mobile */}
- <div className="flex-1 pt-4">
- <div className="h-full">{previewContent}</div>
- </div>
- </div>
- )}
-
- {/* Desktop: Horizontal resizable panels */}
- {!isMobile && (
- <div className="hidden md:flex md:h-full md:min-h-0 md:flex-1 md:flex-col">
- <ResizablePanelGroup
- id={panelGroupId}
- direction="horizontal"
- className="flex-1 md:h-full"
- autoSaveId={
- context === "peek"
- ? "trace-layout-peek"
- : "trace-layout-fullscreen"
- }
- >
- <ResizablePanel
- ref={treePanelRef}
- id="trace-tree-panel"
- order={1}
- defaultSize={TREE_DEFAULT_WIDTH}
- minSize={panelState.minSize}
- maxSize={panelState.maxSize}
- collapsible={true}
- collapsedSize={3}
- onResize={(size) => {
- // Derive collapsed state from actual panel size
- const collapsed = size <= 5;
- if (collapsed !== isTreePanelCollapsed) {
- setIsTreePanelCollapsed(collapsed);
- }
- }}
- className="md:flex md:h-full md:flex-col md:overflow-hidden"
- >
- {isTreePanelCollapsed ? (
- <div className="flex h-full w-full items-start justify-center border-r pt-1">
- <Button
- variant="ghost"
- size="icon"
- onClick={() => {
- // Use minSize as the smallest legal value we can expand to
- treePanelRef.current?.resize(panelState.minSize);
- capture("trace_detail:tree_panel_toggle", {
- collapsed: false,
- });
- }}
- title="Show trace tree"
- className={cn(
- "h-10 w-10",
- shouldPulseToggle && "animate-pulse",
- )}
- >
- <PanelLeftOpen className="h-4 w-4" />
- </Button>
- </div>
- ) : (
- <Command className="mt-1 flex h-full flex-col gap-1 overflow-hidden rounded-none border-0">
- <div className="flex flex-row justify-between pl-1 pr-2">
- {props.selectedTab?.includes("timeline") ? (
- <span className="whitespace-nowrap px-1 py-1.5 text-sm text-muted-foreground">
- Node display
- </span>
- ) : (
- <div className="relative flex-1">
- <CommandInput
- showBorder={false}
- placeholder="Search"
- className="h-7 min-w-20 border-0 pr-0 focus:ring-0"
- value={searchInputValue}
- onValueChange={handleSearchInputChange}
- onKeyDown={handleSearchKeyDown}
- />
- </div>
- )}
- {viewType === "detailed" && (
- <div className="flex flex-row items-center gap-0.5">
- {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"
- }
- className="h-7 w-7"
- >
- {expandedItems.includes(
- `trace-${props.trace.id}`,
- ) ? (
- <FoldVertical className="h-3.5 w-3.5" />
- ) : (
- <UnfoldVertical className="h-3.5 w-3.5" />
- )}
- </Button>
- ) : (
- (() => {
- // 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 =
- collapsedNodes.includes(traceRootId);
-
- return (
- <Button
- onClick={() => {
- if (isEverythingCollapsed) {
- expandAll();
- } else {
- // Collapse all observations AND the trace root
- const allObservationIds =
- props.observations.map((o) => o.id);
- setCollapsedNodes([
- ...allObservationIds,
- traceRootId,
- ]);
- }
- }}
- variant="ghost"
- size="icon"
- title={
- isEverythingCollapsed
- ? "Expand all"
- : "Collapse all"
- }
- className="h-7 w-7"
- >
- {isEverythingCollapsed ? (
- <UnfoldVertical className="h-3.5 w-3.5" />
- ) : (
- <FoldVertical className="h-3.5 w-3.5" />
- )}
- </Button>
- );
- })()
- )}
- <TraceSettingsDropdown
- isGraphViewAvailable={isGraphViewAvailable}
- showGraph={showGraph}
- setShowGraph={setShowGraph}
- showComments={showComments}
- setShowComments={setShowComments}
- scoresOnObservationTree={scoresOnObservationTree}
- setScoresOnObservationTree={
- setScoresOnObservationTree
- }
- durationOnObservationTree={
- durationOnObservationTree
- }
- setDurationOnObservationTree={
- setDurationOnObservationTree
- }
- costTokensOnObservationTree={
- costTokensOnObservationTree
- }
- setCostTokensOnObservationTree={
- setCostTokensOnObservationTree
- }
- colorCodeMetricsOnObservationTree={
- colorCodeMetricsOnObservationTree
- }
- setColorCodeMetricsOnObservationTree={
- setColorCodeMetricsOnObservationTree
- }
- minObservationLevel={minObservationLevel}
- setMinObservationLevel={setMinObservationLevel}
- />
- <Button
- variant="ghost"
- size="icon"
- onClick={downloadTraceAsJson}
- title="Download trace as JSON"
- className="h-7 w-7"
- >
- <Download className="h-3.5 w-3.5" />
- </Button>
- <Button
- variant={
- props.selectedTab?.includes("timeline")
- ? "default"
- : "ghost"
- }
- size="sm"
- onClick={() =>
- props.setSelectedTab?.(
- props.selectedTab?.includes("timeline")
- ? "preview"
- : "timeline",
- "replaceIn",
- )
- }
- className={cn(
- "h-7 px-2 text-xs",
- props.selectedTab?.includes("timeline") &&
- "bg-primary text-primary-foreground",
- )}
- >
- <span className="text-xs">Timeline</span>
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={() => {
- if (isTreePanelCollapsed) {
- treePanelRef.current?.resize(
- panelState.minSize,
- );
- } else {
- treePanelRef.current?.collapse();
- }
- capture("trace_detail:tree_panel_toggle", {
- collapsed: !isTreePanelCollapsed,
- });
- }}
- title={
- isTreePanelCollapsed
- ? "Show trace tree"
- : "Hide trace tree"
- }
- className={cn(
- "h-7 w-7",
- shouldPulseToggle && "animate-pulse",
- )}
- >
- {isTreePanelCollapsed ? (
- <PanelLeftOpen className="h-3.5 w-3.5" />
- ) : (
- <PanelLeftClose className="h-3.5 w-3.5" />
- )}
- </Button>
- </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 ? (
- <ResizablePanelGroup
- direction="vertical"
- className="flex h-full w-full flex-col overflow-hidden"
- onLayout={setTimelineGraphSizes}
- >
- <ResizablePanel
- defaultSize={timelineGraphSizes[0]}
- minSize={5}
- maxSize={95}
- className="overflow-y-auto overflow-x-hidden"
- >
- <TraceTimelineView
- key={`timeline-${props.trace.id}`}
- trace={props.trace}
- displayScores={displayScores}
- observations={props.observations}
- projectId={props.trace.projectId}
- currentObservationId={
- currentObservationId ?? null
- }
- setCurrentObservationId={
- setCurrentObservationId
- }
- expandedItems={expandedItems}
- setExpandedItems={setExpandedItems}
- showDuration={durationOnObservationTree}
- showCostTokens={costTokensOnObservationTree}
- showScores={scoresOnObservationTree}
- showComments={showComments}
- colorCodeMetrics={
- colorCodeMetricsOnObservationTree
- }
- minLevel={minObservationLevel}
- setMinLevel={setMinObservationLevel}
- tree={traceTree}
- />
- </ResizablePanel>
-
- <ResizableHandle className="relative h-px bg-border transition-colors duration-200 after:absolute after:inset-x-0 after:top-0 after:h-1 after:-translate-y-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
- defaultSize={timelineGraphSizes[1]}
- minSize={5}
- maxSize={95}
- className="overflow-hidden"
- >
- <TraceGraphView
- key={`graph-timeline-${props.trace.id}`}
- agentGraphData={agentGraphData}
- />
- </ResizablePanel>
- </ResizablePanelGroup>
- ) : (
- <div className="flex h-full w-full overflow-y-auto overflow-x-hidden">
- <TraceTimelineView
- key={props.trace.id}
- trace={props.trace}
- displayScores={displayScores}
- observations={props.observations}
- projectId={props.trace.projectId}
- currentObservationId={
- currentObservationId ?? null
- }
- setCurrentObservationId={
- setCurrentObservationId
- }
- expandedItems={expandedItems}
- setExpandedItems={setExpandedItems}
- showDuration={durationOnObservationTree}
- showCostTokens={costTokensOnObservationTree}
- showScores={scoresOnObservationTree}
- showComments={showComments}
- colorCodeMetrics={
- colorCodeMetricsOnObservationTree
- }
- minLevel={minObservationLevel}
- setMinLevel={setMinObservationLevel}
- tree={traceTree}
- />
- </div>
- )}
- </div>
- ) : (
- <div className="flex h-full w-full flex-col overflow-hidden">
- {isGraphViewAvailable && showGraph ? (
- <ResizablePanelGroup
- direction="vertical"
- className="flex h-full w-full flex-col overflow-hidden"
- onLayout={setTreeGraphSizes}
- >
- <ResizablePanel
- defaultSize={treeGraphSizes[0]}
- minSize={5}
- maxSize={95}
- className="flex flex-col overflow-hidden pl-0 pr-2"
- >
- <div className="min-h-0 overflow-y-auto pb-2">
- {treeOrSearchContent}
- </div>
- <div className="shrink-0">
- {observationTypeAlert}
- </div>
- </ResizablePanel>
-
- <ResizableHandle className="relative h-px bg-border transition-colors duration-200 after:absolute after:inset-x-0 after:top-0 after:h-1 after:-translate-y-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
- defaultSize={treeGraphSizes[1]}
- minSize={5}
- maxSize={95}
- className="overflow-hidden"
- >
- <TraceGraphView
- key={`graph-tree-${props.trace.id}`}
- agentGraphData={agentGraphData}
- />
- </ResizablePanel>
- </ResizablePanelGroup>
- ) : (
- <div className="flex h-full w-full flex-col overflow-hidden pl-0 pr-2">
- <div className="min-h-0 overflow-y-auto pb-2">
- {treeOrSearchContent}
- </div>
- <div className="shrink-0">
- {observationTypeAlert}
- </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
- id="trace-preview-panel"
- order={2}
- defaultSize={70}
- className="min-w-56 overflow-hidden md:h-full"
- >
- <div className="h-full">{previewContent}</div>
- </ResizablePanel>
- </ResizablePanelGroup>
- </div>
- )}
- </div>
- </JsonExpansionProvider>
- );
-}
diff --git a/web/src/components/trace/lib/helpers.ts b/web/src/components/trace/lib/helpers.ts
deleted file mode 100644
index 14e1f046cd..0000000000
--- a/web/src/components/trace/lib/helpers.ts
+++ /dev/null
@@ -1,470 +0,0 @@
-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 ObservationLevelType,
- ObservationLevel,
- type TraceDomain,
-} from "@langfuse/shared";
-import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
-
-export function nestObservations(
- list: ObservationReturnType[],
- minLevel?: ObservationLevelType,
-): {
- nestedObservations: NestedObservation[];
- hiddenObservationsCount: number;
-} {
- if (list.length === 0)
- return { nestedObservations: [], hiddenObservationsCount: 0 };
-
- // Data prep:
- // - Filter for observations with minimum level
- // - Remove parentObservationId attribute from observations if the id does not exist in the list of observations
- const mutableList = list.filter((o) =>
- getObservationLevels(minLevel).includes(o.level),
- );
- const hiddenObservationsCount = list.length - mutableList.length;
-
- // Build a Set of all observation IDs for O(1) lookup instead of O(n) find
- const observationIds = new Set(list.map((o) => o.id));
-
- mutableList.forEach((observation) => {
- if (
- observation.parentObservationId &&
- !observationIds.has(observation.parentObservationId)
- ) {
- observation.parentObservationId = null;
- }
- });
-
- // Step 0: Sort the list by start time to ensure observations are in right order
- const sortedObservations = mutableList.sort(
- (a, b) => a.startTime.getTime() - b.startTime.getTime(),
- );
-
- // Step 1: Create a map where the keys are object IDs, and the values are
- // the corresponding objects with an added 'children' property.
- const map = new Map<string, NestedObservation>();
- for (const obj of sortedObservations) {
- map.set(obj.id, { ...obj, children: [] });
- }
-
- // Step 2: Create another map for the roots of all trees.
- const roots = new Map<string, NestedObservation>();
-
- // Step 3: Populate the 'children' arrays and root map.
- for (const obj of map.values()) {
- if (obj.parentObservationId) {
- const parent = map.get(obj.parentObservationId);
- if (parent) {
- parent.children.push(obj);
- }
- } else {
- roots.set(obj.id, obj);
- }
- }
-
- // Step 4: Sort children by start time for each parent
- for (const obj of map.values()) {
- obj.children.sort((a, b) => a.startTime.getTime() - b.startTime.getTime());
- }
-
- // Step 5: Return the roots.
- return {
- nestedObservations: Array.from(roots.values()),
- hiddenObservationsCount,
- };
-}
-
-export function calculateDisplayTotalCost(p: {
- allObservations: ObservationReturnType[];
- rootObservationId?: string;
-}): Decimal | undefined {
- // if parentObservationId is provided, only calculate cost for children of that observation
- // need to be checked recursively for all children and children of children
- // loop until no more children to be added
- let observations = p.allObservations;
-
- if (p.rootObservationId) {
- observations = observations.filter(
- (o) =>
- o.parentObservationId === p.rootObservationId ||
- o.id === p.rootObservationId,
- );
-
- while (true) {
- const childrenToAdd = p.allObservations.filter(
- (o) =>
- o.parentObservationId &&
- !observations.map((o2) => o2.id).includes(o.id) &&
- observations.map((o2) => o2.id).includes(o.parentObservationId),
- );
- if (childrenToAdd.length === 0) break;
- observations = [...observations, ...childrenToAdd];
- }
- }
-
- const totalCost = observations.reduce<Decimal | undefined>(
- (prev: Decimal | undefined, curr: ObservationReturnType) => {
- // if we don't have any calculated costs, we can't do anything
- if (!curr.totalCost && !curr.inputCost && !curr.outputCost) return prev;
-
- // if we have either input or output cost, but not total cost, we can use that
- if (!curr.totalCost && (curr.inputCost || curr.outputCost)) {
- const inputCost =
- curr.inputCost != null ? new Decimal(curr.inputCost) : new Decimal(0);
-
- const outputCost =
- curr.outputCost != null
- ? new Decimal(curr.outputCost)
- : new Decimal(0);
-
- const combinedCost = inputCost.plus(outputCost);
-
- return prev
- ? prev.plus(combinedCost)
- : combinedCost.isZero()
- ? undefined
- : combinedCost;
- }
-
- if (!curr.totalCost) return prev;
-
- // if we have total cost, we can use that
- return prev ? prev.plus(curr.totalCost) : new Decimal(curr.totalCost);
- },
- undefined,
- );
-
- return totalCost;
-}
-
-function getObservationLevels(minLevel: ObservationLevelType | undefined) {
- const ascendingLevels = [
- ObservationLevel.DEBUG,
- ObservationLevel.DEFAULT,
- ObservationLevel.WARNING,
- ObservationLevel.ERROR,
- ];
-
- if (!minLevel) return ascendingLevels;
-
- const minLevelIndex = ascendingLevels.indexOf(minLevel);
-
- return ascendingLevels.slice(minLevelIndex);
-}
-
-export const heatMapTextColor = (p: {
- min?: Decimal | number;
- max: Decimal | number;
- value: Decimal | number;
-}) => {
- const { min, max, value } = p;
- const minDecimal = min ? new Decimal(min) : new Decimal(0);
- const maxDecimal = new Decimal(max);
- const valueDecimal = new Decimal(value);
-
- const cutOffs: [number, string][] = [
- [0.75, "text-dark-red"], // 75%
- [0.5, "text-dark-yellow"], // 50%
- ];
- const standardizedValueOnStartEndScale = valueDecimal
- .sub(minDecimal)
- .div(maxDecimal.sub(minDecimal));
- const ratio = standardizedValueOnStartEndScale.toNumber();
-
- // pick based on ratio if threshold is exceeded
- for (const [threshold, color] of cutOffs) {
- if (ratio >= threshold) {
- return color;
- }
- }
- return "";
-};
-
-// Helper function to unnest observations for cost calculation
-export const unnestObservation = (nestedObservation: NestedObservation) => {
- const unnestedObservations = [];
- const { children, ...observation } = nestedObservation;
- unnestedObservations.push(observation);
- children.forEach((child) => {
- unnestedObservations.push(...unnestObservation(child));
- });
- return unnestedObservations;
-};
-
-// Transform trace + observations into unified tree structure
-// Helper function to compute and enrich tree nodes with pre-computed costs
-// This is done bottom-up: compute children first, then sum up to parent
-// Also populates the nodeMap for O(1) lookup by ID
-function enrichTreeNodeWithCosts(
- node: TreeNode,
- nodeMap: Map<string, TreeNode>,
-): TreeNode {
- // First, recursively enrich all children
- const enrichedChildren = node.children.map((child) =>
- enrichTreeNodeWithCosts(child, nodeMap),
- );
-
- // Calculate this node's own cost
- let nodeCost: Decimal | undefined;
-
- if (node.calculatedTotalCost != null) {
- const cost = new Decimal(node.calculatedTotalCost);
- if (!cost.isZero()) {
- nodeCost = cost;
- }
- } 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;
- }
- }
-
- // Sum up all children's total costs
- const childrenTotalCost = enrichedChildren.reduce<Decimal | undefined>(
- (acc, child) => {
- if (!child.totalCost) return acc;
- return acc ? acc.plus(child.totalCost) : child.totalCost;
- },
- undefined,
- );
-
- // Total cost = this node's cost + all children's costs
- const totalCost =
- nodeCost && childrenTotalCost
- ? nodeCost.plus(childrenTotalCost)
- : nodeCost || childrenTotalCost;
-
- const enrichedNode = {
- ...node,
- children: enrichedChildren,
- totalCost,
- };
-
- nodeMap.set(enrichedNode.id, enrichedNode);
-
- return enrichedNode;
-}
-
-// This function is only used internally by buildTraceUiData
-function buildTraceTree(
- trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {
- input: string | null;
- output: string | null;
- latency?: number;
- },
- observations: ObservationReturnType[],
- minLevel?: ObservationLevelType,
-): {
- tree: TreeNode;
- hiddenObservationsCount: number;
- nodeMap: Map<string, TreeNode>;
-} {
- // First, nest the observations as before
- const { nestedObservations, hiddenObservationsCount } = nestObservations(
- observations,
- minLevel,
- );
-
- // Create nodeMap for O(1) lookup by ID
- const nodeMap = new Map<string, TreeNode>();
-
- // 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,
- usageDetails: obs.usageDetails,
- calculatedInputCost: obs.inputCost,
- calculatedOutputCost: obs.outputCost,
- calculatedTotalCost: obs.totalCost,
- parentObservationId: obs.parentObservationId,
- traceId: obs.traceId,
- });
-
- // Convert and enrich children with pre-computed costs and populate nodeMap
- const enrichedChildren = nestedObservations
- .map(convertObservationToTreeNode)
- .map((node) => enrichTreeNodeWithCosts(node, nodeMap));
-
- // Calculate total cost for trace root (sum of all top-level children)
- const traceTotalCost = enrichedChildren.reduce<Decimal | undefined>(
- (acc, child) => {
- if (!child.totalCost) return acc;
- return acc ? acc.plus(child.totalCost) : child.totalCost;
- },
- undefined,
- );
-
- // 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: enrichedChildren,
- latency: trace.latency,
- totalCost: traceTotalCost,
- };
-
- // Add trace root to nodeMap as well
- nodeMap.set(tree.id, tree);
-
- return { tree, hiddenObservationsCount, nodeMap };
-}
-
-// UI helper: build flat search items with per-node aggregated totals and root-level parent totals for heatmap scaling
-
-export function buildTraceUiData(
- trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {
- input: string | null;
- output: string | null;
- latency?: number;
- },
- observations: ObservationReturnType[],
- minLevel?: ObservationLevelType,
-): {
- tree: TreeNode;
- hiddenObservationsCount: number;
- searchItems: TraceSearchListItem[];
- nodeMap: Map<string, TreeNode>;
-} {
- const { tree, hiddenObservationsCount, nodeMap } = 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) {
- const cost = new Decimal(node.calculatedTotalCost);
- if (!cost.isZero()) {
- nodeCost = cost;
- }
- } 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, nodeMap };
-}
-
-/**
- * Download trace data with optionally observations as JSON file
- * @param trace - Trace object to download
- * @param observations - Array of observations (can be basic or with full I/O data)
- * @param filename - Optional custom filename (defaults to trace-{traceId}.json)
- */
-export function downloadTraceAsJson(params: {
- trace: {
- id: string;
- [key: string]: unknown;
- };
- observations: unknown[];
- filename?: string;
-}) {
- const { trace, observations, filename } = params;
-
- const exportData = {
- trace,
- observations,
- };
-
- const jsonString = JSON.stringify(exportData, null, 2);
- const blob = new Blob([jsonString], {
- type: "application/json; charset=utf-8",
- });
- const url = URL.createObjectURL(blob);
-
- const link = document.createElement("a");
- link.href = url;
- link.download = filename || `trace-${trace.id}.json`;
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- URL.revokeObjectURL(url);
-}
diff --git a/web/src/components/trace/lib/types.ts b/web/src/components/trace/lib/types.ts
deleted file mode 100644
index 28c656549e..0000000000
--- a/web/src/components/trace/lib/types.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { type ObservationType } from "@langfuse/shared";
-import type Decimal from "decimal.js";
-
-// 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;
- usageDetails?: Record<string, number>;
- calculatedInputCost?: any;
- calculatedOutputCost?: any;
- calculatedTotalCost?: any;
- // Pre-computed cost for this node + all descendants
- // Calculated bottom-up during tree construction for O(1) access
- // Will be undefined if neither this node nor any descendants have cost data
- totalCost?: Decimal;
- // Trace-specific properties (when type === 'TRACE')
- latency?: number;
- // Observation-specific properties (when type !== 'TRACE')
- parentObservationId?: string | null;
- traceId?: string;
-};
diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace2/ObservationPreview.tsx
similarity index 98%
rename from web/src/components/trace/ObservationPreview.tsx
rename to web/src/components/trace2/ObservationPreview.tsx
index fb95650d93..41a13651b8 100644
--- a/web/src/components/trace/ObservationPreview.tsx
+++ b/web/src/components/trace2/ObservationPreview.tsx
@@ -7,7 +7,7 @@ import {
import { Badge } from "@/src/components/ui/badge";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import { api } from "@/src/utils/api";
-import { IOPreview } from "@/src/components/trace/IOPreview";
+import { IOPreview } from "@/src/components/trace2/components/IOPreview/IOPreview";
import { formatIntervalSeconds } from "@/src/utils/dates";
import Link from "next/link";
import { usdFormatter, formatTokenCounts } from "@/src/utils/numbers";
@@ -20,7 +20,7 @@ import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton
import { cn } from "@/src/utils/tailwind";
import { NewDatasetItemFromExistingObject } from "@/src/features/datasets/components/NewDatasetItemFromExistingObject";
import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";
-import { calculateDisplayTotalCost } from "@/src/components/trace/lib/helpers";
+import { calculateDisplayTotalCost } from "@/src/components/trace2/lib/helpers";
import { Fragment, useState } from "react";
import type Decimal from "decimal.js";
import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";
@@ -30,7 +30,10 @@ import {
TabsBarTrigger,
TabsBarContent,
} from "@/src/components/ui/tabs-bar";
-import { BreakdownTooltip, calculateAggregatedUsage } from "./BreakdownToolTip";
+import {
+ BreakdownTooltip,
+ calculateAggregatedUsage,
+} from "@/src/components/trace2/components/_shared/BreakdownToolTip";
import { ExternalLinkIcon, InfoIcon, PlusCircle } from "lucide-react";
import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";
import { LocalIsoDate } from "@/src/components/LocalIsoDate";
@@ -38,8 +41,8 @@ import { ItemBadge } from "@/src/components/ItemBadge";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import { useRouter } from "next/router";
-import { CopyIdsPopover } from "@/src/components/trace/CopyIdsPopover";
-import { useJsonExpansion } from "@/src/components/trace/JsonExpansionContext";
+import { CopyIdsPopover } from "@/src/components/trace2/components/_shared/CopyIdsPopover";
+import { useJsonExpansion } from "@/src/components/trace2/contexts/JsonExpansionContext";
import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
export const ObservationPreview = ({
diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace2/TracePreview.tsx
similarity index 94%
rename from web/src/components/trace/TracePreview.tsx
rename to web/src/components/trace2/TracePreview.tsx
index f5122f96f1..daaaf95590 100644
--- a/web/src/components/trace/TracePreview.tsx
+++ b/web/src/components/trace2/TracePreview.tsx
@@ -8,7 +8,7 @@ import {
import { AggUsageBadge } from "@/src/components/token-usage-badge";
import { Badge } from "@/src/components/ui/badge";
import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";
-import { IOPreview } from "@/src/components/trace/IOPreview";
+import { IOPreview } from "@/src/components/trace2/components/IOPreview/IOPreview";
import { formatIntervalSeconds } from "@/src/utils/dates";
import { withDefault, StringParam, useQueryParam } from "use-query-params";
import ScoresTable from "@/src/components/table/use-cases/scores";
@@ -28,7 +28,7 @@ import {
TabsBarList,
TabsBarTrigger,
} from "@/src/components/ui/tabs-bar";
-import { BreakdownTooltip } from "@/src/components/trace/BreakdownToolTip";
+import { BreakdownTooltip } from "@/src/components/trace2/components/_shared/BreakdownToolTip";
import { ExternalLinkIcon, InfoIcon } from "lucide-react";
import { LocalIsoDate } from "@/src/components/LocalIsoDate";
import { ItemBadge } from "@/src/components/ItemBadge";
@@ -36,9 +36,11 @@ import Link from "next/link";
import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { useRouter } from "next/router";
-import { CopyIdsPopover } from "@/src/components/trace/CopyIdsPopover";
-import { useJsonExpansion } from "@/src/components/trace/JsonExpansionContext";
-import { TraceLogView } from "@/src/components/trace/TraceLogView";
+import { CopyIdsPopover } from "@/src/components/trace2/components/_shared/CopyIdsPopover";
+import { useJsonExpansion } from "@/src/components/trace2/contexts/JsonExpansionContext";
+import { TraceLogView } from "@/src/components/trace2/components/TraceLogView/TraceLogView";
+import { TraceDataProvider } from "@/src/components/trace2/contexts/TraceDataContext";
+import { ViewPreferencesProvider } from "@/src/components/trace2/contexts/ViewPreferencesContext";
import {
Tooltip,
TooltipContent,
@@ -434,13 +436,20 @@ export const TracePreview = ({
</div>
</TabsBarContent>
<TabsBarContent value="log">
- <TraceLogView
- observations={observations}
- traceId={trace.id}
- projectId={trace.projectId}
- currentView={currentView}
+ <TraceDataProvider
trace={trace}
- />
+ observations={observations}
+ scores={scores}
+ comments={commentCounts ?? new Map()}
+ >
+ <ViewPreferencesProvider>
+ <TraceLogView
+ traceId={trace.id}
+ projectId={trace.projectId}
+ currentView={currentView}
+ />
+ </ViewPreferencesProvider>
+ </TraceDataProvider>
</TabsBarContent>
{showScoresTab && (
<TabsBarContent
diff --git a/web/src/components/trace2/components/_shared/BreakdownToolTip.tsx b/web/src/components/trace2/components/_shared/BreakdownToolTip.tsx
index 8de1c32cbb..506f802cae 100644
--- a/web/src/components/trace2/components/_shared/BreakdownToolTip.tsx
+++ b/web/src/components/trace2/components/_shared/BreakdownToolTip.tsx
@@ -12,16 +12,64 @@ interface Details {
[key: string]: number | undefined;
}
+/**
+ * Aggregates usage or cost details by summing values based on key patterns.
+ * Used to calculate input/output/total values from detailed breakdowns.
+ */
+export const calculateAggregatedUsage = (
+ details: Details | Details[],
+): {
+ input: number;
+ output: number;
+ total: number;
+} => {
+ const aggregatedDetails = Array.isArray(details)
+ ? details.reduce<Details>((acc, curr) => {
+ Object.entries(curr).forEach(([key, value]) => {
+ acc[key] = new Decimal(acc[key] || 0)
+ .plus(new Decimal(value || 0))
+ .toNumber();
+ });
+ return acc;
+ }, {})
+ : details;
+
+ // Sum all keys containing "input"
+ const input = Object.entries(aggregatedDetails)
+ .filter(([key]) => key.includes("input"))
+ .reduce(
+ (sum, [_, value]) =>
+ new Decimal(sum).plus(new Decimal(value ?? 0)).toNumber(),
+ 0,
+ );
+
+ // Sum all keys containing "output"
+ const output = Object.entries(aggregatedDetails)
+ .filter(([key]) => key.includes("output"))
+ .reduce(
+ (sum, [_, value]) =>
+ new Decimal(sum).plus(new Decimal(value ?? 0)).toNumber(),
+ 0,
+ );
+
+ // Get total or calculate from input + output
+ const total = aggregatedDetails.total ?? input + output;
+
+ return { input, output, total };
+};
+
interface BreakdownTooltipProps {
details: Details | Details[];
children: React.ReactNode;
isCost?: boolean;
+ pricingTierName?: string;
}
export const BreakdownTooltip = ({
details,
children,
isCost = false,
+ pricingTierName,
}: BreakdownTooltipProps) => {
const [isOpen, setIsOpen] = useState(false);
@@ -72,6 +120,12 @@ export const BreakdownTooltip = ({
{details.length === 1 ? "generation" : "generations"}
</span>
)}
+ {pricingTierName && (
+ <div className="flex justify-between text-xs text-muted-foreground">
+ <span>Pricing Tier:</span>
+ <span className="font-mono">{pricingTierName}</span>
+ </div>
+ )}
</div>
{/* Input Section */}
diff --git a/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx b/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
index ae812303dd..f013d0312b 100644
--- a/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
+++ b/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
@@ -8,7 +8,7 @@ import { SessionIO } from "@/src/components/session";
import { useState, useEffect } from "react";
import { Button } from "@/src/components/ui/button";
import { ItemBadge } from "@/src/components/ItemBadge";
-import { CopyIdsPopover } from "@/src/components/trace/CopyIdsPopover";
+import { CopyIdsPopover } from "@/src/components/trace2/components/_shared/CopyIdsPopover";
import { Badge } from "@/src/components/ui/badge";
import { Separator } from "@/src/components/ui/separator";
import Link from "next/link";
diff --git a/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx b/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
index 14c2585ae5..bca0f0dacd 100644
--- a/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
+++ b/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
@@ -1,6 +1,7 @@
-import { Trace } from "@/src/components/trace";
-import { ObservationPreview } from "@/src/components/trace/ObservationPreview";
-import { TracePreview } from "@/src/components/trace/TracePreview";
+import { Trace } from "@/src/components/trace2/Trace";
+import { ObservationPreview } from "@/src/components/trace2/ObservationPreview";
+import { TracePreview } from "@/src/components/trace2/TracePreview";
+import { JsonExpansionProvider } from "@/src/components/trace2/contexts/JsonExpansionContext";
import {
type AnnotationQueueItem,
AnnotationQueueObjectType,
@@ -13,7 +14,7 @@ import { AnnotationProcessingLayout } from "../shared/AnnotationProcessingLayout
import { api } from "@/src/utils/api";
import { castToNumberMap } from "@/src/utils/map-utils";
import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";
-import { buildTraceUiData } from "@/src/components/trace/lib/helpers";
+import { buildTraceUiData } from "@/src/components/trace2/lib/helpers";
interface TraceAnnotationProcessorProps {
item: AnnotationQueueItem & {
@@ -103,32 +104,34 @@ export const TraceAnnotationProcessor: React.FC<
const leftPanel =
view === "hideTree" ? (
- <div className="flex h-full flex-col overflow-y-auto pl-4">
- {item.objectType === AnnotationQueueObjectType.TRACE ? (
- <TracePreview
- key={data.id}
- trace={data}
- serverScores={data.scores}
- observations={data.observations}
- viewType="focused"
- showCommentButton={true}
- commentCounts={castToNumberMap(traceCommentCounts.data)}
- precomputedCost={traceTree?.totalCost}
- />
- ) : (
- <ObservationPreview
- observations={data.observations}
- serverScores={data.scores}
- projectId={item.projectId}
- currentObservationId={item.objectId}
- precomputedCost={nodeMap.get(item.objectId)?.totalCost}
- traceId={traceId}
- viewType="focused"
- showCommentButton={true}
- commentCounts={castToNumberMap(observationCommentCounts.data)}
- />
- )}
- </div>
+ <JsonExpansionProvider>
+ <div className="flex h-full flex-col overflow-y-auto pl-4">
+ {item.objectType === AnnotationQueueObjectType.TRACE ? (
+ <TracePreview
+ key={data.id}
+ trace={data}
+ serverScores={data.scores}
+ observations={data.observations}
+ viewType="focused"
+ showCommentButton={true}
+ commentCounts={castToNumberMap(traceCommentCounts.data)}
+ precomputedCost={traceTree?.totalCost}
+ />
+ ) : (
+ <ObservationPreview
+ observations={data.observations}
+ serverScores={data.scores}
+ projectId={item.projectId}
+ currentObservationId={item.objectId}
+ precomputedCost={nodeMap.get(item.objectId)?.totalCost}
+ traceId={traceId}
+ viewType="focused"
+ showCommentButton={true}
+ commentCounts={castToNumberMap(observationCommentCounts.data)}
+ />
+ )}
+ </div>
+ </JsonExpansionProvider>
) : (
<div className="flex h-full flex-col overflow-y-auto">
<Trace
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index a15e4ae75b..23094f8565 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -34,7 +34,7 @@ import { type ScoreAggregate } from "@langfuse/shared";
import TagList from "@/src/features/tag/components/TagList";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";
-import { BreakdownTooltip } from "@/src/components/trace/BreakdownToolTip";
+import { BreakdownTooltip } from "@/src/components/trace2/components/_shared/BreakdownToolTip";
import { InfoIcon, PlusCircle } from "lucide-react";
import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";
import { LocalIsoDate } from "@/src/components/LocalIsoDate";
diff --git a/web/src/features/prompts/components/prompt-detail.tsx b/web/src/features/prompts/components/prompt-detail.tsx
index 23797a84e2..c55977a375 100644
--- a/web/src/features/prompts/components/prompt-detail.tsx
+++ b/web/src/features/prompts/components/prompt-detail.tsx
@@ -7,7 +7,7 @@ import {
withDefault,
} from "use-query-params";
import type { z } from "zod/v4";
-import { OpenAiMessageView } from "@/src/components/trace/IOPreview";
+import { OpenAiMessageView } from "@/src/components/trace2/components/IOPreview/components/ChatMessageList";
import {
TabsBar,
TabsBarList,
@@ -528,6 +528,9 @@ export const PromptDetail = ({
<div className="w-full">
<OpenAiMessageView
messages={chatMessages}
+ shouldRenderMarkdown={true}
+ currentView="pretty"
+ messageToToolCallNumbers={new Map()}
collapseLongHistory={false}
projectIdForPromptButtons={projectId}
/>
diff --git a/web/src/pages/project/[projectId]/traces-old/[traceId].tsx b/web/src/pages/project/[projectId]/traces-old/[traceId].tsx
deleted file mode 100644
index 1fd763d566..0000000000
--- a/web/src/pages/project/[projectId]/traces-old/[traceId].tsx
+++ /dev/null
@@ -1,14 +0,0 @@
-import { TracePage } from "@/src/components/trace/TracePage";
-import { useRouter } from "next/router";
-
-export default function Trace() {
- const router = useRouter();
- const traceId = router.query.traceId as string;
-
- const timestamp =
- router.query.timestamp && typeof router.query.timestamp === "string"
- ? new Date(decodeURIComponent(router.query.timestamp))
- : undefined;
-
- return <TracePage traceId={traceId} timestamp={timestamp} />;
-}
diff --git a/web/src/pages/project/[projectId]/traces-old/setup.tsx b/web/src/pages/project/[projectId]/traces-old/setup.tsx
deleted file mode 100644
index a6c3c0bbc5..0000000000
--- a/web/src/pages/project/[projectId]/traces-old/setup.tsx
+++ /dev/null
@@ -1,140 +0,0 @@
-import React, { useEffect } from "react";
-import { useRouter } from "next/router";
-import { api } from "@/src/utils/api";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import ContainerPage from "@/src/components/layouts/container-page";
-import { ActionButton } from "@/src/components/ActionButton";
-import { SubHeader } from "@/src/components/layouts/header";
-import { Button } from "@/src/components/ui/button";
-import { ApiKeyRender } from "@/src/features/public-api/components/CreateApiKeyButton";
-import { type RouterOutput } from "@/src/utils/types";
-import { useState } from "react";
-
-const TracingSetup = ({
- projectId,
- hasTracingConfigured,
-}: {
- projectId: string;
- hasTracingConfigured?: boolean;
-}) => {
- const [apiKeys, setApiKeys] = useState<
- RouterOutput["projectApiKeys"]["create"] | null
- >(null);
- const utils = api.useUtils();
- const mutCreateApiKey = api.projectApiKeys.create.useMutation({
- onSuccess: (data) => {
- utils.projectApiKeys.invalidate();
- setApiKeys(data);
- },
- });
-
- const createApiKey = async () => {
- try {
- await mutCreateApiKey.mutateAsync({ projectId });
- } catch (error) {
- console.error("Error creating API key:", error);
- }
- };
-
- return (
- <div className="space-y-8">
- <div>
- <SubHeader title="1. Get API Keys" />
- {apiKeys ? (
- <ApiKeyRender
- generatedKeys={apiKeys}
- scope={"project"}
- className="mt-4"
- />
- ) : (
- <div className="flex flex-col gap-4">
- <p className="text-sm text-muted-foreground">
- You need to create an API key to start tracing your application.
- You can create more keys later in the project settings.
- </p>
- <div className="flex gap-2">
- <Button
- onClick={createApiKey}
- loading={mutCreateApiKey.isPending}
- className="self-start"
- >
- Create new API key
- </Button>
- <ActionButton
- href={`/project/${projectId}/settings/api-keys`}
- variant="secondary"
- >
- Manage API keys
- </ActionButton>
- </div>
- </div>
- )}
- </div>
-
- <div>
- <SubHeader
- title="2. Instrument Your Application"
- status={hasTracingConfigured ? "active" : "pending"}
- />
- <p className="mb-4 text-sm text-muted-foreground">
- Langfuse relies on OpenTelemetry to instrument your application and
- export LLM application/agent traces to Langfuse. You can use one of
- our SDKs or 50+ framework integrations. Please follow the quickstart
- in the documentation to add Langfuse to your application.
- </p>
- <ActionButton href="https://langfuse.com/docs/observability/get-started">
- Instrumentation Quickstart
- </ActionButton>
- </div>
- </div>
- );
-};
-
-export default function TracesSetupPage() {
- const router = useRouter();
- const projectId = router.query.projectId as string;
-
- // Check if the user has tracing configured
- const { data: hasTracingConfigured } =
- api.traces.hasTracingConfigured.useQuery(
- { projectId },
- {
- enabled: !!projectId,
- refetchInterval: 5000,
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- },
- );
-
- const capture = usePostHogClientCapture();
- useEffect(() => {
- if (hasTracingConfigured !== undefined) {
- capture("onboarding:tracing_check_active", {
- active: hasTracingConfigured,
- });
- }
- }, [hasTracingConfigured, capture]);
-
- return (
- <ContainerPage
- headerProps={{
- title: "Tracing Setup",
- help: {
- description:
- "Setup tracing to track and analyze your LLM calls. You can create API keys and integrate Langfuse with your application.",
- href: "https://langfuse.com/docs/observability/overview",
- },
- }}
- >
- <div className="flex flex-col gap-4">
- <TracingSetup
- projectId={projectId}
- hasTracingConfigured={hasTracingConfigured ?? false}
- />
- </div>
- </ContainerPage>
- );
-}
diff --git a/web/src/pages/trace-old/[traceId].tsx b/web/src/pages/trace-old/[traceId].tsx
deleted file mode 100644
index 0b15cf4854..0000000000
--- a/web/src/pages/trace-old/[traceId].tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-import { ErrorPage } from "@/src/components/error-page";
-import { getTracesByIdsForAnyProject } from "@langfuse/shared/src/server";
-import { type GetServerSideProps } from "next";
-import { useRouter } from "next/router";
-
-export const getServerSideProps: GetServerSideProps = async (context) => {
- if (!context.params) {
- return {
- props: {
- notFound: true,
- },
- };
- }
-
- const traceId = context.params.traceId as string;
-
- const traces = await getTracesByIdsForAnyProject([traceId]);
-
- if (!traces || traces.length === 0) {
- return {
- props: {
- notFound: true,
- },
- };
- }
-
- if (traces.length > 1) {
- return {
- props: {
- duplicatesFound: true,
- },
- };
- }
-
- return {
- redirect: {
- destination: `/project/${traces[0].projectId}/traces/${traceId}`,
- permanent: false,
- },
- };
-};
-
-const TraceRedirectPage = ({
- notFound,
- duplicatesFound,
-}: {
- notFound?: boolean;
- duplicatesFound?: boolean;
-}) => {
- const router = useRouter();
- if (router.isFallback) {
- return <div className="p-3">Loading...</div>;
- }
-
- if (notFound) {
- return (
- <ErrorPage
- title="Trace not found"
- message="The trace is either still being processed or has been deleted."
- additionalButton={{
- label: "Retry",
- onClick: () => void window.location.reload(),
- }}
- />
- );
- }
-
- if (duplicatesFound) {
- return (
- <ErrorPage
- title="Trace not found"
- message="Please upgrade the SDK as the URL schema has changed."
- />
- );
- }
-
- return null;
-};
-
-export default TraceRedirectPage;