Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
fix: trace hierarchy, cost precision, graph interactivity, and detail navigation (#1084)
Aman Agarwal802b4235a5a5
diff --git a/src/client/src/__tests__/lib/platform/request/request.test.ts b/src/client/src/__tests__/lib/platform/request/request.test.tsindex ff5edd99..4615e0bf 100644--- a/src/client/src/__tests__/lib/platform/request/request.test.ts+++ b/src/client/src/__tests__/lib/platform/request/request.test.ts@@ -157,19 +157,19 @@ describe('getRequestViaTraceId', () => {});describe('getHeirarchyViaSpanId', () => {- it('returns error when no upward data found', async () => {+ it('returns error when span not found (traceId query returns empty)', async () => {(dataCollector as jest.Mock).mockResolvedValue({ data: [], err: null });const result = await getHeirarchyViaSpanId('span-1');- expect(result.err).toBe('Error in fetching heirarchy');+ expect(result.err).toBe('Span not found');});- it('executes downward query when upward span is found and returns hierarchy', async () => {+ it('fetches all spans by traceId and builds hierarchy', async () => {const rootSpan = { SpanId: 'root-span', ParentSpanId: '', TraceId: 't1' };const childSpan = { SpanId: 'child-span', ParentSpanId: 'root-span', TraceId: 't1' };(dataCollector as jest.Mock)- .mockResolvedValueOnce({ data: [rootSpan], err: null }) // upward query- .mockResolvedValueOnce({ data: [rootSpan, childSpan], err: null }); // downward query+ .mockResolvedValueOnce({ data: [{ TraceId: 't1' }], err: null }) // step 1: get traceId+ .mockResolvedValueOnce({ data: [rootSpan, childSpan], err: null }); // step 2: get all spansconst result = await getHeirarchyViaSpanId('child-span');expect(dataCollector).toHaveBeenCalledTimes(2);@@ -177,16 +177,13 @@ describe('getHeirarchyViaSpanId', () => {expect(result.record).toBeDefined();});- it('returns hierarchy error when downward query returns empty data', async () => {- const rootSpan = { SpanId: 'root-span', ParentSpanId: '', TraceId: 't1' };-+ it('returns error when all-spans query fails', async () => {(dataCollector as jest.Mock)- .mockResolvedValueOnce({ data: [rootSpan], err: null })+ .mockResolvedValueOnce({ data: [{ TraceId: 't1' }], err: null }).mockResolvedValueOnce({ data: [], err: 'DB error' });const result = await getHeirarchyViaSpanId('child-span');expect(dataCollector).toHaveBeenCalledTimes(2);- // err from downward query is propagatedexpect(result.err).toBeTruthy();});});diff --git a/src/client/src/app/(playground)/requests/page.tsx b/src/client/src/app/(playground)/requests/page.tsxindex 96bcdd71..205bc693 100644--- a/src/client/src/app/(playground)/requests/page.tsx+++ b/src/client/src/app/(playground)/requests/page.tsx@@ -8,7 +8,7 @@ import {import useFetchWrapper from "@/utils/hooks/useFetchWrapper";import RequestDetails from "@/components/(playground)/request/request-details";import { toast } from "sonner";-import { getFilterDetails } from "@/selectors/filter";+import { getFilterDetails, getUpdateFilter } from "@/selectors/filter";import { useRootStore } from "@/store";import { getPingStatus } from "@/selectors/database-config";import DataTable from "@/components/data-table/table";@@ -20,13 +20,14 @@ import TracingGettingStarted from "@/components/(playground)/getting-started/trafunction RequestPage() {const [, updateRequest] = useRequest();- const { setItems } = useRequestNavigation();+ const { setItems, setTotal, setOffset, setOnPageChange } = useRequestNavigation();const onClick = (item: any) => {!isLoading && updateRequest(item);};const filter = useRootStore(getFilterDetails);+ const updateFilter = useRootStore(getUpdateFilter);const visibilityColumns = useRootStore((state) =>getVisibilityColumnsOfPage(state, "request"));@@ -68,10 +69,29 @@ function RequestPage() {[data]);+ const totalItems = (data as any)?.total || 0;+useEffect(() => {setItems(normalizedData);}, [normalizedData, setItems]);+ useEffect(() => {+ setTotal(totalItems);+ }, [totalItems, setTotal]);++ useEffect(() => {+ setOffset(filter.offset);+ }, [filter.offset, setOffset]);++ // Register page change callback for detail-panel boundary navigation+ useEffect(() => {+ setOnPageChange((dir: -1 | 1) => {+ updateFilter("offset", filter.offset + dir * filter.limit);+ });+ return () => setOnPageChange(null);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [filter.offset, filter.limit, updateFilter, setOnPageChange]);+// Show getting started when there's no trace data AND initial fetch is completeif (existData === false && !isLoadingExist && isFetchedExist) {return (diff --git a/src/client/src/components/(playground)/request/components/attributes-tab.tsx b/src/client/src/components/(playground)/request/components/attributes-tab.tsxindex 0d880977..8c01aa4e 100644--- a/src/client/src/components/(playground)/request/components/attributes-tab.tsx+++ b/src/client/src/components/(playground)/request/components/attributes-tab.tsx@@ -4,6 +4,7 @@ import { TraceMapping } from "@/constants/traces";import {CODE_ITEM_DISPLAY_KEYS,KNOWN_SPAN_ATTR_KEYS,+ getTraceMappingKeyFullPath,} from "@/helpers/client/trace";import { TraceMappingKeyType, TransformedTraceRow } from "@/types/trace";import { isNil } from "lodash";@@ -87,18 +88,31 @@ export function GroupHeader({ label }: { label: string }) {);}-export function AttrRow({ label, value, mono = false, className = "" }: { label: string; value: string; mono?: boolean; className?: string }) {+/** Safely convert any value to a displayable string */+function safeStringify(val: unknown): string {+ if (val === null || val === undefined) return "";+ if (typeof val === "string") return val;+ if (typeof val === "number" || typeof val === "boolean") return String(val);+ try {+ return JSON.stringify(val, null, 2);+ } catch {+ return "[Complex Object]";+ }+}++export function AttrRow({ label, value, mono = false, className = "" }: { label: string; value: unknown; mono?: boolean; className?: string }) {+ const displayValue = safeStringify(value);return (<div className={`flex items-start gap-3 px-4 py-2 border-b border-stone-100 dark:border-stone-800/60 last:border-0 hover:bg-stone-50 dark:hover:bg-stone-800/30 transition-colors ${className}`}>- <span className="w-44 shrink-0 text-xs text-stone-500 dark:text-stone-400 pt-px leading-relaxed">+ <span className="w-44 shrink-0 text-xs text-stone-500 dark:text-stone-400 pt-px leading-relaxed break-all">{label}</span><span- className={`text-xs text-stone-800 dark:text-stone-200 break-all leading-relaxed ${+ className={`text-xs text-stone-800 dark:text-stone-200 break-all leading-relaxed min-w-0 ${mono ? "font-mono" : ""}`}>- {value}+ {displayValue}</span></div>);@@ -127,7 +141,7 @@ export default function AttributesTab({const suffix = mapping?.valueSuffix ?? "";return {key,- label: mapping?.label ?? key,+ label: mapping?.isRoot ? key : (() => { const fp = getTraceMappingKeyFullPath(key); return Array.isArray(fp) ? fp.join(".") : (fp as string); })(),value: `${prefix}${normalizedItem[key]}${suffix}`,};}),@@ -156,7 +170,7 @@ export default function AttributesTab({<div key={group.label}><GroupHeader label={group.label} />{group.entries.map(({ key, label, value }) => (- <AttrRow key={key} label={label} value={String(value)} />+ <AttrRow key={key} label={label} value={value} />))}</div>))}@@ -164,7 +178,7 @@ export default function AttributesTab({<div><GroupHeader label="Custom" />{customEntries.map(([key, value]) => (- <AttrRow key={key} label={key} value={String(value)} mono />+ <AttrRow key={key} label={key} value={value} mono />))}</div>)}diff --git a/src/client/src/components/(playground)/request/components/chat-view.tsx b/src/client/src/components/(playground)/request/components/chat-view.tsxnew file mode 100644index 00000000..c37d4262--- /dev/null+++ b/src/client/src/components/(playground)/request/components/chat-view.tsx@@ -0,0 +1,573 @@+"use client";++/**+ * Chat View — Renders LLM trace spans as a conversational chat timeline.+ *+ * ## Sequencing logic+ *+ * 1. Flatten the hierarchy tree into a flat list of all spans.+ * 2. Sort spans by their Timestamp (wall-clock start time, ascending).+ * 3. For each span, extract chat items (messages, tool calls, indicators).+ * 4. Deduplicate: the root span (and any parent that wraps child LLM calls)+ * often echoes the full conversation. We skip message extraction for any+ * span whose children already produced messages, to avoid double-rendering+ * the same user prompt / assistant response at two tree levels.+ * 5. All items are globally sorted by wall-clock timestampMs.+ */++import { TraceHeirarchySpan } from "@/types/trace";+import { useRequest } from "../request-context";+import {+ getSpanDurationDisplay,+ getSpanCostFormatted,+} from "@/helpers/client/trace";+import {+ Bot,+ ChevronDown,+ ChevronRight,+ Clock,+ Cog,+ DollarSign,+ MessageSquare,+ User,+ Wrench,+} from "lucide-react";+import { useState } from "react";++// ─── Types ───────────────────────────────────────────────────────────────────++type ChatItemType = "message" | "tool-indicator" | "span-indicator";++interface ChatItem {+ type: ChatItemType;+ role?: "user" | "assistant" | "system" | "tool";+ content?: string;+ label?: string;+ meta?: string;+ /** Tool type (e.g. "function") */+ toolType?: string;+ /** Tool call arguments (full, for expandable display) */+ toolArgs?: string;+ span: TraceHeirarchySpan;+ timestampMs: number;+}++// ─── Parsing helpers ─────────────────────────────────────────────────────────++function parseTimestampMs(ts?: string): number {+ if (!ts) return 0;+ const withZ = ts.endsWith("Z") ? ts : ts + "Z";+ const ms = new Date(withZ).getTime();+ return isNaN(ms) ? 0 : ms;+}++function tryParseJson(raw: unknown): any[] | null {+ if (raw == null) return null;+ try {+ const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;+ return Array.isArray(parsed) ? parsed : null;+ } catch {+ return null;+ }+}++function extractTextMessages(+ raw: unknown+): { role: string; content: string }[] {+ const arr = tryParseJson(raw);+ if (!arr) return [];++ const result: { role: string; content: string }[] = [];+ for (const msg of arr) {+ if (!msg) continue;+ const role = msg.role || "unknown";++ if (Array.isArray(msg.parts)) {+ const texts: string[] = [];+ for (const p of msg.parts) {+ if (p?.type === "text" && typeof p.content === "string" && p.content) {+ texts.push(p.content);+ }+ }+ if (texts.length > 0) {+ result.push({ role, content: texts.join("\n") });+ }+ continue;+ }++ if (typeof msg.content === "string" && msg.content.trim()) {+ result.push({ role, content: msg.content });+ continue;+ }++ if (Array.isArray(msg.content)) {+ const texts: string[] = [];+ for (const part of msg.content) {+ if (part?.type === "text" && typeof part.text === "string") {+ texts.push(part.text);+ }+ }+ if (texts.length > 0) {+ result.push({ role, content: texts.join("\n") });+ }+ }+ }+ return result;+}++function normalizeRole(role: string): "user" | "assistant" | "system" | "tool" {+ if (role === "assistant") return "assistant";+ if (role === "system") return "system";+ if (role === "tool" || role === "function") return "tool";+ return "user";+}++function tryPrettyJson(raw: string): string | null {+ try {+ const parsed = JSON.parse(raw);+ return JSON.stringify(parsed, null, 2);+ } catch {+ return null;+ }+}++// ─── Item extraction ─────────────────────────────────────────────────────────++/**+ * Check if a span has LLM message attributes (input or output).+ */+function spanHasMessages(span: TraceHeirarchySpan): boolean {+ const attrs = span.SpanAttributes || {};+ return !!(+ attrs["gen_ai.input.messages"] ||+ attrs["gen_ai.output.messages"] ||+ attrs["gen_ai.content.prompt"] ||+ attrs["gen_ai.content.completion"] ||+ attrs["gen_ai.request.input"] ||+ attrs["gen_ai.response.output"]+ );+}++/**+ * Check if any descendant (child, grandchild, etc.) has messages.+ */+function anyDescendantHasMessages(span: TraceHeirarchySpan): boolean {+ if (!span.children) return false;+ for (const child of span.children) {+ if (spanHasMessages(child) || anyDescendantHasMessages(child)) {+ return true;+ }+ }+ return false;+}++function extractItemsFromSpan(+ span: TraceHeirarchySpan,+ skipMessages: boolean+): ChatItem[] {+ const attrs = span.SpanAttributes || {};+ const items: ChatItem[] = [];+ const ts = parseTimestampMs(span.Timestamp);+ const spanDurationMs = span.Duration / 1e6;++ if (!skipMessages) {+ // ── Input messages ──+ const inputMsgs = extractTextMessages(attrs["gen_ai.input.messages"]);+ if (inputMsgs.length > 0) {+ for (const msg of inputMsgs) {+ items.push({+ type: "message",+ role: normalizeRole(msg.role),+ content: msg.content,+ span,+ timestampMs: ts,+ });+ }+ } else {+ const prompt =+ (attrs["gen_ai.content.prompt"] as string) ||+ (attrs["gen_ai.request.input"] as string);+ if (prompt && prompt.trim()) {+ items.push({+ type: "message",+ role: "user",+ content: prompt,+ span,+ timestampMs: ts,+ });+ }+ }++ // ── Output messages ──+ const outputMsgs = extractTextMessages(attrs["gen_ai.output.messages"]);+ if (outputMsgs.length > 0) {+ for (const msg of outputMsgs) {+ items.push({+ type: "message",+ role: normalizeRole(msg.role),+ content: msg.content,+ span,+ timestampMs: ts + spanDurationMs,+ });+ }+ } else {+ const response =+ (attrs["gen_ai.content.completion"] as string) ||+ (attrs["gen_ai.response.output"] as string);+ if (response && response.trim()) {+ items.push({+ type: "message",+ role: "assistant",+ content: response,+ span,+ timestampMs: ts + spanDurationMs,+ });+ }+ }+ }++ // ── Tool call indicator (always shown — these are actions, not duplicated) ──+ const toolName = attrs["gen_ai.tool.name"] as string | undefined;+ const toolCallId = attrs["gen_ai.tool.call.id"] as string | undefined;+ const toolArgs = attrs["gen_ai.tool.call.arguments"] as string | undefined;+ const toolType = attrs["gen_ai.tool.type"] as string | undefined;+ if (toolName) {+ items.push({+ type: "tool-indicator",+ label: toolName,+ meta: toolCallId || undefined,+ toolType: toolType || undefined,+ toolArgs: toolArgs || undefined,+ span,+ timestampMs: ts + spanDurationMs * 0.5,+ });+ }++ // ── Non-LLM span indicator ──+ if (items.length === 0) {+ const spanKind =+ (attrs["gen_ai.operation.name"] as string) ||+ (attrs["openai.api_type"] as string);+ const isInteresting =+ spanKind ||+ span.SpanName.match(+ /retriev|embed|search|tool|function|db|query|fetch|call/i+ );+ if (isInteresting) {+ items.push({+ type: "span-indicator",+ label: span.SpanName,+ meta: spanKind || undefined,+ span,+ timestampMs: ts,+ });+ }+ }++ return items;+}++// ─── Sub-components ──────────────────────────────────────────────────────────++function ToolIndicator({+ item,+ isSelected,+ onClick,+}: {+ item: ChatItem;+ isSelected: boolean;+ onClick: () => void;+}) {+ const [expanded, setExpanded] = useState(false);+ const prettyArgs = item.toolArgs ? tryPrettyJson(item.toolArgs) : null;+ const displayArgs = prettyArgs || item.toolArgs;++ return (+ <div+ className={`mx-3 rounded-lg border cursor-pointer transition-colors ${+ isSelected+ ? "border-primary/40 bg-primary/5"+ : "border-stone-200 dark:border-stone-700 bg-stone-50 dark:bg-stone-900/50 hover:bg-stone-100 dark:hover:bg-stone-800"+ }`}+ onClick={onClick}+ >+ {/* Header row */}+ <div className="flex items-center gap-2 px-3 py-2">+ <div className="flex items-center justify-center h-6 w-6 rounded-md bg-violet-100 dark:bg-violet-900/40 shrink-0">+ <Wrench className="h-3.5 w-3.5 text-violet-600 dark:text-violet-400" />+ </div>+ <div className="flex flex-col min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ <span className="text-[11px] font-semibold text-violet-700 dark:text-violet-300">+ {item.label}+ </span>+ {item.toolType && (+ <span className="text-[9px] px-1.5 py-0.5 rounded-full bg-violet-100 dark:bg-violet-900/30 text-violet-600 dark:text-violet-400 font-medium">+ {item.toolType}+ </span>+ )}+ </div>+ {item.meta && (+ <span className="text-[9px] text-stone-400 dark:text-stone-500 font-mono truncate">+ {item.meta}+ </span>+ )}+ </div>+ <span className="text-[9px] tabular-nums text-stone-400 dark:text-stone-500 shrink-0">+ {getSpanDurationDisplay(item.span)}+ </span>+ </div>++ {/* Expandable arguments */}+ {displayArgs && (+ <div className="border-t border-stone-200 dark:border-stone-700">+ <button+ className="flex items-center gap-1 px-3 py-1 text-[10px] text-stone-400 dark:text-stone-500 hover:text-stone-600 dark:hover:text-stone-300 w-full"+ onClick={(e) => {+ e.stopPropagation();+ setExpanded(!expanded);+ }}+ >+ {expanded ? (+ <ChevronDown className="h-3 w-3" />+ ) : (+ <ChevronRight className="h-3 w-3" />+ )}+ Arguments+ </button>+ {expanded && (+ <pre className="px-3 pb-2 text-[10px] leading-relaxed text-stone-600 dark:text-stone-400 font-mono overflow-x-auto max-h-48 overflow-y-auto">+ {displayArgs}+ </pre>+ )}+ </div>+ )}+ </div>+ );+}++// ─── Role configs ────────────────────────────────────────────────────────────++const roleConfig = {+ user: {+ icon: <User className="h-3.5 w-3.5" />,+ label: "User",+ align: "items-end" as const,+ bubble:+ "bg-primary/10 dark:bg-primary/15 text-stone-800 dark:text-stone-200 rounded-2xl rounded-br-md",+ },+ assistant: {+ icon: <Bot className="h-3.5 w-3.5" />,+ label: "Assistant",+ align: "items-start" as const,+ bubble:+ "bg-stone-200 dark:bg-stone-800 text-stone-800 dark:text-stone-200 rounded-2xl rounded-bl-md",+ },+ system: {+ icon: <Cog className="h-3.5 w-3.5" />,+ label: "System",+ align: "items-start" as const,+ bubble:+ "bg-amber-50 dark:bg-amber-950/30 text-amber-900 dark:text-amber-200 rounded-2xl rounded-bl-md border border-amber-200 dark:border-amber-800",+ },+ tool: {+ icon: <Wrench className="h-3.5 w-3.5" />,+ label: "Tool Result",+ align: "items-start" as const,+ bubble:+ "bg-violet-50 dark:bg-violet-950/30 text-violet-900 dark:text-violet-200 rounded-2xl rounded-bl-md border border-violet-200 dark:border-violet-800",+ },+};++// ─── Main component ──────────────────────────────────────────────────────────++function flattenSpans(+ span: TraceHeirarchySpan,+ result: TraceHeirarchySpan[]+): void {+ result.push(span);+ if (span.children) {+ for (const child of span.children) {+ flattenSpans(child, result);+ }+ }+}++export default function ChatView({+ record,+}: {+ record: TraceHeirarchySpan;+}) {+ const [request, updateRequest] = useRequest();++ // 1. Flatten tree+ const allSpans: TraceHeirarchySpan[] = [];+ flattenSpans(record, allSpans);++ // 2. Sort by wall-clock start time+ allSpans.sort(+ (a, b) => parseTimestampMs(a.Timestamp) - parseTimestampMs(b.Timestamp)+ );++ // 3. Build a set of SpanIds whose messages should be skipped because+ // their descendants already carry the same conversation.+ const skipMessageSpanIds = new Set<string>();+ for (const span of allSpans) {+ if (+ spanHasMessages(span) &&+ span.children &&+ span.children.length > 0 &&+ anyDescendantHasMessages(span)+ ) {+ skipMessageSpanIds.add(span.SpanId);+ }+ }++ // 4. Extract items+ const allItems: ChatItem[] = [];+ for (const span of allSpans) {+ const skip = skipMessageSpanIds.has(span.SpanId);+ allItems.push(...extractItemsFromSpan(span, skip));+ }+ allItems.sort((a, b) => a.timestampMs - b.timestampMs);++ // 5. Deduplicate messages with identical role + content.+ // In multi-step agent traces, each LLM call span carries the full+ // conversation history in gen_ai.input.messages — so the same user+ // prompt appears in every step. We keep only the first occurrence.+ // Tool indicators and span indicators are never deduped (they're unique actions).+ const seenMessages = new Set<string>();+ const dedupedItems = allItems.filter((item) => {+ if (item.type !== "message") return true; // keep all non-message items+ const key = `${item.role}::${item.content}`;+ if (seenMessages.has(key)) return false;+ seenMessages.add(key);+ return true;+ });++ // 6. Empty state+ if (dedupedItems.length === 0) {+ return (+ <div className="flex flex-col items-center justify-center h-full text-stone-400 dark:text-stone-500 gap-2 py-12">+ <MessageSquare className="h-8 w-8" />+ <p className="text-sm">No chat messages found in this trace</p>+ <p className="text-xs">+ This view works with LLM spans that have prompt/response data+ </p>+ </div>+ );+ }++ return (+ <div className="flex flex-col gap-2.5 py-3">+ {dedupedItems.map((item, i) => {+ const isSelected = request?.spanId === item.span.SpanId;++ // ── Tool call indicator ──+ if (item.type === "tool-indicator") {+ return (+ <ToolIndicator+ key={`${item.span.SpanId}-tool-${i}`}+ item={item}+ isSelected={isSelected}+ onClick={() =>+ updateRequest({ spanId: item.span.SpanId })+ }+ />+ );+ }++ // ── Non-LLM span indicator ──+ if (item.type === "span-indicator") {+ return (+ <div+ key={`${item.span.SpanId}-span-${i}`}+ className={`flex items-center gap-2 mx-3 px-3 py-1.5 rounded-md border cursor-pointer transition-colors ${+ isSelected+ ? "border-primary/40 bg-primary/5"+ : "border-dashed border-stone-200 dark:border-stone-700 hover:bg-stone-100 dark:hover:bg-stone-800"+ }`}+ onClick={() =>+ updateRequest({ spanId: item.span.SpanId })+ }+ >+ <Cog className="h-3 w-3 shrink-0 text-stone-400" />+ <span className="text-[11px] text-stone-500 dark:text-stone-400 truncate">+ {item.label}+ </span>+ {item.meta && (+ <span className="text-[10px] text-stone-400 dark:text-stone-500">+ ({item.meta})+ </span>+ )}+ <span className="ml-auto text-[9px] tabular-nums text-stone-400 dark:text-stone-500 shrink-0">+ {getSpanDurationDisplay(item.span)}+ </span>+ </div>+ );+ }++ // ── Chat message bubble ──+ const role = item.role!;+ const config = roleConfig[role];+ const durationDisplay = getSpanDurationDisplay(item.span);+ const costDisplay = getSpanCostFormatted(item.span, 6);++ return (+ <div+ key={`${item.span.SpanId}-${role}-${i}`}+ className={`flex flex-col gap-0.5 px-3 ${config.align}`}+ >+ {/* Role label + span name */}+ <div+ className={`flex items-center gap-1.5 text-[10px] text-stone-400 dark:text-stone-500 px-1 ${+ role === "user" ? "flex-row-reverse" : ""+ }`}+ >+ {config.icon}+ <span className="font-medium">{config.label}</span>+ <span className="text-stone-300 dark:text-stone-600">+ |+ </span>+ <span className="truncate max-w-[120px]">+ {item.span.SpanName}+ </span>+ </div>++ {/* Bubble */}+ <div+ className={`max-w-[85%] px-3 py-2 text-[12px] leading-relaxed whitespace-pre-wrap break-words cursor-pointer transition-shadow ${+ config.bubble+ } ${+ isSelected+ ? "ring-2 ring-primary ring-offset-1 dark:ring-offset-stone-900"+ : "hover:shadow-md"+ }`}+ onClick={() =>+ updateRequest({ spanId: item.span.SpanId })+ }+ >+ {item.content}+ </div>++ {/* Duration + cost for assistant messages */}+ {role === "assistant" && (+ <div className="flex items-center gap-2 text-[9px] text-stone-400 dark:text-stone-500 px-1 mt-0.5">+ <span className="flex items-center gap-0.5">+ <Clock className="h-2.5 w-2.5" />+ {durationDisplay}+ </span>+ {costDisplay && (+ <span className="flex items-center gap-0.5">+ <DollarSign className="h-2.5 w-2.5" />+ {costDisplay}+ </span>+ )}+ </div>+ )}+ </div>+ );+ })}+ </div>+ );+}diff --git a/src/client/src/components/(playground)/request/components/node-graph.tsx b/src/client/src/components/(playground)/request/components/node-graph.tsxindex 1c7cc9eb..655278f7 100644--- a/src/client/src/components/(playground)/request/components/node-graph.tsx+++ b/src/client/src/components/(playground)/request/components/node-graph.tsx@@ -1,5 +1,24 @@"use client";+/**+ * Graph View — DAG (Directed Acyclic Graph) visualization of span hierarchy.+ *+ * ## Sequencing logic+ *+ * Layout uses a bottom-up tree placement algorithm:+ * 1. Walk the hierarchy tree recursively; leaf spans are placed left-to-right+ * in the order they appear (siblings are pre-sorted by Timestamp in+ * buildHierarchy on the server).+ * 2. Each parent node is centered above its children.+ * 3. Y-axis represents tree depth (parent→child), X-axis spreads siblings.+ *+ * Edges between parent and child are classified as "parallel" or "sequential"+ * by checking whether sibling spans have overlapping time windows:+ * - parallel: spanA.start < spanB.end AND spanB.start < spanA.end+ * - sequential: no time overlap+ * Parallel edges are drawn as dashed indigo lines; sequential as solid gray.+ */+import { TraceHeirarchySpan } from "@/types/trace";import { useRequest } from "../request-context";import {@@ -7,6 +26,8 @@ import {getSpanCostFormatted,getSpanTooltipText,} from "@/helpers/client/trace";+import { useCallback, useEffect, useRef, useState } from "react";+import { Maximize, Minus, Plus } from "lucide-react";const NODE_WIDTH = 160;const NODE_HEIGHT = 52;@@ -20,12 +41,12 @@ interface NodeLayout {}function getNodeStroke(durationNs: number, isSelected: boolean): string {- if (isSelected) return "#6366f1"; // primary+ if (isSelected) return "#6366f1";const seconds = durationNs * 1e-9;- if (seconds > 10) return "#ef4444"; // red- if (seconds > 5) return "#eab308"; // yellow- if (seconds > 1) return "#3b82f6"; // blue- return "#22c55e"; // green+ if (seconds > 10) return "#ef4444";+ if (seconds > 5) return "#eab308";+ if (seconds > 1) return "#3b82f6";+ return "#22c55e";}function getNodeFill(durationNs: number, isSelected: boolean): string {@@ -37,6 +58,67 @@ function getNodeFill(durationNs: number, isSelected: boolean): string {return "rgba(34,197,94,0.06)";}+function parseTimestampMs(ts?: string): number | null {+ if (!ts) return null;+ const withZ = ts.endsWith("Z") ? ts : ts + "Z";+ const ms = new Date(withZ).getTime();+ return isNaN(ms) ? null : ms;+}++function classifySiblingRelationship(+ a: TraceHeirarchySpan,+ b: TraceHeirarchySpan+): "parallel" | "sequential" {+ const aStart = parseTimestampMs(a.Timestamp);+ const bStart = parseTimestampMs(b.Timestamp);+ if (aStart === null || bStart === null) return "sequential";+ const aDurMs = a.Duration / 1e6;+ const bDurMs = b.Duration / 1e6;+ const aEnd = aStart + aDurMs;+ const bEnd = bStart + bDurMs;+ return aStart < bEnd && bStart < aEnd ? "parallel" : "sequential";+}++function detectParallelPairs(root: TraceHeirarchySpan): Set<string> {+ const parallelPairs = new Set<string>();+ function walk(span: TraceHeirarchySpan) {+ if (span.children && span.children.length > 1) {+ for (let i = 0; i < span.children.length; i++) {+ for (let j = i + 1; j < span.children.length; j++) {+ if (+ classifySiblingRelationship(+ span.children[i],+ span.children[j]+ ) === "parallel"+ ) {+ parallelPairs.add(+ [span.children[i].SpanId, span.children[j].SpanId]+ .sort()+ .join("|")+ );+ }+ }+ }+ }+ span.children?.forEach(walk);+ }+ walk(root);+ return parallelPairs;+}++function isParallelSpan(+ span: TraceHeirarchySpan,+ siblings: TraceHeirarchySpan[],+ parallelPairs: Set<string>+): boolean {+ for (const sib of siblings) {+ if (sib.SpanId === span.SpanId) continue;+ const key = [span.SpanId, sib.SpanId].sort().join("|");+ if (parallelPairs.has(key)) return true;+ }+ return false;+}+function layoutTree(root: TraceHeirarchySpan): NodeLayout[] {const nodes: NodeLayout[] = [];let leafCounter = 0;@@ -46,26 +128,21 @@ function layoutTree(root: TraceHeirarchySpan): NodeLayout[] {level: number): { centerX: number } {const y = level * (NODE_HEIGHT + V_GAP);-if (!span.children || span.children.length === 0) {const x = leafCounter * (NODE_WIDTH + H_GAP);leafCounter++;nodes.push({ span, x, y });return { centerX: x + NODE_WIDTH / 2 };}-const childCenters: number[] = [];for (const child of span.children) {const { centerX } = assignPositions(child, level + 1);childCenters.push(centerX);}-const leftmost = childCenters[0];const rightmost = childCenters[childCenters.length - 1];const center = (leftmost + rightmost) / 2;- const x = center - NODE_WIDTH / 2;-- nodes.push({ span, x, y });+ nodes.push({ span, x: center - NODE_WIDTH / 2, y });return { centerX: center };}@@ -74,21 +151,29 @@ function layoutTree(root: TraceHeirarchySpan): NodeLayout[] {}function truncate(text: string, maxLen: number): string {- return text.length > maxLen ? text.slice(0, maxLen - 1) + "…" : text;+ return text.length > maxLen ? text.slice(0, maxLen - 1) + "\u2026" : text;}+const ZOOM_STEP = 0.05;+const MIN_ZOOM = 0.05;+const MAX_ZOOM = 3;+export default function NodeGraph({ record }: { record: TraceHeirarchySpan }) {const [request, updateRequest] = useRequest();+ const containerRef = useRef<HTMLDivElement>(null);+ const [zoom, setZoom] = useState(1);+ const [pan, setPan] = useState({ x: 0, y: 0 });+ const [isPanning, setIsPanning] = useState(false);+ const panStart = useRef({ x: 0, y: 0, panX: 0, panY: 0 });const nodes = layoutTree(record);+ const parallelPairs = detectParallelPairs(record);- // Build a map for edge drawingconst nodeMap = new Map<string, NodeLayout>();for (const n of nodes) {nodeMap.set(n.span.SpanId, n);}- // Compute canvas dimensionsconst minX = Math.min(...nodes.map((n) => n.x));const maxX = Math.max(...nodes.map((n) => n.x + NODE_WIDTH));const maxY = Math.max(...nodes.map((n) => n.y + NODE_HEIGHT));@@ -98,103 +183,326 @@ export default function NodeGraph({ record }: { record: TraceHeirarchySpan }) {const offsetX = -minX + PADDING;const offsetY = PADDING;- // Build edges- const edges: { from: NodeLayout; to: NodeLayout }[] = [];+ const edges: {+ from: NodeLayout;+ to: NodeLayout;+ type: "parallel" | "sequential";+ }[] = [];function collectEdges(span: TraceHeirarchySpan) {const fromLayout = nodeMap.get(span.SpanId);if (!fromLayout) return;if (span.children) {+ const siblings = span.children;for (const child of span.children) {const toLayout = nodeMap.get(child.SpanId);- if (toLayout) edges.push({ from: fromLayout, to: toLayout });+ if (toLayout) {+ edges.push({+ from: fromLayout,+ to: toLayout,+ type: isParallelSpan(child, siblings, parallelPairs)+ ? "parallel"+ : "sequential",+ });+ }collectEdges(child);}}}collectEdges(record);+ const fitToView = useCallback(() => {+ if (!containerRef.current) return;+ const cw = containerRef.current.clientWidth;+ const ch = containerRef.current.clientHeight;+ if (cw === 0 || ch === 0) return;+ const scaleX = cw / svgWidth;+ const scaleY = ch / svgHeight;+ const newZoom = Math.max(+ MIN_ZOOM,+ Math.min(MAX_ZOOM, Math.min(scaleX, scaleY, 1) * 0.85)+ );+ const scaledW = svgWidth * newZoom;+ const scaledH = svgHeight * newZoom;+ setPan({+ x: (cw - scaledW) / 2,+ y: (ch - scaledH) / 2,+ });+ setZoom(newZoom);+ }, [svgWidth, svgHeight]);++ // Auto-fit on mount (key={record.SpanId} in parent ensures fresh mount)+ useEffect(() => {+ const timer = setTimeout(fitToView, 60);+ return () => clearTimeout(timer);+ }, [fitToView]);++ // Also re-fit when the container resizes (e.g. panel drag)+ useEffect(() => {+ if (!containerRef.current) return;+ const ro = new ResizeObserver(() => fitToView());+ ro.observe(containerRef.current);+ return () => ro.disconnect();+ }, [fitToView]);++ const handleWheel = useCallback(+ (e: React.WheelEvent) => {+ e.preventDefault();+ if (!containerRef.current) return;+ const rect = containerRef.current.getBoundingClientRect();+ const mouseX = e.clientX - rect.left;+ const mouseY = e.clientY - rect.top;+ const delta = e.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP;+ const newZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, zoom + delta));+ const scale = newZoom / zoom;+ setPan((p) => ({+ x: mouseX - scale * (mouseX - p.x),+ y: mouseY - scale * (mouseY - p.y),+ }));+ setZoom(newZoom);+ },+ [zoom]+ );++ const handleMouseDown = useCallback(+ (e: React.MouseEvent) => {+ if (e.button !== 0) return;+ setIsPanning(true);+ panStart.current = {+ x: e.clientX,+ y: e.clientY,+ panX: pan.x,+ panY: pan.y,+ };+ },+ [pan]+ );++ const handleMouseMove = useCallback(+ (e: React.MouseEvent) => {+ if (!isPanning) return;+ setPan({+ x: panStart.current.panX + (e.clientX - panStart.current.x),+ y: panStart.current.panY + (e.clientY - panStart.current.y),+ });+ },+ [isPanning]+ );++ const handleMouseUp = useCallback(() => setIsPanning(false), []);+return (- <div>- <svg- width={svgWidth}- height={svgHeight}- viewBox={`0 0 ${svgWidth} ${svgHeight}`}- className="block"- >- {/* Edges */}- {edges.map(({ from, to }, i) => {- const x1 = from.x + offsetX + NODE_WIDTH / 2;- const y1 = from.y + offsetY + NODE_HEIGHT;- const x2 = to.x + offsetX + NODE_WIDTH / 2;- const y2 = to.y + offsetY;- const midY = (y1 + y2) / 2;- const d = `M ${x1} ${y1} C ${x1} ${midY}, ${x2} ${midY}, ${x2} ${y2}`;- return (- <path- key={i}- d={d}- fill="none"- stroke="rgba(120,113,108,0.4)"- strokeWidth={1.5}+ <div className="relative flex-1 w-full min-h-0 h-full">+ {/* Controls — top-right */}+ <div className="absolute top-2 right-2 z-20 flex items-center gap-1 bg-white/90 dark:bg-stone-900/90 rounded-md border border-stone-200 dark:border-stone-700 p-0.5 shadow-sm">+ <button+ onClick={() => setZoom((z) => Math.min(MAX_ZOOM, z + ZOOM_STEP))}+ className="p-1 rounded hover:bg-stone-100 dark:hover:bg-stone-700 transition-colors"+ title="Zoom in"+ >+ <Plus className="h-3.5 w-3.5 text-stone-600 dark:text-stone-300" />+ </button>+ <span className="text-[10px] tabular-nums text-stone-500 dark:text-stone-400 min-w-[32px] text-center select-none">+ {Math.round(zoom * 100)}%+ </span>+ <button+ onClick={() => setZoom((z) => Math.max(MIN_ZOOM, z - ZOOM_STEP))}+ className="p-1 rounded hover:bg-stone-100 dark:hover:bg-stone-700 transition-colors"+ title="Zoom out"+ >+ <Minus className="h-3.5 w-3.5 text-stone-600 dark:text-stone-300" />+ </button>+ <div className="w-px h-4 bg-stone-200 dark:bg-stone-700" />+ <button+ onClick={fitToView}+ className="p-1 rounded hover:bg-primary/10 transition-colors"+ title="Fit to view"+ >+ <Maximize className="h-3.5 w-3.5 text-primary" />+ </button>+ </div>++ {/* Legend — bottom-left, above the canvas */}+ <div className="absolute bottom-2 left-2 z-20 flex items-center gap-3 text-[10px] text-stone-500 dark:text-stone-400 bg-white/90 dark:bg-stone-900/90 rounded px-2 py-1 border border-stone-200 dark:border-stone-700 shadow-sm">+ <span className="flex items-center gap-1">+ <svg width="16" height="6">+ <line+ x1="0"+ y1="3"+ x2="16"+ y2="3"+ stroke="#6366f1"+ strokeWidth="1.5"+ strokeDasharray="4 2"+ />+ </svg>+ Parallel+ </span>+ <span className="flex items-center gap-1">+ <svg width="16" height="6">+ <line+ x1="0"+ y1="3"+ x2="16"+ y2="3"+ stroke="rgba(120,113,108,0.5)"+ strokeWidth="1.5"/>- );- })}-- {/* Nodes */}- {nodes.map(({ span, x, y }) => {- const isSelected = request?.spanId === span.SpanId;- const nx = x + offsetX;- const ny = y + offsetY;- const stroke = getNodeStroke(span.Duration, isSelected);- const fill = getNodeFill(span.Duration, isSelected);- const durationDisplay = getSpanDurationDisplay(span);- const costDisplay = getSpanCostFormatted(span, 4);- const tooltipText = getSpanTooltipText(span);-- return (- <g- key={span.SpanId}- onClick={() => updateRequest({ spanId: span.SpanId })}- style={{ cursor: "pointer" }}- >- <title>{tooltipText}</title>- <rect- x={nx}- y={ny}- width={NODE_WIDTH}- height={NODE_HEIGHT}- rx={6}- fill={fill}- stroke={stroke}- strokeWidth={isSelected ? 2 : 1.5}+ </svg>+ Sequential+ </span>+ </div>++ {/* Pan/zoom canvas — fills all available space */}+ <div+ ref={containerRef}+ className="absolute inset-0"+ style={{ cursor: isPanning ? "grabbing" : "grab" }}+ onWheel={handleWheel}+ onMouseDown={handleMouseDown}+ onMouseMove={handleMouseMove}+ onMouseUp={handleMouseUp}+ onMouseLeave={handleMouseUp}+ >+ <svg+ width={svgWidth}+ height={svgHeight}+ viewBox={`0 0 ${svgWidth} ${svgHeight}`}+ className="block"+ style={{+ transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,+ transformOrigin: "0 0",+ }}+ >+ {/* Edges */}+ {edges.map(({ from, to, type }, i) => {+ const x1 = from.x + offsetX + NODE_WIDTH / 2;+ const y1 = from.y + offsetY + NODE_HEIGHT;+ const x2 = to.x + offsetX + NODE_WIDTH / 2;+ const y2 = to.y + offsetY;+ const midY = (y1 + y2) / 2;+ const isParallel = type === "parallel";+ return (+ <path+ key={i}+ d={`M ${x1} ${y1} C ${x1} ${midY}, ${x2} ${midY}, ${x2} ${y2}`}+ fill="none"+ stroke={+ isParallel+ ? "#6366f1"+ : "rgba(120,113,108,0.5)"+ }+ strokeWidth={1.5}+ strokeDasharray={isParallel ? "6 3" : undefined}/>+ );+ })}++ {/* Edge labels */}+ {edges.map(({ from, to, type }, i) => {+ const x1 = from.x + offsetX + NODE_WIDTH / 2;+ const y1 = from.y + offsetY + NODE_HEIGHT;+ const x2 = to.x + offsetX + NODE_WIDTH / 2;+ const y2 = to.y + offsetY;+ const isParallel = type === "parallel";+ return (<text- x={nx + NODE_WIDTH / 2}- y={ny + 18}- textAnchor="middle"- fontSize={10}- fontWeight={isSelected ? 600 : 400}- fill={isSelected ? "#6366f1" : "currentColor"}- className="fill-stone-700 dark:fill-stone-300"+ key={`label-${i}`}+ x={(x1 + x2) / 2 + 8}+ y={(y1 + y2) / 2}+ fontSize={8}+ fill={+ isParallel+ ? "#6366f1"+ : "rgba(120,113,108,0.6)"+ }+ textAnchor="start"+ dominantBaseline="middle">- {truncate(span.SpanName, 20)}+ {isParallel ? "parallel" : "seq"}</text>- <text- x={nx + NODE_WIDTH / 2}- y={ny + 34}- textAnchor="middle"- fontSize={9}- fill={stroke}- opacity={0.9}+ );+ })}++ {/* Nodes */}+ {nodes.map(({ span, x, y }) => {+ const isSelected =+ request?.spanId === span.SpanId;+ const nx = x + offsetX;+ const ny = y + offsetY;+ const stroke = getNodeStroke(+ span.Duration,+ isSelected+ );+ const fill = getNodeFill(+ span.Duration,+ isSelected+ );+ const durationDisplay =+ getSpanDurationDisplay(span);+ const costDisplay = getSpanCostFormatted(+ span,+ 10+ );+ const tooltipText = getSpanTooltipText(span);++ return (+ <g+ key={span.SpanId}+ onClick={(e) => {+ e.stopPropagation();+ updateRequest({+ spanId: span.SpanId,+ });+ }}+ style={{ cursor: "pointer" }}>- {costDisplay- ? `${durationDisplay} • ${costDisplay}`- : durationDisplay}- </text>- </g>- );- })}- </svg>+ <title>{tooltipText}</title>+ <rect+ x={nx}+ y={ny}+ width={NODE_WIDTH}+ height={NODE_HEIGHT}+ rx={6}+ fill={fill}+ stroke={stroke}+ strokeWidth={+ isSelected ? 2 : 1.5+ }+ />+ <text+ x={nx + NODE_WIDTH / 2}+ y={ny + 18}+ textAnchor="middle"+ fontSize={10}+ fontWeight={+ isSelected ? 600 : 400+ }+ fill={+ isSelected+ ? "#6366f1"+ : "currentColor"+ }+ className="fill-stone-700 dark:fill-stone-300"+ >+ {truncate(span.SpanName, 20)}+ </text>+ <text+ x={nx + NODE_WIDTH / 2}+ y={ny + 34}+ textAnchor="middle"+ fontSize={9}+ fill={stroke}+ opacity={0.9}+ >+ {costDisplay+ ? `${durationDisplay} \u2022 ${costDisplay}`+ : durationDisplay}+ </text>+ </g>+ );+ })}+ </svg>+ </div></div>);}diff --git a/src/client/src/components/(playground)/request/components/resource-attributes-tab.tsx b/src/client/src/components/(playground)/request/components/resource-attributes-tab.tsxindex 9ff12e43..34953475 100644--- a/src/client/src/components/(playground)/request/components/resource-attributes-tab.tsx+++ b/src/client/src/components/(playground)/request/components/resource-attributes-tab.tsx@@ -23,7 +23,7 @@ export default function ResourceAttributesTab({return (<div className="flex flex-col">{entries.map(([key, value]) => (- <AttrRow key={key} label={key} value={String(value)} />+ <AttrRow key={key} label={key} value={value} />))}</div>);diff --git a/src/client/src/components/(playground)/request/components/span-attributes-tab.tsx b/src/client/src/components/(playground)/request/components/span-attributes-tab.tsxindex c6786a3a..fa9045b7 100644--- a/src/client/src/components/(playground)/request/components/span-attributes-tab.tsx+++ b/src/client/src/components/(playground)/request/components/span-attributes-tab.tsx@@ -4,6 +4,7 @@ import { TraceMapping } from "@/constants/traces";import {CODE_ITEM_DISPLAY_KEYS,KNOWN_SPAN_ATTR_KEYS,+ getTraceMappingKeyFullPath,} from "@/helpers/client/trace";import { TraceMappingKeyType, TransformedTraceRow } from "@/types/trace";import { isNil } from "lodash";@@ -101,7 +102,7 @@ export default function SpanAttributesTab({const suffix = mapping?.valueSuffix ?? "";return {key,- label: mapping?.label ?? key,+ label: mapping?.isRoot ? key : (() => { const fp = getTraceMappingKeyFullPath(key); return Array.isArray(fp) ? fp.join(".") : (fp as string); })(),value: `${prefix}${normalizedItem[key]}${suffix}`,};}),@@ -130,7 +131,7 @@ export default function SpanAttributesTab({<div key={group.label}><GroupHeader label={group.label} />{group.entries.map(({ key, label, value }) => (- <AttrRow key={key} label={label} value={String(value)} />+ <AttrRow key={key} label={label} value={value} />))}</div>))}@@ -138,7 +139,7 @@ export default function SpanAttributesTab({<div><GroupHeader label="Custom" />{customEntries.map(([key, value]) => (- <AttrRow key={key} label={key} value={String(value)} mono />+ <AttrRow key={key} label={key} value={value} mono />))}</div>)}diff --git a/src/client/src/components/(playground)/request/components/tabs-content.tsx b/src/client/src/components/(playground)/request/components/tabs-content.tsxindex a84b0e6f..c99105ab 100644--- a/src/client/src/components/(playground)/request/components/tabs-content.tsx+++ b/src/client/src/components/(playground)/request/components/tabs-content.tsx@@ -20,14 +20,14 @@ export default function TabsContent({<AttrRowkey={key.toString()}label={key as string}- value={value.toString()}+ value={value}/>))) : (<AttrRow- key={datumValue.toString()}- label={datumValue as string}- value={""}+ key={`${dataKey}-${index}-val`}+ label={typeof datumValue === "string" ? datumValue : `[${index}]`}+ value={typeof datumValue === "string" ? "" : datumValue}/>)}</section>@@ -35,8 +35,8 @@ export default function TabsContent({: objectEntries(dataValue).map(([key, value]) => (<AttrRowkey={key.toString()}- label={value as string}- value={value as string || ""}+ label={key as string}+ value={value}/>));diff --git a/src/client/src/components/(playground)/request/components/timeline-view.tsx b/src/client/src/components/(playground)/request/components/timeline-view.tsxindex cc63a020..01464f72 100644--- a/src/client/src/components/(playground)/request/components/timeline-view.tsx+++ b/src/client/src/components/(playground)/request/components/timeline-view.tsx@@ -1,5 +1,27 @@"use client";+/**+ * Timeline View — Waterfall/Gantt visualization of span execution.+ *+ * ## Sequencing logic+ *+ * The row order follows a depth-first pre-order traversal of the hierarchy+ * tree, with siblings sorted by their start timestamp (Timestamp field).+ * This means a parent span always appears before its children, and siblings+ * appear in the order they actually started.+ *+ * The horizontal bar position is computed relative to the *trace time window*,+ * which spans from the earliest start timestamp across all spans to the latest+ * end timestamp (start + duration). Using the full trace window — rather than+ * just the root span's self-duration — ensures that bars for late-finishing+ * children or clock-skewed spans remain within bounds.+ *+ * leftPct = (spanStartMs - traceStartMs) / traceWindowMs * 100+ * widthPct = spanDurationMs / traceWindowMs * 100+ *+ * Both are clamped to [0, 100] to prevent overflow.+ */+import { TraceHeirarchySpan } from "@/types/trace";import { useRequest } from "../request-context";import {@@ -13,6 +35,10 @@ interface FlatSpan {level: number;}+/**+ * Depth-first pre-order traversal. Siblings are already sorted by Timestamp+ * in buildHierarchy (server-side), so iteration order == chronological order.+ */function flattenTree(span: TraceHeirarchySpan,level: number,@@ -48,10 +74,38 @@ function formatDuration(durationNs: number): string {return `${(durationNs / 1e3).toFixed(0)}µs`;}-// Column widths as percentages of the total row-const NAME_COL_PCT = 38;-const DURATION_COL_PCT = 14;-// Bar col takes the remainder: 48%+/**+ * Compute the trace time window (earliest start → latest end) across ALL spans.+ * This is more accurate than using the root span's duration alone, because:+ * - A child may start slightly before the root's recorded Timestamp (clock skew)+ * - A child may finish after the root's Duration (async/detached spans)+ */+function computeTraceWindow(flatSpans: FlatSpan[]): {+ startMs: number;+ endMs: number;+ windowMs: number;+} {+ let startMs = Infinity;+ let endMs = -Infinity;++ for (const { span } of flatSpans) {+ const t = parseTimestampMs(span.Timestamp);+ if (t === null) continue;+ const durationMs = span.Duration / 1e6;+ if (t < startMs) startMs = t;+ if (t + durationMs > endMs) endMs = t + durationMs;+ }++ if (!isFinite(startMs) || !isFinite(endMs)) {+ return { startMs: 0, endMs: 1, windowMs: 1 };+ }++ const windowMs = Math.max(endMs - startMs, 0.001); // avoid zero-division+ return { startMs, endMs, windowMs };+}++const NAME_COL_PCT = 32;+const STATS_COL_PCT = 18;export default function TimelineView({record,@@ -63,14 +117,13 @@ export default function TimelineView({const flatSpans: FlatSpan[] = [];flattenTree(record, 0, flatSpans);- const rootStartMs = parseTimestampMs(record.Timestamp);- const totalDurationMs = record.Duration / 1e6;+ const { startMs: traceStartMs, windowMs: traceWindowMs } =+ computeTraceWindow(flatSpans);return (<div className="flex flex-col text-xs select-none">{/* ── Column header ── */}<div className="flex items-end pb-1 mb-1 border-b border-stone-200 dark:border-stone-700 gap-0">- {/* Name column */}<divclassName="shrink-0 text-stone-500 dark:text-stone-400 font-medium pl-1"style={{ width: `${NAME_COL_PCT}%` }}@@ -78,78 +131,76 @@ export default function TimelineView({Span</div>- {/* Time-axis column */}+ {/* Time-axis ticks */}<divclassName="relative h-4"- style={{ width: `${100 - NAME_COL_PCT - DURATION_COL_PCT}%` }}+ style={{ width: `${100 - NAME_COL_PCT - STATS_COL_PCT}%` }}>- {/* Left edge — 0 */}<span className="absolute left-0 top-0 text-stone-400 dark:text-stone-500">0</span>- {/* Mid — 50% */}- <span className="absolute top-0 -translate-x-1/2 text-stone-400 dark:text-stone-500" style={{ left: "50%" }}>- {formatDuration((totalDurationMs / 2) * 1e6)}+ <span+ className="absolute top-0 -translate-x-1/2 text-stone-400 dark:text-stone-500"+ style={{ left: "50%" }}+ >+ {formatDuration((traceWindowMs / 2) * 1e6)}</span>- {/* Right edge — total */}<span className="absolute right-0 top-0 text-stone-400 dark:text-stone-500">- {formatDuration(totalDurationMs * 1e6)}+ {formatDuration(traceWindowMs * 1e6)}</span></div>- {/* Duration label column header */}<div- className="shrink-0 text-right pr-1 text-stone-500 dark:text-stone-400 font-medium"- style={{ width: `${DURATION_COL_PCT}%` }}+ className="shrink-0 text-right pr-1.5 pl-1.5 text-stone-500 dark:text-stone-400 font-medium"+ style={{ width: `${STATS_COL_PCT}%` }}>- s / $+ <div className="leading-none text-[10px]">Duration</div>+ <div className="leading-none text-[9px] text-stone-400 dark:text-stone-500 mt-0.5">+ Cost+ </div></div></div>{/* ── Span rows ── */}- <div className="flex flex-col gap-3">+ <div className="flex flex-col gap-1.5">{flatSpans.map(({ span, level }) => {const isSelected = request?.spanId === span.SpanId;const spanStartMs = parseTimestampMs(span.Timestamp);const spanDurationMs = span.Duration / 1e6;const durationDisplay = getSpanDurationDisplay(span);- const costDisplay = getSpanCostFormatted(span, 4);+ const costDisplay = getSpanCostFormatted(span, 6);const tooltipText = getSpanTooltipText(span);+ // Bar position relative to the full trace time windowlet leftPct = 0;- let widthPct =- totalDurationMs > 0- ? (spanDurationMs / totalDurationMs) * 100- : 100;-- if (- rootStartMs !== null &&- spanStartMs !== null &&- totalDurationMs > 0- ) {+ let widthPct = (spanDurationMs / traceWindowMs) * 100;++ if (spanStartMs !== null) {leftPct =- ((spanStartMs - rootStartMs) / totalDurationMs) * 100;+ ((spanStartMs - traceStartMs) / traceWindowMs) * 100;}- // Clamp so nothing goes out of bounds+ // ClampleftPct = Math.max(0, Math.min(leftPct, 99));- widthPct = Math.max(1, Math.min(widthPct, 100 - leftPct));+ widthPct = Math.max(0.5, Math.min(widthPct, 100 - leftPct));return (<divkey={span.SpanId}- className={`flex items-center h-6 rounded cursor-pointer transition-colors ${+ className={`flex items-center rounded cursor-pointer transition-colors py-1 ${isSelected? "bg-primary/10 dark:bg-primary/10": "hover:bg-stone-200/60 dark:hover:bg-stone-800/60"}`}- onClick={() => updateRequest({ spanId: span.SpanId })}+ onClick={() =>+ updateRequest({ spanId: span.SpanId })+ }title={tooltipText}>- {/* ── Name column ── */}+ {/* Name */}<div- className="shrink-0 h-full flex items-center overflow-hidden pr-2"+ className="shrink-0 flex items-center overflow-hidden pr-2"style={{width: `${NAME_COL_PCT}%`,paddingLeft: `${level * 10 + 4}px`,@@ -166,16 +217,14 @@ export default function TimelineView({</span></div>- {/* ── Bar column ── */}+ {/* Bar */}<div- className="relative h-full flex items-center"+ className="relative h-[10px] overflow-hidden"style={{- width: `${100 - NAME_COL_PCT - DURATION_COL_PCT}%`,+ width: `${100 - NAME_COL_PCT - STATS_COL_PCT}%`,}}>- {/* Background track */}<div className="absolute inset-x-0 h-px bg-stone-200 dark:bg-stone-700 top-1/2 -translate-y-1/2" />- {/* Span bar */}<divclassName={`absolute h-[10px] rounded-sm ${getBarColor(span.Duration)} ${isSelected@@ -189,18 +238,31 @@ export default function TimelineView({/></div>- {/* ── Duration column ── */}+ {/* Duration + Cost */}<div- className={`shrink-0 text-right pr-1 text-[10px] tabular-nums ${- isSelected- ? "text-primary font-medium"- : "text-stone-500 dark:text-stone-400"- }`}- style={{ width: `${DURATION_COL_PCT}%` }}+ className="shrink-0 text-right pr-1.5 pl-1.5 flex flex-col items-end justify-center overflow-hidden"+ style={{ width: `${STATS_COL_PCT}%` }}>- {costDisplay- ? `${durationDisplay} / ${costDisplay}`- : durationDisplay}+ <span+ className={`text-[10px] tabular-nums leading-tight truncate max-w-full ${+ isSelected+ ? "text-primary font-medium"+ : "text-stone-500 dark:text-stone-400"+ }`}+ >+ {durationDisplay}+ </span>+ {costDisplay && (+ <span+ className={`text-[9px] tabular-nums leading-tight truncate max-w-full ${+ isSelected+ ? "text-primary/80"+ : "text-stone-400 dark:text-stone-500"+ }`}+ >+ {costDisplay}+ </span>+ )}</div></div>);diff --git a/src/client/src/components/(playground)/request/heirarchy-display.tsx b/src/client/src/components/(playground)/request/heirarchy-display.tsxindex e749f25e..e11d04c2 100644--- a/src/client/src/components/(playground)/request/heirarchy-display.tsx+++ b/src/client/src/components/(playground)/request/heirarchy-display.tsx@@ -1,7 +1,7 @@import { useRequest } from "./request-context";-import React, { useEffect, useMemo, useState } from "react";-import { FolderTree, DollarSign, ListTree, GanttChart, Network } from "lucide-react";+import React, { useEffect, useMemo, useRef, useState } from "react";+import { FolderTree, DollarSign } from "lucide-react";import { findSpanInHierarchyLodash } from "@/helpers/client/trace";import { TraceHeirarchySpan } from "@/types/trace";import useFetchWrapper from "@/utils/hooks/useFetchWrapper";@@ -11,8 +11,9 @@ import { ResizeablePanel } from "@/components/ui/resizeable-panel";import TimelineView from "./components/timeline-view";import NodeGraph from "./components/node-graph";import TreeNode from "./components/tree-node";+import ChatView from "./components/chat-view";-type ViewMode = "tree" | "timeline" | "graph";+type ViewMode = "tree" | "timeline" | "graph" | "chat";function sumCostRecursive(span: TraceHeirarchySpan): number {const cost = span.Cost != null && span.Cost > 0 ? span.Cost : 0;@@ -22,17 +23,19 @@ function sumCostRecursive(span: TraceHeirarchySpan): number {const DEFAULT_WIDTH = 46;-const VIEW_TABS: { mode: ViewMode; icon: React.ReactNode; label: string }[] = [- { mode: "tree", icon: <ListTree className="h-3.5 w-3.5" />, label: "Tree" },- { mode: "timeline", icon: <GanttChart className="h-3.5 w-3.5" />, label: "Timeline" },- { mode: "graph", icon: <Network className="h-3.5 w-3.5" />, label: "Graph" },+const VIEW_TABS: { mode: ViewMode; label: string }[] = [+ { mode: "tree", label: "Tree" },+ { mode: "chat", label: "Chat" },+ { mode: "timeline", label: "Timeline" },+ { mode: "graph", label: "Graph" },];export default function HeirarchyDisplay() {const [request] = useRequest();- const { data, fireRequest, isLoading, error } = useFetchWrapper();+ const { data, fireRequest, isLoading } = useFetchWrapper();const [accordionValue, setAccordionValue] = useState("");const [viewMode, setViewMode] = useState<ViewMode>("tree");+ const lastFetchedSpanId = useRef<string | null>(null);useEffect(() => {if (!isLoading) {@@ -43,23 +46,31 @@ export default function HeirarchyDisplay() {const typedData =(data as { record: TraceHeirarchySpan; err?: string }) || {};+ const spanId = request?.spanId;+useEffect(() => {+ if (!spanId || isLoading) return;++ if (lastFetchedSpanId.current === spanId) return;+if (- !findSpanInHierarchyLodash(typedData.record || {}, request?.spanId) &&- request?.spanId &&- !isLoading+ typedData.record?.SpanId &&+ findSpanInHierarchyLodash(typedData.record, spanId)) {- fireRequest({- requestType: "GET",- url: `/api/metrics/request/span/${request?.spanId}/heirarchy`,- failureCb: (err?: string) => {- toast.error(err || `Cannot connect to server!`, {- id: "heirarchy-fetch",- });- },- });+ return;}- }, [request, typedData, isLoading]);++ lastFetchedSpanId.current = spanId;+ fireRequest({+ requestType: "GET",+ url: `/api/metrics/request/span/${spanId}/heirarchy`,+ failureCb: (err?: string) => {+ toast.error(err || `Cannot connect to server!`, {+ id: "heirarchy-fetch",+ });+ },+ });+ }, [spanId, isLoading]); // eslint-disable-line react-hooks/exhaustive-depsconst { record } = typedData;const aggregateCost = useMemo(() => (record ? sumCostRecursive(record) : 0), [record]);@@ -74,66 +85,66 @@ export default function HeirarchyDisplay() {minWidth={DEFAULT_WIDTH}maxWidth={700}handlePosition="left"- className="absolute left-0 top-0 -translate-x-full h-full bg-stone-100 dark:bg-stone-900 border border-stone-200 dark:border-stone-800 border-t-0 shadow-lg"+ className="absolute left-0 top-0 -translate-x-full h-full bg-stone-100 dark:bg-stone-900 border border-stone-200 dark:border-stone-800 border-t-0 shadow-lg"><Accordion type="single" collapsible className="flex flex-1 h-full" value={accordionValue}><AccordionItem value="debug" className="border-0 flex flex-1 w-full">+ {/* ── Left rail: accordion toggle only ── */}<AccordionTrigger- className="flex flex-col items-center gap-3 px-3 py-6 hover:no-underline hover:bg-stone-100 dark:hover:bg-stone-900 [&[data-state=open]]:bg-stone-100 dark:[&[data-state=open]]:bg-stone-900/50 [&[data-state=open]>svg]:rotate-90 [&[data-state=closed]>svg]:rotate-[-90deg] border-r border-stone-200 dark:border-stone-800 transition-colors"+ className="flex flex-col items-center gap-3 px-3 py-4 hover:no-underline hover:bg-stone-100 dark:hover:bg-stone-900 [&[data-state=open]]:bg-stone-100 dark:[&[data-state=open]]:bg-stone-900/50 [&[data-state=open]>svg]:rotate-90 [&[data-state=closed]>svg]:rotate-[-90deg] border-r border-stone-200 dark:border-stone-800 transition-colors shrink-0"onClick={() => setAccordionValue(accordionValue === "debug" ? "" : "debug")}>- <div className="flex flex-col items-center gap-3">- <FolderTree className="h-5 w-5 text-stone-600 dark:text-stone-400" />- <span className="text-sm font-semibold [writing-mode:vertical-lr] rotate-180 transform text-stone-700 dark:text-stone-300">+ <div className="flex flex-col items-center gap-2">+ <FolderTree className="h-4.5 w-4.5 text-stone-600 dark:text-stone-400" />+ <span className="text-xs font-semibold [writing-mode:vertical-lr] rotate-180 transform text-stone-700 dark:text-stone-300">Span Hierarchy</span>{isLoading && (- <div className="flex flex-col items-center gap-1">- <div className="w-6 h-6 border-2 border-stone-300 border-t-stone-600 rounded-full animate-spin" />- <span className="text-xs text-stone-500 [writing-mode:vertical-lr] rotate-180">- Loading...- </span>- </div>+ <div className="w-5 h-5 border-2 border-stone-300 border-t-stone-600 rounded-full animate-spin" />)}</div></AccordionTrigger>++ {/* ── Main content area ── */}<AccordionContent className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down transition-all h-full pb-0" parentClassName="h-full w-full"><div className="flex flex-col h-full">- {/* View mode tab strip */}- <div className="flex items-center gap-1 px-3 py-2 border-b border-stone-200 dark:border-stone-800 bg-stone-50 dark:bg-stone-900 shrink-0">- {VIEW_TABS.map(({ mode, icon, label }) => (+ {/* View mode tabs — horizontal at the top */}+ <div className="flex items-center gap-1 px-3 py-1.5 border-b border-stone-200 dark:border-stone-800 bg-stone-50 dark:bg-stone-900 shrink-0">+ {VIEW_TABS.map(({ mode, label }) => (<buttonkey={mode}onClick={() => setViewMode(mode)}- className={`flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium transition-colors ${+ className={`px-2.5 py-1 rounded text-xs font-medium transition-colors ${viewMode === mode- ? "bg-primary/10 text-primary dark:bg-primary/10 dark:text-primary"+ ? "bg-primary/10 text-primary": "text-stone-500 dark:text-stone-400 hover:text-stone-700 dark:hover:text-stone-300 hover:bg-stone-200 dark:hover:bg-stone-800"}`}>- {icon}{label}</button>))}</div>- {/* Header */}- <div className="px-3 pt-2 pb-1 shrink-0 border-b border-stone-200 dark:border-stone-800">- <h3 className="text-sm font-semibold text-stone-900 dark:text-stone-100">- Trace Execution Flow- </h3>- <p className="text-xs text-stone-500 dark:text-stone-400 mt-0.5">- Click spans to view details- </p>- </div>-{/* Content */}- <div className="flex-1 min-h-0 overflow-auto">- <div className="p-3 min-w-fit">- {viewMode === "tree" && <TreeNode span={record} level={0} />}- {viewMode === "timeline" && <TimelineView record={record} />}- {viewMode === "graph" && <NodeGraph record={record} />}- </div>+ <div className={`flex-1 min-h-0 ${viewMode === "graph" ? "flex flex-col" : "overflow-auto"}`}>+ {viewMode === "tree" && (+ <div className="p-3 min-w-fit overflow-auto h-full">+ <TreeNode span={record} level={0} />+ </div>+ )}+ {viewMode === "chat" && (+ <div className="overflow-auto h-full">+ <ChatView record={record} />+ </div>+ )}+ {viewMode === "timeline" && (+ <div className="p-3 min-w-fit overflow-auto h-full">+ <TimelineView record={record} />+ </div>+ )}+ {viewMode === "graph" && (+ <NodeGraph key={record.SpanId} record={record} />+ )}</div>{/* Aggregate cost footer */}@@ -144,7 +155,7 @@ export default function HeirarchyDisplay() {Total cost:</span><span className="text-xs font-semibold text-stone-800 dark:text-stone-200">- ${aggregateCost.toFixed(6)}+ ${aggregateCost.toFixed(10)}</span></div>)}diff --git a/src/client/src/components/(playground)/request/request-context.tsx b/src/client/src/components/(playground)/request/request-context.tsxindex b3de5344..2b46a7d6 100644--- a/src/client/src/components/(playground)/request/request-context.tsx+++ b/src/client/src/components/(playground)/request/request-context.tsx@@ -14,7 +14,12 @@ const RequestContext = createContext<[RequestProps, RequestUpdateProps]>([type RequestListContextType = {items: TransformedTraceRow[];currentIndex: number;+ total: number;+ offset: number;setItems: (items: TransformedTraceRow[]) => void;+ setTotal: (total: number) => void;+ setOffset: (offset: number) => void;+ setOnPageChange: (cb: ((dir: -1 | 1) => void) | null) => void;navigatePrev: () => void;navigateNext: () => void;};@@ -22,7 +27,12 @@ type RequestListContextType = {const RequestListContext = createContext<RequestListContextType>({items: [],currentIndex: -1,+ total: 0,+ offset: 0,setItems: noop,+ setTotal: noop,+ setOffset: noop,+ setOnPageChange: noop,navigatePrev: noop,navigateNext: noop,});@@ -48,12 +58,22 @@ function syncUrlParams(request: RequestProps) {export function RequestProvider({ children }: { children: ReactNode }) {const [request, setRequest] = useState<RequestProps>(null);const [items, setItemsState] = useState<TransformedTraceRow[]>([]);+ const [total, setTotalState] = useState(0);+ const [offset, setOffsetState] = useState(0);// Keep refs so navigatePrev/navigateNext always see the latest valuesconst requestRef = useRef(request);requestRef.current = request;const itemsRef = useRef(items);itemsRef.current = items;+ const onPageChangeRef = useRef<((dir: -1 | 1) => void) | null>(null);+ const totalRef = useRef(total);+ totalRef.current = total;+ const offsetRef = useRef(offset);+ offsetRef.current = offset;+ // Tracks which direction a page-boundary navigation was triggered so we can+ // auto-select the correct item once the new page's data arrives.+ const pendingNavDirection = useRef<-1 | 1 | null>(null);const updateRequest = useCallback((value: RequestProps) => {setRequest(value);@@ -62,6 +82,29 @@ export function RequestProvider({ children }: { children: ReactNode }) {const setItems = useCallback((newItems: TransformedTraceRow[]) => {setItemsState(newItems);+ // If a page-boundary navigation triggered the fetch, auto-select the+ // first item (next page) or last item (previous page) of the new data.+ if (pendingNavDirection.current !== null && newItems.length > 0) {+ const target =+ pendingNavDirection.current === 1+ ? newItems[0]+ : newItems[newItems.length - 1];+ pendingNavDirection.current = null;+ setRequest(target);+ syncUrlParams(target);+ }+ }, []);++ const setTotal = useCallback((t: number) => {+ setTotalState(t);+ }, []);++ const setOffset = useCallback((o: number) => {+ setOffsetState(o);+ }, []);++ const setOnPageChange = useCallback((cb: ((dir: -1 | 1) => void) | null) => {+ onPageChangeRef.current = cb;}, []);// On mount, check URL for spanId to restore the open trace@@ -84,6 +127,10 @@ export function RequestProvider({ children }: { children: ReactNode }) {const prev = itemsRef.current[idx - 1];setRequest(prev);syncUrlParams(prev);+ } else if (idx === 0 && offsetRef.current > 0 && onPageChangeRef.current) {+ // At first item of current page — trigger previous page+ pendingNavDirection.current = -1;+ onPageChangeRef.current(-1);}}, []);@@ -95,6 +142,14 @@ export function RequestProvider({ children }: { children: ReactNode }) {const next = itemsRef.current[idx + 1];setRequest(next);syncUrlParams(next);+ } else if (+ idx === itemsRef.current.length - 1 &&+ offsetRef.current + itemsRef.current.length < totalRef.current &&+ onPageChangeRef.current+ ) {+ // At last item of current page — trigger next page+ pendingNavDirection.current = 1;+ onPageChangeRef.current(1);}}, []);@@ -106,7 +161,18 @@ export function RequestProvider({ children }: { children: ReactNode }) {return (<RequestContext.Provider value={[request, updateRequest]}><RequestListContext.Provider- value={{ items, currentIndex, setItems, navigatePrev, navigateNext }}+ value={{+ items,+ currentIndex,+ total,+ offset,+ setItems,+ setTotal,+ setOffset,+ setOnPageChange,+ navigatePrev,+ navigateNext,+ }}>{children}</RequestListContext.Provider>diff --git a/src/client/src/components/(playground)/request/request-details.tsx b/src/client/src/components/(playground)/request/request-details.tsxindex 5a668448..e4570cc7 100644--- a/src/client/src/components/(playground)/request/request-details.tsx+++ b/src/client/src/components/(playground)/request/request-details.tsx@@ -118,7 +118,7 @@ function LoadingSkeleton() {export default function RequestDetails() {const [isOpen, setIsOpen] = useState(false);const [request, updateRequest] = useRequest();- const { currentIndex, items, navigatePrev, navigateNext } = useRequestNavigation();+ const { currentIndex, items, total, offset, navigatePrev, navigateNext } = useRequestNavigation();const { data, fireRequest, isLoading } = useFetchWrapper();// Cache the last successfully loaded record so navigation never flickers to a skeleton.@@ -229,7 +229,7 @@ export default function RequestDetails() {const parsedCost = parseFloat(normalizedItem?.cost as string);const costValue =isFinite(parsedCost) && parsedCost > 0- ? `$${parsedCost.toFixed(6)}`+ ? `$${parsedCost.toFixed(10)}`: undefined;const parsedTokens = Number(normalizedItem?.totalTokens);const tokensValue =@@ -257,7 +257,8 @@ export default function RequestDetails() {displayClose={false}><SheetHeader className="flex-row bg-stone-100 dark:bg-stone-900 px-3 py-1.5 items-center space-y-0 gap-2">- <SheetTitle className="text-stone-900 dark:text-stone-200 text-md font-bold leading-7 capitalize grow pr-1 truncate">+ {/* capitalize : classname is removed because it was rendering the name incorrectly */}+ <SheetTitle className="text-stone-900 dark:text-stone-200 text-md font-bold leading-7 grow pr-1 truncate">{!normalizedItem? "Loading…": normalizedItem.spanName}@@ -276,18 +277,18 @@ export default function RequestDetails() {<div className="flex items-center gap-0.5 shrink-0"><buttononClick={navigatePrev}- disabled={currentIndex <= 0}+ disabled={currentIndex <= 0 && offset <= 0}className="p-1 rounded text-stone-500 dark:text-stone-400 hover:text-stone-900 dark:hover:text-stone-200 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"title="Previous item"><ChevronLeft className="h-4 w-4" /></button><span className="text-xs text-stone-600 dark:text-stone-500 tabular-nums min-w-[3rem] text-center">- {currentIndex + 1} / {items.length}+ {offset + currentIndex + 1} / {total || items.length}</span><buttononClick={navigateNext}- disabled={currentIndex >= items.length - 1}+ disabled={currentIndex >= items.length - 1 && offset + items.length >= total}className="p-1 rounded text-stone-500 dark:text-stone-400 hover:text-stone-900 dark:hover:text-stone-200 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"title="Next item">@@ -343,7 +344,7 @@ export default function RequestDetails() {label="Eval Cost"value={evaluationSummary.totalCost > 0- ? `$${evaluationSummary.totalCost.toFixed(6)}`+ ? `$${evaluationSummary.totalCost.toFixed(10)}`: undefined}/>@@ -371,7 +372,7 @@ export default function RequestDetails() {value.toString().length > 0 && (<InfoPillkey={key}- title={reverseKey ? TraceMapping[reverseKey].label : key}+ title={key}value={normalizedValue}/>)diff --git a/src/client/src/helpers/client/trace.ts b/src/client/src/helpers/client/trace.tsindex 187ac25a..632e741a 100644--- a/src/client/src/helpers/client/trace.ts+++ b/src/client/src/helpers/client/trace.ts@@ -287,7 +287,7 @@ export function getSpanCostFormatted(*/export function getSpanTooltipText(span: TraceHeirarchySpan): string {const durationDisplay = getSpanDurationDisplay(span);- const costStr = getSpanCostFormatted(span, 6);+ const costStr = getSpanCostFormatted(span, 10);return costStr? `${span.SpanName}\nDuration: ${durationDisplay}\nCost: ${costStr}`: `${span.SpanName}\nDuration: ${durationDisplay}`;diff --git a/src/client/src/helpers/server/trace.ts b/src/client/src/helpers/server/trace.tsindex ec900bb8..bfc2f222 100644--- a/src/client/src/helpers/server/trace.ts+++ b/src/client/src/helpers/server/trace.ts@@ -22,5 +22,18 @@ export const buildHierarchy = (data: any[]) => {}});+ // Sort children at every level by Timestamp (chronological order)+ function sortChildren(node: any) {+ if (node?.children?.length) {+ node.children.sort((a: any, b: any) => {+ const tsA = a.Timestamp ? new Date(a.Timestamp).getTime() : 0;+ const tsB = b.Timestamp ? new Date(b.Timestamp).getTime() : 0;+ return tsA - tsB;+ });+ node.children.forEach(sortChildren);+ }+ }+ sortChildren(root);+return root; // Returns the hierarchical tree};diff --git a/src/client/src/lib/platform/request/index.ts b/src/client/src/lib/platform/request/index.tsindex e53ec52d..9484386d 100644--- a/src/client/src/lib/platform/request/index.ts+++ b/src/client/src/lib/platform/request/index.ts@@ -207,76 +207,62 @@ export async function getRequestViaTraceId(traceId: string) {}export async function getHeirarchyViaSpanId(spanId: string) {- const commonQuery = (- dir: "upward" | "downward",- id: string- ) => `WITH RECURSIVE trace_hierarchy AS (- SELECT- ${getTraceMappingKeyFullPath("id")},- ${getTraceMappingKeyFullPath("parentSpanId")},- ${getTraceMappingKeyFullPath("spanId")},- ${getTraceMappingKeyFullPath("spanName")},- ${getTraceMappingKeyFullPath("requestDuration")},- toFloat64OrZero(SpanAttributes['${getTraceMappingKeyFullPath("cost")}']) AS Cost,- Timestamp,- StatusCode,- 0 AS level- FROM- ${OTEL_TRACES_TABLE_NAME}- WHERE- SpanId = '${id}' -- Starting SpanId-- UNION ALL-- SELECT- ot.${getTraceMappingKeyFullPath("id")},- ot.${getTraceMappingKeyFullPath("parentSpanId")},- ot.${getTraceMappingKeyFullPath("spanId")},- ot.${getTraceMappingKeyFullPath("spanName")},- ot.${getTraceMappingKeyFullPath("requestDuration")},- toFloat64OrZero(ot.SpanAttributes['${getTraceMappingKeyFullPath("cost")}']) AS Cost,- ot.Timestamp,- ot.StatusCode,- th.level + 1 AS level- FROM- ${OTEL_TRACES_TABLE_NAME} ot- INNER JOIN- trace_hierarchy th- ON- ${dir === "upward"- ? `ot.${getTraceMappingKeyFullPath(- "spanId"- )} = th.${getTraceMappingKeyFullPath("parentSpanId")}`- : `ot.${getTraceMappingKeyFullPath(- "parentSpanId"- )} = th.${getTraceMappingKeyFullPath("spanId")}`- }- )- SELECT *- FROM trace_hierarchy- ORDER BY level DESC;`;+ // Step 1: Get the TraceId for this span+ const traceIdQuery = `+ SELECT ${getTraceMappingKeyFullPath("id")}+ FROM ${OTEL_TRACES_TABLE_NAME}+ WHERE SpanId = '${spanId}'+ LIMIT 1`;- const { data: upwardData, err: upwardErr } = await dataCollector({- query: commonQuery("upward", spanId),+ const { data: traceIdData, err: traceIdErr } = await dataCollector({+ query: traceIdQuery,});- if ((upwardData as any[])?.[0]?.SpanId) {- const { data: downwardData, err: downwardErr } = await dataCollector({- query: commonQuery("downward", (upwardData as any[])?.[0]?.SpanId),- });+ if (traceIdErr || !Array.isArray(traceIdData) || traceIdData.length === 0) {+ console.error(`[heirarchy] Failed to find TraceId for spanId=${spanId}:`, traceIdErr);+ return { err: "Span not found", record: {} };+ }- const heirarchy = buildHierarchy(downwardData as any[]);+ const traceId = traceIdData[0].TraceId;+ if (!traceId) {+ console.error(`[heirarchy] TraceId is empty for spanId=${spanId}. Row:`, traceIdData[0]);+ return { err: "TraceId not found for span", record: {} };+ }- return {- err: upwardErr || downwardErr || (heirarchy ? null : "Error in fetching heirarchy"),- record: heirarchy,- };+ // Step 2: Fetch ALL spans belonging to this trace (include SpanAttributes for chat view)+ const allSpansQuery = `+ SELECT+ ${getTraceMappingKeyFullPath("id")},+ ${getTraceMappingKeyFullPath("parentSpanId")},+ ${getTraceMappingKeyFullPath("spanId")},+ ${getTraceMappingKeyFullPath("spanName")},+ ${getTraceMappingKeyFullPath("requestDuration")},+ toFloat64OrZero(SpanAttributes['${getTraceMappingKeyFullPath("cost")}']) AS Cost,+ Timestamp,+ StatusCode,+ SpanAttributes+ FROM ${OTEL_TRACES_TABLE_NAME}+ WHERE ${getTraceMappingKeyFullPath("id")} = '${traceId}'+ ORDER BY Timestamp ASC`;++ const { data: allSpans, err: allSpansErr } = await dataCollector({+ query: allSpansQuery,+ });++ if (allSpansErr || !Array.isArray(allSpans) || allSpans.length === 0) {+ console.error(`[heirarchy] Failed to fetch spans for traceId=${traceId}:`, allSpansErr);+ return { err: "Failed to fetch trace spans", record: {} };}- return {- err: "Error in fetching heirarchy",- record: {},- };+ // Step 3: Build the hierarchy tree in JS+ const heirarchy = buildHierarchy(allSpans as any[]);++ if (!heirarchy) {+ console.error(`[heirarchy] buildHierarchy returned null for traceId=${traceId}, ${allSpans.length} spans`);+ return { err: "Error building hierarchy", record: {} };+ }++ return { err: null, record: heirarchy };}export async function getRequestExist() {diff --git a/src/client/src/types/trace.ts b/src/client/src/types/trace.tsindex 97942d97..b4908c6e 100644--- a/src/client/src/types/trace.ts+++ b/src/client/src/types/trace.ts@@ -151,5 +151,6 @@ export interface TraceHeirarchySpan {Timestamp?: string;StatusCode?: string;Cost?: number;+ SpanAttributes?: Record<string, string | number>;children?: TraceHeirarchySpan[];}