Skip to content

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

feat: add grouped trace views and vertical span execution graph (#1160)

Aman Agarwal8d7454d51b2a
diff --git a/docs/latest/openlit/observability/tracing.mdx b/docs/latest/openlit/observability/tracing.mdx
index f38f0960..b2b7ba16 100644
--- a/docs/latest/openlit/observability/tracing.mdx
+++ b/docs/latest/openlit/observability/tracing.mdx
@@ -19,6 +19,28 @@ The OpenLIT platform provides comprehensive trace visualization capabilities. Yo
2. **Dashboard Widgets**: Create custom trace widgets in your dashboards to monitor specific trace metrics, latency trends, and performance insights alongside other observability data.
+## Group traces
+
+Use **Group By** on the Traces page to roll up large trace lists into meaningful groups before drilling into individual spans. Grouping works with the selected time range and any active filters, so you can narrow the dataset first and then compare trace segments.
+
+You can group traces by:
+
+- **Model**: Compare requests by `gen_ai.request.model`.
+- **Provider**: Compare requests by `gen_ai.system`.
+- **Span Name**: Group repeated operations or framework steps.
+- **Application**: Compare services using the `service.name` resource attribute.
+- **Custom attribute**: Group by any span attribute, resource attribute, or top-level trace field available in your trace data.
+
+Grouped rows show the number of spans in each group, total cost, token usage, and average duration. Click a group row to drill into the matching traces. The breadcrumb above the table shows the current grouping path and lets you return to all groups or remove grouping.
+
+<Note>
+ Grouping is best for finding high-volume models, expensive providers, slow span types, or application-level hotspots before opening an individual trace.
+</Note>
+
+## Filter and group together
+
+Grouping can be combined with the existing trace filters. For example, you can filter to a single environment, apply a maximum cost threshold, and then group by model to find which models dominate that filtered slice. Custom attribute filters and custom group-by attributes can be used together when you need to inspect application-specific metadata.
+
---
<CardGroup cols={3}>
@@ -40,4 +62,4 @@ The OpenLIT platform provides comprehensive trace visualization capabilities. Yo
href="/latest/operator/overview"
>
Automatically inject instrumentation into existing workloads without modifying pod specs, container images, or application code.
- </Card>
\ No newline at end of file
+ </Card>
diff --git a/src/client/package-lock.json b/src/client/package-lock.json
index 926e922d..bb1ee539 100644
--- a/src/client/package-lock.json
+++ b/src/client/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "openlit",
- "version": "1.18.1",
+ "version": "1.18.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openlit",
- "version": "1.18.1",
+ "version": "1.18.2",
"dependencies": {
"@ai-sdk/anthropic": "^3.0.6",
"@ai-sdk/cohere": "^3.0.3",
diff --git a/src/client/package.json b/src/client/package.json
index 55c72b43..903c3ffb 100644
--- a/src/client/package.json
+++ b/src/client/package.json
@@ -1,6 +1,6 @@
{
"name": "openlit",
- "version": "1.18.1",
+ "version": "1.18.2",
"private": true,
"scripts": {
"dev": "next dev",
diff --git a/src/client/src/__tests__/lib/platform/graph-transform.test.ts b/src/client/src/__tests__/lib/platform/graph-transform.test.ts
new file mode 100644
index 00000000..2ccbae56
--- /dev/null
+++ b/src/client/src/__tests__/lib/platform/graph-transform.test.ts
@@ -0,0 +1,111 @@
+import {
+ PARALLEL_X_GAP,
+ transformTracesToGraph,
+ getParallelPairs,
+} from "@/lib/platform/graph-transform";
+
+const span = (
+ SpanId: string,
+ Timestamp: string,
+ Duration: number,
+ children = []
+) => ({
+ SpanId,
+ SpanName: SpanId,
+ Timestamp,
+ Duration,
+ children,
+});
+
+describe("graph transform", () => {
+ it("builds a sequential execution chain for non-overlapping children", () => {
+ const root = span("root", "2026-01-01T00:00:00.000Z", 200_000_000, [
+ span("a", "2026-01-01T00:00:00.000Z", 100_000_000),
+ span("b", "2026-01-01T00:00:00.100Z", 50_000_000),
+ span("c", "2026-01-01T00:00:00.120Z", 20_000_000),
+ ]);
+
+ const graph = transformTracesToGraph(root);
+ const edgeKeys = graph.edges.map((edge) => `${edge.kind}:${edge.from}->${edge.to}`);
+
+ expect(edgeKeys).toEqual(expect.arrayContaining([
+ "SEQUENTIAL:root->a",
+ "SEQUENTIAL:a->b",
+ "PARALLEL:b->c",
+ ]));
+ expect(edgeKeys).not.toContain("DELEGATED:root->a");
+ expect(edgeKeys).not.toContain("DELEGATED:root->b");
+ expect(getParallelPairs(root)).toEqual(new Set(["b|c"]));
+
+ expect(graph.nodes.get("root")!.y).toBeLessThan(graph.nodes.get("a")!.y);
+ expect(graph.nodes.get("a")!.y).toBeLessThan(graph.nodes.get("b")!.y);
+ expect(graph.nodes.get("b")!.y).toBe(graph.nodes.get("c")!.y);
+ });
+
+ it("links parent to first child then child one to child two for nested tool spans", () => {
+ const root = span("tool", "2026-04-28 09:20:28.191000000", "12280349416" as any, [
+ span("blocked", "2026-04-28 09:20:28.192000000", "2186599875" as any),
+ span("execution", "2026-04-28 09:20:30.405000000", "10066277083" as any),
+ ]);
+
+ const graph = transformTracesToGraph(root);
+ const edgeKeys = graph.edges.map((edge) => `${edge.kind}:${edge.from}->${edge.to}`);
+
+ expect(edgeKeys).toEqual([
+ "SEQUENTIAL:tool->blocked",
+ "SEQUENTIAL:blocked->execution",
+ ]);
+ });
+
+ it("treats late tail overlap as sequential handoff, not parallel", () => {
+ const root = span("interaction", "2026-04-28 09:20:09.276000000", "355460816917" as any, [
+ span("llm", "2026-04-28 09:20:17.804000000", "12724790542" as any),
+ span("tool", "2026-04-28 09:20:28.191000000", "12280349416" as any),
+ ]);
+
+ const graph = transformTracesToGraph(root);
+ const edgeKeys = graph.edges.map((edge) => `${edge.kind}:${edge.from}->${edge.to}`);
+
+ expect(edgeKeys).toEqual([
+ "SEQUENTIAL:interaction->llm",
+ "SEQUENTIAL:llm->tool",
+ ]);
+ });
+
+ it("lays out parallel siblings at the same depth side-by-side", () => {
+ const root = span("root", "2026-01-01T00:00:00.000Z", 100_000_000, [
+ span("first", "2026-01-01T00:00:00.000Z", 50_000_000),
+ span("second", "2026-01-01T00:00:00.000Z", 50_000_000),
+ ]);
+
+ const graph = transformTracesToGraph(root);
+ const rootNode = graph.nodes.get("root")!;
+ const firstNode = graph.nodes.get("first")!;
+ const secondNode = graph.nodes.get("second")!;
+
+ expect(firstNode.y).toBeCloseTo(secondNode.y);
+ expect(secondNode.x - firstNode.x).toBeCloseTo(PARALLEL_X_GAP);
+ expect((firstNode.x + secondNode.x) / 2).toBeCloseTo(rootNode.x + 220);
+ });
+
+ it("lays out execution vertically with child spans indented", () => {
+ const root = span("root", "2026-01-01T00:00:00.000Z", 300_000_000, [
+ span("left", "2026-01-01T00:00:00.000Z", 50_000_000, [
+ span("left-child", "2026-01-01T00:00:00.010Z", 10_000_000),
+ ]),
+ span("right", "2026-01-01T00:00:00.080Z", 20_000_000),
+ ]);
+
+ const graph = transformTracesToGraph(root);
+ const rootNode = graph.nodes.get("root")!;
+ const leftNode = graph.nodes.get("left")!;
+ const leftChildNode = graph.nodes.get("left-child")!;
+ const rightNode = graph.nodes.get("right")!;
+
+ expect(leftNode.x).toBeGreaterThan(rootNode.x);
+ expect(leftChildNode.x).toBeGreaterThan(leftNode.x);
+ expect(leftNode.y).toBeGreaterThan(rootNode.y);
+ expect(leftChildNode.y).toBeGreaterThan(leftNode.y);
+ expect(rightNode.y).toBeGreaterThan(leftChildNode.y);
+ });
+});
diff --git a/src/client/src/__tests__/lib/platform/request/request.test.ts b/src/client/src/__tests__/lib/platform/request/request.test.ts
index 4615e0bf..4c3896a8 100644
--- a/src/client/src/__tests__/lib/platform/request/request.test.ts
+++ b/src/client/src/__tests__/lib/platform/request/request.test.ts
@@ -14,6 +14,7 @@ import {
getHeirarchyViaSpanId,
getRequestExist,
getAttributeKeys,
+ getGroupedRequests,
} from '@/lib/platform/request/index';
import { dataCollector } from '@/lib/platform/common';
@@ -241,3 +242,23 @@ describe('getAttributeKeys', () => {
expect(call2[0].query).toContain('ResourceAttributes');
});
});
+
+describe('getGroupedRequests', () => {
+ it('returns an error and skips querying for an invalid Field groupBy', async () => {
+ const result = await getGroupedRequests(baseParams as any, 'Field:!!!');
+
+ expect(result.err).toBe('Invalid groupBy value');
+ expect(result.data).toEqual([]);
+ expect(dataCollector).not.toHaveBeenCalled();
+ });
+
+ it('builds a grouped query for an allowed Field groupBy', async () => {
+ (dataCollector as jest.Mock).mockResolvedValue({ data: [{ group_value: 'ok' }], err: null });
+
+ await getGroupedRequests(baseParams as any, 'Field:SpanName');
+
+ expect(dataCollector).toHaveBeenCalledTimes(1);
+ const { query } = (dataCollector as jest.Mock).mock.calls[0][0];
+ expect(query).toContain('SpanName AS group_value');
+ });
+});
diff --git a/src/client/src/app/(playground)/exceptions/page.tsx b/src/client/src/app/(playground)/exceptions/page.tsx
index ba62e27e..dad510bf 100644
--- a/src/client/src/app/(playground)/exceptions/page.tsx
+++ b/src/client/src/app/(playground)/exceptions/page.tsx
@@ -7,7 +7,7 @@ import {
} from "@/components/(playground)/request/request-context";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
import { toast } from "sonner";
-import { getFilterDetails } from "@/selectors/filter";
+import { getFilterDetails, getUpdateFilter } from "@/selectors/filter";
import { useRootStore } from "@/store";
import { getPingStatus } from "@/selectors/database-config";
import RequestDetails from "@/components/(playground)/request/request-details";
@@ -17,66 +17,102 @@ import { columns } from "@/components/(playground)/exceptions/columns";
import { getVisibilityColumnsOfPage } from "@/selectors/page";
import TracesFilter from "@/components/(playground)/filter/traces-filter";
import ExceptionsGettingStarted from "@/components/(playground)/getting-started/tracing";
+import GroupedTable, { buildGroupValueFilter } from "@/components/(playground)/request/grouped-table";
+import GroupBreadcrumb from "@/components/(playground)/request/group-breadcrumb";
import { usePostHog } from "posthog-js/react";
import { CLIENT_EVENTS } from "@/constants/events";
function ExceptionPage() {
const filter = useRootStore(getFilterDetails);
+ const updateFilter = useRootStore(getUpdateFilter);
const [, updateRequest] = useRequest();
- const { setItems } = useRequestNavigation();
+ const { setItems, setTotal, setOffset, setOnPageChange } = useRequestNavigation();
const onClick = (item: any) => {
!isLoading && updateRequest(item);
};
+
const pingStatus = useRootStore(getPingStatus);
+ const visibilityColumns = useRootStore((state) =>
+ getVisibilityColumnsOfPage(state, "exception")
+ );
const { data, fireRequest, isFetched, isLoading } = useFetchWrapper();
const { data: existData, fireRequest: fireExistRequest, isFetched: isFetchedExist, isLoading: isLoadingExist } = useFetchWrapper();
+
useEffect(() => {
fireExistRequest({
requestType: "POST",
url: "/api/metrics/request/exist",
});
- // eslint-disable-next-line react-hooks/exhaustive-deps
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
- const visibilityColumns = useRootStore((state) =>
- getVisibilityColumnsOfPage(state, "exception")
- );
+ // When groupBy + groupValue are both set, inject the group filter into the flat list fetch
+ const effectiveFilter = useMemo(() => {
+ if (filter.groupBy && filter.groupValue) {
+ return {
+ ...filter,
+ selectedConfig: buildGroupValueFilter(filter.groupBy, filter.groupValue, filter.selectedConfig),
+ };
+ }
+ return filter;
+ }, [filter]);
+
+ // Show flat list when: no groupBy, OR groupBy + groupValue (drilled in)
+ const showFlatList = !filter.groupBy || !!filter.groupValue;
const fetchData = useCallback(async () => {
fireRequest({
- body: JSON.stringify(filter),
+ body: JSON.stringify(effectiveFilter),
requestType: "POST",
url: "/api/metrics/exception",
failureCb: (err?: string) => {
toast.error(err || `Cannot connect to server!`, {
- id: "request-page",
+ id: "exception-page",
});
},
});
- }, [filter, fireRequest]);
+ }, [effectiveFilter, fireRequest]);
useEffect(() => {
if (
- filter.timeLimit.start &&
- filter.timeLimit.end &&
- pingStatus === "success"
+ effectiveFilter.filterReady &&
+ effectiveFilter.timeLimit.start &&
+ effectiveFilter.timeLimit.end &&
+ pingStatus === "success" &&
+ showFlatList
)
fetchData();
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [filter, pingStatus]);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [effectiveFilter, pingStatus, showFlatList]);
const normalizedData = useMemo(
() => ((data as any)?.records || []).map(normalizeTrace),
[data]
);
+ const totalItems = (data as any)?.total || 0;
+
useEffect(() => {
setItems(normalizedData);
}, [normalizedData, setItems]);
+ useEffect(() => {
+ setTotal(totalItems);
+ }, [totalItems, setTotal]);
+
+ useEffect(() => {
+ setOffset(filter.offset);
+ }, [filter.offset, setOffset]);
+
+ useEffect(() => {
+ setOnPageChange((dir: -1 | 1) => {
+ updateFilter("offset", filter.offset + dir * filter.limit);
+ });
+ return () => setOnPageChange(null);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [filter.offset, filter.limit, updateFilter, setOnPageChange]);
- // Show getting started when there's no trace data AND initial fetch is complete
if (existData === false && !isLoadingExist && isFetchedExist) {
return (
<div className="flex flex-col w-full h-full overflow-auto">
@@ -88,20 +124,37 @@ function ExceptionPage() {
return (
<>
<TracesFilter
- total={(data as any)?.total}
+ total={showFlatList ? totalItems : undefined}
includeOnlySorting={["Timestamp"]}
- pageName={"exception"}
+ pageName="exception"
columns={columns}
supportDynamicFilters
/>
- <DataTable
- columns={columns}
- data={normalizedData}
- isFetched={isFetched || pingStatus !== "pending"}
- isLoading={isLoading || pingStatus === "pending"}
- visibilityColumns={visibilityColumns}
- onClick={onClick}
- />
+
+ {filter.groupBy && (
+ <GroupBreadcrumb
+ groupBy={filter.groupBy}
+ groupValue={filter.groupValue}
+ rootLabel="All Exceptions"
+ updateFilter={updateFilter}
+ />
+ )}
+
+ {filter.groupBy && !filter.groupValue ? (
+ <GroupedTable
+ groupBy={filter.groupBy}
+ apiUrl="/api/metrics/exception/grouped"
+ />
+ ) : (
+ <DataTable
+ columns={columns}
+ data={normalizedData}
+ isFetched={isFetched || pingStatus !== "pending"}
+ isLoading={isLoading || pingStatus === "pending"}
+ visibilityColumns={visibilityColumns}
+ onClick={onClick}
+ />
+ )}
<RequestDetails />
</>
);
diff --git a/src/client/src/app/(playground)/requests/page.tsx b/src/client/src/app/(playground)/requests/page.tsx
index 9e2ac7c6..46dd78a0 100644
--- a/src/client/src/app/(playground)/requests/page.tsx
+++ b/src/client/src/app/(playground)/requests/page.tsx
@@ -17,6 +17,8 @@ import { normalizeTrace } from "@/helpers/client/trace";
import { getVisibilityColumnsOfPage } from "@/selectors/page";
import TracesFilter from "@/components/(playground)/filter/traces-filter";
import TracingGettingStarted from "@/components/(playground)/getting-started/tracing";
+import GroupedTable, { buildGroupValueFilter } from "@/components/(playground)/request/grouped-table";
+import GroupBreadcrumb from "@/components/(playground)/request/group-breadcrumb";
import { usePostHog } from "posthog-js/react";
import { CLIENT_EVENTS } from "@/constants/events";
@@ -36,6 +38,7 @@ function RequestPage() {
const pingStatus = useRootStore(getPingStatus);
const { data, fireRequest, isFetched, isLoading } = useFetchWrapper();
const { data: existData, fireRequest: fireExistRequest, isFetched: isFetchedExist, isLoading: isLoadingExist } = useFetchWrapper();
+
useEffect(() => {
fireExistRequest({
requestType: "POST",
@@ -43,9 +46,21 @@ function RequestPage() {
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
+
+ // When both groupBy and groupValue are set, inject the group filter into the flat list fetch
+ const effectiveFilter = useMemo(() => {
+ if (filter.groupBy && filter.groupValue) {
+ return {
+ ...filter,
+ selectedConfig: buildGroupValueFilter(filter.groupBy, filter.groupValue, filter.selectedConfig),
+ };
+ }
+ return filter;
+ }, [filter]);
+
const fetchData = useCallback(async () => {
fireRequest({
- body: JSON.stringify(filter),
+ body: JSON.stringify(effectiveFilter),
requestType: "POST",
url: "/api/metrics/request",
failureCb: (err?: string) => {
@@ -54,17 +69,22 @@ function RequestPage() {
});
},
});
- }, [filter, fireRequest]);
+ }, [effectiveFilter, fireRequest]);
+
+ // Show flat list when: no groupBy, OR groupBy + groupValue (drilled in)
+ const showFlatList = !filter.groupBy || !!filter.groupValue;
useEffect(() => {
if (
- filter.timeLimit.start &&
- filter.timeLimit.end &&
- pingStatus === "success"
+ effectiveFilter.filterReady &&
+ effectiveFilter.timeLimit.start &&
+ effectiveFilter.timeLimit.end &&
+ pingStatus === "success" &&
+ showFlatList
)
fetchData();
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [filter, pingStatus]);
+ }, [effectiveFilter, pingStatus, showFlatList]);
const normalizedData = useMemo(
() => ((data as any)?.records || []).map(normalizeTrace),
@@ -106,19 +126,33 @@ function RequestPage() {
return (
<>
<TracesFilter
- total={(data as any)?.total}
+ total={showFlatList ? (data as any)?.total : undefined}
supportDynamicFilters
pageName="request"
columns={columns}
/>
- <DataTable
- columns={columns}
- data={normalizedData}
- isFetched={isFetched || pingStatus !== "pending"}
- isLoading={isLoading || pingStatus === "pending"}
- visibilityColumns={visibilityColumns}
- onClick={onClick}
- />
+
+ {/* Breadcrumb — visible as soon as groupBy is selected */}
+ {filter.groupBy && (
+ <GroupBreadcrumb
+ groupBy={filter.groupBy}
+ groupValue={filter.groupValue}
+ updateFilter={updateFilter}
+ />
+ )}
+
+ {filter.groupBy && !filter.groupValue ? (
+ <GroupedTable groupBy={filter.groupBy} />
+ ) : (
+ <DataTable
+ columns={columns}
+ data={normalizedData}
+ isFetched={isFetched || pingStatus !== "pending"}
+ isLoading={isLoading || pingStatus === "pending"}
+ visibilityColumns={visibilityColumns}
+ onClick={onClick}
+ />
+ )}
<RequestDetails />
</>
);
diff --git a/src/client/src/app/api/metrics/exception/grouped/route.ts b/src/client/src/app/api/metrics/exception/grouped/route.ts
new file mode 100644
index 00000000..6d329b9b
--- /dev/null
+++ b/src/client/src/app/api/metrics/exception/grouped/route.ts
@@ -0,0 +1,34 @@
+import { MetricParams, TimeLimit } from "@/lib/platform/common";
+import { getGroupedRequests } 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 selectedConfig = formData.selectedConfig || {};
+ const groupBy = formData.groupBy as string;
+
+ if (!groupBy) {
+ return Response.json({ err: "groupBy is required" }, { status: 400 });
+ }
+
+ const params: MetricParams = {
+ timeLimit,
+ selectedConfig,
+ statusCode: ["STATUS_CODE_ERROR", "Error"],
+ };
+
+ const validationParam = validateMetricsRequest(
+ params,
+ validateMetricsRequestType.GET_ALL
+ );
+
+ if (!validationParam.success)
+ return Response.json(validationParam.err, { status: 400 });
+
+ const res = await getGroupedRequests(params, groupBy);
+ return Response.json(res);
+}
diff --git a/src/client/src/app/api/metrics/request/grouped/route.ts b/src/client/src/app/api/metrics/request/grouped/route.ts
new file mode 100644
index 00000000..2c169af4
--- /dev/null
+++ b/src/client/src/app/api/metrics/request/grouped/route.ts
@@ -0,0 +1,34 @@
+import { MetricParams, TimeLimit } from "@/lib/platform/common";
+import { getGroupedRequests } from "@/lib/platform/request";
+import {
+ validateMetricsRequest,
+ validateMetricsRequestType,
+} from "@/helpers/server/platform";
+import { GroupByKey } from "@/types/store/filter";
+
+export async function POST(request: Request) {
+ const formData = await request.json();
+ const timeLimit = formData.timeLimit as TimeLimit;
+ const selectedConfig = formData.selectedConfig || {};
+ const groupBy = formData.groupBy as GroupByKey;
+
+ if (!groupBy) {
+ return Response.json({ err: "groupBy is required" }, { status: 400 });
+ }
+
+ const params: MetricParams = {
+ timeLimit,
+ selectedConfig,
+ };
+
+ const validationParam = validateMetricsRequest(
+ params,
+ validateMetricsRequestType.GET_ALL
+ );
+
+ if (!validationParam.success)
+ return Response.json(validationParam.err, { status: 400 });
+
+ const res = await getGroupedRequests(params, groupBy);
+ return Response.json(res);
+}
diff --git a/src/client/src/components/(playground)/filter/refresh-rate.tsx b/src/client/src/components/(playground)/filter/refresh-rate.tsx
index 2abcccb0..b8095cd3 100644
--- a/src/client/src/components/(playground)/filter/refresh-rate.tsx
+++ b/src/client/src/components/(playground)/filter/refresh-rate.tsx
@@ -88,7 +88,7 @@ const RefreshRate = () => {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button variant="outline" className="flex gap-4 shrink-0 justify-start group-data-[state=close]:justify-center p-1 overflow-hidden text-stone-500 dark:text-stone-100 hover:bg-stone-600 dark:hover:bg-stone-600 hover:text-stone-100 font-normal h-auto w-auto ml-auto">
+ <Button variant="outline" className="flex gap-4 shrink-0 justify-start group-data-[state=close]:justify-center py-1 px-2 overflow-hidden font-normal h-auto w-auto ml-auto 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">
<TimerReset className={`size-3 shrink-0`} />
<span className="block text-ellipsis overflow-hidden whitespace-nowrap grow text-xs">{filter.refreshRate}</span>
<ChevronsUpDown className={`size-3 block shrink-0`} />
diff --git a/src/client/src/components/(playground)/filter/traces-filter.tsx b/src/client/src/components/(playground)/filter/traces-filter.tsx
index 4fbfeaa4..fd0ec783 100644
--- a/src/client/src/components/(playground)/filter/traces-filter.tsx
+++ b/src/client/src/components/(playground)/filter/traces-filter.tsx
@@ -15,7 +15,8 @@ import ComboDropdown from "./combo-dropdown";
import SlideWithValue from "./slider-with-value";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
-import { Plus, SlidersHorizontal, Trash2, ChevronDown } from "lucide-react";
+import { Plus, SlidersHorizontal, Trash2, ChevronDown, Layers, Link2 } from "lucide-react";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { getPingStatus } from "@/selectors/database-config";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
@@ -27,7 +28,9 @@ import {
CustomFilter,
CustomFilterAttributeType,
FilterConfig,
+ FilterSorting,
FilterType,
+ TIME_RANGES,
} from "@/types/store/filter";
import { usePostHog } from "posthog-js/react";
import { CLIENT_EVENTS } from "@/constants/events";
@@ -583,6 +586,270 @@ const DynamicFilters = ({
);
};
+// ─── GroupBy selector ─────────────────────────────────────────────────────────
+
+const GROUP_BY_OPTIONS: { key: string; label: string }[] = [
+ { key: "model", label: "Model" },
+ { key: "provider", label: "Provider" },
+ { key: "spanName", label: "Span Name" },
+ { key: "applicationName", label: "Application" },
+];
+
+const PREDEFINED_GROUP_BY_KEYS = new Set<string>(GROUP_BY_OPTIONS.map((o) => o.key));
+
+function getGroupByDisplayLabel(groupBy: string | undefined): string | undefined {
+ if (!groupBy) return undefined;
+ const predefined = GROUP_BY_OPTIONS.find((o) => o.key === groupBy)?.label;
+ if (predefined) return predefined;
+ const sep = groupBy.indexOf(":");
+ return sep !== -1 ? groupBy.slice(sep + 1) : groupBy;
+}
+
+// Simple inline suggest input — renders suggestions as a regular div child (no portal)
+// so it doesn't conflict with the Popover's DismissableLayer.
+function InlineSuggest({
+ value,
+ onChange,
+ options,
+ placeholder,
+}: {
+ value: string;
+ onChange: (val: string) => void;
+ options: string[];
+ placeholder?: string;
+}) {
+ const [open, setOpen] = useState(false);
+ const filtered = value
+ ? options.filter((o) => o.toLowerCase().includes(value.toLowerCase())).slice(0, 40)
+ : options.slice(0, 40);
+
+ return (
+ <div className="relative">
+ <Input
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ onFocus={() => setOpen(true)}
+ onBlur={() => setTimeout(() => setOpen(false), 120)}
+ placeholder={placeholder}
+ className="h-7 text-xs"
+ />
+ {open && filtered.length > 0 && (
+ <div className="absolute top-full left-0 right-0 z-50 mt-0.5 max-h-40 overflow-auto rounded-md border border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950 shadow-md">
+ {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();
+ onChange(opt);
+ setOpen(false);
+ }}
+ >
+ {opt}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function GroupByDropdown({
+ groupBy,
+ onChangeGroupBy,
+}: {
+ groupBy?: string;
+ onChangeGroupBy: (key: string | undefined) => void;
+}) {
+ const attributeKeys = useRootStore(getAttributeKeys);
+ const [open, setOpen] = useState(false);
+ const [customAttrType, setCustomAttrType] = useState<CustomFilterAttributeType>("SpanAttributes");
+ const [customKey, setCustomKey] = useState("");
+
+ // When groupBy changes externally (e.g. from URL restore), pre-fill the custom form
+ useEffect(() => {
+ if (groupBy && !PREDEFINED_GROUP_BY_KEYS.has(groupBy)) {
+ const sep = groupBy.indexOf(":");
+ if (sep !== -1) {
+ const attrType = groupBy.slice(0, sep) as CustomFilterAttributeType;
+ const key = groupBy.slice(sep + 1);
+ setCustomAttrType(attrType);
+ setCustomKey(key);
+ } else {
+ setCustomKey(groupBy);
+ }
+ } else if (!groupBy) {
+ setCustomKey("");
+ }
+ }, [groupBy]);
+
+ const activeLabel = getGroupByDisplayLabel(groupBy);
+ const isCustomActive = !!groupBy && !PREDEFINED_GROUP_BY_KEYS.has(groupBy);
+
+ const customOptions =
+ customAttrType === "SpanAttributes"
+ ? (attributeKeys?.spanAttributeKeys ?? [])
+ : customAttrType === "ResourceAttributes"
+ ? (attributeKeys?.resourceAttributeKeys ?? [])
+ : [];
+
+ const applyCustom = () => {
+ const k = customKey.trim();
+ if (!k) return;
+ onChangeGroupBy(`${customAttrType}:${k}`);
+ setOpen(false);
+ };
+
+ const selectPredefined = (key: string | undefined) => {
+ onChangeGroupBy(key);
+ setOpen(false);
+ };
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ 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 p-1 h-[30px] relative gap-1.5 text-xs aspect-square"
+ variant="outline"
+ >
+ <Layers className="w-3 h-3 shrink-0" />
+ {activeLabel ? <span className="max-w-[80px] truncate">{activeLabel}</span> : null}
+ {groupBy && (
+ <span className="w-2 h-2 bg-primary absolute -top-0 -right-0 rounded-full" />
+ )}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-64 p-1" align="end">
+ {/* Predefined options */}
+ <button
+ className="flex w-full items-center px-2 py-1.5 text-xs rounded hover:bg-stone-100 dark:hover:bg-stone-800 text-stone-700 dark:text-stone-300"
+ onClick={() => selectPredefined(undefined)}
+ >
+ None
+ {!groupBy && <span className="ml-auto text-primary">✓</span>}
+ </button>
+ {GROUP_BY_OPTIONS.map(({ key, label }) => (
+ <button
+ key={key}
+ className="flex w-full items-center px-2 py-1.5 text-xs rounded hover:bg-stone-100 dark:hover:bg-stone-800 text-stone-700 dark:text-stone-300"
+ onClick={() => selectPredefined(key)}
+ >
+ {label}
+ {groupBy === key && <span className="ml-auto text-primary">✓</span>}
+ </button>
+ ))}
+
+ {/* Custom attribute section */}
+ <div className="border-t dark:border-stone-700 mt-1 pt-2 px-1 pb-1">
+ <p className="text-xs text-stone-400 dark:text-stone-500 mb-1.5">
+ Custom attribute
+ {isCustomActive && <span className="ml-1.5 text-primary">✓</span>}
+ </p>
+ <div className="flex flex-col gap-1.5">
+ <select
+ value={customAttrType}
+ onChange={(e) => {
+ setCustomAttrType(e.target.value as CustomFilterAttributeType);
+ setCustomKey("");
+ }}
+ className="h-7 w-full rounded-md border border-stone-200 dark:border-stone-700 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>
+ <InlineSuggest
+ value={customKey}
+ onChange={setCustomKey}
+ options={customOptions}
+ placeholder="e.g. gen_ai.request.user"
+ />
+ <Button
+ size="default"
+ variant="outline"
+ className="h-7 text-xs w-full"
+ onClick={applyCustom}
+ >
+ Apply
+ </Button>
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+// ─── Local storage persistence ────────────────────────────────────────────────
+
+const FILTER_STORAGE_KEY = "openlit_filter_v1";
+
+// Params that indicate a meaningful filter is present in the URL
+const FILTER_PARAM_KEYS = ["tr", "ts", "te", "limit", "models", "providers", "traceTypes", "appNames", "spanNames", "envs", "maxCost", "cf", "gb", "gbv"];
+
+type PersistedFilter = {
+ timeLimitType: string;
+ timeLimitStart?: string;
+ timeLimitEnd?: string;
+ limit: number;
+ selectedConfig: Partial<FilterConfig>;
+ sorting: FilterSorting;
+ groupBy?: string;
+ groupValue?: string;
+};
+
+function saveFilterToStorage(filter: FilterType) {
+ try {
+ const toSave: PersistedFilter = {
+ timeLimitType: filter.timeLimit.type,
+ timeLimitStart: filter.timeLimit.start
+ ? new Date(filter.timeLimit.start).toISOString()
+ : undefined,
+ timeLimitEnd: filter.timeLimit.end
+ ? new Date(filter.timeLimit.end).toISOString()
+ : undefined,
+ limit: filter.limit,
+ selectedConfig: filter.selectedConfig,
+ sorting: filter.sorting,
+ groupBy: filter.groupBy,
+ groupValue: filter.groupValue,
+ };
+ localStorage.setItem(FILTER_STORAGE_KEY, JSON.stringify(toSave));
+ } catch {}
+}
+
+function loadFilterFromStorage(): PersistedFilter | null {
+ try {
+ const raw = localStorage.getItem(FILTER_STORAGE_KEY);
+ return raw ? (JSON.parse(raw) as PersistedFilter) : null;
+ } catch {
+ return null;
+ }
+}
+
+function applyStoredFilter(
+ saved: PersistedFilter,
+ updateFilter: (key: string, value: any, extraParams?: any) => void,
+ validTimeRanges: Set<string>
+) {
+ // Time limit first (it resets selectedConfig, so must come before selectedConfig)
+ if (saved.timeLimitType === "CUSTOM" && saved.timeLimitStart && saved.timeLimitEnd) {
+ updateFilter("timeLimit.type", "CUSTOM", {
+ start: new Date(saved.timeLimitStart),
+ end: new Date(saved.timeLimitEnd),
+ });
+ } else if (validTimeRanges.has(saved.timeLimitType)) {
+ updateFilter("timeLimit.type", saved.timeLimitType as TIME_RANGES);
+ }
+ if (saved.limit) updateFilter("limit", saved.limit);
+ if (saved.selectedConfig && hasActiveConfig(saved.selectedConfig)) {
+ updateFilter("selectedConfig", saved.selectedConfig);
+ }
+ if (saved.sorting?.type) updateFilter("sorting", saved.sorting);
+ if (saved.groupBy) updateFilter("groupBy", saved.groupBy);
+ if (saved.groupValue) updateFilter("groupValue", saved.groupValue);
+}
+
// ─── URL filter sync hook ─────────────────────────────────────────────────────
const VALID_TIME_RANGES = new Set(["24H", "7D", "1M", "3M", "CUSTOM"]);
@@ -593,42 +860,51 @@ function useFilterUrlSync(filter: FilterType, updateFilter: (key: string, value:
// 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)
+ // On mount: URL params take priority; fall back to localStorage if URL has none.
useEffect(() => {
if (initializedFromUrl.current) return;
initializedFromUrl.current = true;
const params = new URLSearchParams(window.location.search);
+ const hasUrlParams = FILTER_PARAM_KEYS.some((k) => params.has(k));
- // 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),
- });
+ if (hasUrlParams) {
+ // ── Apply URL params ──────────────────────────────────────────────
+ 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);
}
- } else {
- updateFilter("timeLimit.type", tr);
}
+ const limitParam = params.get("limit");
+ if (limitParam) {
+ const parsed = parseInt(limitParam, 10);
+ if (!isNaN(parsed) && parsed > 0) updateFilter("limit", parsed);
+ }
+ const config = paramsToConfig(params);
+ if (hasActiveConfig(config)) updateFilter("selectedConfig", config);
+ const gb = params.get("gb");
+ if (gb) updateFilter("groupBy", gb);
+ const gbv = params.get("gbv");
+ if (gbv) updateFilter("groupValue", gbv);
+ } else {
+ // ── Fall back to localStorage ─────────────────────────────────────
+ const saved = loadFilterFromStorage();
+ if (saved) applyStoredFilter(saved, updateFilter, VALID_TIME_RANGES);
}
- // 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);
- }
+ // Signal that the initial filter read (URL / localStorage) is complete.
+ // Pages use this flag to avoid fetching before the correct params are applied.
+ updateFilter("filterReady", true);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
@@ -657,13 +933,24 @@ function useFilterUrlSync(filter: FilterType, updateFilter: (key: string, value:
// Selected config
configToParams(filter.selectedConfig, params);
+ // Group by
+ if (filter.groupBy) params.set("gb", filter.groupBy);
+ else params.delete("gb");
+
+ // Group value
+ if (filter.groupValue) params.set("gbv", filter.groupValue);
+ else params.delete("gbv");
+
const qs = params.toString();
- if (qs === prevSerializedRef.current) return;
- prevSerializedRef.current = qs;
+ if (qs !== prevSerializedRef.current) {
+ prevSerializedRef.current = qs;
+ router.replace(`${pathname}${qs ? `?${qs}` : ""}`, { scroll: false });
+ }
- router.replace(`${pathname}${qs ? `?${qs}` : ""}`, { scroll: false });
+ // Persist to localStorage so other pages (and refreshes) pick up these filters
+ saveFilterToStorage(filter);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [filter.timeLimit.type, filter.timeLimit.start, filter.timeLimit.end, filter.limit, filter.selectedConfig]);
+ }, [filter.timeLimit.type, filter.timeLimit.start, filter.timeLimit.end, filter.limit, filter.selectedConfig, filter.groupBy, filter.groupValue]);
}
// ─── TracesFilter (exported) ──────────────────────────────────────────────────
@@ -675,7 +962,7 @@ export default function TracesFilter({
pageName,
columns,
}: {
- total: number;
+ total?: number;
supportDynamicFilters?: boolean;
includeOnlySorting?: string[];
pageName: PAGE;
@@ -686,6 +973,29 @@ export default function TracesFilter({
const filterConfig = useRootStore(getFilterConfig);
const updateFilter = useRootStore(getUpdateFilter);
+ const onChangeGroupBy = (key: string | undefined) => {
+ updateFilter("groupBy", key ?? null);
+ };
+
+ const onShareLink = () => {
+ if (typeof window === "undefined") return;
+
+ const clipboard = navigator.clipboard;
+ if (!clipboard?.writeText) {
+ toast.error("Copy to clipboard is not supported in this browser");
+ return;
+ }
+
+ clipboard
+ .writeText(window.location.href)
+ .then(() => {
+ toast.success("Link copied to clipboard");
+ })
+ .catch(() => {
+ toast.error("Could not copy link");
+ });
+ };
+
useFilterUrlSync(filter, updateFilter);
const onClickPageAction = (dir: -1 | 1) => {
@@ -731,22 +1041,28 @@ export default function TracesFilter({
<div className="flex flex-col items-center w-full justify-between mb-4">
<div className="flex w-full gap-4">
<Filter />
- {filterConfig && total > 0 && (
+ {filterConfig && !!total && total > 0 && (
<TracesPagination
currentPage={filter.offset / filter.limit + 1}
currentSize={filter.limit}
- totalPage={ceil((total || 0) / filter.limit)}
+ totalPage={ceil(total / filter.limit)}
onClickPageAction={onClickPageAction}
onClickPageLimit={onClickPageLimit}
/>
)}
<VisibilityColumns columns={columns} pageName={pageName} />
- {total > 0 && (
+ {!!total && total > 0 && (
<Sorting
sorting={filter.sorting}
includeOnlySorting={includeOnlySorting}
/>
)}
+ {supportDynamicFilters && (
+ <GroupByDropdown
+ groupBy={filter.groupBy}
+ onChangeGroupBy={onChangeGroupBy}
+ />
+ )}
{supportDynamicFilters && (
<Button
variant="outline"
@@ -760,6 +1076,15 @@ export default function TracesFilter({
)}
</Button>
)}
+ <Button
+ variant="outline"
+ size="default"
+ title="Copy shareable link"
+ 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 aspect-square p-1 h-[30px]"
+ onClick={onShareLink}
+ >
+ <Link2 className="w-3 h-3" />
+ </Button>
</div>
{supportDynamicFilters && (
<DynamicFilters
diff --git a/src/client/src/components/(playground)/filter/traces-pagination.tsx b/src/client/src/components/(playground)/filter/traces-pagination.tsx
index e1b27071..aa7c48ce 100644
--- a/src/client/src/components/(playground)/filter/traces-pagination.tsx
+++ b/src/client/src/components/(playground)/filter/traces-pagination.tsx
@@ -48,14 +48,14 @@ export default function TracesPagination(props: PaginationProps) {
<p className="text-xs shrink-0 mr-1 self-center text-stone-950 dark:text-stone-100">
Size :{" "}
</p>
- <div className="w-[100px]">
+ <div className="w-[80px]">
<Select
onValueChange={onSizeChange}
defaultValue={`${props.currentSize}`}
>
<SelectTrigger
id="model"
- className="items-center [&_[data-description]]:hidden text-stone-950 dark:text-stone-100 h-auto py-1"
+ className="items-center [&_[data-description]]:hidden h-auto py-1 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 px-2 h-[30px] relative gap-1 text-xs"
>
<SelectValue
placeholder={`${props.currentSize}`}
@@ -84,7 +84,7 @@ export default function TracesPagination(props: PaginationProps) {
<PaginationContent>
<PaginationItem>
<PaginationPrevious
- className={`py-1 h-auto ${
+ className={`py-1 h-full ${
firstPage
? "pointer-events-none cursor-not-allowed text-stone-400"
: "text-stone-950 dark:text-stone-100"
@@ -101,7 +101,7 @@ export default function TracesPagination(props: PaginationProps) {
</PaginationItem>
<PaginationItem>
<PaginationNext
- className={`py-1 h-auto ${
+ className={`py-1 h-full ${
lastPage
? "pointer-events-none cursor-not-allowed text-stone-400"
: "text-stone-950 dark:text-stone-100"
diff --git a/src/client/src/components/(playground)/request/components/node-graph.tsx b/src/client/src/components/(playground)/request/components/node-graph.tsx
index 655278f7..2085af11 100644
--- a/src/client/src/components/(playground)/request/components/node-graph.tsx
+++ b/src/client/src/components/(playground)/request/components/node-graph.tsx
@@ -1,22 +1,15 @@
"use client";
/**
- * Graph View — DAG (Directed Acyclic Graph) visualization of span hierarchy.
+ * Graph view for the span hierarchy.
*
- * ## Sequencing logic
+ * The transform creates three edge kinds:
+ * - SEQUENTIAL: parent enters first child, or one execution wave follows another.
+ * - PARALLEL: two sibling spans overlap in time.
+ * - DELEGATED: supported as a fallback structural edge.
*
- * Layout uses a bottom-up tree placement algorithm:
- * 1. Walk the hierarchy tree recursively; leaf spans are placed left-to-right
- * in the order they appear (siblings are pre-sorted by Timestamp in
- * buildHierarchy on the server).
- * 2. Each parent node is centered above its children.
- * 3. Y-axis represents tree depth (parent→child), X-axis spreads siblings.
- *
- * Edges between parent and child are classified as "parallel" or "sequential"
- * by checking whether sibling spans have overlapping time windows:
- * - parallel: spanA.start < spanB.end AND spanB.start < spanA.end
- * - sequential: no time overlap
- * Parallel edges are drawn as dashed indigo lines; sequential as solid gray.
+ * Y position is execution order. X position is hierarchy indentation, with
+ * parallel spans spread into temporary side-by-side lanes.
*/
import { TraceHeirarchySpan } from "@/types/trace";
@@ -26,477 +19,250 @@ import {
getSpanCostFormatted,
getSpanTooltipText,
} from "@/helpers/client/trace";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { transformTracesToGraph } from "@/lib/platform/graph-transform";
+import { useCallback, useEffect, useRef, useMemo, useState } from "react";
import { Maximize, Minus, Plus } from "lucide-react";
-const NODE_WIDTH = 160;
-const NODE_HEIGHT = 52;
-const H_GAP = 24;
-const V_GAP = 48;
-
-interface NodeLayout {
- span: TraceHeirarchySpan;
- x: number;
- y: number;
-}
+const NODE_W = 160;
+const NODE_H = 52;
+const ZOOM_STEP = 0.05;
+const MIN_ZOOM = 0.05;
+const MAX_ZOOM = 3;
-function getNodeStroke(durationNs: number, isSelected: boolean): string {
- if (isSelected) return "#6366f1";
- const seconds = durationNs * 1e-9;
- if (seconds > 10) return "#ef4444";
- if (seconds > 5) return "#eab308";
- if (seconds > 1) return "#3b82f6";
+function nodeStroke(ns: number, sel: boolean): string {
+ if (sel) return "#6366f1";
+ const s = ns * 1e-9;
+ if (s > 10) return "#ef4444";
+ if (s > 5) return "#eab308";
+ if (s > 1) return "#3b82f6";
return "#22c55e";
}
-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)";
+function nodeFill(ns: number, sel: boolean): string {
+ if (sel) return "rgba(99,102,241,0.09)";
+ const s = ns * 1e-9;
+ if (s > 10) return "rgba(239,68,68,0.06)";
+ if (s > 5) return "rgba(234,179,8,0.06)";
+ if (s > 1) return "rgba(59,130,246,0.06)";
return "rgba(34,197,94,0.06)";
}
-function parseTimestampMs(ts?: string): number | null {
- if (!ts) return null;
- const withZ = ts.endsWith("Z") ? ts : ts + "Z";
- const ms = new Date(withZ).getTime();
- return isNaN(ms) ? null : ms;
-}
-
-function classifySiblingRelationship(
- a: TraceHeirarchySpan,
- b: TraceHeirarchySpan
-): "parallel" | "sequential" {
- const aStart = parseTimestampMs(a.Timestamp);
- const bStart = parseTimestampMs(b.Timestamp);
- if (aStart === null || bStart === null) return "sequential";
- const aDurMs = a.Duration / 1e6;
- const bDurMs = b.Duration / 1e6;
- const aEnd = aStart + aDurMs;
- const bEnd = bStart + bDurMs;
- return aStart < bEnd && bStart < aEnd ? "parallel" : "sequential";
-}
-
-function detectParallelPairs(root: TraceHeirarchySpan): Set<string> {
- const parallelPairs = new Set<string>();
- function walk(span: TraceHeirarchySpan) {
- if (span.children && span.children.length > 1) {
- for (let i = 0; i < span.children.length; i++) {
- for (let j = i + 1; j < span.children.length; j++) {
- if (
- classifySiblingRelationship(
- span.children[i],
- span.children[j]
- ) === "parallel"
- ) {
- parallelPairs.add(
- [span.children[i].SpanId, span.children[j].SpanId]
- .sort()
- .join("|")
- );
- }
- }
- }
- }
- span.children?.forEach(walk);
- }
- walk(root);
- return parallelPairs;
-}
-
-function isParallelSpan(
- span: TraceHeirarchySpan,
- siblings: TraceHeirarchySpan[],
- parallelPairs: Set<string>
-): boolean {
- for (const sib of siblings) {
- if (sib.SpanId === span.SpanId) continue;
- const key = [span.SpanId, sib.SpanId].sort().join("|");
- if (parallelPairs.has(key)) return true;
- }
- return false;
-}
-
-function layoutTree(root: TraceHeirarchySpan): NodeLayout[] {
- const nodes: NodeLayout[] = [];
- let leafCounter = 0;
-
- 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;
- nodes.push({ span, x: center - NODE_WIDTH / 2, 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) + "\u2026" : text;
+function trunc(s: string, n: number): string {
+ return s.length > n ? s.slice(0, n - 1) + "…" : s;
}
-const ZOOM_STEP = 0.05;
-const MIN_ZOOM = 0.05;
-const MAX_ZOOM = 3;
-
export default function NodeGraph({ record }: { record: TraceHeirarchySpan }) {
const [request, updateRequest] = useRequest();
const containerRef = useRef<HTMLDivElement>(null);
const [zoom, setZoom] = useState(1);
const [pan, setPan] = useState({ x: 0, y: 0 });
- const [isPanning, setIsPanning] = useState(false);
- const panStart = useRef({ x: 0, y: 0, panX: 0, panY: 0 });
-
- const nodes = layoutTree(record);
- const parallelPairs = detectParallelPairs(record);
-
- const nodeMap = new Map<string, NodeLayout>();
- for (const n of nodes) {
- nodeMap.set(n.span.SpanId, n);
- }
-
- 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;
+ const [panning, setPanning] = useState(false);
+ const dragStart = useRef({ mx: 0, my: 0, px: 0, py: 0 });
+
+ const graph = useMemo(() => transformTracesToGraph(record), [record]);
+ const nodeById = useMemo(() => graph.nodes, [graph.nodes]);
+ const seqMarkerId = useMemo(
+ () => `arr-seq-${record.SpanId.replace(/[^a-zA-Z0-9_-]/g, "")}`,
+ [record.SpanId]
+ );
- const edges: {
- from: NodeLayout;
- to: NodeLayout;
- type: "parallel" | "sequential";
- }[] = [];
- function collectEdges(span: TraceHeirarchySpan) {
- const fromLayout = nodeMap.get(span.SpanId);
- if (!fromLayout) return;
- if (span.children) {
- const siblings = span.children;
- for (const child of span.children) {
- const toLayout = nodeMap.get(child.SpanId);
- if (toLayout) {
- edges.push({
- from: fromLayout,
- to: toLayout,
- type: isParallelSpan(child, siblings, parallelPairs)
- ? "parallel"
- : "sequential",
- });
- }
- collectEdges(child);
- }
- }
- }
- collectEdges(record);
+ const PAD = 40;
+ const xs = Array.from(nodeById.values()).map(n => n.x);
+ const ys = Array.from(nodeById.values()).map(n => n.y);
+ const minX = Math.min(...xs);
+ const maxX = Math.max(...xs);
+ const minY = Math.min(...ys);
+ const maxY = Math.max(...ys);
+ const svgW = (maxX - minX) + NODE_W + PAD * 2;
+ const svgH = (maxY - minY) + NODE_H + PAD * 2;
+ const ox = -minX + PAD;
+ const oy = -minY + PAD;
const fitToView = useCallback(() => {
- if (!containerRef.current) return;
- const cw = containerRef.current.clientWidth;
- const ch = containerRef.current.clientHeight;
- if (cw === 0 || ch === 0) return;
- const scaleX = cw / svgWidth;
- const scaleY = ch / svgHeight;
- const newZoom = Math.max(
- MIN_ZOOM,
- Math.min(MAX_ZOOM, Math.min(scaleX, scaleY, 1) * 0.85)
- );
- const scaledW = svgWidth * newZoom;
- const scaledH = svgHeight * newZoom;
- setPan({
- x: (cw - scaledW) / 2,
- y: (ch - scaledH) / 2,
- });
- setZoom(newZoom);
- }, [svgWidth, svgHeight]);
-
- // Auto-fit on mount (key={record.SpanId} in parent ensures fresh mount)
+ const el = containerRef.current;
+ if (!el) return;
+ const { clientWidth: cw, clientHeight: ch } = el;
+ if (!cw || !ch) return;
+ const z = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, Math.min(cw / svgW, ch / svgH) * 0.9));
+ setPan({ x: (cw - svgW * z) / 2, y: (ch - svgH * z) / 2 });
+ setZoom(z);
+ }, [svgW, svgH]);
+
+ useEffect(() => { const t = setTimeout(fitToView, 60); return () => clearTimeout(t); }, [fitToView]);
useEffect(() => {
- const timer = setTimeout(fitToView, 60);
- return () => clearTimeout(timer);
- }, [fitToView]);
-
- // Also re-fit when the container resizes (e.g. panel drag)
- useEffect(() => {
- if (!containerRef.current) return;
- const ro = new ResizeObserver(() => fitToView());
- ro.observe(containerRef.current);
+ const el = containerRef.current;
+ if (!el) return;
+ const ro = new ResizeObserver(fitToView);
+ ro.observe(el);
return () => ro.disconnect();
}, [fitToView]);
- const handleWheel = useCallback(
- (e: React.WheelEvent) => {
- e.preventDefault();
- if (!containerRef.current) return;
- const rect = containerRef.current.getBoundingClientRect();
- const mouseX = e.clientX - rect.left;
- const mouseY = e.clientY - rect.top;
- const delta = e.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP;
- const newZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, zoom + delta));
- const scale = newZoom / zoom;
- setPan((p) => ({
- x: mouseX - scale * (mouseX - p.x),
- y: mouseY - scale * (mouseY - p.y),
- }));
- setZoom(newZoom);
- },
- [zoom]
- );
-
- const handleMouseDown = useCallback(
- (e: React.MouseEvent) => {
- if (e.button !== 0) return;
- setIsPanning(true);
- panStart.current = {
- x: e.clientX,
- y: e.clientY,
- panX: pan.x,
- panY: pan.y,
- };
- },
- [pan]
- );
-
- const handleMouseMove = useCallback(
- (e: React.MouseEvent) => {
- if (!isPanning) return;
- setPan({
- x: panStart.current.panX + (e.clientX - panStart.current.x),
- y: panStart.current.panY + (e.clientY - panStart.current.y),
- });
- },
- [isPanning]
- );
-
- const handleMouseUp = useCallback(() => setIsPanning(false), []);
+ const onWheel = useCallback((e: React.WheelEvent) => {
+ e.preventDefault();
+ const el = containerRef.current;
+ if (!el) return;
+ const r = el.getBoundingClientRect();
+ const mx = e.clientX - r.left;
+ const my = e.clientY - r.top;
+ const nz = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, zoom + (e.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP)));
+ const sc = nz / zoom;
+ setPan(p => ({ x: mx - sc * (mx - p.x), y: my - sc * (my - p.y) }));
+ setZoom(nz);
+ }, [zoom]);
+
+ const onMouseDown = useCallback((e: React.MouseEvent) => {
+ if (e.button !== 0) return;
+ setPanning(true);
+ dragStart.current = { mx: e.clientX, my: e.clientY, px: pan.x, py: pan.y };
+ }, [pan]);
+
+ const onMouseMove = useCallback((e: React.MouseEvent) => {
+ if (!panning) return;
+ setPan({ x: dragStart.current.px + e.clientX - dragStart.current.mx, y: dragStart.current.py + e.clientY - dragStart.current.my });
+ }, [panning]);
+
+ const onMouseUp = useCallback(() => setPanning(false), []);
return (
<div className="relative flex-1 w-full min-h-0 h-full">
- {/* Controls — top-right */}
+
+ {/* Zoom controls */}
<div className="absolute top-2 right-2 z-20 flex items-center gap-1 bg-white/90 dark:bg-stone-900/90 rounded-md border border-stone-200 dark:border-stone-700 p-0.5 shadow-sm">
- <button
- onClick={() => setZoom((z) => Math.min(MAX_ZOOM, z + ZOOM_STEP))}
- className="p-1 rounded hover:bg-stone-100 dark:hover:bg-stone-700 transition-colors"
- title="Zoom in"
- >
- <Plus className="h-3.5 w-3.5 text-stone-600 dark:text-stone-300" />
- </button>
- <span className="text-[10px] tabular-nums text-stone-500 dark:text-stone-400 min-w-[32px] text-center select-none">
- {Math.round(zoom * 100)}%
- </span>
- <button
- onClick={() => setZoom((z) => Math.max(MIN_ZOOM, z - ZOOM_STEP))}
- className="p-1 rounded hover:bg-stone-100 dark:hover:bg-stone-700 transition-colors"
- title="Zoom out"
- >
- <Minus className="h-3.5 w-3.5 text-stone-600 dark:text-stone-300" />
- </button>
+ <button onClick={() => setZoom(z => Math.min(MAX_ZOOM, z + ZOOM_STEP))} className="p-1 rounded hover:bg-stone-100 dark:hover:bg-stone-700" title="Zoom in"><Plus className="h-3.5 w-3.5 text-stone-600 dark:text-stone-300" /></button>
+ <span className="text-[10px] tabular-nums text-stone-500 dark:text-stone-400 min-w-[32px] text-center select-none">{Math.round(zoom * 100)}%</span>
+ <button onClick={() => setZoom(z => Math.max(MIN_ZOOM, z - ZOOM_STEP))} className="p-1 rounded hover:bg-stone-100 dark:hover:bg-stone-700" title="Zoom out"><Minus className="h-3.5 w-3.5 text-stone-600 dark:text-stone-300" /></button>
<div className="w-px h-4 bg-stone-200 dark:bg-stone-700" />
- <button
- onClick={fitToView}
- className="p-1 rounded hover:bg-primary/10 transition-colors"
- title="Fit to view"
- >
- <Maximize className="h-3.5 w-3.5 text-primary" />
- </button>
+ <button onClick={fitToView} className="p-1 rounded hover:bg-primary/10" title="Fit to view"><Maximize className="h-3.5 w-3.5 text-primary" /></button>
</div>
- {/* Legend — bottom-left, above the canvas */}
- <div className="absolute bottom-2 left-2 z-20 flex items-center gap-3 text-[10px] text-stone-500 dark:text-stone-400 bg-white/90 dark:bg-stone-900/90 rounded px-2 py-1 border border-stone-200 dark:border-stone-700 shadow-sm">
- <span className="flex items-center gap-1">
- <svg width="16" height="6">
- <line
- x1="0"
- y1="3"
- x2="16"
- y2="3"
- stroke="#6366f1"
- strokeWidth="1.5"
- strokeDasharray="4 2"
- />
- </svg>
- Parallel
- </span>
- <span className="flex items-center gap-1">
- <svg width="16" height="6">
- <line
- x1="0"
- y1="3"
- x2="16"
- y2="3"
- stroke="rgba(120,113,108,0.5)"
- strokeWidth="1.5"
- />
- </svg>
+ {/* Legend */}
+ <div className="absolute bottom-2 left-2 z-20 flex flex-col gap-1.5 text-[10px] text-stone-500 dark:text-stone-400 bg-white/90 dark:bg-stone-900/90 rounded px-2.5 py-2 border border-stone-200 dark:border-stone-700 shadow-sm">
+ <div className="font-semibold text-stone-700 dark:text-stone-300 mb-0.5">Edge Types</div>
+ <span className="flex items-center gap-2">
+ <svg width="24" height="6"><line x1="0" y1="3" x2="24" y2="3" stroke="#3b82f6" strokeWidth="1.5" /></svg>
Sequential
</span>
+ <span className="flex items-center gap-2">
+ <svg width="24" height="6"><line x1="0" y1="3" x2="24" y2="3" stroke="#6366f1" strokeWidth="1.5" strokeDasharray="5 3" /></svg>
+ Parallel
+ </span>
</div>
- {/* Pan/zoom canvas — fills all available space */}
+ {/* Canvas */}
<div
ref={containerRef}
className="absolute inset-0"
- style={{ cursor: isPanning ? "grabbing" : "grab" }}
- onWheel={handleWheel}
- onMouseDown={handleMouseDown}
- onMouseMove={handleMouseMove}
- onMouseUp={handleMouseUp}
- onMouseLeave={handleMouseUp}
+ style={{ cursor: panning ? "grabbing" : "grab" }}
+ onWheel={onWheel}
+ onMouseDown={onMouseDown}
+ onMouseMove={onMouseMove}
+ onMouseUp={onMouseUp}
+ onMouseLeave={onMouseUp}
>
<svg
- width={svgWidth}
- height={svgHeight}
- viewBox={`0 0 ${svgWidth} ${svgHeight}`}
+ width={svgW} height={svgH}
+ viewBox={`0 0 ${svgW} ${svgH}`}
className="block"
- style={{
- transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
- transformOrigin: "0 0",
- }}
+ style={{ transform: `translate(${pan.x}px,${pan.y}px) scale(${zoom})`, transformOrigin: "0 0" }}
>
- {/* Edges */}
- {edges.map(({ from, to, type }, i) => {
- const x1 = from.x + offsetX + NODE_WIDTH / 2;
- const y1 = from.y + offsetY + NODE_HEIGHT;
- const x2 = to.x + offsetX + NODE_WIDTH / 2;
- const y2 = to.y + offsetY;
- const midY = (y1 + y2) / 2;
- const isParallel = type === "parallel";
+ <defs>
+ <marker id={seqMarkerId} markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto">
+ <path d="M 0 1 L 7 4 L 0 7 Z" fill="#3b82f6" />
+ </marker>
+ </defs>
+
+ {graph.edges.map((edge, i) => {
+ const fromNode = nodeById.get(edge.from);
+ const toNode = nodeById.get(edge.to);
+ if (!fromNode || !toNode) return null;
+
+ const isSeq = edge.kind === "SEQUENTIAL";
+ const isPar = edge.kind === "PARALLEL";
+ const isDelegate = edge.kind === "DELEGATED";
+
+ const stroke = isDelegate ? "rgba(156,163,175,0.75)" : isSeq ? "#3b82f6" : "#6366f1";
+ const dash = isPar ? "6 3" : undefined;
+ const marker = isSeq ? `url(#${seqMarkerId})` : undefined;
+
+ if (!isPar) {
+ const x1 = fromNode.x + ox + NODE_W / 2;
+ const y1 = fromNode.y + oy + NODE_H;
+ const x2 = toNode.x + ox + NODE_W / 2;
+ const y2 = toNode.y + oy;
+ const midY = (y1 + y2) / 2;
+
+ return (
+ <path key={`e${i}`}
+ d={`M ${x1} ${y1} C ${x1} ${midY}, ${x2} ${midY}, ${x2} ${y2}`}
+ fill="none"
+ stroke={stroke}
+ strokeWidth={isDelegate ? 1 : 1.5}
+ markerEnd={marker}
+ opacity={isDelegate ? 0.72 : 0.88}
+ />
+ );
+ }
+
+ const leftToRight = fromNode.x <= toNode.x;
+ const x1 = fromNode.x + ox + (leftToRight ? NODE_W : 0);
+ const x2 = toNode.x + ox + (leftToRight ? 0 : NODE_W);
+ const y1 = fromNode.y + oy + NODE_H / 2;
+ const y2 = toNode.y + oy + NODE_H / 2;
+ const midX = (x1 + x2) / 2;
+
return (
- <path
- key={i}
- d={`M ${x1} ${y1} C ${x1} ${midY}, ${x2} ${midY}, ${x2} ${y2}`}
+ <path key={`e${i}`}
+ d={`M ${x1} ${y1} C ${midX} ${y1}, ${midX} ${y2}, ${x2} ${y2}`}
fill="none"
- stroke={
- isParallel
- ? "#6366f1"
- : "rgba(120,113,108,0.5)"
- }
- strokeWidth={1.5}
- strokeDasharray={isParallel ? "6 3" : undefined}
+ stroke={stroke}
+ strokeWidth={1.4}
+ strokeDasharray={dash}
+ opacity={0.55}
/>
);
})}
- {/* Edge labels */}
- {edges.map(({ from, to, type }, i) => {
- const x1 = from.x + offsetX + NODE_WIDTH / 2;
- const y1 = from.y + offsetY + NODE_HEIGHT;
- const x2 = to.x + offsetX + NODE_WIDTH / 2;
- const y2 = to.y + offsetY;
- const isParallel = type === "parallel";
- return (
- <text
- key={`label-${i}`}
- x={(x1 + x2) / 2 + 8}
- y={(y1 + y2) / 2}
- fontSize={8}
- fill={
- isParallel
- ? "#6366f1"
- : "rgba(120,113,108,0.6)"
- }
- textAnchor="start"
- dominantBaseline="middle"
- >
- {isParallel ? "parallel" : "seq"}
- </text>
- );
- })}
-
- {/* Nodes */}
- {nodes.map(({ span, x, y }) => {
- const isSelected =
- request?.spanId === span.SpanId;
- const nx = x + offsetX;
- const ny = y + offsetY;
- const stroke = getNodeStroke(
- span.Duration,
- isSelected
- );
- const fill = getNodeFill(
- span.Duration,
- isSelected
- );
- const durationDisplay =
- getSpanDurationDisplay(span);
- const costDisplay = getSpanCostFormatted(
- span,
- 10
- );
- const tooltipText = getSpanTooltipText(span);
+ {Array.from(nodeById.values()).map(node => {
+ const sel = request?.spanId === node.spanId;
+ const nx = node.x + ox;
+ const ny = node.y + oy;
+ const str = nodeStroke(node.duration, sel);
+ const fil = nodeFill(node.duration, sel);
+ const displaySpan = {
+ SpanId: node.spanId,
+ SpanName: node.spanName,
+ Duration: node.duration,
+ Timestamp: node.timestamp,
+ Cost: node.cost,
+ };
+ const dur = getSpanDurationDisplay(displaySpan);
+ const cost = getSpanCostFormatted(displaySpan, 4);
+ const tooltipText = getSpanTooltipText(displaySpan);
return (
- <g
- key={span.SpanId}
- onClick={(e) => {
- e.stopPropagation();
- updateRequest({
- spanId: span.SpanId,
- });
- }}
+ <g key={node.spanId}
+ onClick={e => { e.stopPropagation(); updateRequest({ spanId: node.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"
- }
+
+ <rect x={nx} y={ny} width={NODE_W} height={NODE_H} rx={6}
+ fill={fil} stroke={str} strokeWidth={sel ? 2 : 1.5} />
+
+ <text x={nx + NODE_W / 2} y={ny + 18}
+ textAnchor="middle" fontSize={10}
+ fontWeight={sel ? 600 : 400}
+ fill={sel ? "#6366f1" : "currentColor"}
className="fill-stone-700 dark:fill-stone-300"
>
- {truncate(span.SpanName, 20)}
+ {trunc(node.spanName, 20)}
</text>
- <text
- x={nx + NODE_WIDTH / 2}
- y={ny + 34}
- textAnchor="middle"
- fontSize={9}
- fill={stroke}
- opacity={0.9}
+
+ <text x={nx + NODE_W / 2} y={ny + 34}
+ textAnchor="middle" fontSize={9}
+ fill={str} opacity={0.85}
>
- {costDisplay
- ? `${durationDisplay} \u2022 ${costDisplay}`
- : durationDisplay}
+ {cost ? `${dur} • ${cost}` : dur}
</text>
</g>
);
diff --git a/src/client/src/components/(playground)/request/group-breadcrumb.tsx b/src/client/src/components/(playground)/request/group-breadcrumb.tsx
new file mode 100644
index 00000000..45ce67c7
--- /dev/null
+++ b/src/client/src/components/(playground)/request/group-breadcrumb.tsx
@@ -0,0 +1,66 @@
+"use client";
+import { ChevronRight, X } from "lucide-react";
+import { getGroupByLabel } from "./grouped-table";
+
+export default function GroupBreadcrumb({
+ groupBy,
+ groupValue,
+ rootLabel = "All Requests",
+ updateFilter,
+}: {
+ groupBy: string;
+ groupValue?: string;
+ rootLabel?: string;
+ updateFilter: (key: string, value: any) => void;
+}) {
+ const groupLabel = getGroupByLabel(groupBy);
+
+ const handleX = () => {
+ if (groupValue) {
+ updateFilter("groupValue", null);
+ } else {
+ updateFilter("groupBy", null);
+ }
+ };
+
+ return (
+ <div className="flex items-center gap-1.5 mb-3 text-xs select-none">
+ <button
+ onClick={() => { updateFilter("groupValue", null); updateFilter("groupBy", null); }}
+ className="text-stone-400 dark:text-stone-500 hover:text-stone-600 dark:hover:text-stone-300 transition-colors"
+ >
+ {rootLabel}
+ </button>
+
+ <ChevronRight className="w-3 h-3 text-stone-300 dark:text-stone-600 shrink-0" />
+
+ {groupValue ? (
+ <button
+ onClick={() => updateFilter("groupValue", null)}
+ className="text-stone-500 dark:text-stone-400 hover:text-stone-700 dark:hover:text-stone-200 transition-colors"
+ >
+ {groupLabel}
+ </button>
+ ) : (
+ <span className="font-medium text-stone-700 dark:text-stone-200">{groupLabel}</span>
+ )}
+
+ {groupValue && (
+ <>
+ <ChevronRight className="w-3 h-3 text-stone-300 dark:text-stone-600 shrink-0" />
+ <span className="font-medium text-stone-700 dark:text-stone-200 truncate max-w-[240px]">
+ {groupValue}
+ </span>
+ </>
+ )}
+
+ <button
+ onClick={handleX}
+ title={groupValue ? "Back to groups" : "Remove grouping"}
+ className="ml-0.5 p-0.5 rounded text-stone-400 hover:text-stone-600 dark:hover:text-stone-200 hover:bg-stone-100 dark:hover:bg-stone-800 transition-colors shrink-0"
+ >
+ <X className="w-3 h-3" />
+ </button>
+ </div>
+ );
+}
diff --git a/src/client/src/components/(playground)/request/grouped-table.tsx b/src/client/src/components/(playground)/request/grouped-table.tsx
new file mode 100644
index 00000000..8fc970a4
--- /dev/null
+++ b/src/client/src/components/(playground)/request/grouped-table.tsx
@@ -0,0 +1,208 @@
+"use client";
+import { useState, useEffect, useCallback } from "react";
+import { ChevronRight } from "lucide-react";
+import { fill } from "lodash";
+import { useRootStore } from "@/store";
+import { getFilterDetails, getUpdateFilter } from "@/selectors/filter";
+import { getPingStatus } from "@/selectors/database-config";
+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
+import { CustomFilter, CustomFilterAttributeType, FilterConfig } from "@/types/store/filter";
+import { PRIMARY_BACKGROUND } from "@/constants/common-classes";
+
+// ─── Shared utilities (also imported by requests/page.tsx) ────────────────────
+
+const PREDEFINED_FILTER_MAP: Record<string, { attributeType: CustomFilterAttributeType; key: string }> = {
+ model: { attributeType: "SpanAttributes", key: "gen_ai.request.model" },
+ provider: { attributeType: "SpanAttributes", key: "gen_ai.system" },
+ spanName: { attributeType: "Field", key: "SpanName" },
+ applicationName: { attributeType: "ResourceAttributes", key: "service.name" },
+};
+
+export const PREDEFINED_LABEL_MAP: Record<string, string> = {
+ model: "Model",
+ provider: "Provider",
+ spanName: "Span Name",
+ applicationName: "Application",
+};
+
+export function getGroupFilterSpec(groupBy: string): { attributeType: CustomFilterAttributeType; key: string } {
+ if (groupBy in PREDEFINED_FILTER_MAP) return PREDEFINED_FILTER_MAP[groupBy];
+ const sep = groupBy.indexOf(":");
+ if (sep === -1) return { attributeType: "SpanAttributes", key: groupBy };
+ const attrType = groupBy.slice(0, sep) as CustomFilterAttributeType;
+ const key = groupBy.slice(sep + 1);
+ return { attributeType: attrType, key };
+}
+
+export function getGroupByLabel(groupBy: string): string {
+ if (groupBy in PREDEFINED_LABEL_MAP) return PREDEFINED_LABEL_MAP[groupBy];
+ const sep = groupBy.indexOf(":");
+ return sep !== -1 ? groupBy.slice(sep + 1) : groupBy;
+}
+
+// Always build via getGroupFilterSpec so the flat-list filter uses the exact same
+// ClickHouse expression as the GROUP BY query (avoids mismatches like the
+// applicationName path which resolves incorrectly through FilterConfig field names).
+export function buildGroupValueFilter(
+ groupBy: string,
+ groupValue: string,
+ currentConfig: Partial<FilterConfig>
+): Partial<FilterConfig> {
+ const filterSpec = getGroupFilterSpec(groupBy);
+ const existing: CustomFilter[] = (currentConfig.customFilters ?? []).filter(
+ (f) => !(f.attributeType === filterSpec.attributeType && f.key === filterSpec.key)
+ );
+ return {
+ ...currentConfig,
+ customFilters: [
+ ...existing,
+ { attributeType: filterSpec.attributeType, key: filterSpec.key, value: groupValue },
+ ],
+ };
+}
+
+// ─── Component internals ──────────────────────────────────────────────────────
+
+interface GroupSummary {
+ group_value: string;
+ count: number;
+ total_cost: number;
+ total_tokens: number;
+ avg_duration_seconds: number;
+}
+
+const GRID_COLS = "grid-cols-[1fr_100px_110px_110px_110px_32px]";
+
+function SkeletonRow() {
+ return (
+ <div className={`grid ${GRID_COLS} w-full animate-pulse border-b dark:border-stone-800`}>
+ {fill(new Array(6), 0).map((_, i) => (
+ <div key={i} className="px-3 py-3.5">
+ <div className="h-2.5 rounded bg-stone-200 dark:bg-stone-700 w-3/4" />
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function GroupRow({
+ group,
+ onClickGroup,
+}: {
+ group: GroupSummary;
+ onClickGroup: (groupValue: string) => void;
+}) {
+ const label = group.group_value || "—";
+ const isEmpty = !group.group_value;
+
+ return (
+ <div
+ className={`grid ${GRID_COLS} w-full border-b dark:border-stone-800 last:border-b-0 text-sm group ${
+ isEmpty ? "opacity-50" : "cursor-pointer hover:bg-stone-50 dark:hover:bg-stone-800/60"
+ }`}
+ onClick={() => !isEmpty && onClickGroup(group.group_value)}
+ >
+ <div className="px-3 py-3 font-medium text-stone-700 dark:text-stone-200 truncate" title={label}>
+ {label}
+ </div>
+ <div className="px-3 py-3 text-right tabular-nums text-stone-600 dark:text-stone-300">
+ {group.count.toLocaleString()}
+ </div>
+ <div className="px-3 py-3 text-right tabular-nums text-stone-600 dark:text-stone-300">
+ {group.total_cost > 0 ? `$${group.total_cost.toFixed(4)}` : "—"}
+ </div>
+ <div className="px-3 py-3 text-right tabular-nums text-stone-600 dark:text-stone-300">
+ {group.total_tokens > 0 ? group.total_tokens.toLocaleString() : "—"}
+ </div>
+ <div className="px-3 py-3 text-right tabular-nums text-stone-600 dark:text-stone-300">
+ {group.avg_duration_seconds > 0 ? `${group.avg_duration_seconds.toFixed(2)}s` : "—"}
+ </div>
+ <div className="px-3 py-3 flex items-center justify-center">
+ {!isEmpty && (
+ <ChevronRight className="w-3.5 h-3.5 text-stone-300 dark:text-stone-600 group-hover:text-stone-500 dark:group-hover:text-stone-400 transition-colors" />
+ )}
+ </div>
+ </div>
+ );
+}
+
+export default function GroupedTable({
+ groupBy,
+ apiUrl = "/api/metrics/request/grouped",
+}: {
+ groupBy: string;
+ apiUrl?: string;
+}) {
+ const filter = useRootStore(getFilterDetails);
+ const updateFilter = useRootStore(getUpdateFilter);
+ const pingStatus = useRootStore(getPingStatus);
+ const { data, fireRequest, isFetched, isLoading } = useFetchWrapper();
+
+ const fetchGroups = useCallback(() => {
+ fireRequest({
+ body: JSON.stringify({ ...filter, groupBy }),
+ requestType: "POST",
+ url: apiUrl,
+ });
+ }, [filter, groupBy, fireRequest, apiUrl]);
+
+ useEffect(() => {
+ // Don't fetch before URL/localStorage params have been applied.
+ // Also skip re-fetching when groupValue changes — the component is about
+ // to unmount as the page transitions to the flat list view.
+ if (
+ filter.filterReady &&
+ !filter.groupValue &&
+ filter.timeLimit.start &&
+ filter.timeLimit.end &&
+ pingStatus === "success"
+ ) {
+ fetchGroups();
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [filter, groupBy, pingStatus]);
+
+ // Clicking a group drills into it — sets groupValue so the page
+ // switches to the filtered flat list with a breadcrumb.
+ const handleGroupClick = useCallback((groupValue: string) => {
+ updateFilter("groupValue", groupValue);
+ }, [updateFilter]);
+
+ const groups: GroupSummary[] = (data as any)?.data ?? [];
+ const groupLabel = getGroupByLabel(groupBy);
+
+ return (
+ <div className={`flex flex-col w-full overflow-auto scrollbar-hidden border dark:border-stone-800 rounded-md grow ${PRIMARY_BACKGROUND}`}>
+ {/* Column header */}
+ <div className={`grid ${GRID_COLS} w-full sticky top-0 z-10 bg-stone-100 dark:bg-stone-900 text-xs font-medium text-stone-500 dark:text-stone-400 border-b dark:border-stone-800`}>
+ <div className="px-3 py-2">{groupLabel}</div>
+ <div className="px-3 py-2 text-right">Spans</div>
+ <div className="px-3 py-2 text-right">Total Cost</div>
+ <div className="px-3 py-2 text-right">Tokens</div>
+ <div className="px-3 py-2 text-right">Avg Duration</div>
+ <div />
+ </div>
+
+ {/* Loading skeleton */}
+ {(!isFetched || (isLoading && !groups.length)) &&
+ fill(new Array(8), 0).map((_, i) => <SkeletonRow key={i} />)
+ }
+
+ {/* Group rows */}
+ {groups.map((group) => (
+ <GroupRow
+ key={group.group_value ?? "__empty__"}
+ group={group}
+ onClickGroup={handleGroupClick}
+ />
+ ))}
+
+ {/* Empty state */}
+ {isFetched && !isLoading && groups.length === 0 && (
+ <div className="flex items-center justify-center py-16 text-sm text-stone-400 dark:text-stone-500">
+ No data found for the selected filters.
+ </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 e11d04c2..464a7c0b 100644
--- a/src/client/src/components/(playground)/request/heirarchy-display.tsx
+++ b/src/client/src/components/(playground)/request/heirarchy-display.tsx
@@ -109,7 +109,7 @@ export default function HeirarchyDisplay() {
<AccordionContent className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down transition-all h-full pb-0" parentClassName="h-full w-full">
<div className="flex flex-col h-full">
{/* View mode tabs — horizontal at the top */}
- <div className="flex items-center gap-1 px-3 py-1.5 border-b border-stone-200 dark:border-stone-800 bg-stone-50 dark:bg-stone-900 shrink-0">
+ <div className="flex items-center gap-1 px-3 py-1.5 border-b border-stone-200 dark:border-stone-800 bg-stone-50 dark:bg-stone-900 shrink-0 z-10">
{VIEW_TABS.map(({ mode, label }) => (
<button
key={mode}
diff --git a/src/client/src/lib/platform/graph-transform.ts b/src/client/src/lib/platform/graph-transform.ts
new file mode 100644
index 00000000..57358f38
--- /dev/null
+++ b/src/client/src/lib/platform/graph-transform.ts
@@ -0,0 +1,289 @@
+/**
+ * Transform an OpenTelemetry span tree into renderable graph nodes and edges.
+ *
+ * Edges model execution flow, not raw parent_id structure:
+ * - parent -> first child is sequential execution entry.
+ * - child siblings are sequential when one wave finishes before the next starts.
+ * - child siblings are parallel when their time windows overlap.
+ */
+
+export interface GraphNode {
+ id: string;
+ spanId: string;
+ spanName: string;
+ timestamp?: string;
+ duration: number;
+ cost?: number;
+ x: number;
+ y: number;
+ depth: number;
+}
+
+export type EdgeKind = "DELEGATED" | "SEQUENTIAL" | "PARALLEL";
+
+export interface GraphEdgeData {
+ from: string;
+ to: string;
+ kind: EdgeKind;
+}
+
+export interface DAG {
+ nodes: Map<string, GraphNode>;
+ edges: GraphEdgeData[];
+}
+
+interface Span {
+ SpanId: string;
+ SpanName: string;
+ Timestamp?: string;
+ Duration: number | string;
+ Cost?: number;
+ children?: Span[];
+}
+
+interface TimedSpan {
+ span: Span;
+ order: number;
+ start: number | null;
+ end: number | null;
+ duration: number;
+}
+
+interface SiblingAnalysis {
+ groups: Span[][];
+ parallelEdges: GraphEdgeData[];
+ sequentialEdges: GraphEdgeData[];
+}
+
+const NODE_WIDTH = 160;
+const X_GAP = 220;
+export const PARALLEL_X_GAP = NODE_WIDTH + 72;
+const V_GAP = 112;
+const EPSILON_MS = 0.001;
+
+function timestampMs(timestamp?: string): number | null {
+ if (!timestamp) return null;
+
+ const ms = Date.parse(timestamp.endsWith("Z") ? timestamp : `${timestamp}Z`);
+ return Number.isFinite(ms) ? ms : null;
+}
+
+function timed(span: Span, order: number): TimedSpan {
+ const start = timestampMs(span.Timestamp);
+ const durationMs = Number(span.Duration || 0) / 1e6;
+ const end = start == null ? null : start + Math.max(0, durationMs);
+
+ return { span, order, start, end, duration: Math.max(0, durationMs) };
+}
+
+function overlaps(a: TimedSpan, b: TimedSpan): boolean {
+ if (a.start == null || a.end == null || b.start == null || b.end == null) {
+ return false;
+ }
+
+ return a.start < b.end - EPSILON_MS && b.start < a.end - EPSILON_MS;
+}
+
+function startsInSameExecutionWindow(a: TimedSpan, b: TimedSpan): boolean {
+ if (a.start == null || b.start == null) return false;
+
+ const startDelta = Math.abs(b.start - a.start);
+ const shortestDuration = Math.min(a.duration, b.duration);
+ const windowMs = Math.max(50, Math.min(1000, shortestDuration * 0.2));
+
+ return startDelta <= windowMs;
+}
+
+function runsInParallel(a: TimedSpan, b: TimedSpan): boolean {
+ return overlaps(a, b) && startsInSameExecutionWindow(a, b);
+}
+
+function sortTimedSiblings(children: Span[]): TimedSpan[] {
+ return children
+ .map(timed)
+ .sort((a, b) => {
+ if (a.start == null && b.start == null) return a.order - b.order;
+ if (a.start == null) return 1;
+ if (b.start == null) return -1;
+ if (a.start !== b.start) return a.start - b.start;
+ return a.order - b.order;
+ });
+}
+
+function pickLatestEnding(group: TimedSpan[]): TimedSpan {
+ return group.reduce((latest, item) => {
+ if (latest.end == null) return item;
+ if (item.end == null) return latest;
+ if (item.end !== latest.end) return item.end > latest.end ? item : latest;
+ return item.order > latest.order ? item : latest;
+ }, group[0]);
+}
+
+function pickEarliestStarting(group: TimedSpan[]): TimedSpan {
+ return group.reduce((earliest, item) => {
+ if (earliest.start == null) return item;
+ if (item.start == null) return earliest;
+ if (item.start !== earliest.start) {
+ return item.start < earliest.start ? item : earliest;
+ }
+ return item.order < earliest.order ? item : earliest;
+ }, group[0]);
+}
+
+function analyzeSiblings(children: Span[] = []): SiblingAnalysis {
+ if (children.length < 2) {
+ return { groups: children.length ? [children] : [], parallelEdges: [], sequentialEdges: [] };
+ }
+
+ const sorted = sortTimedSiblings(children);
+ const timedGroups: TimedSpan[][] = [];
+ let activeGroup: TimedSpan[] = [];
+
+ for (const child of sorted) {
+ const startsInActiveGroup =
+ activeGroup.some((activeChild) => runsInParallel(activeChild, child));
+
+ if (!activeGroup.length || startsInActiveGroup) {
+ activeGroup.push(child);
+ continue;
+ }
+
+ timedGroups.push(activeGroup);
+ activeGroup = [child];
+ }
+
+ if (activeGroup.length) {
+ timedGroups.push(activeGroup);
+ }
+
+ const parallelEdges: GraphEdgeData[] = [];
+ for (const group of timedGroups) {
+ if (group.length < 2) continue;
+
+ for (let i = 0; i < group.length; i++) {
+ for (let j = i + 1; j < group.length; j++) {
+ if (!runsInParallel(group[i], group[j])) continue;
+
+ parallelEdges.push({
+ from: group[i].span.SpanId,
+ to: group[j].span.SpanId,
+ kind: "PARALLEL",
+ });
+ }
+ }
+ }
+
+ const sequentialEdges: GraphEdgeData[] = [];
+ for (let i = 0; i < timedGroups.length - 1; i++) {
+ const from = pickLatestEnding(timedGroups[i]).span.SpanId;
+ const to = pickEarliestStarting(timedGroups[i + 1]).span.SpanId;
+
+ if (from !== to) {
+ sequentialEdges.push({ from, to, kind: "SEQUENTIAL" });
+ }
+ }
+
+ return {
+ groups: timedGroups.map((group) => group.map((child) => child.span)),
+ parallelEdges,
+ sequentialEdges,
+ };
+}
+
+function collectNodesAndEdges(span: Span, nodes: Map<string, GraphNode>, edges: GraphEdgeData[], depth = 0) {
+ nodes.set(span.SpanId, {
+ id: span.SpanId,
+ spanId: span.SpanId,
+ spanName: span.SpanName,
+ timestamp: span.Timestamp,
+ duration: Number(span.Duration || 0),
+ cost: span.Cost,
+ x: 0,
+ y: depth * V_GAP,
+ depth,
+ });
+
+ if (!span.children?.length) return;
+
+ const siblingAnalysis = analyzeSiblings(span.children);
+ const firstGroup = siblingAnalysis.groups[0];
+ if (firstGroup?.length) {
+ edges.push({
+ from: span.SpanId,
+ to: firstGroup[0].SpanId,
+ kind: "SEQUENTIAL",
+ });
+ }
+
+ edges.push(...siblingAnalysis.sequentialEdges, ...siblingAnalysis.parallelEdges);
+
+ for (const child of span.children) {
+ collectNodesAndEdges(child, nodes, edges, depth + 1);
+ }
+}
+
+function layoutVerticalFlow(root: Span, nodes: Map<string, GraphNode>) {
+ function place(span: Span, y: number, x: number): number {
+ const node = nodes.get(span.SpanId);
+ if (node) {
+ node.x = x;
+ node.y = y;
+ }
+
+ if (!span.children?.length) {
+ return y;
+ }
+
+ const analysis = analyzeSiblings(span.children);
+ let nextY = y + V_GAP;
+ let subtreeBottom = y;
+
+ for (const group of analysis.groups) {
+ if (group.length === 1) {
+ subtreeBottom = place(group[0], nextY, x + X_GAP);
+ nextY = subtreeBottom + V_GAP;
+ continue;
+ }
+
+ const startX = x + X_GAP - ((group.length - 1) * PARALLEL_X_GAP) / 2;
+ let groupBottom = nextY;
+ for (let i = 0; i < group.length; i++) {
+ groupBottom = Math.max(
+ groupBottom,
+ place(group[i], nextY, startX + i * PARALLEL_X_GAP)
+ );
+ }
+ subtreeBottom = groupBottom;
+ nextY = groupBottom + V_GAP;
+ }
+
+ return subtreeBottom;
+ }
+
+ place(root, 0, 0);
+}
+
+export function transformTracesToGraph(root: Span): DAG {
+ const nodes = new Map<string, GraphNode>();
+ const edges: GraphEdgeData[] = [];
+
+ collectNodesAndEdges(root, nodes, edges);
+ layoutVerticalFlow(root, nodes);
+
+ return { nodes, edges };
+}
+
+export function getParallelPairs(root: Span): Set<string> {
+ const pairs = new Set<string>();
+
+ function walk(span: Span) {
+ const analysis = analyzeSiblings(span.children);
+ for (const edge of analysis.parallelEdges) {
+ pairs.add([edge.from, edge.to].sort().join("|"));
+ }
+ span.children?.forEach(walk);
+ }
+
+ walk(root);
+ return pairs;
+}
diff --git a/src/client/src/lib/platform/request/index.ts b/src/client/src/lib/platform/request/index.ts
index 9484386d..168738e6 100644
--- a/src/client/src/lib/platform/request/index.ts
+++ b/src/client/src/lib/platform/request/index.ts
@@ -9,6 +9,50 @@ import {
getFilterWhereCondition,
} from "@/helpers/server/platform";
+const PREDEFINED_GROUP_BY: Record<string, string> = {
+ model: `SpanAttributes['gen_ai.request.model']`,
+ provider: `SpanAttributes['gen_ai.system']`,
+ spanName: `SpanName`,
+ applicationName: `ResourceAttributes['service.name']`,
+};
+
+const ALLOWED_FIELD_GROUP_BY = new Set([
+ "TraceId",
+ "ParentSpanId",
+ "TraceState",
+ "SpanId",
+ "SpanName",
+ "SpanKind",
+ "ServiceName",
+ "ScopeName",
+ "ScopeVersion",
+ "Timestamp",
+ "Duration",
+ "StatusCode",
+ "StatusMessage",
+]);
+
+export function getGroupByExpression(groupBy: string): string | null {
+ if (groupBy in PREDEFINED_GROUP_BY) return PREDEFINED_GROUP_BY[groupBy];
+ const sep = groupBy.indexOf(":");
+ if (sep === -1) {
+ const sanitized = groupBy.replace(/'/g, "''").trim();
+ if (!sanitized) return null;
+ return `SpanAttributes['${sanitized}']`;
+ }
+ const attrType = groupBy.slice(0, sep);
+ const key = groupBy.slice(sep + 1).replace(/'/g, "''").trim();
+ if (!key) return null;
+ if (attrType === "ResourceAttributes") return `ResourceAttributes['${key}']`;
+ if (attrType === "Field") {
+ const field = key.replace(/[^A-Za-z0-9_.]/g, "");
+ if (!field || !ALLOWED_FIELD_GROUP_BY.has(field)) return null;
+ return field;
+ }
+ if (attrType === "SpanAttributes") return `SpanAttributes['${key}']`;
+ return `SpanAttributes['${key}']`;
+}
+
export async function getRequestPerTime(params: MetricParams) {
const { start, end } = params.timeLimit;
const dateTrunc = dateTruncGroupingLogic(end as Date, start as Date);
@@ -297,4 +341,27 @@ export async function getAttributeKeys(params: MetricParams) {
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
+}
+
+export async function getGroupedRequests(params: MetricParams, groupBy: string) {
+ const expr = getGroupByExpression(groupBy);
+ if (!expr) {
+ return {
+ err: "Invalid groupBy value",
+ data: [],
+ };
+ }
+ const query = `
+ SELECT
+ ${expr} AS group_value,
+ CAST(COUNT(*) AS INTEGER) AS count,
+ CAST(SUM(toFloat64OrZero(SpanAttributes['gen_ai.usage.cost'])) AS FLOAT) AS total_cost,
+ CAST(SUM(toInt64OrZero(SpanAttributes['gen_ai.usage.total_tokens'])) AS INTEGER) AS total_tokens,
+ CAST(AVG(Duration) * 1e-9 AS FLOAT) AS avg_duration_seconds
+ FROM ${OTEL_TRACES_TABLE_NAME}
+ WHERE ${getFilterWhereCondition(params, true)}
+ GROUP BY group_value
+ ORDER BY count DESC
+ `;
+ return dataCollector({ query });
+}
diff --git a/src/client/src/store/filter.ts b/src/client/src/store/filter.ts
index 647efd96..dde55f42 100644
--- a/src/client/src/store/filter.ts
+++ b/src/client/src/store/filter.ts
@@ -105,6 +105,13 @@ export const filterStoreSlice: FilterStore = lens((setStore, getStore) => ({
case "limit":
case "selectedConfig":
case "sorting":
+ case "groupBy":
+ set(object, "offset", 0);
+ // Changing groupBy always resets the drilled-in groupValue so stale
+ // drill-down filters don't bleed into the new group selection.
+ set(object, "groupValue", null);
+ break;
+ case "groupValue":
set(object, "offset", 0);
break;
case "offset":
diff --git a/src/client/src/types/store/filter.ts b/src/client/src/types/store/filter.ts
index bfd49e75..e168ec83 100644
--- a/src/client/src/types/store/filter.ts
+++ b/src/client/src/types/store/filter.ts
@@ -1,5 +1,6 @@
export type TIME_RANGES = "24H" | "7D" | "1M" | "3M" | "CUSTOM";
export type REFRESH_RATES = "Never" | "30s" | "1m" | "5m" | "15m";
+export type GroupByKey = string;
export type FilterSorting = {
type: string;
@@ -17,6 +18,9 @@ export interface FilterType {
selectedConfig: Partial<FilterConfig>;
sorting: FilterSorting;
refreshRate: REFRESH_RATES;
+ groupBy?: GroupByKey;
+ groupValue?: string;
+ filterReady?: boolean;
}
export type CustomFilterAttributeType = "SpanAttributes" | "ResourceAttributes" | "Field";