Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

fix: trace view ui updated with timeline view, graph view and some extra information on the request details sheet (#1036)

Aman Agarwald8df550ebeed
diff --git a/docs/latest/sdk/integrations/overview.mdx b/docs/latest/sdk/integrations/overview.mdx
index 36c74863..b2b9433d 100644
--- a/docs/latest/sdk/integrations/overview.mdx
+++ b/docs/latest/sdk/integrations/overview.mdx
@@ -2259,6 +2259,7 @@ Start integrating and monitoring your applications with OpenLIT in just one line
>
<div style={{position: "absolute", top: "12px", right: "12px", display: "flex", gap: "4px"}}>
<img src="https://cdn.simpleicons.org/python/ffa500" width="16" height="16" alt="Python SDK" title="Python SDK" />
+ <img src="https://cdn.simpleicons.org/typescript/ffa500" width="16" height="16" alt="TypeScript SDK" title="TypeScript SDK" />
</div>
</Card>
@@ -2309,6 +2310,7 @@ Start integrating and monitoring your applications with OpenLIT in just one line
>
<div style={{position: "absolute", top: "12px", right: "12px", display: "flex", gap: "4px"}}>
<img src="https://cdn.simpleicons.org/python/ffa500" width="16" height="16" alt="Python SDK" title="Python SDK" />
+ <img src="https://cdn.simpleicons.org/typescript/ffa500" width="16" height="16" alt="TypeScript SDK" title="TypeScript SDK" />
</div>
</Card>
@@ -2327,6 +2329,7 @@ Start integrating and monitoring your applications with OpenLIT in just one line
>
<div style={{position: "absolute", top: "12px", right: "12px", display: "flex", gap: "4px"}}>
<img src="https://cdn.simpleicons.org/python/ffa500" width="16" height="16" alt="Python SDK" title="Python SDK" />
+ <img src="https://cdn.simpleicons.org/typescript/ffa500" width="16" height="16" alt="TypeScript SDK" title="TypeScript SDK" />
</div>
</Card>
diff --git a/src/client/src/app/(playground)/exceptions/page.tsx b/src/client/src/app/(playground)/exceptions/page.tsx
index 36caeca9..b195c6e9 100644
--- a/src/client/src/app/(playground)/exceptions/page.tsx
+++ b/src/client/src/app/(playground)/exceptions/page.tsx
@@ -1,15 +1,15 @@
"use client";
-import { useCallback, useEffect } from "react";
+import { useCallback, useEffect, useMemo } from "react";
import {
RequestProvider,
useRequest,
+ useRequestNavigation,
} from "@/components/(playground)/request/request-context";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
import { toast } from "sonner";
import { getFilterDetails } from "@/selectors/filter";
import { useRootStore } from "@/store";
import { getPingStatus } from "@/selectors/database-config";
-import { omit } from "lodash";
import RequestDetails from "@/components/(playground)/request/request-details";
import { normalizeTrace } from "@/helpers/client/trace";
import DataTable from "@/components/data-table/table";
@@ -21,6 +21,7 @@ import ExceptionsGettingStarted from "@/components/(playground)/getting-started/
function ExceptionPage() {
const filter = useRootStore(getFilterDetails);
const [, updateRequest] = useRequest();
+ const { setItems } = useRequestNavigation();
const onClick = (item: any) => {
!isLoading && updateRequest(item);
@@ -42,7 +43,7 @@ function ExceptionPage() {
const fetchData = useCallback(async () => {
fireRequest({
- body: JSON.stringify(omit(filter, ["selectedConfig"])),
+ body: JSON.stringify(filter),
requestType: "POST",
url: "/api/metrics/exception",
failureCb: (err?: string) => {
@@ -63,7 +64,14 @@ function ExceptionPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [filter, pingStatus]);
- const normalizedData = ((data as any)?.records || []).map(normalizeTrace);
+ const normalizedData = useMemo(
+ () => ((data as any)?.records || []).map(normalizeTrace),
+ [data]
+ );
+
+ useEffect(() => {
+ setItems(normalizedData);
+ }, [normalizedData, setItems]);
// Show getting started when there's no trace data AND initial fetch is complete
@@ -82,6 +90,7 @@ function ExceptionPage() {
includeOnlySorting={["Timestamp"]}
pageName={"exception"}
columns={columns}
+ supportDynamicFilters
/>
<DataTable
columns={columns}
diff --git a/src/client/src/app/(playground)/requests/page.tsx b/src/client/src/app/(playground)/requests/page.tsx
index 0b39d7b3..96bcdd71 100644
--- a/src/client/src/app/(playground)/requests/page.tsx
+++ b/src/client/src/app/(playground)/requests/page.tsx
@@ -1,8 +1,9 @@
"use client";
-import { useCallback, useEffect } from "react";
+import { useCallback, useEffect, useMemo } from "react";
import {
RequestProvider,
useRequest,
+ useRequestNavigation,
} from "@/components/(playground)/request/request-context";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
import RequestDetails from "@/components/(playground)/request/request-details";
@@ -19,6 +20,7 @@ import TracingGettingStarted from "@/components/(playground)/getting-started/tra
function RequestPage() {
const [, updateRequest] = useRequest();
+ const { setItems } = useRequestNavigation();
const onClick = (item: any) => {
!isLoading && updateRequest(item);
@@ -61,7 +63,14 @@ function RequestPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [filter, pingStatus]);
- const normalizedData = ((data as any)?.records || []).map(normalizeTrace);
+ const normalizedData = useMemo(
+ () => ((data as any)?.records || []).map(normalizeTrace),
+ [data]
+ );
+
+ useEffect(() => {
+ setItems(normalizedData);
+ }, [normalizedData, setItems]);
// Show getting started when there's no trace data AND initial fetch is complete
if (existData === false && !isLoadingExist && isFetchedExist) {
diff --git a/src/client/src/app/api/metrics/request/attribute-keys/route.ts b/src/client/src/app/api/metrics/request/attribute-keys/route.ts
new file mode 100644
index 00000000..0c385f71
--- /dev/null
+++ b/src/client/src/app/api/metrics/request/attribute-keys/route.ts
@@ -0,0 +1,28 @@
+import { MetricParams, TimeLimit } from "@/lib/platform/common";
+import { getAttributeKeys } from "@/lib/platform/request";
+import {
+ validateMetricsRequest,
+ validateMetricsRequestType,
+} from "@/helpers/server/platform";
+
+export async function POST(request: Request) {
+ const formData = await request.json();
+ const timeLimit = formData.timeLimit as TimeLimit;
+
+ const params: MetricParams = {
+ timeLimit,
+ };
+
+ const validationParam = validateMetricsRequest(
+ params,
+ validateMetricsRequestType.GET_ALL
+ );
+
+ if (!validationParam.success)
+ return Response.json(validationParam.err, {
+ status: 400,
+ });
+
+ const res = await getAttributeKeys(params);
+ return Response.json(res);
+}
diff --git a/src/client/src/components/(playground)/filter/index.tsx b/src/client/src/components/(playground)/filter/index.tsx
index 7771dac1..d18aede5 100644
--- a/src/client/src/components/(playground)/filter/index.tsx
+++ b/src/client/src/components/(playground)/filter/index.tsx
@@ -35,7 +35,7 @@ const Filter = ({ className = "" }: { className?: string }) => {
return (
<div className={`flex grow gap-4 ${className}`}>
- <Tabs defaultValue={filter.timeLimit.type} onValueChange={handleChange}>
+ <Tabs value={filter.timeLimit.type} onValueChange={handleChange}>
<TabsList className="p-0 h-[30px] border border-stone-200 dark:border-stone-800">
{TIME_RANGE_TABS.map(({ label, key }) => (
<TabsTrigger key={key} value={key} className="py-1.5 text-xs">
diff --git a/src/client/src/components/(playground)/filter/traces-filter.tsx b/src/client/src/components/(playground)/filter/traces-filter.tsx
index cbd03423..a22119fc 100644
--- a/src/client/src/components/(playground)/filter/traces-filter.tsx
+++ b/src/client/src/components/(playground)/filter/traces-filter.tsx
@@ -6,24 +6,203 @@ import {
getFilterDetails,
getUpdateFilter,
getUpdateConfig,
+ getAttributeKeys,
+ getUpdateAttributeKeys,
} from "@/selectors/filter";
import { useRootStore } from "@/store";
import Sorting from "./sorting";
import ComboDropdown from "./combo-dropdown";
import SlideWithValue from "./slider-with-value";
import { Button } from "@/components/ui/button";
-import { SlidersHorizontal } from "lucide-react";
+import { Input } from "@/components/ui/input";
+import { Plus, SlidersHorizontal, Trash2, ChevronDown } from "lucide-react";
import { getPingStatus } from "@/selectors/database-config";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { createPortal } from "react-dom";
import { toast } from "sonner";
-import { FilterConfig, FilterType } from "@/types/store/filter";
+import {
+ AttributeKeys,
+ CustomFilter,
+ CustomFilterAttributeType,
+ FilterConfig,
+ FilterType,
+} from "@/types/store/filter";
import { usePostHog } from "posthog-js/react";
import { CLIENT_EVENTS } from "@/constants/events";
import VisibilityColumns from "./visibility-columns";
import { PAGE } from "@/types/store/page";
import { Columns } from "@/components/data-table/columns";
+import { useRouter, usePathname } from "next/navigation";
+
+// ─── Combobox (text input + inline dropdown, portal-rendered to escape overflow) ───
+
+const Combobox = ({
+ value,
+ onChange,
+ options,
+ placeholder,
+ className,
+}: {
+ value: string;
+ onChange: (val: string) => void;
+ options: string[];
+ placeholder?: string;
+ className?: string;
+}) => {
+ const [open, setOpen] = useState(false);
+ const [inputValue, setInputValue] = useState(value);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const [dropdownStyle, setDropdownStyle] = useState<React.CSSProperties>({});
+
+ useEffect(() => {
+ setInputValue(value);
+ }, [value]);
+
+ const updateDropdownPos = () => {
+ if (inputRef.current) {
+ const rect = inputRef.current.getBoundingClientRect();
+ setDropdownStyle({
+ position: "fixed",
+ top: rect.bottom + 2,
+ left: rect.left,
+ width: Math.max(rect.width, 224),
+ });
+ }
+ };
+
+ const filtered = inputValue
+ ? options.filter((o) => o.toLowerCase().includes(inputValue.toLowerCase()))
+ : options;
+
+ const commit = (val: string) => {
+ onChange(val);
+ setInputValue(val);
+ setOpen(false);
+ };
+
+ return (
+ <div className={`relative ${className ?? "w-44"}`}>
+ <Input
+ ref={inputRef}
+ placeholder={placeholder ?? ""}
+ value={inputValue}
+ onChange={(e) => {
+ setInputValue(e.target.value);
+ onChange(e.target.value);
+ if (!open) { updateDropdownPos(); setOpen(true); }
+ }}
+ onFocus={() => { updateDropdownPos(); setOpen(true); }}
+ onBlur={() => setTimeout(() => setOpen(false), 120)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const exact = filtered.find(
+ (o) => o.toLowerCase() === inputValue.toLowerCase()
+ );
+ commit(exact ?? inputValue);
+ } else if (e.key === "Escape") {
+ setOpen(false);
+ } else if (e.key === "ArrowDown" && open && filtered.length > 0) {
+ e.preventDefault();
+ }
+ }}
+ className={`h-7 text-xs w-full ${options.length > 0 ? "pr-6" : ""}`}
+ />
+ {options.length > 0 && (
+ <ChevronDown className="absolute right-1.5 top-1/2 -translate-y-1/2 w-3 h-3 text-stone-400 pointer-events-none" />
+ )}
+ {open && filtered.length > 0 && typeof window !== "undefined" && createPortal(
+ <div
+ style={dropdownStyle}
+ className="z-[9999] rounded-md border border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950 shadow-md max-h-48 overflow-auto"
+ >
+ {filtered.map((opt) => (
+ <button
+ key={opt}
+ type="button"
+ className="w-full text-left text-xs px-2 py-1.5 hover:bg-stone-100 dark:hover:bg-stone-800 text-stone-700 dark:text-stone-300"
+ onMouseDown={(e) => {
+ e.preventDefault();
+ commit(opt);
+ }}
+ >
+ {opt}
+ </button>
+ ))}
+ </div>,
+ document.body
+ )}
+ </div>
+ );
+};
+
+// ─── URL sync helpers ─────────────────────────────────────────────────────────
+
+// Separator used inside a single custom-filter param value: type|key|value
+const CF_SEP = "|";
+
+function configToParams(config: Partial<FilterConfig>, params: URLSearchParams) {
+ params.delete("models");
+ params.delete("providers");
+ params.delete("traceTypes");
+ params.delete("appNames");
+ params.delete("envs");
+ params.delete("maxCost");
+ // remove all existing cf entries
+ params.delete("cf");
+
+ if (config.models?.length) params.set("models", config.models.join(","));
+ if (config.providers?.length) params.set("providers", config.providers.join(","));
+ if (config.traceTypes?.length) params.set("traceTypes", config.traceTypes.join(","));
+ if (config.applicationNames?.length) params.set("appNames", config.applicationNames.join(","));
+ if (config.environments?.length) params.set("envs", config.environments.join(","));
+ if (config.maxCost) params.set("maxCost", String(config.maxCost));
+ config.customFilters?.forEach(({ attributeType, key, value }) => {
+ if (key && value) {
+ params.append("cf", [attributeType, key, value].join(CF_SEP));
+ }
+ });
+}
+
+function paramsToConfig(params: URLSearchParams): Partial<FilterConfig> {
+ const config: Partial<FilterConfig> = {};
+ const models = params.get("models");
+ if (models) config.models = models.split(",").filter(Boolean);
+ const providers = params.get("providers");
+ if (providers) config.providers = providers.split(",").filter(Boolean);
+ const traceTypes = params.get("traceTypes");
+ if (traceTypes) config.traceTypes = traceTypes.split(",").filter(Boolean);
+ const appNames = params.get("appNames");
+ if (appNames) config.applicationNames = appNames.split(",").filter(Boolean);
+ const envs = params.get("envs");
+ if (envs) config.environments = envs.split(",").filter(Boolean);
+ const maxCost = params.get("maxCost");
+ if (maxCost) config.maxCost = parseFloat(maxCost);
+ const cfValues = params.getAll("cf");
+ if (cfValues.length) {
+ config.customFilters = cfValues.map((raw) => {
+ const [attributeType, key, ...rest] = raw.split(CF_SEP);
+ return {
+ attributeType: (attributeType || "SpanAttributes") as CustomFilterAttributeType,
+ key: key || "",
+ value: rest.join(CF_SEP),
+ };
+ }).filter((f) => f.key && f.value);
+ }
+ return config;
+}
+
+function hasActiveConfig(config: Partial<FilterConfig>): boolean {
+ return Object.values(config).some((v) => {
+ if (Array.isArray(v)) return v.length > 0;
+ if (typeof v === "number") return v > 0;
+ return !!v;
+ });
+}
+
+// ─── DynamicFilters ───────────────────────────────────────────────────────────
const DynamicFilters = ({
isVisibleFilters,
@@ -39,11 +218,24 @@ const DynamicFilters = ({
const pingStatus = useRootStore(getPingStatus);
const filterDetails = useRootStore(getFilterDetails);
const updateConfig = useRootStore(getUpdateConfig);
+ const attributeKeys = useRootStore(getAttributeKeys);
+ const updateAttributeKeys = useRootStore(getUpdateAttributeKeys);
const { fireRequest } = useFetchWrapper();
+ const { fireRequest: fireAttrKeysRequest } = useFetchWrapper();
const updateFilter = useRootStore(getUpdateFilter);
const [selectedFilterValues, setSelectedFilterValues] = useState<
Partial<FilterConfig>
>(filterDetails.selectedConfig || {});
+ const [customFilters, setCustomFilters] = useState<CustomFilter[]>(
+ filterDetails.selectedConfig?.customFilters || []
+ );
+
+ // Keep local UI state in sync when the store's selectedConfig changes externally
+ // (e.g. URL params applied on mount, or Clear Filters)
+ useEffect(() => {
+ setSelectedFilterValues(filterDetails.selectedConfig || {});
+ setCustomFilters(filterDetails.selectedConfig?.customFilters || []);
+ }, [filterDetails.selectedConfig]);
const clearFilter = (type: keyof FilterConfig) => {
setSelectedFilterValues((e) => ({ ...e, [type]: undefined }));
@@ -80,11 +272,39 @@ const DynamicFilters = ({
}
};
- const fetchConfig = useCallback(async () => {
+ const addCustomFilter = () => {
+ setCustomFilters((prev) => [
+ ...prev,
+ { attributeType: "SpanAttributes", key: "", value: "" },
+ ]);
+ };
+
+ const removeCustomFilter = (index: number) => {
+ setCustomFilters((prev) => prev.filter((_, i) => i !== index));
+ };
+
+ const updateCustomFilter = (
+ index: number,
+ field: "attributeType" | "key" | "value",
+ val: string
+ ) => {
+ setCustomFilters((prev) =>
+ prev.map((f, i) =>
+ i === index
+ ? {
+ ...f,
+ [field]: val as CustomFilterAttributeType,
+ // Reset key when attribute type changes
+ ...(field === "attributeType" ? { key: "" } : {}),
+ }
+ : f
+ )
+ );
+ };
+
+ const fetchConfig = useCallback(async (timeLimit: FilterType["timeLimit"]) => {
fireRequest({
- body: JSON.stringify({
- timeLimit: filter.timeLimit,
- }),
+ body: JSON.stringify({ timeLimit }),
requestType: "POST",
url: "/api/metrics/request/config",
successCb: (resp) => {
@@ -96,8 +316,10 @@ const DynamicFilters = ({
});
},
});
- }, [filter]);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+ // Fetch filter config when time window changes or config is cleared after a range change.
useEffect(() => {
if (
filter.timeLimit.start &&
@@ -105,124 +327,329 @@ const DynamicFilters = ({
pingStatus === "success" &&
!filterConfig
) {
- fetchConfig();
+ fetchConfig(filter.timeLimit);
}
- }, [filter, pingStatus, filterConfig, fetchConfig]);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [filter.timeLimit.type, filter.timeLimit.start, filter.timeLimit.end, pingStatus, filterConfig]);
+
+ const fetchAttributeKeys = useCallback(async (timeLimit: FilterType["timeLimit"]) => {
+ fireAttrKeysRequest({
+ body: JSON.stringify({ timeLimit }),
+ requestType: "POST",
+ url: "/api/metrics/request/attribute-keys",
+ successCb: (resp) => {
+ if (resp?.spanAttributeKeys !== undefined) {
+ updateAttributeKeys({
+ spanAttributeKeys: resp.spanAttributeKeys,
+ resourceAttributeKeys: resp.resourceAttributeKeys,
+ } as AttributeKeys);
+ }
+ },
+ failureCb: () => {
+ // silently fail – attribute keys are a nice-to-have
+ },
+ });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ // Fetch attribute keys whenever the time window changes.
+ // Use leaf primitives as deps – lodash merge mutates timeLimit in-place
+ // so the object reference never changes between renders.
+ useEffect(() => {
+ if (
+ filter.timeLimit.start &&
+ filter.timeLimit.end &&
+ pingStatus === "success"
+ ) {
+ fetchAttributeKeys(filter.timeLimit);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [filter.timeLimit.type, filter.timeLimit.start, filter.timeLimit.end, pingStatus]);
const updateFilterStore = () => {
- updateFilter("selectedConfig", selectedFilterValues);
+ const validCustomFilters = customFilters.filter((f) => f.key && f.value);
+ updateFilter("selectedConfig", {
+ ...selectedFilterValues,
+ customFilters:
+ validCustomFilters.length > 0 ? validCustomFilters : undefined,
+ });
posthog?.capture(CLIENT_EVENTS.TRACE_FILTER_APPLIED);
};
const clearFilterStore = () => {
setSelectedFilterValues({});
+ setCustomFilters([]);
posthog?.capture(CLIENT_EVENTS.TRACE_FILTER_CLEARED);
updateFilter("selectedConfig", {}, { clearFilter: true });
};
return (
<div
- className={`flex w-full overflow-hidden transition-all gap-4 ${
+ className={`flex flex-col w-full overflow-hidden transition-all gap-3 ${
isVisibleFilters ? "h-auto mt-4" : "h-0 mt-0"
}`}
>
- <div className="flex grow gap-3 overflow-auto">
- {filterConfig?.traceTypes?.length ? (
- <ComboDropdown
- options={filterConfig?.traceTypes.map((p) => ({
- label: p,
- value: p,
- }))}
- title="Types"
- type="traceTypes"
- updateSelectedValues={updateSelectedValues}
- selectedValues={selectedFilterValues.traceTypes}
- clearItem={clearFilter}
- />
- ) : null}
- {filterConfig?.models?.length ? (
- <ComboDropdown
- options={filterConfig?.models.map((m) => ({ label: m, value: m }))}
- title="Models"
- type="models"
- updateSelectedValues={updateSelectedValues}
- selectedValues={selectedFilterValues.models}
- clearItem={clearFilter}
- />
- ) : null}
- {filterConfig?.providers?.length ? (
- <ComboDropdown
- options={filterConfig?.providers.map((p) => ({
- label: p,
- value: p,
- }))}
- title="Providers"
- type="providers"
- updateSelectedValues={updateSelectedValues}
- selectedValues={selectedFilterValues.providers}
- clearItem={clearFilter}
- />
- ) : null}
- {filterConfig?.maxCost ? (
- <SlideWithValue
- label="Max Cost"
- value={selectedFilterValues.maxCost || 0}
- maxValue={filterConfig.maxCost}
- onChange={updateSelectedValues}
- type="maxCost"
- />
- ) : null}
- {filterConfig?.applicationNames?.length ? (
- <ComboDropdown
- options={filterConfig?.applicationNames.map((a) => ({
- label: a,
- value: a,
- }))}
- title="Application Names"
- type="applicationNames"
- updateSelectedValues={updateSelectedValues}
- selectedValues={selectedFilterValues.applicationNames}
- clearItem={clearFilter}
- />
- ) : null}
- {filterConfig?.environments?.length ? (
- <ComboDropdown
- options={filterConfig?.environments.map((e) => ({
- label: e,
- value: e,
- }))}
- title="Environments"
- type="environments"
- updateSelectedValues={updateSelectedValues}
- selectedValues={selectedFilterValues.environments}
- clearItem={clearFilter}
- />
- ) : null}
+ {/* Predefined filter dropdowns + action buttons */}
+ <div className="flex w-full gap-4 items-start">
+ <div className="flex grow gap-3 overflow-auto flex-wrap">
+ {filterConfig?.traceTypes?.length ? (
+ <ComboDropdown
+ options={filterConfig?.traceTypes.map((p) => ({
+ label: p,
+ value: p,
+ }))}
+ title="Types"
+ type="traceTypes"
+ updateSelectedValues={updateSelectedValues}
+ selectedValues={selectedFilterValues.traceTypes}
+ clearItem={clearFilter}
+ />
+ ) : null}
+ {filterConfig?.models?.length ? (
+ <ComboDropdown
+ options={filterConfig?.models.map((m) => ({ label: m, value: m }))}
+ title="Models"
+ type="models"
+ updateSelectedValues={updateSelectedValues}
+ selectedValues={selectedFilterValues.models}
+ clearItem={clearFilter}
+ />
+ ) : null}
+ {filterConfig?.providers?.length ? (
+ <ComboDropdown
+ options={filterConfig?.providers.map((p) => ({
+ label: p,
+ value: p,
+ }))}
+ title="Providers"
+ type="providers"
+ updateSelectedValues={updateSelectedValues}
+ selectedValues={selectedFilterValues.providers}
+ clearItem={clearFilter}
+ />
+ ) : null}
+ {filterConfig?.maxCost ? (
+ <SlideWithValue
+ label="Max Cost"
+ value={selectedFilterValues.maxCost || 0}
+ maxValue={filterConfig.maxCost}
+ onChange={updateSelectedValues}
+ type="maxCost"
+ />
+ ) : null}
+ {filterConfig?.applicationNames?.length ? (
+ <ComboDropdown
+ options={filterConfig?.applicationNames.map((a) => ({
+ label: a,
+ value: a,
+ }))}
+ title="Application Names"
+ type="applicationNames"
+ updateSelectedValues={updateSelectedValues}
+ selectedValues={selectedFilterValues.applicationNames}
+ clearItem={clearFilter}
+ />
+ ) : null}
+ {filterConfig?.environments?.length ? (
+ <ComboDropdown
+ options={filterConfig?.environments.map((e) => ({
+ label: e,
+ value: e,
+ }))}
+ title="Environments"
+ type="environments"
+ updateSelectedValues={updateSelectedValues}
+ selectedValues={selectedFilterValues.environments}
+ clearItem={clearFilter}
+ />
+ ) : null}
+ </div>
+ <div className="flex shrink-0 gap-3">
+ {areFiltersApplied && (
+ <Button
+ variant="ghost"
+ size="default"
+ className="text-stone-500 hover:text-stone-600 dark:text-stone-400 dark:hover:text-stone-300 py-1.5 px-2 relative h-auto text-xs"
+ onClick={clearFilterStore}
+ >
+ Clear Filters
+ </Button>
+ )}
+ <Button
+ variant="outline"
+ size="default"
+ className="text-stone-500 hover:text-stone-600 dark:text-stone-400 dark:hover:text-stone-300 dark:bg-stone-800 dark:hover:bg-stone-900 py-1.5 px-2 relative h-auto text-xs"
+ onClick={updateFilterStore}
+ >
+ Apply Filters
+ </Button>
+ </div>
</div>
- <div className="flex shrink-0 gap-3">
- {areFiltersApplied && (
+
+ {/* Custom attribute key-value filters */}
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-3">
+ <span className="text-xs text-stone-500 dark:text-stone-400 shrink-0">
+ Custom Attributes
+ </span>
<Button
variant="ghost"
size="default"
- className="text-stone-500 hover:text-stone-600 dark:text-stone-400 dark:hover:text-stone-300 py-1.5 px-2 relative h-auto text-xs"
- onClick={clearFilterStore}
+ className="text-stone-500 hover:text-stone-600 dark:text-stone-400 dark:hover:text-stone-300 py-1 px-2 h-auto text-xs gap-1"
+ onClick={addCustomFilter}
>
- Clear Filters
+ <Plus className="w-3 h-3" />
+ Add
</Button>
+ </div>
+ {customFilters.length > 0 && (
+ <div className="flex flex-wrap gap-2 max-h-[120px] overflow-auto">
+ {customFilters.map((cf, index) => (
+ <div key={index} className="flex items-center gap-1.5">
+ <select
+ value={cf.attributeType}
+ onChange={(e) =>
+ updateCustomFilter(index, "attributeType", e.target.value)
+ }
+ className="h-7 rounded-md border border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950 text-stone-900 dark:text-stone-100 text-xs px-1.5 focus-visible:outline-none"
+ >
+ <option value="SpanAttributes">Span Attributes</option>
+ <option value="ResourceAttributes">Resource Attributes</option>
+ <option value="Field">Field</option>
+ </select>
+
+ {cf.attributeType === "Field" ? (
+ <Input
+ placeholder="e.g. SpanName"
+ value={cf.key}
+ onChange={(e) =>
+ updateCustomFilter(index, "key", e.target.value)
+ }
+ className="h-7 text-xs w-44"
+ />
+ ) : (
+ <Combobox
+ value={cf.key}
+ onChange={(val) => updateCustomFilter(index, "key", val)}
+ options={
+ cf.attributeType === "SpanAttributes"
+ ? (attributeKeys?.spanAttributeKeys ?? [])
+ : (attributeKeys?.resourceAttributeKeys ?? [])
+ }
+ placeholder="e.g. gen_ai.system"
+ />
+ )}
+
+ <Input
+ placeholder="Value"
+ value={cf.value}
+ onChange={(e) =>
+ updateCustomFilter(index, "value", e.target.value)
+ }
+ className="h-7 text-xs w-32"
+ />
+ <Button
+ variant="ghost"
+ size="default"
+ className="h-7 w-7 p-0 shrink-0 text-stone-400 hover:text-red-500"
+ onClick={() => removeCustomFilter(index)}
+ >
+ <Trash2 className="w-3.5 h-3.5" />
+ </Button>
+ </div>
+ ))}
+ </div>
)}
- <Button
- variant="outline"
- size="default"
- className="text-stone-500 hover:text-stone-600 dark:text-stone-400 dark:hover:text-stone-300 dark:bg-stone-800 dark:hover:bg-stone-900 py-1.5 px-2 relative h-auto text-xs"
- onClick={updateFilterStore}
- >
- Apply Filters
- </Button>
</div>
</div>
);
};
+// ─── URL filter sync hook ─────────────────────────────────────────────────────
+
+const VALID_TIME_RANGES = new Set(["24H", "7D", "1M", "3M", "CUSTOM"]);
+
+function useFilterUrlSync(filter: FilterType, updateFilter: (key: string, value: any, extraParams?: any) => void) {
+ const router = useRouter();
+ const pathname = usePathname();
+ // Tracks whether the initial URL read has been applied to the store
+ const initializedFromUrl = useRef(false);
+
+ // On mount: read URL params and apply to the store (client-side only)
+ useEffect(() => {
+ if (initializedFromUrl.current) return;
+ initializedFromUrl.current = true;
+
+ const params = new URLSearchParams(window.location.search);
+
+ // Time limit
+ const tr = params.get("tr");
+ if (tr && VALID_TIME_RANGES.has(tr)) {
+ if (tr === "CUSTOM") {
+ const ts = params.get("ts");
+ const te = params.get("te");
+ if (ts && te) {
+ updateFilter("timeLimit.type", "CUSTOM", {
+ start: new Date(ts),
+ end: new Date(te),
+ });
+ }
+ } else {
+ updateFilter("timeLimit.type", tr);
+ }
+ }
+
+ // Page size
+ const limitParam = params.get("limit");
+ if (limitParam) {
+ const parsed = parseInt(limitParam, 10);
+ if (!isNaN(parsed) && parsed > 0) updateFilter("limit", parsed);
+ }
+
+ // Selected config (filters)
+ const config = paramsToConfig(params);
+ if (hasActiveConfig(config)) {
+ updateFilter("selectedConfig", config);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ // When filter state changes: write all serialisable parts to the URL
+ const prevSerializedRef = useRef<string>("");
+ useEffect(() => {
+ if (!initializedFromUrl.current) return;
+
+ const params = new URLSearchParams(window.location.search);
+
+ // Time limit
+ params.set("tr", filter.timeLimit.type);
+ if (filter.timeLimit.type === "CUSTOM") {
+ if (filter.timeLimit.start)
+ params.set("ts", new Date(filter.timeLimit.start).toISOString());
+ if (filter.timeLimit.end)
+ params.set("te", new Date(filter.timeLimit.end).toISOString());
+ } else {
+ params.delete("ts");
+ params.delete("te");
+ }
+
+ // Page size
+ params.set("limit", String(filter.limit));
+
+ // Selected config
+ configToParams(filter.selectedConfig, params);
+
+ const qs = params.toString();
+ if (qs === prevSerializedRef.current) return;
+ prevSerializedRef.current = qs;
+
+ router.replace(`${pathname}${qs ? `?${qs}` : ""}`, { scroll: false });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [filter.timeLimit.type, filter.timeLimit.start, filter.timeLimit.end, filter.limit, filter.selectedConfig]);
+}
+
+// ─── TracesFilter (exported) ──────────────────────────────────────────────────
+
export default function TracesFilter({
total,
supportDynamicFilters = false,
@@ -240,6 +667,9 @@ export default function TracesFilter({
const filter = useRootStore(getFilterDetails);
const filterConfig = useRootStore(getFilterConfig);
const updateFilter = useRootStore(getUpdateFilter);
+
+ useFilterUrlSync(filter, updateFilter);
+
const onClickPageAction = (dir: -1 | 1) => {
updateFilter("offset", filter.offset + dir * filter.limit);
};
@@ -249,24 +679,19 @@ export default function TracesFilter({
};
const toggleIsVisibleFilters = () => setIsVisibileFilters((e) => !e);
- const showDynamicFilters =
- filterConfig &&
- Object.keys(filterConfig).filter((k) => {
- const key = k as keyof FilterConfig;
- if (typeof filterConfig[key] === "number") {
- return (filterConfig[key] as number) > 0;
- } else if (
- typeof filterConfig[key] === "object" &&
- (filterConfig[key] as string[]).length
- ) {
- return true;
- }
- return false;
- }).length > 0;
const areFiltersApplied =
Object.keys(filter.selectedConfig).filter((k) => {
const key = k as keyof FilterConfig;
+ if (key === "customFilters") {
+ return (
+ (
+ filter.selectedConfig.customFilters?.filter(
+ (f) => f.key && f.value
+ ) || []
+ ).length > 0
+ );
+ }
if (typeof filter.selectedConfig[key] === "number") {
return (filter.selectedConfig[key] as number) > 0;
} else if (
@@ -304,7 +729,7 @@ export default function TracesFilter({
includeOnlySorting={includeOnlySorting}
/>
)}
- {showDynamicFilters && supportDynamicFilters && (
+ {supportDynamicFilters && (
<Button
variant="outline"
size="default"
@@ -313,7 +738,7 @@ export default function TracesFilter({
>
<SlidersHorizontal className="w-3 h-3" />
{areFiltersApplied && (
- <span className="w-1 h-1 bg-primary absolute top-1 right-1 rounded-full" />
+ <span className="w-2 h-2 bg-primary absolute top-1 right-1 rounded-full animate-ping" />
)}
</Button>
)}
diff --git a/src/client/src/components/(playground)/request/columns.tsx b/src/client/src/components/(playground)/request/columns.tsx
index 63f9774a..ad1fa182 100644
--- a/src/client/src/components/(playground)/request/columns.tsx
+++ b/src/client/src/components/(playground)/request/columns.tsx
@@ -9,7 +9,7 @@ export const columns: Columns<TraceMappingKeyType, TransformedTraceRow> = {
header: () => TraceMapping.id.label,
cell: ({ row }) => (
<div
- className="rounded-md group-hover:text-stone-100 text-stone-700 dark:text-stone-300 block overflow-hidden text-ellipsis"
+ className="rounded-md text-stone-700 dark:text-stone-300 block overflow-hidden text-ellipsis"
title={row.id}
>
{row.id}
diff --git a/src/client/src/components/(playground)/request/components/attributes-tab.tsx b/src/client/src/components/(playground)/request/components/attributes-tab.tsx
new file mode 100644
index 00000000..eb4e1ba9
--- /dev/null
+++ b/src/client/src/components/(playground)/request/components/attributes-tab.tsx
@@ -0,0 +1,173 @@
+"use client";
+
+import { TraceMapping } from "@/constants/traces";
+import {
+ CODE_ITEM_DISPLAY_KEYS,
+ KNOWN_SPAN_ATTR_KEYS,
+} from "@/helpers/client/trace";
+import { TraceMappingKeyType, TransformedTraceRow } from "@/types/trace";
+import { isNil } from "lodash";
+
+type AttrGroup = { label: string; keys: TraceMappingKeyType[] };
+
+const ATTR_GROUPS: AttrGroup[] = [
+ {
+ label: "Model & Request",
+ keys: [
+ "model", "provider", "type", "endpoint", "responseModel", "outputType",
+ "temperature", "requestTopP", "requestTopK",
+ "requestFrequencyPenalty", "requestPresencePenalty",
+ "maxTokens", "randomSeed", "requestChoiceCount",
+ "requestIsStream", "requestUser", "requestToolChoice", "reasoningEffort",
+ ],
+ },
+ {
+ label: "Response",
+ keys: ["responseId", "finishReason"],
+ },
+ {
+ label: "Usage",
+ keys: [
+ "promptTokens", "completionTokens", "totalTokens", "cost",
+ "cacheReadTokens", "cacheCreationTokens", "reasoningTokens",
+ ],
+ },
+ {
+ label: "Latency",
+ keys: ["ttft", "tbt"],
+ },
+ {
+ label: "Tools",
+ keys: ["toolName", "toolCallId"],
+ },
+ {
+ label: "OpenAI",
+ keys: [
+ "openaiApiType", "openaiRequestServiceTier",
+ "openaiResponseServiceTier", "openaiSystemFingerprint",
+ ],
+ },
+ {
+ label: "Media",
+ keys: ["audioVoice", "audioFormat", "audioSpeed", "imageSize", "imageQuality", "imageStyle"],
+ },
+ {
+ label: "Embeddings",
+ keys: ["embeddingFormat", "embeddingDimension"],
+ },
+ {
+ label: "Fine-tuning",
+ keys: [
+ "trainingFile", "validationFile", "fineTuneBatchSize",
+ "learningRateMultiplier", "fineTuneNEpochs", "fineTuneModelSuffix", "finetuneJobStatus",
+ ],
+ },
+ {
+ label: "Database",
+ keys: [
+ "operation", "system", "dbSystemName", "dbOperationName",
+ "collectionName", "nResults", "documentsCount", "idsCount", "vectorCount",
+ ],
+ },
+ {
+ label: "Framework",
+ keys: ["owner", "repo"],
+ },
+];
+
+const CODE_ITEM_KEY_SET = new Set<string>(CODE_ITEM_DISPLAY_KEYS);
+
+export function GroupHeader({ label }: { label: string }) {
+ return (
+ <div className="sticky top-0 px-4 py-1.5 bg-stone-100 dark:bg-stone-800/80 border-y border-stone-200 dark:border-stone-700 first:border-t-0">
+ <span className="text-[10px] font-semibold uppercase tracking-wider text-stone-400 dark:text-stone-500">
+ {label}
+ </span>
+ </div>
+ );
+}
+
+export function AttrRow({ label, value, mono = false }: { label: string; value: string; mono?: boolean }) {
+ 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">
+ <span className="w-44 shrink-0 text-xs text-stone-500 dark:text-stone-400 pt-px leading-relaxed">
+ {label}
+ </span>
+ <span
+ className={`text-xs text-stone-800 dark:text-stone-200 break-all leading-relaxed ${
+ mono ? "font-mono" : ""
+ }`}
+ >
+ {value}
+ </span>
+ </div>
+ );
+}
+
+export default function AttributesTab({
+ normalizedItem,
+ spanAttributes,
+}: {
+ normalizedItem: TransformedTraceRow;
+ spanAttributes: Record<string, string | number>;
+}) {
+ const groups = ATTR_GROUPS.map((group) => ({
+ label: group.label,
+ entries: group.keys
+ .filter((key) => {
+ if (CODE_ITEM_KEY_SET.has(key)) return false;
+ const value = normalizedItem[key];
+ if (isNil(value) || value === "" || value === TraceMapping[key]?.defaultValue)
+ return false;
+ return true;
+ })
+ .map((key) => {
+ const mapping = TraceMapping[key];
+ const prefix = mapping?.valuePrefix ?? "";
+ const suffix = mapping?.valueSuffix ?? "";
+ return {
+ key,
+ label: mapping?.label ?? key,
+ value: `${prefix}${normalizedItem[key]}${suffix}`,
+ };
+ }),
+ })).filter((g) => g.entries.length > 0);
+
+ const customEntries = Object.entries(spanAttributes).filter(
+ ([key, value]) =>
+ !KNOWN_SPAN_ATTR_KEYS.has(key) &&
+ !isNil(value) &&
+ String(value).length > 0
+ );
+
+ const hasContent = groups.length > 0 || customEntries.length > 0;
+
+ if (!hasContent) {
+ return (
+ <div className="flex items-center justify-center h-24 text-sm text-stone-400 dark:text-stone-500">
+ No span attributes
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col">
+ {groups.map((group) => (
+ <div key={group.label}>
+ <GroupHeader label={group.label} />
+ {group.entries.map(({ key, label, value }) => (
+ <AttrRow key={key} label={label} value={String(value)} />
+ ))}
+ </div>
+ ))}
+ {customEntries.length > 0 && (
+ <div>
+ <GroupHeader label="Custom" />
+ {customEntries.map(([key, value]) => (
+ <AttrRow key={key} label={key} value={String(value)} mono />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/client/src/components/(playground)/request/components/content-data.tsx b/src/client/src/components/(playground)/request/components/content-data.tsx
index 9bc16268..b928ad29 100644
--- a/src/client/src/components/(playground)/request/components/content-data.tsx
+++ b/src/client/src/components/(playground)/request/components/content-data.tsx
@@ -9,19 +9,15 @@ export default function ContentDataItem({
dataValue?: string;
}) {
return (
- <div
- className={`grid ${
- dataValue ? "grid-cols-2" : ""
- } px-4 py-2 group cursor-pointer dark:bg-stone-700 dark:border-stone-800 dark:last:border-stone-800 odd:bg-stone-200/[0.4] even:bg-stone-200/[0.8] dark:odd:bg-stone-700/[0.4] dark:even:bg-stone-700/[0.8]`}
- >
- <div className="break-all pr-2 text-stone-500 dark:text-stone-300">
+ <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">
+ <span className="w-44 shrink-0 text-xs text-stone-500 dark:text-stone-400 pt-px leading-relaxed">
{dataKey}
- </div>
- {!(isNil(dataValue) || dataValue === "") && (
- <div className="break-all pl-2 group-hover:text-stone-950 dark:group-hover:text-stone-100">
+ </span>
+ {!(isNil(dataValue) || dataValue === "") ? (
+ <span className="text-xs text-stone-800 dark:text-stone-200 break-all leading-relaxed flex-1 min-w-0">
<JsonViewer value={dataValue} />
- </div>
- )}
+ </span>
+ ) : null}
</div>
);
}
diff --git a/src/client/src/components/(playground)/request/components/node-graph.tsx b/src/client/src/components/(playground)/request/components/node-graph.tsx
new file mode 100644
index 00000000..1c7cc9eb
--- /dev/null
+++ b/src/client/src/components/(playground)/request/components/node-graph.tsx
@@ -0,0 +1,200 @@
+"use client";
+
+import { TraceHeirarchySpan } from "@/types/trace";
+import { useRequest } from "../request-context";
+import {
+ getSpanDurationDisplay,
+ getSpanCostFormatted,
+ getSpanTooltipText,
+} from "@/helpers/client/trace";
+
+const NODE_WIDTH = 160;
+const NODE_HEIGHT = 52;
+const H_GAP = 24;
+const V_GAP = 48;
+
+interface NodeLayout {
+ span: TraceHeirarchySpan;
+ x: number;
+ y: number;
+}
+
+function getNodeStroke(durationNs: number, isSelected: boolean): string {
+ if (isSelected) return "#6366f1"; // primary
+ 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
+}
+
+function getNodeFill(durationNs: number, isSelected: boolean): string {
+ if (isSelected) return "rgba(99,102,241,0.08)";
+ const seconds = durationNs * 1e-9;
+ if (seconds > 10) return "rgba(239,68,68,0.06)";
+ if (seconds > 5) return "rgba(234,179,8,0.06)";
+ if (seconds > 1) return "rgba(59,130,246,0.06)";
+ return "rgba(34,197,94,0.06)";
+}
+
+function layoutTree(root: TraceHeirarchySpan): NodeLayout[] {
+ const nodes: NodeLayout[] = [];
+ let leafCounter = 0;
+
+ function assignPositions(
+ span: TraceHeirarchySpan,
+ 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 });
+ return { centerX: center };
+ }
+
+ assignPositions(root, 0);
+ return nodes;
+}
+
+function truncate(text: string, maxLen: number): string {
+ return text.length > maxLen ? text.slice(0, maxLen - 1) + "…" : text;
+}
+
+export default function NodeGraph({ record }: { record: TraceHeirarchySpan }) {
+ const [request, updateRequest] = useRequest();
+
+ const nodes = layoutTree(record);
+
+ // Build a map for edge drawing
+ const nodeMap = new Map<string, NodeLayout>();
+ for (const n of nodes) {
+ nodeMap.set(n.span.SpanId, n);
+ }
+
+ // Compute canvas dimensions
+ const 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));
+ const PADDING = 20;
+ const svgWidth = maxX - minX + PADDING * 2;
+ const svgHeight = maxY + PADDING * 2;
+ const offsetX = -minX + PADDING;
+ const offsetY = PADDING;
+
+ // Build edges
+ const edges: { from: NodeLayout; to: NodeLayout }[] = [];
+ function collectEdges(span: TraceHeirarchySpan) {
+ const fromLayout = nodeMap.get(span.SpanId);
+ if (!fromLayout) return;
+ if (span.children) {
+ for (const child of span.children) {
+ const toLayout = nodeMap.get(child.SpanId);
+ if (toLayout) edges.push({ from: fromLayout, to: toLayout });
+ collectEdges(child);
+ }
+ }
+ }
+ collectEdges(record);
+
+ 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}
+ />
+ );
+ })}
+
+ {/* 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}
+ />
+ <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} • ${costDisplay}`
+ : durationDisplay}
+ </text>
+ </g>
+ );
+ })}
+ </svg>
+ </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.tsx
new file mode 100644
index 00000000..9ff12e43
--- /dev/null
+++ b/src/client/src/components/(playground)/request/components/resource-attributes-tab.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import { isNil } from "lodash";
+import { AttrRow } from "./attributes-tab";
+
+export default function ResourceAttributesTab({
+ resourceAttributes,
+}: {
+ resourceAttributes: Record<string, string>;
+}) {
+ const entries = Object.entries(resourceAttributes || {}).filter(
+ ([, value]) => !isNil(value) && String(value).length > 0
+ );
+
+ if (entries.length === 0) {
+ return (
+ <div className="flex items-center justify-center h-16 text-sm text-stone-400 dark:text-stone-500">
+ No resource attributes
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col">
+ {entries.map(([key, value]) => (
+ <AttrRow key={key} label={key} value={String(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.tsx
new file mode 100644
index 00000000..c6786a3a
--- /dev/null
+++ b/src/client/src/components/(playground)/request/components/span-attributes-tab.tsx
@@ -0,0 +1,147 @@
+"use client";
+
+import { TraceMapping } from "@/constants/traces";
+import {
+ CODE_ITEM_DISPLAY_KEYS,
+ KNOWN_SPAN_ATTR_KEYS,
+} from "@/helpers/client/trace";
+import { TraceMappingKeyType, TransformedTraceRow } from "@/types/trace";
+import { isNil } from "lodash";
+import { AttrRow, GroupHeader } from "./attributes-tab";
+
+type AttrGroup = { label: string; keys: TraceMappingKeyType[] };
+
+const ATTR_GROUPS: AttrGroup[] = [
+ {
+ label: "Model & Request",
+ keys: [
+ "model", "provider", "type", "endpoint", "responseModel", "outputType",
+ "temperature", "requestTopP", "requestTopK",
+ "requestFrequencyPenalty", "requestPresencePenalty",
+ "maxTokens", "randomSeed", "requestChoiceCount",
+ "requestIsStream", "requestUser", "requestToolChoice", "reasoningEffort",
+ ],
+ },
+ {
+ label: "Response",
+ keys: ["responseId", "finishReason"],
+ },
+ {
+ label: "Usage",
+ keys: [
+ "promptTokens", "completionTokens", "totalTokens", "cost",
+ "cacheReadTokens", "cacheCreationTokens", "reasoningTokens",
+ ],
+ },
+ {
+ label: "Latency",
+ keys: ["ttft", "tbt"],
+ },
+ {
+ label: "Tools",
+ keys: ["toolName", "toolCallId"],
+ },
+ {
+ label: "OpenAI",
+ keys: [
+ "openaiApiType", "openaiRequestServiceTier",
+ "openaiResponseServiceTier", "openaiSystemFingerprint",
+ ],
+ },
+ {
+ label: "Media",
+ keys: ["audioVoice", "audioFormat", "audioSpeed", "imageSize", "imageQuality", "imageStyle"],
+ },
+ {
+ label: "Embeddings",
+ keys: ["embeddingFormat", "embeddingDimension"],
+ },
+ {
+ label: "Fine-tuning",
+ keys: [
+ "trainingFile", "validationFile", "fineTuneBatchSize",
+ "learningRateMultiplier", "fineTuneNEpochs", "fineTuneModelSuffix", "finetuneJobStatus",
+ ],
+ },
+ {
+ label: "Database",
+ keys: [
+ "operation", "system", "dbSystemName", "dbOperationName",
+ "collectionName", "nResults", "documentsCount", "idsCount", "vectorCount",
+ ],
+ },
+ {
+ label: "Framework",
+ keys: ["owner", "repo"],
+ },
+];
+
+const CODE_ITEM_KEY_SET = new Set<string>(CODE_ITEM_DISPLAY_KEYS);
+
+export default function SpanAttributesTab({
+ normalizedItem,
+ spanAttributes,
+}: {
+ normalizedItem: TransformedTraceRow;
+ spanAttributes: Record<string, string | number>;
+}) {
+ const groups = ATTR_GROUPS.map((group) => ({
+ label: group.label,
+ entries: group.keys
+ .filter((key) => {
+ if (CODE_ITEM_KEY_SET.has(key)) return false;
+ const value = normalizedItem[key];
+ if (isNil(value) || value === "" || value === TraceMapping[key]?.defaultValue)
+ return false;
+ return true;
+ })
+ .map((key) => {
+ const mapping = TraceMapping[key];
+ const prefix = mapping?.valuePrefix ?? "";
+ const suffix = mapping?.valueSuffix ?? "";
+ return {
+ key,
+ label: mapping?.label ?? key,
+ value: `${prefix}${normalizedItem[key]}${suffix}`,
+ };
+ }),
+ })).filter((g) => g.entries.length > 0);
+
+ const customEntries = Object.entries(spanAttributes || {}).filter(
+ ([key, value]) =>
+ !KNOWN_SPAN_ATTR_KEYS.has(key) &&
+ !isNil(value) &&
+ String(value).length > 0
+ );
+
+ const hasContent = groups.length > 0 || customEntries.length > 0;
+
+ if (!hasContent) {
+ return (
+ <div className="flex items-center justify-center h-16 text-sm text-stone-400 dark:text-stone-500">
+ No span attributes
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col">
+ {groups.map((group) => (
+ <div key={group.label}>
+ <GroupHeader label={group.label} />
+ {group.entries.map(({ key, label, value }) => (
+ <AttrRow key={key} label={label} value={String(value)} />
+ ))}
+ </div>
+ ))}
+ {customEntries.length > 0 && (
+ <div>
+ <GroupHeader label="Custom" />
+ {customEntries.map(([key, value]) => (
+ <AttrRow key={key} label={key} value={String(value)} mono />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/client/src/components/(playground)/request/components/tabs-content.tsx b/src/client/src/components/(playground)/request/components/tabs-content.tsx
index fa6fd9eb..a84b0e6f 100644
--- a/src/client/src/components/(playground)/request/components/tabs-content.tsx
+++ b/src/client/src/components/(playground)/request/components/tabs-content.tsx
@@ -1,6 +1,6 @@
import { objectEntries } from "@/utils/object";
import { isArray, isPlainObject } from "lodash";
-import ContentDataItem from "./content-data";
+import { AttrRow } from "./attributes-tab";
export default function TabsContent({
dataKey,
@@ -9,26 +9,36 @@ export default function TabsContent({
dataKey: string;
dataValue: Record<string, any> | string[] | Record<string, any>[];
}) {
- return isArray(dataValue)
+ const content = isArray(dataValue)
? dataValue.map((datumValue, index) => (
- <section key={`${dataKey}-${index}`}>
- {index !== 0 ? (
- <div className="py-1 px-2 dark:bg-stone-800"></div>
- ) : null}
- {isPlainObject(datumValue) ? (
- objectEntries(datumValue).map(([key, value]) => (
- <ContentDataItem
- key={key.toString()}
- dataKey={key.toString()}
- dataValue={value}
- />
- ))
- ) : (
- <ContentDataItem dataKey={datumValue} />
- )}
- </section>
- ))
+ <section key={`${dataKey}-${index}`} className="flex flex-col">
+ {index !== 0 ? (
+ <div className="h-px bg-stone-200 dark:bg-stone-700" />
+ ) : null}
+ {isPlainObject(datumValue) ? (
+ objectEntries(datumValue).map(([key, value]) => (
+ <AttrRow
+ key={key.toString()}
+ label={key as string}
+ value={value.toString()}
+ />
+ ))
+ ) : (
+ <AttrRow
+ key={datumValue.toString()}
+ label={datumValue as string}
+ value={""}
+ />
+ )}
+ </section>
+ ))
: objectEntries(dataValue).map(([key, value]) => (
- <ContentDataItem key={key} dataKey={key} dataValue={value} />
- ));
+ <AttrRow
+ key={key.toString()}
+ label={value as string}
+ value={value as string || ""}
+ />
+ ));
+
+ return <div className="flex flex-col">{content}</div>;
}
diff --git a/src/client/src/components/(playground)/request/components/timeline-view.tsx b/src/client/src/components/(playground)/request/components/timeline-view.tsx
new file mode 100644
index 00000000..cc63a020
--- /dev/null
+++ b/src/client/src/components/(playground)/request/components/timeline-view.tsx
@@ -0,0 +1,211 @@
+"use client";
+
+import { TraceHeirarchySpan } from "@/types/trace";
+import { useRequest } from "../request-context";
+import {
+ getSpanDurationDisplay,
+ getSpanCostFormatted,
+ getSpanTooltipText,
+} from "@/helpers/client/trace";
+
+interface FlatSpan {
+ span: TraceHeirarchySpan;
+ level: number;
+}
+
+function flattenTree(
+ span: TraceHeirarchySpan,
+ level: number,
+ result: FlatSpan[]
+): void {
+ result.push({ span, level });
+ if (span.children) {
+ for (const child of span.children) {
+ flattenTree(child, level + 1, result);
+ }
+ }
+}
+
+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 getBarColor(durationNs: number): string {
+ const seconds = durationNs * 1e-9;
+ if (seconds > 10) return "bg-red-500";
+ if (seconds > 5) return "bg-yellow-500";
+ if (seconds > 1) return "bg-blue-500";
+ return "bg-green-500";
+}
+
+function formatDuration(durationNs: number): string {
+ const ms = durationNs / 1e6;
+ if (ms >= 1000) return `${(ms / 1000).toFixed(2)}s`;
+ if (ms >= 1) return `${ms.toFixed(1)}ms`;
+ 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%
+
+export default function TimelineView({
+ record,
+}: {
+ record: TraceHeirarchySpan;
+}) {
+ const [request, updateRequest] = useRequest();
+
+ const flatSpans: FlatSpan[] = [];
+ flattenTree(record, 0, flatSpans);
+
+ const rootStartMs = parseTimestampMs(record.Timestamp);
+ const totalDurationMs = record.Duration / 1e6;
+
+ 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 */}
+ <div
+ className="shrink-0 text-stone-500 dark:text-stone-400 font-medium pl-1"
+ style={{ width: `${NAME_COL_PCT}%` }}
+ >
+ Span
+ </div>
+
+ {/* Time-axis column */}
+ <div
+ className="relative h-4"
+ style={{ width: `${100 - NAME_COL_PCT - DURATION_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>
+ {/* Right edge — total */}
+ <span className="absolute right-0 top-0 text-stone-400 dark:text-stone-500">
+ {formatDuration(totalDurationMs * 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}%` }}
+ >
+ s / $
+ </div>
+ </div>
+
+ {/* ── Span rows ── */}
+ <div className="flex flex-col gap-3">
+ {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 tooltipText = getSpanTooltipText(span);
+
+ let leftPct = 0;
+ let widthPct =
+ totalDurationMs > 0
+ ? (spanDurationMs / totalDurationMs) * 100
+ : 100;
+
+ if (
+ rootStartMs !== null &&
+ spanStartMs !== null &&
+ totalDurationMs > 0
+ ) {
+ leftPct =
+ ((spanStartMs - rootStartMs) / totalDurationMs) * 100;
+ }
+
+ // Clamp so nothing goes out of bounds
+ leftPct = Math.max(0, Math.min(leftPct, 99));
+ widthPct = Math.max(1, Math.min(widthPct, 100 - leftPct));
+
+ return (
+ <div
+ key={span.SpanId}
+ className={`flex items-center h-6 rounded cursor-pointer transition-colors ${
+ isSelected
+ ? "bg-primary/10 dark:bg-primary/10"
+ : "hover:bg-stone-200/60 dark:hover:bg-stone-800/60"
+ }`}
+ onClick={() => updateRequest({ spanId: span.SpanId })}
+ title={tooltipText}
+ >
+ {/* ── Name column ── */}
+ <div
+ className="shrink-0 h-full flex items-center overflow-hidden pr-2"
+ style={{
+ width: `${NAME_COL_PCT}%`,
+ paddingLeft: `${level * 10 + 4}px`,
+ }}
+ >
+ <span
+ className={`truncate text-[11px] leading-none ${
+ isSelected
+ ? "text-primary font-medium"
+ : "text-stone-700 dark:text-stone-300"
+ }`}
+ >
+ {span.SpanName}
+ </span>
+ </div>
+
+ {/* ── Bar column ── */}
+ <div
+ className="relative h-full flex items-center"
+ style={{
+ width: `${100 - NAME_COL_PCT - DURATION_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 */}
+ <div
+ className={`absolute h-[10px] rounded-sm ${getBarColor(span.Duration)} ${
+ isSelected
+ ? "ring-1 ring-primary ring-offset-0"
+ : "opacity-80"
+ }`}
+ style={{
+ left: `${leftPct}%`,
+ width: `${widthPct}%`,
+ }}
+ />
+ </div>
+
+ {/* ── Duration column ── */}
+ <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}%` }}
+ >
+ {costDisplay
+ ? `${durationDisplay} / ${costDisplay}`
+ : durationDisplay}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/src/client/src/components/(playground)/request/components/tree-node.tsx b/src/client/src/components/(playground)/request/components/tree-node.tsx
new file mode 100644
index 00000000..b65853b0
--- /dev/null
+++ b/src/client/src/components/(playground)/request/components/tree-node.tsx
@@ -0,0 +1,166 @@
+"use client";
+
+import { useState } from "react";
+import { useRequest } from "../request-context";
+import { Zap, Clock, Activity, ChevronRight } from "lucide-react";
+import { getSpanDurationDisplay, getSpanTooltipText } from "@/helpers/client/trace";
+import { TraceHeirarchySpan } from "@/types/trace";
+
+const INDENT = 28;
+const NODE_HEIGHT = 40;
+const NODE_CENTER = NODE_HEIGHT / 2;
+
+interface TreeNodeProps {
+ span: TraceHeirarchySpan;
+ level: number;
+ isLast?: boolean;
+ parentPath?: boolean[];
+}
+
+function CurvedConnector({ isLast }: { isLast: boolean }) {
+ return (
+ <svg
+ className="absolute pointer-events-none text-stone-400 dark:text-stone-600"
+ style={{
+ left: -INDENT,
+ top: 0,
+ width: INDENT + 4,
+ overflow: "visible",
+ }}
+ height={isLast ? NODE_CENTER + 2 : "100%"}
+ preserveAspectRatio="none"
+ >
+ {/* Vertical line down (for non-last siblings) */}
+ {!isLast && (
+ <line
+ x1="6"
+ y1="0"
+ x2="6"
+ y2="100%"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ />
+ )}
+ {/* Curved elbow: vertical down → curve right → horizontal to node */}
+ <path
+ d={`M 6,0 L 6,${NODE_CENTER - 8} Q 6,${NODE_CENTER} 14,${NODE_CENTER} L ${INDENT},${NODE_CENTER}`}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ />
+ </svg>
+ );
+}
+
+export default function TreeNode({ span, level, isLast = false, parentPath = [] }: TreeNodeProps) {
+ const [request, updateRequest] = useRequest();
+ const [isExpanded, setIsExpanded] = useState(true);
+ const hasChildren = span.children && span.children.length > 0;
+ const isSelected = request?.spanId === span.SpanId;
+
+ const onClick = () => {
+ if (request?.spanId !== span.SpanId) {
+ updateRequest({
+ spanId: span.SpanId,
+ });
+ }
+ };
+
+ const toggleExpanded = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ setIsExpanded(!isExpanded);
+ };
+
+ const durationDisplay = getSpanDurationDisplay(span);
+ const tooltipText = getSpanTooltipText(span);
+
+ const getSpanTypeIcon = (spanName: string) => {
+ if (spanName.includes("browser_action")) return <Activity className="h-3.5 w-3.5" />;
+ if (spanName.includes("model_request")) return <Zap className="h-3.5 w-3.5" />;
+ if (spanName.includes("execute_task")) return <Clock className="h-3.5 w-3.5" />;
+ return <Zap className="h-3.5 w-3.5" />;
+ };
+
+ const getTimingColor = () => {
+ const time = parseFloat(durationDisplay);
+ if (time > 10) return "text-red-600 dark:text-red-400";
+ if (time > 5) return "text-yellow-600 dark:text-yellow-400";
+ if (time > 1) return "text-blue-600 dark:text-blue-400";
+ return "text-green-600 dark:text-green-400";
+ };
+
+ return (
+ <div className="relative">
+ {level > 0 && <CurvedConnector isLast={isLast} />}
+
+ {/* Node row */}
+ <div
+ className="flex items-center gap-2 cursor-pointer"
+ style={{ minHeight: NODE_HEIGHT }}
+ onClick={onClick}
+ title={tooltipText}
+ >
+ {hasChildren ? (
+ <button
+ onClick={toggleExpanded}
+ className={`flex h-6 w-6 shrink-0 items-center justify-center rounded-full transition-all duration-200 ${
+ isSelected
+ ? "bg-primary/20 text-primary"
+ : "bg-stone-200/80 dark:bg-stone-700/80 text-stone-500 dark:text-stone-400 hover:bg-stone-300/80 dark:hover:bg-stone-600/80"
+ }`}
+ aria-label={isExpanded ? "Collapse" : "Expand"}
+ >
+ <ChevronRight
+ className={`h-3.5 w-3.5 transition-transform duration-200 ${isExpanded ? "rotate-90" : ""}`}
+ />
+ </button>
+ ) : (
+ <div className="flex h-6 w-6 shrink-0 items-center justify-center">
+ <div className="h-2 w-2 rounded-full bg-stone-400 dark:bg-stone-500" />
+ </div>
+ )}
+
+ <div
+ className={`flex flex-1 min-w-0 items-center gap-3 rounded-md px-2 py-1.5 transition-colors ${
+ isSelected
+ ? "bg-primary/[0.08] dark:bg-primary/[0.08] text-primary dark:text-primary"
+ : "hover:bg-stone-200/50 dark:hover:bg-stone-800 text-stone-700 dark:text-stone-300"
+ }`}
+ >
+ <div
+ className={`flex h-6 w-6 shrink-0 items-center justify-center rounded ${
+ isSelected
+ ? "bg-primary/20 text-primary"
+ : "bg-stone-100 dark:bg-stone-800 text-stone-600 dark:text-stone-400"
+ }`}
+ >
+ {getSpanTypeIcon(span.SpanName)}
+ </div>
+ <span className="flex-1 overflow-hidden text-ellipsis whitespace-nowrap text-sm min-w-0">
+ {span.SpanName}
+ </span>
+ <span className={`shrink-0 text-sm ${getTimingColor()}`}>
+ {durationDisplay}
+ </span>
+ </div>
+ </div>
+
+ {/* Children */}
+ {hasChildren && isExpanded && (
+ <div className="relative" style={{ marginLeft: INDENT }}>
+ {span?.children!.map((child, index) => (
+ <TreeNode
+ key={child.SpanId}
+ span={child}
+ level={level + 1}
+ isLast={index === span.children!.length - 1}
+ parentPath={[...parentPath, !isLast]}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/client/src/components/(playground)/request/heirarchy-display.tsx b/src/client/src/components/(playground)/request/heirarchy-display.tsx
index 777398ad..4118ebb0 100644
--- a/src/client/src/components/(playground)/request/heirarchy-display.tsx
+++ b/src/client/src/components/(playground)/request/heirarchy-display.tsx
@@ -1,174 +1,38 @@
import { useRequest } from "./request-context";
-import React, { useEffect, useState } from "react";
-import { FolderTree, Zap, Clock, Activity, Minus, Plus } from "lucide-react";
-import {
- findSpanInHierarchyLodash,
- getNormalizedTraceAttribute,
-} from "@/helpers/client/trace";
+import React, { useEffect, useMemo, useState } from "react";
+import { FolderTree, DollarSign, ListTree, GanttChart, Network } from "lucide-react";
+import { findSpanInHierarchyLodash } from "@/helpers/client/trace";
import { TraceHeirarchySpan } from "@/types/trace";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
import { toast } from "sonner";
-import { TraceMapping } from "@/constants/traces";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
-import { ScrollArea } from "@/components/ui/scroll-area";
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";
-interface TreeNodeProps {
- span: TraceHeirarchySpan;
- level: number;
- isLast?: boolean;
- parentPath?: boolean[];
-}
-
-export function TreeNode({ span, level, isLast = false, parentPath = [] }: TreeNodeProps) {
- const [request, updateRequest] = useRequest();
- const [isExpanded, setIsExpanded] = useState(true);
- const hasChildren = span.children && span.children.length > 0;
- const isSelected = request?.spanId === span.SpanId;
-
- const onClick = () => {
- if (request?.spanId !== span.SpanId) {
- updateRequest({
- spanId: span.SpanId,
- });
- }
- };
-
- const toggleExpanded = (e: React.MouseEvent) => {
- e.stopPropagation();
- setIsExpanded(!isExpanded);
- };
-
- const duration = parseFloat(
- getNormalizedTraceAttribute("requestDuration", span.Duration) as string
- ).toFixed(2);
-
- const getSpanTypeIcon = (spanName: string) => {
- if (spanName.includes('browser_action')) return <Activity className="h-3.5 w-3.5" />;
- if (spanName.includes('model_request')) return <Zap className="h-3.5 w-3.5" />;
- if (spanName.includes('execute_task')) return <Clock className="h-3.5 w-3.5" />;
- return <Zap className="h-3.5 w-3.5" />;
- };
-
- const getTimingColor = () => {
- const time = parseFloat(duration);
- if (time > 10) return "text-red-600 dark:text-red-400";
- if (time > 5) return "text-yellow-600 dark:text-yellow-400";
- if (time > 1) return "text-blue-600 dark:text-blue-400";
- return "text-green-600 dark:text-green-400";
- };
-
- const CONNECTION_LINES_CLASSES = "absolute left-3 bg-stone-400 dark:bg-stone-700"
-
- return (
- <div className="relative">
- {/* Connection lines */}
- {/* {level > 0 && renderConnectionLines()} */}
- <div className="absolute left-0 top-0 bottom-0 flex">
- {parentPath.map((showLine, index) => (
- <div key={index} className="w-6 relative">
- {showLine && (
- <div className={`${CONNECTION_LINES_CLASSES} top-0 bottom-0 w-px`} />
- )}
- </div>
- ))}
-
- {level > 0 && (
- <div className="w-6 relative">
- {/* Vertical line */}
- <div className={`${CONNECTION_LINES_CLASSES} top-0 h-6 w-px`} />
- {/* Horizontal line */}
- <div className={`${CONNECTION_LINES_CLASSES} top-6 w-3 h-px`} />
- {/* Corner connector for non-last items */}
- {!isLast && (
- <div className={`${CONNECTION_LINES_CLASSES} top-6 bottom-0 w-px`} />
- )}
- </div>
- )}
- </div>
-
- {/* Node content */}
- <div
- className={`flex items-center gap-3 py-2 pr-4 rounded-md transition-colors cursor-pointer group ${level === 0 ? 'ml-0' : `ml-${(level + 1) * 6}`
- }
- ${isSelected
- ? "bg-primary/[0.05] dark:bg-primary/[0.05] text-primary dark:text-primary"
- : "hover:bg-stone-200/[0.5] dark:hover:bg-stone-800 text-stone-700 dark:text-stone-300"
- }
- `}
- style={{ marginLeft: level > 0 ? `${(level + 1) * 24}px` : '0' }}
- onClick={onClick}
- title={span.SpanName}
- >
- {/* Expand/collapse button for parents */}
- {hasChildren && (
- <button
- onClick={toggleExpanded}
- className={`flex items-center justify-center w-5 h-5 rounded border
- ${isSelected
- ? "text-primary/[0.5] dark:text-primary/[0.5] border-primary/[0.5] dark:border-primary/[0.5]"
- : "text-stone-400 dark:text-stone-700 border-stone-400 dark:border-stone-700 "
- }
- `}
- aria-label={isExpanded ? 'Collapse' : 'Expand'}
- >
- {isExpanded ? (
- <Minus className="w-3 h-3" />
- ) : (
- <Plus className="w-3 h-3" />
- )}
- </button>
- )}
-
- {/* Icon */}
- <div className={`flex items-center justify-center w-6 h-6 rounded
- ${isSelected
- ? "bg-primary/[0.2] dark:bg-primary/[0.2] text-primary dark:text-primary"
- : "bg-stone-100 dark:bg-stone-800 text-stone-600 dark:text-stone-400"
- }`}>
- {getSpanTypeIcon(span.SpanName)}
- </div>
-
- {/* Title */}
- <span className={`text-sm flex-1 overflow-hidden text-ellipsis whitespace-nowrap`}>
- {span.SpanName}
- </span>
+type ViewMode = "tree" | "timeline" | "graph";
- {/* Timing */}
- <span className={`text-sm ${getTimingColor()}`}>
- {duration}{TraceMapping.requestDuration.valueSuffix}
- </span>
- </div>
-
- {/* Children */}
- {hasChildren && isExpanded && (
- <div className="relative">
- {span?.children!.map((child, index) => {
- const isLastChild = index === span.children!.length - 1;
-
- return (
- <TreeNode
- key={child.SpanId}
- span={child}
- level={level + 1}
- isLast={isLastChild}
- parentPath={[...parentPath, !isLast]}
- />
- );
- })}
- </div>
- )}
- </div>
- );
+function sumCostRecursive(span: TraceHeirarchySpan): number {
+ const cost = span.Cost != null && span.Cost > 0 ? span.Cost : 0;
+ const childrenCost = (span.children || []).reduce((acc, c) => acc + sumCostRecursive(c), 0);
+ return cost + childrenCost;
}
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" },
+];
+
export default function HeirarchyDisplay() {
const [request] = useRequest();
const { data, fireRequest, isLoading, error } = useFetchWrapper();
const [accordionValue, setAccordionValue] = useState("");
+ const [viewMode, setViewMode] = useState<ViewMode>("tree");
useEffect(() => {
if (!isLoading) {
@@ -199,6 +63,8 @@ export default function HeirarchyDisplay() {
}, [request, typedData, isLoading, error]);
const { record } = typedData;
+ const aggregateCost = useMemo(() => (record ? sumCostRecursive(record) : 0), [record]);
+
if (isLoading || typedData.err || !record || !record.SpanId) {
return null;
}
@@ -209,12 +75,12 @@ 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 border-t-0 dark:border-stone-800 border-r-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">
<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-700 transition-colors"
+ 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"
onClick={() => setAccordionValue(accordionValue === "debug" ? "" : "debug")}
>
<div className="flex flex-col items-center gap-3">
@@ -233,22 +99,60 @@ export default function HeirarchyDisplay() {
</div>
</AccordionTrigger>
<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">
- <ScrollArea className="h-full w-full">
- <div className="p-3">
- <div className="mb-3 pb-2 border-b border-stone-200 dark:border-stone-700">
- <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-1">
- Click spans to view details
- </p>
+ <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 }) => (
+ <button
+ key={mode}
+ onClick={() => setViewMode(mode)}
+ className={`flex items-center gap-1.5 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"
+ : "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>
- <TreeNode span={record} level={0} />
</div>
- </ScrollArea>
+
+ {/* Aggregate cost footer */}
+ {aggregateCost > 0 && (
+ <div className="shrink-0 flex items-center gap-2 px-3 py-2 border-t border-stone-200 dark:border-stone-800 bg-stone-50 dark:bg-stone-900/50">
+ <DollarSign className="h-3.5 w-3.5 text-stone-500 dark:text-stone-400" />
+ <span className="text-xs font-medium text-stone-600 dark:text-stone-400">
+ Total cost:
+ </span>
+ <span className="text-xs font-semibold text-stone-800 dark:text-stone-200">
+ ${aggregateCost.toFixed(6)}
+ </span>
+ </div>
+ )}
+ </div>
</AccordionContent>
</AccordionItem>
</Accordion>
</ResizeablePanel>
);
-}
\ No newline at end of file
+}
diff --git a/src/client/src/components/(playground)/request/request-context.tsx b/src/client/src/components/(playground)/request/request-context.tsx
index c91d7e81..0eb01ec4 100644
--- a/src/client/src/components/(playground)/request/request-context.tsx
+++ b/src/client/src/components/(playground)/request/request-context.tsx
@@ -1,6 +1,6 @@
import { TransformedTraceRow } from "@/types/trace";
import { noop } from "@/utils/noop";
-import { ReactNode, createContext, useContext, useState } from "react";
+import { ReactNode, createContext, useCallback, useContext, useRef, useState } from "react";
type RequestProps = TransformedTraceRow | null;
@@ -11,15 +11,70 @@ const RequestContext = createContext<[RequestProps, RequestUpdateProps]>([
noop,
]);
+type RequestListContextType = {
+ items: TransformedTraceRow[];
+ currentIndex: number;
+ setItems: (items: TransformedTraceRow[]) => void;
+ navigatePrev: () => void;
+ navigateNext: () => void;
+};
+
+const RequestListContext = createContext<RequestListContextType>({
+ items: [],
+ currentIndex: -1,
+ setItems: noop,
+ navigatePrev: noop,
+ navigateNext: noop,
+});
+
export function RequestProvider({ children }: { children: ReactNode }) {
const [request, setRequest] = useState<RequestProps>(null);
- const updateRequest = (value: RequestProps) => {
+ const [items, setItemsState] = useState<TransformedTraceRow[]>([]);
+
+ // Keep refs so navigatePrev/navigateNext always see the latest values
+ const requestRef = useRef(request);
+ requestRef.current = request;
+ const itemsRef = useRef(items);
+ itemsRef.current = items;
+
+ const updateRequest = useCallback((value: RequestProps) => {
setRequest(value);
- };
+ }, []);
+
+ const setItems = useCallback((newItems: TransformedTraceRow[]) => {
+ setItemsState(newItems);
+ }, []);
+
+ const navigatePrev = useCallback(() => {
+ const idx = itemsRef.current.findIndex(
+ (item) => item.spanId === requestRef.current?.spanId
+ );
+ if (idx > 0) {
+ setRequest(itemsRef.current[idx - 1]);
+ }
+ }, []);
+
+ const navigateNext = useCallback(() => {
+ const idx = itemsRef.current.findIndex(
+ (item) => item.spanId === requestRef.current?.spanId
+ );
+ if (idx >= 0 && idx < itemsRef.current.length - 1) {
+ setRequest(itemsRef.current[idx + 1]);
+ }
+ }, []);
+
+ const currentIndex =
+ request && items.length > 0
+ ? items.findIndex((item) => item.spanId === request.spanId)
+ : -1;
return (
<RequestContext.Provider value={[request, updateRequest]}>
- {children}
+ <RequestListContext.Provider
+ value={{ items, currentIndex, setItems, navigatePrev, navigateNext }}
+ >
+ {children}
+ </RequestListContext.Provider>
</RequestContext.Provider>
);
}
@@ -31,3 +86,7 @@ export function useRequest() {
}
return context;
}
+
+export function useRequestNavigation() {
+ return useContext(RequestListContext);
+}
diff --git a/src/client/src/components/(playground)/request/request-details.tsx b/src/client/src/components/(playground)/request/request-details.tsx
index 8d488b3a..5ecd544e 100644
--- a/src/client/src/components/(playground)/request/request-details.tsx
+++ b/src/client/src/components/(playground)/request/request-details.tsx
@@ -1,4 +1,4 @@
-import { useRequest } from "@/components/(playground)/request/request-context";
+import { useRequest, useRequestNavigation } from "@/components/(playground)/request/request-context";
import Image from "next/image";
import { isArray, isNil, isPlainObject } from "lodash";
import {
@@ -8,7 +8,7 @@ import {
normalizeTrace,
} from "@/helpers/client/trace";
import { ReverseTraceMapping, TraceMapping } from "@/constants/traces";
-import { ExternalLink, X } from "lucide-react";
+import { ExternalLink, X, DollarSign, Zap, Clock, Cpu, ChevronLeft, ChevronRight } from "lucide-react";
import {
Sheet,
SheetContent,
@@ -17,7 +17,7 @@ import {
} from "@/components/ui/sheet";
import { objectEntries, objectKeys } from "@/utils/object";
import { ValueOf } from "@/types/util";
-import { useCallback, useEffect, useState } from "react";
+import { ReactNode, useCallback, useEffect, useState } from "react";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
import { toast } from "sonner";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
@@ -27,15 +27,110 @@ import InfoPill from "./components/info-pill";
import CodeItem from "./components/code-item";
import TabsContentData from "./components/tabs-content";
import ExtraTabs from "./components/extra-tabs";
+import ResourceAttributesTab from "./components/resource-attributes-tab";
+import SpanAttributesTab from "./components/span-attributes-tab";
+
+// Root-level TraceRow scalar fields that are already shown elsewhere in the UI and
+// should NOT be duplicated as info pills.
+const REDUNDANT_ROOT_FIELDS = new Set([
+ "TraceId", // shown in header as short trace ID chip
+ "SpanName", // shown in header as the panel title
+ "StatusCode", // shown in header as status badge
+ "Duration", // shown in metric card
+ "TraceState", // almost always empty
+]);
+
+function StatusBadge({ statusCode }: { statusCode?: string }) {
+ const isError =
+ statusCode === "STATUS_CODE_ERROR" || statusCode === "Error";
+ return (
+ <span
+ className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold ${
+ isError
+ ? "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"
+ : "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400"
+ }`}
+ >
+ <span
+ className={`w-1.5 h-1.5 rounded-full ${
+ isError ? "bg-red-500" : "bg-green-500"
+ }`}
+ />
+ {isError ? "Error" : "OK"}
+ </span>
+ );
+}
+
+function MetricCard({
+ icon,
+ label,
+ value,
+}: {
+ icon: ReactNode;
+ label: string;
+ value: string | number | undefined;
+}) {
+ return (
+ <div className="flex flex-col gap-1 px-3 py-2 bg-stone-100 dark:bg-stone-800 rounded-lg min-w-[100px] shrink-0">
+ <div className="flex items-center gap-1.5 text-stone-500 dark:text-stone-400">
+ {icon}
+ <span className="text-xs font-medium">{label}</span>
+ </div>
+ <span className="text-sm font-semibold text-stone-800 dark:text-stone-200 truncate">
+ {value ?? "—"}
+ </span>
+ </div>
+ );
+}
+
+function LoadingSkeleton() {
+ return (
+ <div className="flex flex-col gap-4 p-4 animate-pulse">
+ {/* Header skeleton */}
+ <div className="flex gap-2 items-center">
+ <div className="h-5 w-5 rounded-full bg-stone-300 dark:bg-stone-700" />
+ <div className="h-4 w-32 rounded bg-stone-300 dark:bg-stone-700" />
+ <div className="h-4 w-48 rounded bg-stone-300 dark:bg-stone-700" />
+ </div>
+ {/* Metrics strip skeleton */}
+ <div className="flex gap-2">
+ {[1, 2, 3, 4].map((i) => (
+ <div
+ key={i}
+ className="h-14 w-28 rounded-lg bg-stone-300 dark:bg-stone-700"
+ />
+ ))}
+ </div>
+ {/* Pills skeleton */}
+ <div className="flex flex-wrap gap-2">
+ {[1, 2, 3, 4, 5, 6].map((i) => (
+ <div
+ key={i}
+ className="h-7 w-24 rounded bg-stone-300 dark:bg-stone-700"
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
export default function RequestDetails() {
const [isOpen, setIsOpen] = useState(false);
const [request, updateRequest] = useRequest();
+ const { currentIndex, items, navigatePrev, navigateNext } = useRequestNavigation();
const { data, fireRequest, isLoading } = useFetchWrapper();
+ // Cache the last successfully loaded record so navigation never flickers to a skeleton.
+ // While a new fetch is in-flight we keep showing the stale data at reduced opacity.
+ const [displayData, setDisplayData] = useState<{
+ item: TransformedTraceRow;
+ rawRecord: TraceRow;
+ } | null>(null);
+
const onClose = () => {
updateRequest(null);
setIsOpen(false);
+ setDisplayData(null);
};
const fetchData = useCallback(async () => {
@@ -57,6 +152,17 @@ export default function RequestDetails() {
}
}, [request?.spanId, fetchData]);
+ // Commit successful fetches into the display cache
+ useEffect(() => {
+ const record = (data as { record?: TraceRow })?.record;
+ if (record?.TraceId && !isLoading) {
+ setDisplayData({
+ item: normalizeTrace(record),
+ rawRecord: record,
+ });
+ }
+ }, [data, isLoading]);
+
useEffect(() => {
if (isOpen) {
// Pushing the change to the end of the call stack
@@ -70,20 +176,20 @@ export default function RequestDetails() {
}
}, [isOpen]);
- const isFetchingData =
- !(data as { record?: TraceRow })?.record?.TraceId || isLoading;
+ // Show the skeleton only on the very first open (nothing cached yet).
+ // On subsequent navigations keep the old content visible while the new fetch runs.
+ const isFirstLoad = isLoading && !displayData;
+ const isTransitioning = isLoading && !!displayData;
- const normalizedItem: TransformedTraceRow | null = isFetchingData
- ? null
- : normalizeTrace((data as { record: TraceRow }).record);
+ const normalizedItem: TransformedTraceRow | null = displayData?.item ?? null;
+ const rawRecord: TraceRow | null = displayData?.rawRecord ?? null;
const extraTabs = normalizedItem
? getExtraTabsContentTypes(normalizedItem)
: [];
const tabKeys: string[] = [...extraTabs];
- const reducedData = isFetchingData
- ? { arrays: [], objects: [], values: [] }
- : objectEntries((data as { record: TraceRow }).record || {}).reduce(
+ const reducedData = rawRecord
+ ? objectEntries(rawRecord || {}).reduce(
(
acc: {
arrays: [keyof TraceRow, ValueOf<TraceRow>][];
@@ -109,55 +215,143 @@ export default function RequestDetails() {
return acc;
},
{ arrays: [], objects: [], values: [] }
- );
+ )
+ : { arrays: [], objects: [], values: [] };
+
+ // Derived display values for metrics strip
+ const parsedCost = parseFloat(normalizedItem?.cost as string);
+ const costValue =
+ isFinite(parsedCost) && parsedCost > 0
+ ? `$${parsedCost.toFixed(6)}`
+ : undefined;
+ const parsedTokens = Number(normalizedItem?.totalTokens);
+ const tokensValue =
+ isFinite(parsedTokens) && parsedTokens > 0
+ ? String(parsedTokens)
+ : undefined;
+ const parsedDuration = parseFloat(normalizedItem?.requestDuration as string);
+ const durationValue = isFinite(parsedDuration)
+ ? `${parsedDuration.toFixed(2)}s`
+ : undefined;
+ const modelValue =
+ normalizedItem?.model && normalizedItem.model !== "-"
+ ? String(normalizedItem.model)
+ : undefined;
+
+ // Trace ID (short display)
+ const traceId = rawRecord?.TraceId;
+ const shortTraceId = traceId ? `${traceId.slice(0, 8)}…` : undefined;
return (
<Sheet open={isOpen}>
<SheetContent
- className="max-w-none sm:max-w-none w-2/5 p-0 gap-0 flex flex-col border-l border-stone-200 dark:border-stone-800 top-[57px] h-auto focus-visible:outline-none"
+ className="max-w-none sm:max-w-none w-[55%] p-0 gap-0 flex flex-col border-l border-stone-200 dark:border-stone-800 top-2 bottom-2 h-auto focus-visible:outline-none"
displayOverlay={false}
displayClose={false}
>
- <SheetHeader className="flex-row bg-stone-950 px-3 py-2 items-center space-y-0">
- <SheetTitle className="text-stone-200 text-md font-bold leading-7 capitalize grow pr-3">
- {isFetchingData || !normalizedItem
- ? "..."
+ <SheetHeader className="flex-row bg-stone-100 dark:bg-stone-900 px-3 py-1.5 items-center space-y-0 gap-2 flex-wrap">
+ <SheetTitle className="text-stone-900 dark:text-stone-200 text-md font-bold leading-7 capitalize grow pr-1 truncate">
+ {!normalizedItem
+ ? "Loading…"
: normalizedItem.spanName}
</SheetTitle>
+ {normalizedItem && (
+ <>
+ <StatusBadge statusCode={normalizedItem.statusCode as string} />
+ {shortTraceId && (
+ <span className="text-xs text-stone-600 dark:text-stone-400 font-mono bg-stone-200 dark:bg-stone-800 px-1.5 py-0.5 rounded">
+ {shortTraceId}
+ </span>
+ )}
+ </>
+ )}
+ {currentIndex >= 0 && (
+ <div className="flex items-center gap-0.5 shrink-0">
+ <button
+ onClick={navigatePrev}
+ disabled={currentIndex <= 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}
+ </span>
+ <button
+ onClick={navigateNext}
+ disabled={currentIndex >= items.length - 1}
+ 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"
+ >
+ <ChevronRight className="h-4 w-4" />
+ </button>
+ </div>
+ )}
<X
- className="text-stone-200 shrink-0 mt-0 space-y-0 cursor-pointer"
+ className="text-stone-800 dark:text-stone-200 shrink-0 mt-0 space-y-0 cursor-pointer"
onClick={onClose}
/>
</SheetHeader>
- {isFetchingData || !normalizedItem ? (
- <div className="flex flex-col items-center justify-center h-full text-3xl">
- ...
- </div>
- ) : (
- <div className="flex flex-col gap-0 overflow-y-scroll bg-stone-100 dark:bg-stone-900 grow pb-4">
- <div className="flex items-start flex-wrap gap-1 p-4 bg-stone-200 dark:bg-stone-100/[0.15]">
- {reducedData.values.map(([key, value]) => {
- const reverseKey = ReverseTraceMapping[key];
- const normalizedValue = `${
- reverseKey ? TraceMapping[reverseKey].valuePrefix || "" : ""
- }${
- reverseKey
- ? getNormalizedTraceAttribute(reverseKey, value)
- : value
- }${
- reverseKey ? TraceMapping[reverseKey].valueSuffix || "" : ""
- }`;
- return (
- !isNil(value) &&
- value.toString().length > 0 && (
- <InfoPill
- key={key}
- title={reverseKey ? TraceMapping[reverseKey].label : key}
- value={normalizedValue}
- />
- )
- );
- })}
+
+ {isFirstLoad ? (
+ <LoadingSkeleton />
+ ) : !normalizedItem ? null : (
+ <div
+ className={`flex flex-col gap-0 overflow-y-scroll bg-stone-100 dark:bg-stone-900 grow pb-4 transition-opacity duration-200 ${
+ isTransitioning ? "opacity-40" : "opacity-100"
+ }`}
+ >
+ {/* Key metrics strip */}
+ <div className="shrink-0 flex items-center gap-2 px-4 py-3 overflow-x-auto bg-white dark:bg-stone-950 border-b border-stone-200 dark:border-stone-800">
+ <MetricCard
+ icon={<DollarSign className="h-3.5 w-3.5" />}
+ label="Cost"
+ value={costValue}
+ />
+ <MetricCard
+ icon={<Zap className="h-3.5 w-3.5" />}
+ label="Total Tokens"
+ value={tokensValue}
+ />
+ <MetricCard
+ icon={<Clock className="h-3.5 w-3.5" />}
+ label="Duration"
+ value={durationValue}
+ />
+ <MetricCard
+ icon={<Cpu className="h-3.5 w-3.5" />}
+ label="Model"
+ value={modelValue}
+ />
+ </div>
+
+ {/* Info pills — root-level span metadata (context, correlation IDs, scope) */}
+ <div className="shrink-0 flex items-start flex-wrap gap-1 p-4 bg-stone-200 dark:bg-stone-100/[0.15]">
+ {reducedData.values
+ .filter(([key]) => !REDUNDANT_ROOT_FIELDS.has(key as string))
+ .map(([key, value]) => {
+ const reverseKey = ReverseTraceMapping[key];
+ const normalizedValue = `${
+ reverseKey ? TraceMapping[reverseKey].valuePrefix || "" : ""
+ }${
+ reverseKey
+ ? getNormalizedTraceAttribute(reverseKey, value)
+ : value
+ }${
+ reverseKey ? TraceMapping[reverseKey].valueSuffix || "" : ""
+ }`;
+ return (
+ !isNil(value) &&
+ value.toString().length > 0 && (
+ <InfoPill
+ key={key}
+ title={reverseKey ? TraceMapping[reverseKey].label : key}
+ value={normalizedValue}
+ />
+ )
+ );
+ })}
{CODE_ITEM_DISPLAY_KEYS.map(
(key) =>
normalizedItem[key] && (
@@ -191,10 +385,9 @@ export default function RequestDetails() {
</span>
</a>
)}
- {/* Image */}
</div>
- <Tabs className="" defaultValue={tabKeys[0].toString()}>
+ <Tabs className="" defaultValue={tabKeys[0]?.toString()}>
<TabsList className="h-auto flex overflow-auto justify-start w-full rounded-none pt-2 bg-transparent dark:bg-transparent px-0">
{tabKeys.map((key) => {
return (
@@ -222,10 +415,18 @@ export default function RequestDetails() {
key={key.toString()}
className="mt-0"
>
- <TabsContentData
- dataKey={key}
- dataValue={value as Record<string, any>}
- />
+ {
+ key === "ResourceAttributes" ? (
+ <ResourceAttributesTab resourceAttributes={value as Record<string, any>} />
+ ) : key === "SpanAttributes" ? (
+ <SpanAttributesTab normalizedItem={normalizedItem} spanAttributes={value as Record<string, string | number>} />
+ ) : (
+ <TabsContentData
+ dataKey={key}
+ dataValue={value as string[] | Record<string, any>[]}
+ />
+ )
+ }
</TabsContent>
);
})}
diff --git a/src/client/src/components/ui/accordion.tsx b/src/client/src/components/ui/accordion.tsx
index 16281845..fffa239e 100644
--- a/src/client/src/components/ui/accordion.tsx
+++ b/src/client/src/components/ui/accordion.tsx
@@ -34,7 +34,7 @@ const AccordionTrigger = React.forwardRef<
{...props}
>
{children}
- <ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
+ <ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200 text-stone-600 dark:text-stone-400" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
))
diff --git a/src/client/src/components/ui/input.tsx b/src/client/src/components/ui/input.tsx
index f2f0456d..459382c1 100644
--- a/src/client/src/components/ui/input.tsx
+++ b/src/client/src/components/ui/input.tsx
@@ -11,7 +11,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
<input
type={type}
className={cn(
- "flex h-10 w-full rounded-md border border-stone-200 bg-white px-3 py-2 text-sm file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-stone-500 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 dark:border-stone-800 dark:bg-stone-950 dark:placeholder:text-stone-400",
+ "flex h-10 w-full rounded-md border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-stone-500 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-100 dark:placeholder:text-stone-400",
className
)}
ref={ref}
diff --git a/src/client/src/constants/traces.ts b/src/client/src/constants/traces.ts
index 9010343f..f7fdb9bd 100644
--- a/src/client/src/constants/traces.ts
+++ b/src/client/src/constants/traces.ts
@@ -3,27 +3,38 @@ import {
BookKey,
Boxes,
Braces,
+ Brain,
CircleDollarSign,
CircleGauge,
ClipboardType,
+ Code2,
Combine,
Container,
Crop,
+ Database,
DoorClosed,
Factory,
FileAudio2,
FileCog,
FileStack,
Fingerprint,
+ Hammer,
+ Hash,
ImageIcon,
+ Layers,
+ MessageSquare,
MessageSquareWarning,
PyramidIcon,
+ Radio,
ScanSearch,
ShieldCheck,
+ Sliders,
SquareCode,
SquareRadical,
TicketCheck,
TicketPlus,
+ Timer,
+ User,
} from "lucide-react";
import { objectKeys } from "@/utils/object";
import { isArray } from "lodash";
@@ -153,8 +164,9 @@ export const TraceMapping: Record<TraceMappingKeyType, TraceMappingValueType> =
temperature: {
label: "Temperature",
type: "float",
- path: "temperature",
+ path: "request.temperature",
prefix: SpanAttributesGenAIPrefix,
+ icon: Sliders,
},
// Tokens & Cost
@@ -299,7 +311,7 @@ export const TraceMapping: Record<TraceMappingKeyType, TraceMappingValueType> =
embeddingFormat: {
label: "Embedding Format",
type: "string",
- path: "request.embedding_format",
+ path: "request.encoding_formats",
prefix: SpanAttributesGenAIPrefix,
},
embeddingDimension: {
@@ -443,6 +455,237 @@ export const TraceMapping: Record<TraceMappingKeyType, TraceMappingValueType> =
prefix: SpanAttributesGenAIPrefix,
icon: SquareCode,
},
+
+ // ── Request sampling / generation params ────────────────────────
+ requestTopP: {
+ label: "Top P",
+ type: "float",
+ path: "request.top_p",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Sliders,
+ },
+ requestTopK: {
+ label: "Top K",
+ type: "float",
+ path: "request.top_k",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Sliders,
+ },
+ requestFrequencyPenalty: {
+ label: "Frequency Penalty",
+ type: "float",
+ path: "request.frequency_penalty",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Sliders,
+ },
+ requestPresencePenalty: {
+ label: "Presence Penalty",
+ type: "float",
+ path: "request.presence_penalty",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Sliders,
+ },
+ requestIsStream: {
+ label: "Streaming",
+ type: "string",
+ path: "request.is_stream",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Radio,
+ },
+ requestUser: {
+ label: "User",
+ type: "string",
+ path: "request.user",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: User,
+ },
+ requestChoiceCount: {
+ label: "Choice Count",
+ type: "integer",
+ path: "request.choice.count",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Hash,
+ },
+ requestStopSequences: {
+ label: "Stop Sequences",
+ type: "string",
+ path: "request.stop_sequences",
+ prefix: SpanAttributesGenAIPrefix,
+ },
+ requestToolChoice: {
+ label: "Tool Choice",
+ type: "string",
+ path: "request.tool_choice",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Hammer,
+ },
+
+ // ── Response attributes ──────────────────────────────────────────
+ responseId: {
+ label: "Response ID",
+ type: "string",
+ path: "response.id",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Hash,
+ },
+ responseModel: {
+ label: "Response Model",
+ type: "string",
+ path: "response.model",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Boxes,
+ },
+ outputType: {
+ label: "Output Type",
+ type: "string",
+ path: "output.type",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Code2,
+ },
+
+ // ── Tool calling ─────────────────────────────────────────────────
+ toolName: {
+ label: "Tool Name",
+ type: "string",
+ path: "tool.name",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Hammer,
+ },
+ toolCallId: {
+ label: "Tool Call ID",
+ type: "string",
+ path: "tool.call.id",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Hash,
+ },
+ toolArgs: {
+ label: "Tool Arguments",
+ type: "string",
+ path: "tool.args",
+ prefix: SpanAttributesGenAIPrefix,
+ },
+
+ // ── Token details ────────────────────────────────────────────────
+ cacheReadTokens: {
+ label: "Cache Read Tokens",
+ type: "integer",
+ path: "usage.cache_read.input_tokens",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Database,
+ defaultValue: "-",
+ },
+ cacheCreationTokens: {
+ label: "Cache Creation Tokens",
+ type: "integer",
+ path: "usage.cache_creation.input_tokens",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Database,
+ defaultValue: "-",
+ },
+ reasoningTokens: {
+ label: "Reasoning Tokens",
+ type: "integer",
+ path: "usage.completion_tokens_details.reasoning_tokens",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Brain,
+ defaultValue: "-",
+ },
+
+ // ── Streaming latency ────────────────────────────────────────────
+ ttft: {
+ label: "Time to First Token",
+ type: "float",
+ path: "server.time_to_first_token",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Timer,
+ valueSuffix: "s",
+ },
+ tbt: {
+ label: "Time Per Output Token",
+ type: "float",
+ path: "server.time_per_output_token",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Timer,
+ valueSuffix: "s",
+ },
+
+ // ── Content ──────────────────────────────────────────────────────
+ systemInstructions: {
+ label: "System Instructions",
+ type: "string",
+ path: "system_instructions",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: MessageSquare,
+ },
+ contentReasoning: {
+ label: "Reasoning Content",
+ type: "string",
+ path: "content.reasoning",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Brain,
+ },
+
+ // ── Reasoning / effort ───────────────────────────────────────────
+ reasoningEffort: {
+ label: "Reasoning Effort",
+ type: "string",
+ path: "request.reasoning_effort",
+ prefix: SpanAttributesGenAIPrefix,
+ icon: Brain,
+ },
+
+ // ── OpenAI-specific ──────────────────────────────────────────────
+ openaiApiType: {
+ label: "API Type",
+ type: "string",
+ path: "api.type",
+ prefix: "openai",
+ icon: Code2,
+ },
+ openaiRequestServiceTier: {
+ label: "Service Tier (Req)",
+ type: "string",
+ path: "request.service_tier",
+ prefix: "openai",
+ icon: Layers,
+ },
+ openaiResponseServiceTier: {
+ label: "Service Tier (Res)",
+ type: "string",
+ path: "response.service_tier",
+ prefix: "openai",
+ icon: Layers,
+ },
+ openaiSystemFingerprint: {
+ label: "System Fingerprint",
+ type: "string",
+ path: "response.system_fingerprint",
+ prefix: "openai",
+ icon: Fingerprint,
+ },
+
+ // ── DB (new OTel paths) ──────────────────────────────────────────
+ dbSystemName: {
+ label: "DB System",
+ type: "string",
+ path: "system.name",
+ prefix: SpanAttributesDBPrefix,
+ icon: Database,
+ },
+ dbOperationName: {
+ label: "DB Operation",
+ type: "string",
+ path: "operation.name",
+ prefix: SpanAttributesDBPrefix,
+ icon: SquareRadical,
+ },
+ dbQueryText: {
+ label: "Query",
+ type: "string",
+ path: "query.text",
+ prefix: SpanAttributesDBPrefix,
+ icon: SquareCode,
+ },
};
function getReverseTraceMapping(): Record<string, TraceMappingKeyType> {
diff --git a/src/client/src/helpers/client/trace.ts b/src/client/src/helpers/client/trace.ts
index e308f086..a66daf8d 100644
--- a/src/client/src/helpers/client/trace.ts
+++ b/src/client/src/helpers/client/trace.ts
@@ -120,8 +120,101 @@ export const CODE_ITEM_DISPLAY_KEYS: TraceMappingKeyType[] = [
"retrievalSource",
/* Exception */
"statusMessage",
+ /* Long-text span attrs */
+ "systemInstructions",
+ "contentReasoning",
+ "toolArgs",
+ "dbQueryText",
];
+/**
+ * Span attribute keys to surface as individual InfoPills in the detail panel.
+ * These are non-root TraceMapping entries (i.e. sourced from SpanAttributes).
+ * Ordered so the most important attributes appear first.
+ */
+export const SPAN_ATTR_INFO_PILL_KEYS: TraceMappingKeyType[] = [
+ // Core LLM identifiers
+ "model", "provider", "type", "endpoint", "responseModel", "outputType",
+ // Request parameters
+ "temperature", "requestTopP", "requestTopK",
+ "requestFrequencyPenalty", "requestPresencePenalty",
+ "maxTokens", "randomSeed", "requestChoiceCount",
+ "requestIsStream", "requestUser", "requestToolChoice",
+ // Response
+ "responseId", "finishReason",
+ // Token usage
+ "promptTokens", "completionTokens", "totalTokens", "cost",
+ "cacheReadTokens", "cacheCreationTokens", "reasoningTokens",
+ // Streaming latency
+ "ttft", "tbt",
+ // Tool calls
+ "toolName", "toolCallId",
+ // Reasoning
+ "reasoningEffort",
+ // OpenAI-specific
+ "openaiApiType", "openaiRequestServiceTier", "openaiResponseServiceTier",
+ "openaiSystemFingerprint",
+ // Audio
+ "audioVoice", "audioFormat", "audioSpeed",
+ // Image
+ "imageSize", "imageQuality", "imageStyle",
+ // Embedding
+ "embeddingFormat", "embeddingDimension",
+ // Fine-tuning
+ "trainingFile", "validationFile", "fineTuneBatchSize",
+ "learningRateMultiplier", "fineTuneNEpochs", "fineTuneModelSuffix", "finetuneJobStatus",
+ // Vector DB
+ "operation", "system", "dbSystemName", "dbOperationName",
+ "collectionName", "nResults", "documentsCount", "idsCount", "vectorCount",
+ // Framework
+ "owner", "repo",
+];
+
+/**
+ * Set of all SpanAttribute dot-path keys that are already covered by TraceMapping.
+ * Any key in SpanAttributes that is NOT in this set is a custom user-defined attribute.
+ */
+export const KNOWN_SPAN_ATTR_KEYS = new Set<string>(
+ objectKeys(TraceMapping)
+ .filter((key) => !TraceMapping[key].isRoot)
+ .map((key) => {
+ const path = getTraceMappingKeyFullPath(key);
+ return Array.isArray(path) ? path.join(".") : (path as string);
+ })
+);
+
+/**
+ * Get formatted duration string for a hierarchy span (e.g. "1.20s").
+ */
+export function getSpanDurationDisplay(span: TraceHeirarchySpan): string {
+ const durationStr = parseFloat(
+ getNormalizedTraceAttribute("requestDuration", span.Duration) as string
+ ).toFixed(2);
+ return `${durationStr}${TraceMapping.requestDuration.valueSuffix}`;
+}
+
+/**
+ * Get formatted cost string for a hierarchy span, or null if no cost.
+ */
+export function getSpanCostFormatted(
+ span: TraceHeirarchySpan,
+ precision = 6
+): string | null {
+ if (span.Cost == null || span.Cost <= 0) return null;
+ return `$${Number(span.Cost).toFixed(precision)}`;
+}
+
+/**
+ * Get tooltip text for a hierarchy span (name, duration, cost).
+ */
+export function getSpanTooltipText(span: TraceHeirarchySpan): string {
+ const durationDisplay = getSpanDurationDisplay(span);
+ const costStr = getSpanCostFormatted(span, 6);
+ return costStr
+ ? `${span.SpanName}\nDuration: ${durationDisplay}\nCost: ${costStr}`
+ : `${span.SpanName}\nDuration: ${durationDisplay}`;
+}
+
export function findSpanInHierarchyLodash(
hierarchy: TraceHeirarchySpan,
targetSpanId: string
diff --git a/src/client/src/helpers/server/platform.ts b/src/client/src/helpers/server/platform.ts
index a7cbd309..f129a4df 100644
--- a/src/client/src/helpers/server/platform.ts
+++ b/src/client/src/helpers/server/platform.ts
@@ -242,6 +242,27 @@ export const getFilterWhereCondition = (
.join(", ")})`
);
}
+
+ if (filter.selectedConfig.customFilters?.length) {
+ filter.selectedConfig.customFilters.forEach(({ attributeType, key, value }) => {
+ if (key && value) {
+ const safeValue = value.replace(/'/g, "''");
+ if (attributeType === "SpanAttributes") {
+ const safeKey = key.replace(/'/g, "''");
+ whereArray.push(`SpanAttributes['${safeKey}'] = '${safeValue}'`);
+ } else if (attributeType === "ResourceAttributes") {
+ const safeKey = key.replace(/'/g, "''");
+ whereArray.push(`ResourceAttributes['${safeKey}'] = '${safeValue}'`);
+ } else if (attributeType === "Field") {
+ // Direct column — key must be an identifier, strip anything non-alphanumeric/underscore
+ const safeKey = key.replace(/[^A-Za-z0-9_.]/g, "");
+ if (safeKey) {
+ whereArray.push(`${safeKey} = '${safeValue}'`);
+ }
+ }
+ }
+ });
+ }
}
if (filter.notOrEmpty && filter.notOrEmpty?.length > 0) {
diff --git a/src/client/src/lib/platform/request/index.ts b/src/client/src/lib/platform/request/index.ts
index 1c93a6dc..ecf194f2 100644
--- a/src/client/src/lib/platform/request/index.ts
+++ b/src/client/src/lib/platform/request/index.ts
@@ -213,12 +213,15 @@ export async function getHeirarchyViaSpanId(spanId: string) {
${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
@@ -227,6 +230,9 @@ export async function getHeirarchyViaSpanId(spanId: string) {
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
@@ -272,4 +278,33 @@ export async function getHeirarchyViaSpanId(spanId: string) {
export async function getRequestExist() {
const query = `SELECT COUNT(*) AS total_requests FROM ${OTEL_TRACES_TABLE_NAME}`;
return dataCollector({ query });
+}
+
+export async function getAttributeKeys(params: MetricParams) {
+ const spanKeysQuery = `
+ SELECT DISTINCT arrayJoin(mapKeys(SpanAttributes)) AS key
+ FROM ${OTEL_TRACES_TABLE_NAME}
+ WHERE ${getFilterWhereCondition(params)}
+ ORDER BY key
+ LIMIT 500
+ `;
+
+ const resourceKeysQuery = `
+ SELECT DISTINCT arrayJoin(mapKeys(ResourceAttributes)) AS key
+ FROM ${OTEL_TRACES_TABLE_NAME}
+ WHERE ${getFilterWhereCondition(params)}
+ ORDER BY key
+ LIMIT 500
+ `;
+
+ const [spanResult, resourceResult] = await Promise.all([
+ dataCollector({ query: spanKeysQuery }),
+ dataCollector({ query: resourceKeysQuery }),
+ ]);
+
+ return {
+ err: spanResult.err || resourceResult.err,
+ spanAttributeKeys: (spanResult.data as { key: string }[] | undefined)?.map((r) => r.key) ?? [],
+ resourceAttributeKeys: (resourceResult.data as { key: string }[] | undefined)?.map((r) => r.key) ?? [],
+ };
}
\ No newline at end of file
diff --git a/src/client/src/selectors/filter.ts b/src/client/src/selectors/filter.ts
index 7453e384..0a645ca8 100644
--- a/src/client/src/selectors/filter.ts
+++ b/src/client/src/selectors/filter.ts
@@ -9,6 +9,10 @@ export const getFilterConfig = (state: RootStore) => state.filter.config;
export const getUpdateConfig = (state: RootStore) => state.filter.updateConfig;
+export const getAttributeKeys = (state: RootStore) => state.filter.attributeKeys;
+
+export const getUpdateAttributeKeys = (state: RootStore) => state.filter.updateAttributeKeys;
+
export const useFilters = () => {
return useRootStore((state: RootStore) => state.filter);
};
diff --git a/src/client/src/store/filter.ts b/src/client/src/store/filter.ts
index 489d9e5f..bbd1bf25 100644
--- a/src/client/src/store/filter.ts
+++ b/src/client/src/store/filter.ts
@@ -2,6 +2,7 @@ import { merge, set } from "lodash";
import { addDays, addMonths, addWeeks } from "date-fns";
import { lens } from "@dhmk/zustand-lens";
import {
+ AttributeKeys,
FilterConfig,
FilterSorting,
FilterStore,
@@ -126,7 +127,7 @@ export const filterStoreSlice: FilterStore = lens((setStore, getStore) => ({
details: {
...merge(getStore().details, object),
selectedConfig:
- resetConfig || extraParams?.clearFilter
+ extraParams?.clearFilter
? {}
: object.selectedConfig
? object.selectedConfig
@@ -138,4 +139,7 @@ export const filterStoreSlice: FilterStore = lens((setStore, getStore) => ({
updateConfig: (config: FilterConfig) => {
setStore({ config });
},
+ updateAttributeKeys: (attributeKeys: AttributeKeys) => {
+ setStore({ attributeKeys });
+ },
}));
diff --git a/src/client/src/types/platform.ts b/src/client/src/types/platform.ts
index dd2a46f2..4999f8bf 100644
--- a/src/client/src/types/platform.ts
+++ b/src/client/src/types/platform.ts
@@ -15,6 +15,7 @@ export type FilterWhereConditionType = {
traceTypes: string[];
applicationNames: string[];
environments: string[];
+ customFilters: { attributeType: string; key: string; value: string }[];
}>;
notOrEmpty?: { key: string }[];
notEmpty?: { key: string }[];
diff --git a/src/client/src/types/store/filter.ts b/src/client/src/types/store/filter.ts
index 864a0a77..50c60b7d 100644
--- a/src/client/src/types/store/filter.ts
+++ b/src/client/src/types/store/filter.ts
@@ -19,6 +19,14 @@ export interface FilterType {
refreshRate: REFRESH_RATES;
}
+export type CustomFilterAttributeType = "SpanAttributes" | "ResourceAttributes" | "Field";
+
+export type CustomFilter = {
+ attributeType: CustomFilterAttributeType;
+ key: string;
+ value: string;
+};
+
export interface FilterConfig {
providers: string[];
maxCost: number;
@@ -27,11 +35,19 @@ export interface FilterConfig {
traceTypes: string[];
applicationNames: string[];
environments: string[];
+ customFilters?: CustomFilter[];
}
+export type AttributeKeys = {
+ spanAttributeKeys: string[];
+ resourceAttributeKeys: string[];
+};
+
export type FilterStore = {
details: FilterType;
config?: FilterConfig;
+ attributeKeys?: AttributeKeys;
updateFilter: (key: string, value: any, extraParams?: any) => void;
updateConfig: (config: FilterConfig) => void;
+ updateAttributeKeys: (keys: AttributeKeys) => void;
};
diff --git a/src/client/src/types/trace.ts b/src/client/src/types/trace.ts
index 032ec9c7..97942d97 100644
--- a/src/client/src/types/trace.ts
+++ b/src/client/src/types/trace.ts
@@ -59,7 +59,45 @@ export type TraceMappingKeyType =
| "filter"
| "owner"
| "repo"
- | "retrievalSource";
+ | "retrievalSource"
+ // Request sampling params
+ | "requestTopP"
+ | "requestTopK"
+ | "requestFrequencyPenalty"
+ | "requestPresencePenalty"
+ | "requestIsStream"
+ | "requestUser"
+ | "requestChoiceCount"
+ | "requestStopSequences"
+ | "requestToolChoice"
+ // Response attributes
+ | "responseId"
+ | "responseModel"
+ | "outputType"
+ // Tool calling
+ | "toolName"
+ | "toolCallId"
+ | "toolArgs"
+ // Token details
+ | "cacheReadTokens"
+ | "cacheCreationTokens"
+ | "reasoningTokens"
+ // Streaming latency
+ | "ttft"
+ | "tbt"
+ // Content
+ | "systemInstructions"
+ | "contentReasoning"
+ // OpenAI-specific
+ | "reasoningEffort"
+ | "openaiApiType"
+ | "openaiRequestServiceTier"
+ | "openaiResponseServiceTier"
+ | "openaiSystemFingerprint"
+ // DB (new OTel paths)
+ | "dbSystemName"
+ | "dbOperationName"
+ | "dbQueryText";
export type TraceMappingValueType = {
label: string;
@@ -110,5 +148,8 @@ export interface TraceHeirarchySpan {
SpanId: string;
SpanName: string;
Duration: number;
+ Timestamp?: string;
+ StatusCode?: string;
+ Cost?: number;
children?: TraceHeirarchySpan[];
}