Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
Feat: Revamp telemetry data views and trace detail experience (#1200)
Aman Agarwal99ffe9a54606
diff --git a/src/client/src/__tests__/helpers/client/filter-persistence.test.ts b/src/client/src/__tests__/helpers/client/filter-persistence.test.tsnew file mode 100644index 00000000..d82f7a60--- /dev/null+++ b/src/client/src/__tests__/helpers/client/filter-persistence.test.ts@@ -0,0 +1,41 @@+import {+ getFilterStorageKey,+ stripFilterParams,+} from "@/helpers/client/filter-persistence";++describe("filter persistence helpers", () => {+ it("scopes filter storage keys by observability type/page", () => {+ expect(getFilterStorageKey("request")).toBe("openlit_filter_v1:request");+ expect(getFilterStorageKey("metrics")).toBe("openlit_filter_v1:metrics");+ expect(getFilterStorageKey("logs")).toBe("openlit_filter_v1:logs");+ expect(getFilterStorageKey("request")).not.toBe(+ getFilterStorageKey("logs")+ );+ });++ it("keeps the legacy global key when no scope is provided", () => {+ expect(getFilterStorageKey()).toBe("openlit_filter_v1");+ });++ it("strips filter params while preserving non-filter observability params", () => {+ const params = new URLSearchParams({+ tab: "traces",+ selected: "span-1",+ models: "gpt-4o-mini",+ services: "api",+ tr: "7D",+ gb: "serviceName",+ limit: "50",+ });++ stripFilterParams(params);++ expect(params.get("tab")).toBe("traces");+ expect(params.get("selected")).toBe("span-1");+ expect(params.has("models")).toBe(false);+ expect(params.has("services")).toBe(false);+ expect(params.has("tr")).toBe(false);+ expect(params.has("gb")).toBe(false);+ expect(params.has("limit")).toBe(false);+ });+});diff --git a/src/client/src/__tests__/helpers/client/observability-registry.test.ts b/src/client/src/__tests__/helpers/client/observability-registry.test.tsnew file mode 100644index 00000000..0489d00c--- /dev/null+++ b/src/client/src/__tests__/helpers/client/observability-registry.test.ts@@ -0,0 +1,28 @@+import {+ OBSERVABILITY_SIGNALS,+ getSignalConfig,+} from "@/components/(playground)/observability/registry";++describe("observability signal registry", () => {+ it("uses traces as the default signal for embedded monitoring views", () => {+ expect(getSignalConfig(null).key).toBe("traces");+ expect(getSignalConfig(undefined).key).toBe("traces");+ expect(getSignalConfig("unknown").key).toBe("traces");+ });++ it("exposes a renderable traces config for agent monitoring", () => {+ const traces = getSignalConfig("traces");++ expect(traces.key).toBe("traces");+ expect(traces.listUrl).toBe("/api/metrics/request");+ expect(traces.getRowId({ spanId: "span-1" })).toBe("span-1");+ expect(traces.getDetailHref({ spanId: "span-1" }, "/agents/a?tab=monitoring")).toBe(+ "/telemetry/traces/span-1?from=%2Fagents%2Fa%3Ftab%3Dmonitoring"+ );+ });++ it("keeps every signal key unique", () => {+ const keys = OBSERVABILITY_SIGNALS.map((signal) => signal.key);+ expect(new Set(keys).size).toBe(keys.length);+ });+});diff --git a/src/client/src/__tests__/helpers/client/observability.test.ts b/src/client/src/__tests__/helpers/client/observability.test.tsnew file mode 100644index 00000000..080529ad--- /dev/null+++ b/src/client/src/__tests__/helpers/client/observability.test.ts@@ -0,0 +1,48 @@+import { prepareObservabilitySignalChange } from "@/helpers/client/observability";+import { filterStoreSlice } from "@/store/filter";+import { withLenses } from "@dhmk/zustand-lens";+import { create } from "zustand";++const createStore = () => create<any>()(withLenses({ filter: filterStoreSlice }));++describe("prepareObservabilitySignalChange", () => {+ it("clears transient grouping state without clearing selected filters", () => {+ const updateConfig = jest.fn();+ const updateFilter = jest.fn();++ prepareObservabilitySignalChange(updateConfig, updateFilter);++ expect(updateConfig).toHaveBeenCalledWith(undefined);+ expect(updateFilter).toHaveBeenCalledWith("groupBy", null);+ expect(updateFilter).not.toHaveBeenCalledWith(+ "selectedConfig",+ expect.anything(),+ expect.anything()+ );+ expect(updateFilter).not.toHaveBeenCalledWith(+ "selectedConfig",+ expect.anything()+ );+ });++ it("preserves selectedConfig when applied to the filter store", () => {+ const store = createStore();++ store.getState().filter.updateFilter("selectedConfig", {+ models: ["gpt-4o-mini"],+ services: ["api"],+ });+ store.getState().filter.updateFilter("groupBy", "serviceName");++ prepareObservabilitySignalChange(+ store.getState().filter.updateConfig,+ store.getState().filter.updateFilter+ );++ expect(store.getState().filter.details.selectedConfig).toEqual({+ models: ["gpt-4o-mini"],+ services: ["api"],+ });+ expect(store.getState().filter.details.groupBy).toBeNull();+ });+});diff --git a/src/client/src/__tests__/helpers/client/trace.test.ts b/src/client/src/__tests__/helpers/client/trace.test.tsindex 2aaba5f2..bb90cfd9 100644--- a/src/client/src/__tests__/helpers/client/trace.test.ts+++ b/src/client/src/__tests__/helpers/client/trace.test.ts@@ -2,6 +2,7 @@ import {integerParser,floatParser,getTraceMappingKeyFullPath,+ getTraceMappingKeyFullPaths,getExtraTabsContentTypes,getNormalizedTraceAttribute,normalizeTrace,@@ -91,6 +92,26 @@ describe('getTraceMappingKeyFullPath', () => {expect(Array.isArray(result)).toBe(true);});+ it('returns all configured fallback paths for token mappings', () => {+ const result = getTraceMappingKeyFullPaths('promptTokens');+ expect(result).toEqual([+ 'gen_ai.usage.input_tokens',+ 'gen_ai.client.token.usage.input',+ 'input_tokens',+ 'prompt_tokens',+ ]);+ });++ it('returns all configured fallback paths as arrays when requested', () => {+ const result = getTraceMappingKeyFullPaths('completionTokens', true);+ expect(result).toEqual([+ ['gen_ai', 'usage.output_tokens'],+ ['gen_ai', 'client.token.usage.output'],+ ['output_tokens'],+ ['completion_tokens'],+ ]);+ });+describe('array prefix and path branches (runtime-patched TraceMapping)', () => {beforeAll(() => {(TraceMapping as any)[ARRAY_PREFIX_KEY] = {@@ -295,6 +316,35 @@ describe('normalizeTrace', () => {expect(result.completionTokens).toBe(50);});+ it('falls back to direct input_tokens and output_tokens span attributes', () => {+ const trace = {+ SpanId: 'span-direct-tokens',+ Timestamp: '2024-01-15T10:30:00.000Z',+ SpanAttributes: {+ input_tokens: '123',+ output_tokens: '456',+ },+ } as any;++ const result = normalizeTrace(trace);+ expect(result.promptTokens).toBe(123);+ expect(result.completionTokens).toBe(456);+ });++ it('derives totalTokens from prompt and completion tokens when total is missing', () => {+ const trace = {+ SpanId: 'span-derived-total',+ Timestamp: '2024-01-15T10:30:00.000Z',+ SpanAttributes: {+ 'gen_ai.usage.input_tokens': '125',+ 'gen_ai.usage.output_tokens': '75',+ },+ } as any;++ const result = normalizeTrace(trace);+ expect(result.totalTokens).toBe(200);+ });+it('prefers primary token attrs over fallback', () => {const trace = {SpanId: 'span-fb-4',diff --git a/src/client/src/__tests__/lib/platform/observability.test.ts b/src/client/src/__tests__/lib/platform/observability.test.tsnew file mode 100644index 00000000..fe39debc--- /dev/null+++ b/src/client/src/__tests__/lib/platform/observability.test.ts@@ -0,0 +1,206 @@+jest.mock("@/lib/platform/common", () => ({+ OTEL_LOGS_TABLE_NAME: "otel_logs",+ OTEL_TRACES_TABLE_NAME: "otel_traces",+ OTEL_METRICS_GAUGE_TABLE_NAME: "otel_metrics_gauge",+ OTEL_METRICS_SUM_TABLE_NAME: "otel_metrics_sum",+ OTEL_METRICS_HISTOGRAM_TABLE_NAME: "otel_metrics_histogram",+ OTEL_METRICS_SUMMARY_TABLE_NAME: "otel_metrics_summary",+ OTEL_METRICS_EXPONENTIAL_HISTOGRAM_TABLE_NAME:+ "otel_metrics_exponential_histogram",+ dataCollector: jest.fn(),+}));++jest.mock("@/helpers/server/platform", () => ({+ dateTruncGroupingLogic: jest.fn(() => "hour"),+ getFilterWhereCondition: jest.fn(() => "trace_filter = 1"),+}));++import { dataCollector } from "@/lib/platform/common";+import {+ getLogAttributeKeys,+ getLogByRowId,+ getLogs,+ getLogsConfig,+ getMetricAttributeKeys,+ getMetricDetail,+ getMetrics,+ getMetricsConfig,+ getSignalSummary,+} from "@/lib/platform/observability";++const params = {+ timeLimit: {+ type: "24H",+ start: "2026-05-15T00:00:00.000Z",+ end: "2026-05-16T00:00:00.000Z",+ },+ selectedConfig: {},+};++beforeEach(() => {+ jest.clearAllMocks();+ (dataCollector as jest.Mock).mockResolvedValue({ data: [], err: null });+});++describe("observability platform queries", () => {+ it("builds logs config with log filters", async () => {+ await getLogsConfig({+ ...params,+ selectedConfig: {+ services: ["api"],+ severities: ["ERROR"],+ customFilters: [+ {+ attributeType: "LogAttributes",+ key: "session.id",+ value: "abc'123",+ },+ ],+ },+ } as any);++ const query = (dataCollector as jest.Mock).mock.calls[0][0].query;+ expect(query).toContain("FROM otel_logs");+ expect(query).toContain("ServiceName IN ('api')");+ expect(query).toContain("lower(SeverityText) IN ('error')");+ expect(query).toContain("LogAttributes['session.id'] = 'abc\\'123'");+ });++ it("loads log attribute keys from log, resource, and scope maps", async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [{ key: "log.key" }], err: null })+ .mockResolvedValueOnce({ data: [{ key: "resource.key" }], err: null })+ .mockResolvedValueOnce({ data: [{ key: "scope.key" }], err: null });++ const result = await getLogAttributeKeys(params as any);++ expect(result.logAttributeKeys).toEqual(["log.key"]);+ expect(result.resourceAttributeKeys).toEqual(["resource.key"]);+ expect(result.scopeAttributeKeys).toEqual(["scope.key"]);+ expect(dataCollector).toHaveBeenCalledTimes(3);+ });++ it("returns paginated logs and count", async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [{ total: 12 }], err: null })+ .mockResolvedValueOnce({ data: [{ rowId: "1", Body: "hello" }], err: null });++ const result = await getLogs({+ ...params,+ limit: 10,+ offset: 5,+ sorting: { type: "SeverityText", direction: "asc" },+ } as any);++ expect(result.total).toBe(12);+ expect(result.records).toEqual([{ rowId: "1", Body: "hello" }]);+ const query = (dataCollector as jest.Mock).mock.calls[1][0].query;+ expect(query).toContain("ORDER BY SeverityText asc");+ expect(query).toContain("LIMIT 10");+ expect(query).toContain("OFFSET 5");+ });++ it("returns count errors before loading log records", async () => {+ (dataCollector as jest.Mock).mockResolvedValueOnce({ err: "count failed" });++ await expect(getLogs(params as any)).resolves.toEqual({ err: "count failed" });+ expect(dataCollector).toHaveBeenCalledTimes(1);+ });++ it("builds signal summaries for traces, logs, and metrics", async () => {+ (dataCollector as jest.Mock).mockResolvedValue({+ data: [{ label: "05/16 01:00", count: 4 }],+ err: null,+ });++ const trace = await getSignalSummary(params as any, "traces");+ const traceQuery = (dataCollector as jest.Mock).mock.calls[0][0].query;+ const logs = await getSignalSummary(params as any, "logs");+ const logsQuery = (dataCollector as jest.Mock).mock.calls[1][0].query;+ const metrics = await getSignalSummary(params as any, "metrics");+ const metricsQuery = (dataCollector as jest.Mock).mock.calls[2][0].query;++ expect(trace.total).toBe(4);+ expect(traceQuery).toContain("FROM otel_traces");+ expect(logsQuery).toContain("FROM otel_logs");+ expect(metricsQuery).toContain("UNION ALL");+ expect(logs.bucket).toBe("hour");+ expect(metrics.peak).toBe(4);+ });++ it("sanitizes log row ids before lookup", async () => {+ await getLogByRowId("abc123 OR 1=1");++ const query = (dataCollector as jest.Mock).mock.calls[0][0].query;+ expect(query).toContain("= 12311");+ expect(query).not.toContain("OR 1=1");+ });++ it("builds metrics config and metric attribute keys across all metric tables", async () => {+ await getMetricsConfig({+ ...params,+ selectedConfig: { metricTypes: ["gauge"], services: ["api"] },+ } as any);+ expect((dataCollector as jest.Mock).mock.calls[0][0].query).toContain(+ "otel_metrics_gauge"+ );+ expect((dataCollector as jest.Mock).mock.calls[0][0].query).not.toContain(+ "otel_metrics_sum"+ );++ (dataCollector as jest.Mock).mockClear();+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [{ key: "metric.key" }], err: null })+ .mockResolvedValueOnce({ data: [{ key: "resource.key" }], err: null })+ .mockResolvedValueOnce({ data: [{ key: "scope.key" }], err: null });++ const result = await getMetricAttributeKeys(params as any);++ expect(result.metricAttributeKeys).toEqual(["metric.key"]);+ expect(result.resourceAttributeKeys).toEqual(["resource.key"]);+ expect(result.scopeAttributeKeys).toEqual(["scope.key"]);+ });++ it("returns grouped metric rows with a total", async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [{ total: 3 }], err: null })+ .mockResolvedValueOnce({ data: [{ metricName: "cpu", pointCount: 2 }], err: null });++ const result = await getMetrics({+ ...params,+ limit: 20,+ offset: 10,+ selectedConfig: { metricTypes: ["sum"] },+ } as any);++ expect(result.total).toBe(3);+ expect(result.records).toEqual([{ metricName: "cpu", pointCount: 2 }]);+ const query = (dataCollector as jest.Mock).mock.calls[1][0].query;+ expect(query).toContain("GROUP BY MetricName, metric_type, ServiceName");+ expect(query).toContain("LIMIT 20");+ expect(query).toContain("OFFSET 10");+ });++ it("returns metric count errors before loading metric rows", async () => {+ (dataCollector as jest.Mock).mockResolvedValueOnce({ err: "metric count failed" });++ await expect(getMetrics(params as any)).resolves.toEqual({+ err: "metric count failed",+ });+ expect(dataCollector).toHaveBeenCalledTimes(1);+ });++ it("loads metric detail series and latest points with scoped filters", async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [{ request_time: "2026/05/16 01:00", value: 1 }], err: null })+ .mockResolvedValueOnce({ data: [{ MetricName: "cpu.usage", metric_value: 2 }], err: null });++ const result = await getMetricDetail("cpu.usage", "gauge", "api", params as any);++ expect(result.series).toEqual([{ request_time: "2026/05/16 01:00", value: 1 }]);+ expect(result.points).toEqual([{ MetricName: "cpu.usage", metric_value: 2 }]);+ expect((dataCollector as jest.Mock).mock.calls[0][0].query).toContain(+ "MetricName = 'cpu.usage'"+ );+ });+});diff --git a/src/client/src/__tests__/lib/platform/pricing/pricing.test.ts b/src/client/src/__tests__/lib/platform/pricing/pricing.test.tsindex cf2e1fac..c07e5023 100644--- a/src/client/src/__tests__/lib/platform/pricing/pricing.test.ts+++ b/src/client/src/__tests__/lib/platform/pricing/pricing.test.ts@@ -34,6 +34,13 @@ jest.mock('@/helpers/server/trace', () => ({};return map[key] || key;}),+ getTraceMappingKeyFullPaths: jest.fn((key: string) => {+ const map: Record<string, string[]> = {+ promptTokens: ['gen_ai.usage.input_tokens', 'input_tokens', 'prompt_tokens'],+ completionTokens: ['gen_ai.usage.output_tokens', 'output_tokens', 'completion_tokens'],+ };+ return map[key] || [key];+ }),}));jest.mock('@/constants/traces', () => ({SUPPORTED_EVALUATION_OPERATIONS: ['chat'],@@ -145,6 +152,66 @@ describe('setPricingForSpanId', () => {);});+ it('computes cost from direct input and output token attributes', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1' });+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({+ record: {+ SpanId: 'span-1',+ Timestamp: '2026-01-01',+ SpanAttributes: {+ 'gen_ai.system': 'openai',+ 'gen_ai.request.model': 'gpt-4o',+ input_tokens: '300',+ output_tokens: '400',+ },+ },+ });+ (ProviderRegistry.getModel as jest.Mock).mockResolvedValue({+ id: 'gpt-4o',+ inputPricePerMToken: 2.5,+ outputPricePerMToken: 10.0,+ });+ (dataCollector as jest.Mock).mockResolvedValue({ err: null });++ const result = await setPricingForSpanId('span-1');++ expect(result.success).toBe(true);+ expect(result.data!.cost).toBeCloseTo(+ (300 / 1_000_000) * 2.5 + (400 / 1_000_000) * 10.0+ );+ });++ it('keeps canonical gen_ai token attributes ahead of direct fallback keys', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1' });+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({+ record: {+ SpanId: 'span-1',+ Timestamp: '2026-01-01',+ SpanAttributes: {+ 'gen_ai.system': 'openai',+ 'gen_ai.request.model': 'gpt-4o',+ 'gen_ai.usage.input_tokens': '100',+ 'gen_ai.usage.output_tokens': '200',+ input_tokens: '300',+ output_tokens: '400',+ },+ },+ });+ (ProviderRegistry.getModel as jest.Mock).mockResolvedValue({+ id: 'gpt-4o',+ inputPricePerMToken: 2.5,+ outputPricePerMToken: 10.0,+ });+ (dataCollector as jest.Mock).mockResolvedValue({ err: null });++ const result = await setPricingForSpanId('span-1');++ expect(result.success).toBe(true);+ expect(result.data!.cost).toBeCloseTo(+ (100 / 1_000_000) * 2.5 + (200 / 1_000_000) * 10.0+ );+ });+it('returns error when model not found', async () => {(getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1' });(getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: mockTrace });@@ -276,6 +343,49 @@ describe('autoUpdatePricing', () => {);});+ it('auto pricing supports direct token attributes', async () => {+ (getPricingConfigById as jest.Mock).mockResolvedValue({+ id: 'pc-1',+ databaseConfigId: 'db-1',+ });+ (asaw as jest.Mock).mockResolvedValue([null, { id: 'db-1' }]);+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({+ data: [+ {+ SpanId: 'span-1',+ Timestamp: '2026-01-01',+ SpanAttributes: {+ 'gen_ai.system': 'openai',+ 'gen_ai.request.model': 'gpt-4o',+ input_tokens: '100',+ output_tokens: '200',+ },+ },+ ],+ })+ .mockResolvedValueOnce({ err: null });++ (ProviderRegistry.getModel as jest.Mock).mockResolvedValue({+ id: 'gpt-4o',+ inputPricePerMToken: 2.5,+ outputPricePerMToken: 10.0,+ });++ const result = await autoUpdatePricing({+ pricingConfigId: 'pc-1',+ cronId: 'cron-1',+ });++ expect(result.success).toBe(true);+ expect(insertCronLog).toHaveBeenCalledWith(+ expect.objectContaining({+ meta: expect.objectContaining({ totalUpdated: 1 }),+ }),+ 'db-1'+ );+ });+it('returns error when pricing config not found', async () => {(getPricingConfigById as jest.Mock).mockResolvedValue(null);diff --git a/src/client/src/app/(playground)/agents/[agentKey]/page.tsx b/src/client/src/app/(playground)/agents/[agentKey]/page.tsxindex ce0a003c..72f04363 100644--- a/src/client/src/app/(playground)/agents/[agentKey]/page.tsx+++ b/src/client/src/app/(playground)/agents/[agentKey]/page.tsx@@ -45,7 +45,7 @@ const LLMDashboard = dynamic(});const RequestsPage = dynamic(- () => import("@/app/(playground)/requests/page"),+ () => import("@/components/(playground)/agents/agent-monitoring-tab"),{loading: () => <TabLoading label={getMessage().AGENTS_LOADING_REQUESTS} />,ssr: false,diff --git a/src/client/src/app/(playground)/exceptions/page.tsx b/src/client/src/app/(playground)/exceptions/page.tsxindex dad510bf..d3690441 100644--- a/src/client/src/app/(playground)/exceptions/page.tsx+++ b/src/client/src/app/(playground)/exceptions/page.tsx@@ -1,175 +1,6 @@-"use client";-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, getUpdateFilter } from "@/selectors/filter";-import { useRootStore } from "@/store";-import { getPingStatus } from "@/selectors/database-config";-import RequestDetails from "@/components/(playground)/request/request-details";-import { normalizeTrace } from "@/helpers/client/trace";-import DataTable from "@/components/data-table/table";-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, 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- }, []);-- // 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(effectiveFilter),- requestType: "POST",- url: "/api/metrics/exception",- failureCb: (err?: string) => {- toast.error(err || `Cannot connect to server!`, {- id: "exception-page",- });- },- });- }, [effectiveFilter, fireRequest]);-- useEffect(() => {- if (- effectiveFilter.filterReady &&- effectiveFilter.timeLimit.start &&- effectiveFilter.timeLimit.end &&- pingStatus === "success" &&- showFlatList- )- fetchData();- // 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]);-- if (existData === false && !isLoadingExist && isFetchedExist) {- return (- <div className="flex flex-col w-full h-full overflow-auto">- <ExceptionsGettingStarted />- </div>- );- }-- return (- <>- <TracesFilter- total={showFlatList ? totalItems : undefined}- includeOnlySorting={["Timestamp"]}- pageName="exception"- columns={columns}- supportDynamicFilters- />-- {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 />- </>- );-}+import { redirect } from "next/navigation";export default function Page() {- const posthog = usePostHog();-- useEffect(() => {- posthog?.capture(CLIENT_EVENTS.EXCEPTIONS_PAGE_VISITED);- }, []);-- return (- <RequestProvider>- <ExceptionPage />- </RequestProvider>- );+ redirect("/telemetry?tab=exceptions");+ return null;}diff --git a/src/client/src/app/(playground)/observability/exceptions/[id]/page.tsx b/src/client/src/app/(playground)/observability/exceptions/[id]/page.tsxnew file mode 100644index 00000000..c121fc38--- /dev/null+++ b/src/client/src/app/(playground)/observability/exceptions/[id]/page.tsx@@ -0,0 +1,19 @@+import { redirect } from "next/navigation";++export default function ExceptionRedirect({+ params,+ searchParams,+}: {+ params: { id: string };+ searchParams: Record<string, string | string[] | undefined>;+}) {+ const query = new URLSearchParams();+ Object.entries(searchParams).forEach(([key, value]) => {+ if (Array.isArray(value)) {+ value.forEach((item) => query.append(key, item));+ return;+ }+ if (value) query.set(key, value);+ });+ redirect(`/telemetry/exceptions/${params.id}${query.toString() ? `?${query.toString()}` : ""}`);+}diff --git a/src/client/src/app/(playground)/observability/metrics/[name]/page.tsx b/src/client/src/app/(playground)/observability/metrics/[name]/page.tsxnew file mode 100644index 00000000..aad8195f--- /dev/null+++ b/src/client/src/app/(playground)/observability/metrics/[name]/page.tsx@@ -0,0 +1,19 @@+import { redirect } from "next/navigation";++export default function MetricRedirect({+ params,+ searchParams,+}: {+ params: { name: string };+ searchParams: Record<string, string | string[] | undefined>;+}) {+ const query = new URLSearchParams();+ Object.entries(searchParams).forEach(([key, value]) => {+ if (Array.isArray(value)) {+ value.forEach((item) => query.append(key, item));+ return;+ }+ if (value) query.set(key, value);+ });+ redirect(`/telemetry/metrics/${params.name}${query.toString() ? `?${query.toString()}` : ""}`);+}diff --git a/src/client/src/app/(playground)/observability/page.tsx b/src/client/src/app/(playground)/observability/page.tsxnew file mode 100644index 00000000..7ed2d6b4--- /dev/null+++ b/src/client/src/app/(playground)/observability/page.tsx@@ -0,0 +1,17 @@+import { redirect } from "next/navigation";++export default function ObservabilityRedirect({+ searchParams,+}: {+ searchParams: Record<string, string | string[] | undefined>;+}) {+ const params = new URLSearchParams();+ Object.entries(searchParams).forEach(([key, value]) => {+ if (Array.isArray(value)) {+ value.forEach((item) => params.append(key, item));+ return;+ }+ if (value) params.set(key, value);+ });+ redirect(`/telemetry${params.toString() ? `?${params.toString()}` : ""}`);+}diff --git a/src/client/src/app/(playground)/observability/traces/[id]/page.tsx b/src/client/src/app/(playground)/observability/traces/[id]/page.tsxnew file mode 100644index 00000000..f1160842--- /dev/null+++ b/src/client/src/app/(playground)/observability/traces/[id]/page.tsx@@ -0,0 +1,19 @@+import { redirect } from "next/navigation";++export default function TraceRedirect({+ params,+ searchParams,+}: {+ params: { id: string };+ searchParams: Record<string, string | string[] | undefined>;+}) {+ const query = new URLSearchParams();+ Object.entries(searchParams).forEach(([key, value]) => {+ if (Array.isArray(value)) {+ value.forEach((item) => query.append(key, item));+ return;+ }+ if (value) query.set(key, value);+ });+ redirect(`/telemetry/traces/${params.id}${query.toString() ? `?${query.toString()}` : ""}`);+}diff --git a/src/client/src/app/(playground)/requests/page.tsx b/src/client/src/app/(playground)/requests/page.tsxindex 46dd78a0..ed2ff151 100644--- a/src/client/src/app/(playground)/requests/page.tsx+++ b/src/client/src/app/(playground)/requests/page.tsx@@ -1,173 +1,6 @@-"use client";-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";-import { toast } from "sonner";-import { getFilterDetails, getUpdateFilter } from "@/selectors/filter";-import { useRootStore } from "@/store";-import { getPingStatus } from "@/selectors/database-config";-import DataTable from "@/components/data-table/table";-import { columns } from "@/components/(playground)/request/columns";-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";--function RequestPage() {- const [, updateRequest] = useRequest();- const { setItems, setTotal, setOffset, setOnPageChange } = useRequestNavigation();-- const onClick = (item: any) => {- !isLoading && updateRequest(item);- };-- const filter = useRootStore(getFilterDetails);- const updateFilter = useRootStore(getUpdateFilter);- const visibilityColumns = useRootStore((state) =>- getVisibilityColumnsOfPage(state, "request")- );- const pingStatus = useRootStore(getPingStatus);- 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- }, []);-- // 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(effectiveFilter),- requestType: "POST",- url: "/api/metrics/request",- failureCb: (err?: string) => {- toast.error(err || `Cannot connect to server!`, {- id: "request-page",- });- },- });- }, [effectiveFilter, fireRequest]);-- // Show flat list when: no groupBy, OR groupBy + groupValue (drilled in)- const showFlatList = !filter.groupBy || !!filter.groupValue;-- useEffect(() => {- if (- effectiveFilter.filterReady &&- effectiveFilter.timeLimit.start &&- effectiveFilter.timeLimit.end &&- pingStatus === "success" &&- showFlatList- )- fetchData();- // 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]);-- // Register page change callback for detail-panel boundary navigation- useEffect(() => {- setOnPageChange((dir: -1 | 1) => {- updateFilter("offset", filter.offset + dir * filter.limit);- });- return () => setOnPageChange(null);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [filter.offset, filter.limit, updateFilter, setOnPageChange]);-- // Show getting started when there's no trace data AND initial fetch is complete- if (existData === false && !isLoadingExist && isFetchedExist) {- return (- <div className="flex flex-col w-full h-full overflow-auto">- <TracingGettingStarted />- </div>- );- }-- return (- <>- <TracesFilter- total={showFlatList ? (data as any)?.total : undefined}- supportDynamicFilters- pageName="request"- columns={columns}- />-- {/* 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 />- </>- );-}+import { redirect } from "next/navigation";export default function Page() {- const posthog = usePostHog();-- useEffect(() => {- posthog?.capture(CLIENT_EVENTS.REQUESTS_PAGE_VISITED);- }, []);-- return (- <RequestProvider>- <RequestPage />- </RequestProvider>- );+ redirect("/telemetry?tab=traces");+ return null;}diff --git a/src/client/src/app/(playground)/telemetry/exceptions/[id]/page.tsx b/src/client/src/app/(playground)/telemetry/exceptions/[id]/page.tsxnew file mode 100644index 00000000..51d8e628--- /dev/null+++ b/src/client/src/app/(playground)/telemetry/exceptions/[id]/page.tsx@@ -0,0 +1,5 @@+import TraceDetailPage from "@/components/(playground)/observability/trace-detail-page";++export default function Page({ params }: { params: { id: string } }) {+ return <TraceDetailPage spanId={params.id} type="exceptions" />;+}diff --git a/src/client/src/app/(playground)/telemetry/metrics/[name]/page.tsx b/src/client/src/app/(playground)/telemetry/metrics/[name]/page.tsxnew file mode 100644index 00000000..2354705f--- /dev/null+++ b/src/client/src/app/(playground)/telemetry/metrics/[name]/page.tsx@@ -0,0 +1,5 @@+import MetricDetailPage from "@/components/(playground)/observability/metric-detail-page";++export default function Page({ params }: { params: { name: string } }) {+ return <MetricDetailPage name={decodeURIComponent(params.name)} />;+}diff --git a/src/client/src/app/(playground)/telemetry/page.tsx b/src/client/src/app/(playground)/telemetry/page.tsxnew file mode 100644index 00000000..1388d141--- /dev/null+++ b/src/client/src/app/(playground)/telemetry/page.tsx@@ -0,0 +1,87 @@+"use client";++import { useEffect } from "react";+import { useRouter, useSearchParams } from "next/navigation";+import ObservabilitySignalList from "@/components/(playground)/observability/signal-list";+import {+ OBSERVABILITY_SIGNALS,+ getSignalConfig,+} from "@/components/(playground)/observability/registry";+import { usePostHog } from "posthog-js/react";+import { stripFilterParams } from "@/helpers/client/filter-persistence";+import { prepareObservabilitySignalChange } from "@/helpers/client/observability";+import { getUpdateConfig, getUpdateFilter } from "@/selectors/filter";+import { useRootStore } from "@/store";++export default function TelemetryPage() {+ const searchParams = useSearchParams();+ const router = useRouter();+ const posthog = usePostHog();+ const updateConfig = useRootStore(getUpdateConfig);+ const updateFilter = useRootStore(getUpdateFilter);+ const activeTab = searchParams.get("tab") || "traces";+ const activeConfig = getSignalConfig(activeTab);+ const ActiveIcon = activeConfig.icon;++ useEffect(() => {+ posthog?.capture("OBSERVABILITY_PAGE_VISITED", {+ tab: activeConfig.key,+ });+ }, [activeConfig.key, posthog]);++ const onTabChange = (value: string) => {+ prepareObservabilitySignalChange(updateConfig, updateFilter);+ const params = new URLSearchParams(searchParams.toString());+ stripFilterParams(params);+ params.set("tab", value);+ params.delete("selected");+ router.replace(`/telemetry?${params.toString()}`, { scroll: false });+ };++ return (+ <div className="flex h-full w-full flex-col gap-4 overflow-hidden">+ <section className="rounded-md border border-stone-200 bg-white px-3 py-2 dark:border-stone-800 dark:bg-stone-950">+ <div className="flex flex-col gap-2 xl:flex-row xl:items-center xl:justify-between">+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <span className={`rounded-md border p-1.5 ${activeConfig.tone}`}>+ <ActiveIcon className="h-4 w-4" />+ </span>+ <div>+ <p className="text-[11px] uppercase tracking-wide text-stone-500 dark:text-stone-400">+ Telemetry+ </p>+ <h1 className="text-base font-semibold text-stone-950 dark:text-stone-50">+ {activeConfig.label}+ </h1>+ </div>+ </div>+ </div>+ <div className="grid grid-cols-2 gap-2 md:flex md:flex-wrap md:justify-end">+ {OBSERVABILITY_SIGNALS.map((signal) => {+ const Icon = signal.icon;+ const isActive = signal.key === activeConfig.key;+ return (+ <button+ key={signal.key}+ onClick={() => onTabChange(signal.key)}+ className={`inline-flex items-center gap-2 rounded-md border px-2.5 py-1.5 text-xs transition ${+ isActive+ ? signal.tone+ : "border-stone-200 bg-stone-50 text-stone-600 hover:bg-stone-100 dark:border-stone-800 dark:bg-stone-900 dark:text-stone-300 dark:hover:bg-stone-800"+ }`}+ >+ <Icon className="h-4 w-4" />+ <span className="font-medium">{signal.label}</span>+ </button>+ );+ })}+ </div>+ </div>+ </section>+ <section className="min-h-0 flex-1 overflow-auto rounded-md border border-stone-200 bg-white p-4 dark:border-stone-800 dark:bg-stone-950">+ <ObservabilitySignalList key={activeConfig.key} config={activeConfig} />+ </section>+ </div>+ );+}diff --git a/src/client/src/app/(playground)/telemetry/traces/[id]/page.tsx b/src/client/src/app/(playground)/telemetry/traces/[id]/page.tsxnew file mode 100644index 00000000..106f264a--- /dev/null+++ b/src/client/src/app/(playground)/telemetry/traces/[id]/page.tsx@@ -0,0 +1,5 @@+import TraceDetailPage from "@/components/(playground)/observability/trace-detail-page";++export default function Page({ params }: { params: { id: string } }) {+ return <TraceDetailPage spanId={params.id} type="traces" />;+}diff --git a/src/client/src/app/api/observability/metrics/[name]/route.ts b/src/client/src/app/api/observability/metrics/[name]/route.tsnew file mode 100644index 00000000..1b2968ba--- /dev/null+++ b/src/client/src/app/api/observability/metrics/[name]/route.ts@@ -0,0 +1,20 @@+import { MetricParams, TimeLimit } from "@/lib/platform/common";+import { getMetricDetail } from "@/lib/platform/observability";++export async function POST(+ request: Request,+ { params }: { params: { name: string } }+) {+ const formData = await request.json();+ const metricName = decodeURIComponent(params.name);+ const metricType = formData.metricType as string | undefined;+ const serviceName = formData.serviceName as string | undefined;+ const metricParams: MetricParams = {+ timeLimit: formData.timeLimit as TimeLimit,+ selectedConfig: formData.selectedConfig || {},+ };++ return Response.json(+ await getMetricDetail(metricName, metricType, serviceName, metricParams)+ );+}diff --git a/src/client/src/app/api/observability/metrics/attribute-keys/route.ts b/src/client/src/app/api/observability/metrics/attribute-keys/route.tsnew file mode 100644index 00000000..935d2690--- /dev/null+++ b/src/client/src/app/api/observability/metrics/attribute-keys/route.ts@@ -0,0 +1,20 @@+import { MetricParams, TimeLimit } from "@/lib/platform/common";+import { getMetricAttributeKeys } from "@/lib/platform/observability";+import {+ validateMetricsRequest,+ validateMetricsRequestType,+} from "@/helpers/server/platform";++export async function POST(request: Request) {+ const formData = await request.json();+ const params: MetricParams = {+ timeLimit: formData.timeLimit as TimeLimit,+ };+ const validation = validateMetricsRequest(+ params,+ validateMetricsRequestType.GET_ALL+ );+ if (!validation.success) return Response.json(validation.err, { status: 400 });++ return Response.json(await getMetricAttributeKeys(params));+}diff --git a/src/client/src/app/api/observability/metrics/config/route.ts b/src/client/src/app/api/observability/metrics/config/route.tsnew file mode 100644index 00000000..754b0d1a--- /dev/null+++ b/src/client/src/app/api/observability/metrics/config/route.ts@@ -0,0 +1,20 @@+import { MetricParams, TimeLimit } from "@/lib/platform/common";+import { getMetricsConfig } from "@/lib/platform/observability";+import {+ validateMetricsRequest,+ validateMetricsRequestType,+} from "@/helpers/server/platform";++export async function POST(request: Request) {+ const formData = await request.json();+ const params: MetricParams = {+ timeLimit: formData.timeLimit as TimeLimit,+ };+ const validation = validateMetricsRequest(+ params,+ validateMetricsRequestType.GET_ALL+ );+ if (!validation.success) return Response.json(validation.err, { status: 400 });++ return Response.json(await getMetricsConfig(params));+}diff --git a/src/client/src/app/api/observability/metrics/route.ts b/src/client/src/app/api/observability/metrics/route.tsnew file mode 100644index 00000000..8b4d91dc--- /dev/null+++ b/src/client/src/app/api/observability/metrics/route.ts@@ -0,0 +1,24 @@+import { MetricParams, TimeLimit } from "@/lib/platform/common";+import { getMetrics } from "@/lib/platform/observability";+import {+ validateMetricsRequest,+ validateMetricsRequestType,+} from "@/helpers/server/platform";++export async function POST(request: Request) {+ const formData = await request.json();+ const params: MetricParams = {+ timeLimit: formData.timeLimit as TimeLimit,+ limit: formData.limit || 25,+ offset: formData.offset || 0,+ selectedConfig: formData.selectedConfig || {},+ sorting: formData.sorting || {},+ };+ const validation = validateMetricsRequest(+ params,+ validateMetricsRequestType.GET_ALL+ );+ if (!validation.success) return Response.json(validation.err, { status: 400 });++ return Response.json(await getMetrics(params));+}diff --git a/src/client/src/app/api/observability/summary/[signal]/route.ts b/src/client/src/app/api/observability/summary/[signal]/route.tsnew file mode 100644index 00000000..d48eb17c--- /dev/null+++ b/src/client/src/app/api/observability/summary/[signal]/route.ts@@ -0,0 +1,36 @@+import { MetricParams, TimeLimit } from "@/lib/platform/common";+import { getSignalSummary } from "@/lib/platform/observability";+import {+ validateMetricsRequest,+ validateMetricsRequestType,+} from "@/helpers/server/platform";++const VALID_SIGNALS = new Set(["traces", "exceptions", "logs", "metrics"]);++export async function POST(+ request: Request,+ { params }: { params: { signal: string } }+) {+ if (!VALID_SIGNALS.has(params.signal)) {+ return Response.json({ err: "Invalid signal" }, { status: 400 });+ }++ const formData = await request.json();+ const metricParams: MetricParams = {+ timeLimit: formData.timeLimit as TimeLimit,+ selectedConfig: formData.selectedConfig || {},+ };++ const validation = validateMetricsRequest(+ metricParams,+ validateMetricsRequestType.GET_ALL+ );+ if (!validation.success) return Response.json(validation.err, { status: 400 });++ return Response.json(+ await getSignalSummary(+ metricParams,+ params.signal as "traces" | "exceptions" | "logs" | "metrics"+ )+ );+}diff --git a/src/client/src/app/api/telemetry/metrics/[name]/route.ts b/src/client/src/app/api/telemetry/metrics/[name]/route.tsnew file mode 100644index 00000000..1b2968ba--- /dev/null+++ b/src/client/src/app/api/telemetry/metrics/[name]/route.ts@@ -0,0 +1,20 @@+import { MetricParams, TimeLimit } from "@/lib/platform/common";+import { getMetricDetail } from "@/lib/platform/observability";++export async function POST(+ request: Request,+ { params }: { params: { name: string } }+) {+ const formData = await request.json();+ const metricName = decodeURIComponent(params.name);+ const metricType = formData.metricType as string | undefined;+ const serviceName = formData.serviceName as string | undefined;+ const metricParams: MetricParams = {+ timeLimit: formData.timeLimit as TimeLimit,+ selectedConfig: formData.selectedConfig || {},+ };++ return Response.json(+ await getMetricDetail(metricName, metricType, serviceName, metricParams)+ );+}diff --git a/src/client/src/app/api/telemetry/metrics/attribute-keys/route.ts b/src/client/src/app/api/telemetry/metrics/attribute-keys/route.tsnew file mode 100644index 00000000..935d2690--- /dev/null+++ b/src/client/src/app/api/telemetry/metrics/attribute-keys/route.ts@@ -0,0 +1,20 @@+import { MetricParams, TimeLimit } from "@/lib/platform/common";+import { getMetricAttributeKeys } from "@/lib/platform/observability";+import {+ validateMetricsRequest,+ validateMetricsRequestType,+} from "@/helpers/server/platform";++export async function POST(request: Request) {+ const formData = await request.json();+ const params: MetricParams = {+ timeLimit: formData.timeLimit as TimeLimit,+ };+ const validation = validateMetricsRequest(+ params,+ validateMetricsRequestType.GET_ALL+ );+ if (!validation.success) return Response.json(validation.err, { status: 400 });++ return Response.json(await getMetricAttributeKeys(params));+}diff --git a/src/client/src/app/api/telemetry/metrics/config/route.ts b/src/client/src/app/api/telemetry/metrics/config/route.tsnew file mode 100644index 00000000..754b0d1a--- /dev/null+++ b/src/client/src/app/api/telemetry/metrics/config/route.ts@@ -0,0 +1,20 @@+import { MetricParams, TimeLimit } from "@/lib/platform/common";+import { getMetricsConfig } from "@/lib/platform/observability";+import {+ validateMetricsRequest,+ validateMetricsRequestType,+} from "@/helpers/server/platform";++export async function POST(request: Request) {+ const formData = await request.json();+ const params: MetricParams = {+ timeLimit: formData.timeLimit as TimeLimit,+ };+ const validation = validateMetricsRequest(+ params,+ validateMetricsRequestType.GET_ALL+ );+ if (!validation.success) return Response.json(validation.err, { status: 400 });++ return Response.json(await getMetricsConfig(params));+}diff --git a/src/client/src/app/api/telemetry/metrics/route.ts b/src/client/src/app/api/telemetry/metrics/route.tsnew file mode 100644index 00000000..8b4d91dc--- /dev/null+++ b/src/client/src/app/api/telemetry/metrics/route.ts@@ -0,0 +1,24 @@+import { MetricParams, TimeLimit } from "@/lib/platform/common";+import { getMetrics } from "@/lib/platform/observability";+import {+ validateMetricsRequest,+ validateMetricsRequestType,+} from "@/helpers/server/platform";++export async function POST(request: Request) {+ const formData = await request.json();+ const params: MetricParams = {+ timeLimit: formData.timeLimit as TimeLimit,+ limit: formData.limit || 25,+ offset: formData.offset || 0,+ selectedConfig: formData.selectedConfig || {},+ sorting: formData.sorting || {},+ };+ const validation = validateMetricsRequest(+ params,+ validateMetricsRequestType.GET_ALL+ );+ if (!validation.success) return Response.json(validation.err, { status: 400 });++ return Response.json(await getMetrics(params));+}diff --git a/src/client/src/app/api/telemetry/summary/[signal]/route.ts b/src/client/src/app/api/telemetry/summary/[signal]/route.tsnew file mode 100644index 00000000..d48eb17c--- /dev/null+++ b/src/client/src/app/api/telemetry/summary/[signal]/route.ts@@ -0,0 +1,36 @@+import { MetricParams, TimeLimit } from "@/lib/platform/common";+import { getSignalSummary } from "@/lib/platform/observability";+import {+ validateMetricsRequest,+ validateMetricsRequestType,+} from "@/helpers/server/platform";++const VALID_SIGNALS = new Set(["traces", "exceptions", "logs", "metrics"]);++export async function POST(+ request: Request,+ { params }: { params: { signal: string } }+) {+ if (!VALID_SIGNALS.has(params.signal)) {+ return Response.json({ err: "Invalid signal" }, { status: 400 });+ }++ const formData = await request.json();+ const metricParams: MetricParams = {+ timeLimit: formData.timeLimit as TimeLimit,+ selectedConfig: formData.selectedConfig || {},+ };++ const validation = validateMetricsRequest(+ metricParams,+ validateMetricsRequestType.GET_ALL+ );+ if (!validation.success) return Response.json(validation.err, { status: 400 });++ return Response.json(+ await getSignalSummary(+ metricParams,+ params.signal as "traces" | "exceptions" | "logs" | "metrics"+ )+ );+}diff --git a/src/client/src/components/(playground)/agents/agent-monitoring-tab.tsx b/src/client/src/components/(playground)/agents/agent-monitoring-tab.tsxnew file mode 100644index 00000000..c9cc0898--- /dev/null+++ b/src/client/src/components/(playground)/agents/agent-monitoring-tab.tsx@@ -0,0 +1,8 @@+"use client";++import ObservabilitySignalList from "@/components/(playground)/observability/signal-list";+import { getSignalConfig } from "@/components/(playground)/observability/registry";++export default function AgentMonitoringTab() {+ return <ObservabilitySignalList config={getSignalConfig("traces")} />;+}diff --git a/src/client/src/components/(playground)/chat/chat-floating-button.tsx b/src/client/src/components/(playground)/chat/chat-floating-button.tsxindex 11df4e5a..2eeb48ea 100644--- a/src/client/src/components/(playground)/chat/chat-floating-button.tsx+++ b/src/client/src/components/(playground)/chat/chat-floating-button.tsx@@ -41,7 +41,7 @@ export default function ChatFloatingButton() {<TooltipTrigger asChild><Link href="/chat"><button- aria-label="Open Otter chat"+ aria-label="Open Otter"className="relative flex items-center justify-center h-14 w-14 rounded-full bg-white dark:bg-stone-300 border border-stone-200 dark:border-stone-700 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 transition-all duration-200 group"><Otter className="transition-transform group-hover:rotate-6 text-stone-700" />diff --git a/src/client/src/components/(playground)/clickhouse-connectivity-wrapper.tsx b/src/client/src/components/(playground)/clickhouse-connectivity-wrapper.tsxindex 7c07da88..c3d075e5 100644--- a/src/client/src/components/(playground)/clickhouse-connectivity-wrapper.tsx+++ b/src/client/src/components/(playground)/clickhouse-connectivity-wrapper.tsx@@ -8,7 +8,7 @@ import { usePathname } from "next/navigation";import { useEffect } from "react";import Loader from "../common/loader";-const ALLOWED_CONNECTIVITY_ALERT = /^\/home$|^\/dashboard$|^\/requests$|^\/exceptions$|^\/d\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$|^\/prompt-hub$|^\/vault$|^\/dashboards/;+const ALLOWED_CONNECTIVITY_ALERT = /^\/home$|^\/dashboard$|^\/telemetry(?:\/.*)?$|^\/observability(?:\/.*)?$|^\/requests$|^\/exceptions$|^\/d\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$|^\/prompt-hub$|^\/vault$|^\/dashboards/;export default function ClickhouseConnectivityWrapper({ children }: { children: React.ReactNode }) {const pingDetails = useRootStore(getPingDetails);diff --git a/src/client/src/components/(playground)/filter/refresh-rate.tsx b/src/client/src/components/(playground)/filter/refresh-rate.tsxindex a28e09a2..56ba4b5d 100644--- a/src/client/src/components/(playground)/filter/refresh-rate.tsx+++ b/src/client/src/components/(playground)/filter/refresh-rate.tsx@@ -12,7 +12,7 @@ import { Button } from "@/components/ui/button";const REFRESH_RATE_EVENT = "refresh-rate";const PAGES_ENABLED_FOR_REFRESH_RATE =- /^\/home$|^\/dashboard$|^\/requests$|^\/exceptions$|^\/agents(?:\/.*)?$|^\/d\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;+ /^\/home$|^\/dashboard$|^\/telemetry(?:\/.*)?$|^\/observability(?:\/.*)?$|^\/requests$|^\/exceptions$|^\/agents(?:\/.*)?$|^\/d\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;const refreshTimes = {[REFRESH_RATE_TYPE["30s"]]: 30 * 1000,diff --git a/src/client/src/components/(playground)/filter/traces-filter.tsx b/src/client/src/components/(playground)/filter/traces-filter.tsxindex cc824109..a4ca5c70 100644--- a/src/client/src/components/(playground)/filter/traces-filter.tsx+++ b/src/client/src/components/(playground)/filter/traces-filter.tsx@@ -38,6 +38,13 @@ import VisibilityColumns from "./visibility-columns";import { PAGE } from "@/types/store/page";import { Columns } from "@/components/data-table/columns";import { useRouter, usePathname } from "next/navigation";+import getMessage from "@/constants/messages";+import {+ FILTER_PARAM_KEYS,+ getFilterStorageKey,+} from "@/helpers/client/filter-persistence";++const m = getMessage();// ─── Combobox (text input + inline dropdown, portal-rendered to escape overflow) ───@@ -154,6 +161,10 @@ function configToParams(config: Partial<FilterConfig>, params: URLSearchParams)params.delete("spanNames");params.delete("envs");params.delete("maxCost");+ params.delete("services");+ params.delete("severities");+ params.delete("metricNames");+ params.delete("metricTypes");// remove all existing cf entriesparams.delete("cf");@@ -164,6 +175,10 @@ function configToParams(config: Partial<FilterConfig>, params: URLSearchParams)if (config.spanNames?.length) params.set("spanNames", config.spanNames.join(","));if (config.environments?.length) params.set("envs", config.environments.join(","));if (config.maxCost) params.set("maxCost", String(config.maxCost));+ if (config.services?.length) params.set("services", config.services.join(","));+ if (config.severities?.length) params.set("severities", config.severities.join(","));+ if (config.metricNames?.length) params.set("metricNames", config.metricNames.join(","));+ if (config.metricTypes?.length) params.set("metricTypes", config.metricTypes.join(","));config.customFilters?.forEach(({ attributeType, key, value }) => {if (key && value) {params.append("cf", [attributeType, key, value].join(CF_SEP));@@ -187,6 +202,14 @@ function paramsToConfig(params: URLSearchParams): Partial<FilterConfig> {if (envs) config.environments = envs.split(",").filter(Boolean);const maxCost = params.get("maxCost");if (maxCost) config.maxCost = parseFloat(maxCost);+ const services = params.get("services");+ if (services) config.services = services.split(",").filter(Boolean);+ const severities = params.get("severities");+ if (severities) config.severities = severities.split(",").filter(Boolean);+ const metricNames = params.get("metricNames");+ if (metricNames) config.metricNames = metricNames.split(",").filter(Boolean);+ const metricTypes = params.get("metricTypes");+ if (metricTypes) config.metricTypes = metricTypes.split(",").filter(Boolean);const cfValues = params.getAll("cf");if (cfValues.length) {config.customFilters = cfValues.map((raw) => {@@ -215,10 +238,16 @@ const DynamicFilters = ({isVisibleFilters,filter,areFiltersApplied,+ configUrl,+ attributeKeysUrl,+ customAttributeTypes,}: {isVisibleFilters: boolean;filter: FilterType;areFiltersApplied: boolean;+ configUrl: string;+ attributeKeysUrl: string;+ customAttributeTypes: CustomFilterAttributeType[];}) => {const posthog = usePostHog();const filterConfig = useRootStore(getFilterConfig);@@ -260,6 +289,10 @@ const DynamicFilters = ({case "applicationNames":case "spanNames":case "environments":+ case "services":+ case "severities":+ case "metricNames":+ case "metricTypes":if (operationType === "add") {setSelectedFilterValues((s) => {const typeArray = s[type] || [];@@ -283,7 +316,7 @@ const DynamicFilters = ({const addCustomFilter = () => {setCustomFilters((prev) => [...prev,- { attributeType: "SpanAttributes", key: "", value: "" },+ { attributeType: customAttributeTypes[0] ?? "Field", key: "", value: "" },]);};@@ -314,7 +347,7 @@ const DynamicFilters = ({fireRequest({body: JSON.stringify({ timeLimit }),requestType: "POST",- url: "/api/metrics/request/config",+ url: configUrl,successCb: (resp) => {updateConfig(resp.data?.[0]);},@@ -325,7 +358,7 @@ const DynamicFilters = ({},});// eslint-disable-next-line react-hooks/exhaustive-deps- }, []);+ }, [configUrl]);// Fetch filter config when time window changes or config is cleared after a range change.useEffect(() => {@@ -344,12 +377,15 @@ const DynamicFilters = ({fireAttrKeysRequest({body: JSON.stringify({ timeLimit }),requestType: "POST",- url: "/api/metrics/request/attribute-keys",+ url: attributeKeysUrl,successCb: (resp) => {if (resp?.spanAttributeKeys !== undefined) {updateAttributeKeys({spanAttributeKeys: resp.spanAttributeKeys,resourceAttributeKeys: resp.resourceAttributeKeys,+ logAttributeKeys: resp.logAttributeKeys,+ scopeAttributeKeys: resp.scopeAttributeKeys,+ metricAttributeKeys: resp.metricAttributeKeys,} as AttributeKeys);}},@@ -358,7 +394,7 @@ const DynamicFilters = ({},});// eslint-disable-next-line react-hooks/exhaustive-deps- }, []);+ }, [attributeKeysUrl]);// Fetch attribute keys whenever the time window changes.// Use leaf primitives as deps – lodash merge mutates timeLimit in-place@@ -391,6 +427,40 @@ const DynamicFilters = ({updateFilter("selectedConfig", {}, { clearFilter: true });};+ const getAttributeOptions = (attributeType: CustomFilterAttributeType) => {+ switch (attributeType) {+ case "SpanAttributes":+ return attributeKeys?.spanAttributeKeys ?? [];+ case "ResourceAttributes":+ return attributeKeys?.resourceAttributeKeys ?? [];+ case "LogAttributes":+ return attributeKeys?.logAttributeKeys ?? [];+ case "ScopeAttributes":+ return attributeKeys?.scopeAttributeKeys ?? [];+ case "Attributes":+ return attributeKeys?.metricAttributeKeys ?? [];+ default:+ return [];+ }+ };++ const getAttributeTypeLabel = (attributeType: CustomFilterAttributeType) => {+ switch (attributeType) {+ case "SpanAttributes":+ return m.OBSERVABILITY_SPAN_ATTRIBUTES;+ case "ResourceAttributes":+ return m.OBSERVABILITY_RESOURCE_ATTRIBUTES;+ case "LogAttributes":+ return m.OBSERVABILITY_LOG_ATTRIBUTES;+ case "ScopeAttributes":+ return m.OBSERVABILITY_SCOPE_ATTRIBUTES;+ case "Attributes":+ return m.OBSERVABILITY_METRIC_ATTRIBUTES;+ case "Field":+ return m.OBSERVABILITY_FIELD;+ }+ };+return (<divclassName={`flex flex-col w-full overflow-hidden transition-all gap-3 ${@@ -406,7 +476,7 @@ const DynamicFilters = ({label: p,value: p,}))}- title="Types"+ title={m.OBSERVABILITY_TYPES}type="traceTypes"updateSelectedValues={updateSelectedValues}selectedValues={selectedFilterValues.traceTypes}@@ -416,7 +486,7 @@ const DynamicFilters = ({{filterConfig?.models?.length ? (<ComboDropdownoptions={filterConfig?.models.map((m) => ({ label: m, value: m }))}- title="Models"+ title={m.OBSERVABILITY_MODELS}type="models"updateSelectedValues={updateSelectedValues}selectedValues={selectedFilterValues.models}@@ -429,7 +499,7 @@ const DynamicFilters = ({label: p,value: p,}))}- title="Providers"+ title={m.OBSERVABILITY_PROVIDERS}type="providers"updateSelectedValues={updateSelectedValues}selectedValues={selectedFilterValues.providers}@@ -438,7 +508,7 @@ const DynamicFilters = ({) : null}{filterConfig?.maxCost ? (<SlideWithValue- label="Max Cost"+ label={m.OBSERVABILITY_MAX_COST}value={selectedFilterValues.maxCost || 0}maxValue={filterConfig.maxCost}onChange={updateSelectedValues}@@ -451,7 +521,7 @@ const DynamicFilters = ({label: a,value: a,}))}- title="Application Names"+ title={m.OBSERVABILITY_APPLICATION_NAMES}type="applicationNames"updateSelectedValues={updateSelectedValues}selectedValues={selectedFilterValues.applicationNames}@@ -464,7 +534,7 @@ const DynamicFilters = ({label: s,value: s,}))}- title="Span Names"+ title={m.OBSERVABILITY_SPAN_NAMES}type="spanNames"updateSelectedValues={updateSelectedValues}selectedValues={selectedFilterValues.spanNames}@@ -477,13 +547,65 @@ const DynamicFilters = ({label: e,value: e,}))}- title="Environments"+ title={m.OBSERVABILITY_ENVIRONMENTS}type="environments"updateSelectedValues={updateSelectedValues}selectedValues={selectedFilterValues.environments}clearItem={clearFilter}/>) : null}+ {filterConfig?.services?.length ? (+ <ComboDropdown+ options={filterConfig.services.map((service) => ({+ label: service,+ value: service,+ }))}+ title={m.OBSERVABILITY_SERVICES}+ type="services"+ updateSelectedValues={updateSelectedValues}+ selectedValues={selectedFilterValues.services}+ clearItem={clearFilter}+ />+ ) : null}+ {filterConfig?.severities?.length ? (+ <ComboDropdown+ options={filterConfig.severities.map((severity) => ({+ label: severity,+ value: severity,+ }))}+ title={m.OBSERVABILITY_SEVERITIES}+ type="severities"+ updateSelectedValues={updateSelectedValues}+ selectedValues={selectedFilterValues.severities}+ clearItem={clearFilter}+ />+ ) : null}+ {filterConfig?.metricNames?.length ? (+ <ComboDropdown+ options={filterConfig.metricNames.map((metricName) => ({+ label: metricName,+ value: metricName,+ }))}+ title={m.OBSERVABILITY_METRIC_NAMES}+ type="metricNames"+ updateSelectedValues={updateSelectedValues}+ selectedValues={selectedFilterValues.metricNames}+ clearItem={clearFilter}+ />+ ) : null}+ {filterConfig?.metricTypes?.length ? (+ <ComboDropdown+ options={filterConfig.metricTypes.map((metricType) => ({+ label: metricType,+ value: metricType,+ }))}+ title={m.OBSERVABILITY_METRIC_TYPES}+ type="metricTypes"+ updateSelectedValues={updateSelectedValues}+ selectedValues={selectedFilterValues.metricTypes}+ clearItem={clearFilter}+ />+ ) : null}</div><div className="flex shrink-0 gap-3">{areFiltersApplied && (@@ -520,7 +642,7 @@ const DynamicFilters = ({onClick={addCustomFilter}><Plus className="w-3 h-3" />- Add+ {m.OBSERVABILITY_ADD}</Button></div>{customFilters.length > 0 && (@@ -534,14 +656,16 @@ const DynamicFilters = ({}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>+ {customAttributeTypes.map((attributeType) => (+ <option key={attributeType} value={attributeType}>+ {getAttributeTypeLabel(attributeType)}+ </option>+ ))}</select>{cf.attributeType === "Field" ? (<Input- placeholder="e.g. SpanName"+ placeholder={m.OBSERVABILITY_SPAN_NAME_EXAMPLE}value={cf.key}onChange={(e) =>updateCustomFilter(index, "key", e.target.value)@@ -553,16 +677,14 @@ const DynamicFilters = ({value={cf.key}onChange={(val) => updateCustomFilter(index, "key", val)}options={- cf.attributeType === "SpanAttributes"- ? (attributeKeys?.spanAttributeKeys ?? [])- : (attributeKeys?.resourceAttributeKeys ?? [])+ getAttributeOptions(cf.attributeType)}- placeholder="e.g. gen_ai.system"+ placeholder={m.OBSERVABILITY_ATTRIBUTE_KEY_EXAMPLE}/>)}<Input- placeholder="Value"+ placeholder={m.OBSERVABILITY_VALUE}value={cf.value}onChange={(e) =>updateCustomFilter(index, "value", e.target.value)@@ -589,10 +711,10 @@ 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" },+ { key: "model", label: m.OBSERVABILITY_MODEL },+ { key: "provider", label: m.OBSERVABILITY_PROVIDERS },+ { key: "spanName", label: m.OBSERVABILITY_SPAN_NAMES },+ { key: "applicationName", label: m.OBSERVABILITY_APPLICATION },];const PREDEFINED_GROUP_BY_KEYS = new Set<string>(GROUP_BY_OPTIONS.map((o) => o.key));@@ -658,9 +780,12 @@ function InlineSuggest({function GroupByDropdown({groupBy,onChangeGroupBy,+ customAttributeTypes = ["SpanAttributes", "ResourceAttributes", "Field"],}: {groupBy?: string;onChangeGroupBy: (key: string | undefined) => void;+ customAttributeTypes?: CustomFilterAttributeType[];+ filterStorageScope?: string;}) {const attributeKeys = useRootStore(getAttributeKeys);const [open, setOpen] = useState(false);@@ -690,8 +815,14 @@ function GroupByDropdown({const customOptions =customAttrType === "SpanAttributes"? (attributeKeys?.spanAttributeKeys ?? [])- : customAttrType === "ResourceAttributes"+ : customAttrType === "ResourceAttributes"? (attributeKeys?.resourceAttributeKeys ?? [])+ : customAttrType === "LogAttributes"+ ? (attributeKeys?.logAttributeKeys ?? [])+ : customAttrType === "ScopeAttributes"+ ? (attributeKeys?.scopeAttributeKeys ?? [])+ : customAttrType === "Attributes"+ ? (attributeKeys?.metricAttributeKeys ?? []): [];const applyCustom = () => {@@ -755,9 +886,21 @@ function GroupByDropdown({}}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>+ {customAttributeTypes.map((attributeType) => (+ <option key={attributeType} value={attributeType}>+ {attributeType === "SpanAttributes"+ ? m.OBSERVABILITY_SPAN_ATTRIBUTES+ : attributeType === "ResourceAttributes"+ ? m.OBSERVABILITY_RESOURCE_ATTRIBUTES+ : attributeType === "LogAttributes"+ ? m.OBSERVABILITY_LOG_ATTRIBUTES+ : attributeType === "ScopeAttributes"+ ? m.OBSERVABILITY_SCOPE_ATTRIBUTES+ : attributeType === "Attributes"+ ? m.OBSERVABILITY_METRIC_ATTRIBUTES+ : m.OBSERVABILITY_FIELD}+ </option>+ ))}</select><InlineSuggestvalue={customKey}@@ -782,11 +925,6 @@ function GroupByDropdown({// ─── 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;@@ -798,7 +936,7 @@ type PersistedFilter = {groupValue?: string;};-function saveFilterToStorage(filter: FilterType) {+function saveFilterToStorage(filter: FilterType, storageKey: string) {try {// Strip ephemeral scope fields — `serviceNames` is the lock set by// AgentScopeProvider on the agent-detail page; persisting it would leak@@ -821,13 +959,13 @@ function saveFilterToStorage(filter: FilterType) {groupBy: filter.groupBy,groupValue: filter.groupValue,};- localStorage.setItem(FILTER_STORAGE_KEY, JSON.stringify(toSave));+ localStorage.setItem(storageKey, JSON.stringify(toSave));} catch {}}-function loadFilterFromStorage(): PersistedFilter | null {+function loadFilterFromStorage(storageKey: string): PersistedFilter | null {try {- const raw = localStorage.getItem(FILTER_STORAGE_KEY);+ const raw = localStorage.getItem(storageKey);return raw ? (JSON.parse(raw) as PersistedFilter) : null;} catch {return null;@@ -866,9 +1004,14 @@ function applyStoredFilter(const VALID_TIME_RANGES = new Set(["24H", "7D", "1M", "3M", "CUSTOM"]);-function useFilterUrlSync(filter: FilterType, updateFilter: (key: string, value: any, extraParams?: any) => void) {+function useFilterUrlSync(+ filter: FilterType,+ updateFilter: (key: string, value: any, extraParams?: any) => void,+ storageScope?: string+) {const router = useRouter();const pathname = usePathname();+ const storageKey = getFilterStorageKey(storageScope);// Tracks whether the initial URL read has been applied to the storeconst initializedFromUrl = useRef(false);@@ -902,6 +1045,11 @@ function useFilterUrlSync(filter: FilterType, updateFilter: (key: string, value:const parsed = parseInt(limitParam, 10);if (!isNaN(parsed) && parsed > 0) updateFilter("limit", parsed);}+ const offsetParam = params.get("offset");+ if (offsetParam) {+ const parsed = parseInt(offsetParam, 10);+ if (!isNaN(parsed) && parsed >= 0) updateFilter("offset", parsed);+ }const config = paramsToConfig(params);if (hasActiveConfig(config)) updateFilter("selectedConfig", config);const gb = params.get("gb");@@ -910,7 +1058,7 @@ function useFilterUrlSync(filter: FilterType, updateFilter: (key: string, value:if (gbv) updateFilter("groupValue", gbv);} else {// ── Fall back to localStorage ─────────────────────────────────────- const saved = loadFilterFromStorage();+ const saved = loadFilterFromStorage(storageKey);if (saved) applyStoredFilter(saved, updateFilter, VALID_TIME_RANGES);}@@ -941,6 +1089,7 @@ function useFilterUrlSync(filter: FilterType, updateFilter: (key: string, value:// Page sizeparams.set("limit", String(filter.limit));+ params.set("offset", String(filter.offset));// Selected configconfigToParams(filter.selectedConfig, params);@@ -960,9 +1109,9 @@ function useFilterUrlSync(filter: FilterType, updateFilter: (key: string, value:}// Persist to localStorage so other pages (and refreshes) pick up these filters- saveFilterToStorage(filter);+ saveFilterToStorage(filter, storageKey);// eslint-disable-next-line react-hooks/exhaustive-deps- }, [filter.timeLimit.type, filter.timeLimit.start, filter.timeLimit.end, filter.limit, filter.selectedConfig, filter.groupBy, filter.groupValue]);+ }, [filter.timeLimit.type, filter.timeLimit.start, filter.timeLimit.end, filter.limit, filter.offset, filter.selectedConfig, filter.groupBy, filter.groupValue, storageKey]);}// ─── TracesFilter (exported) ──────────────────────────────────────────────────@@ -970,15 +1119,27 @@ function useFilterUrlSync(filter: FilterType, updateFilter: (key: string, value:export default function TracesFilter({total,supportDynamicFilters = false,+ showGroupBy = true,+ showVisibilityColumns = true,includeOnlySorting,pageName,columns,+ configUrl = "/api/metrics/request/config",+ attributeKeysUrl = "/api/metrics/request/attribute-keys",+ customAttributeTypes = ["SpanAttributes", "ResourceAttributes", "Field"],+ filterStorageScope,}: {total?: number;supportDynamicFilters?: boolean;+ showGroupBy?: boolean;+ showVisibilityColumns?: boolean;includeOnlySorting?: string[];pageName: PAGE;columns: Columns<any, any>;+ configUrl?: string;+ attributeKeysUrl?: string;+ customAttributeTypes?: CustomFilterAttributeType[];+ filterStorageScope?: string;}) {const [isVisibleFilters, setIsVisibileFilters] = useState<boolean>(false);const filter = useRootStore(getFilterDetails);@@ -994,21 +1155,21 @@ export default function TracesFilter({const clipboard = navigator.clipboard;if (!clipboard?.writeText) {- toast.error("Copy to clipboard is not supported in this browser");+ toast.error(m.OBSERVABILITY_COPY_UNSUPPORTED);return;}clipboard.writeText(window.location.href).then(() => {- toast.success("Link copied to clipboard");+ toast.success(m.OBSERVABILITY_LINK_COPIED);}).catch(() => {- toast.error("Could not copy link");+ toast.error(m.OBSERVABILITY_LINK_COPY_FAILED);});};- useFilterUrlSync(filter, updateFilter);+ useFilterUrlSync(filter, updateFilter, filterStorageScope || pageName);const onClickPageAction = (dir: -1 | 1) => {updateFilter("offset", filter.offset + dir * filter.limit);@@ -1062,17 +1223,20 @@ export default function TracesFilter({onClickPageLimit={onClickPageLimit}/>)}- <VisibilityColumns columns={columns} pageName={pageName} />+ {showVisibilityColumns && (+ <VisibilityColumns columns={columns} pageName={pageName} />+ )}{!!total && total > 0 && (<Sortingsorting={filter.sorting}includeOnlySorting={includeOnlySorting}/>)}- {supportDynamicFilters && (+ {supportDynamicFilters && showGroupBy && (<GroupByDropdowngroupBy={filter.groupBy}onChangeGroupBy={onChangeGroupBy}+ customAttributeTypes={customAttributeTypes}/>)}{supportDynamicFilters && (@@ -1091,7 +1255,7 @@ export default function TracesFilter({<Buttonvariant="outline"size="default"- title="Copy shareable link"+ title={m.OBSERVABILITY_COPY_SHARE_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}>@@ -1103,6 +1267,9 @@ export default function TracesFilter({isVisibleFilters={isVisibleFilters}filter={filter}areFiltersApplied={areFiltersApplied}+ configUrl={configUrl}+ attributeKeysUrl={attributeKeysUrl}+ customAttributeTypes={customAttributeTypes}/>)}</div>diff --git a/src/client/src/components/(playground)/filter/visibility-columns.tsx b/src/client/src/components/(playground)/filter/visibility-columns.tsxindex 477de5ed..5e506c96 100644--- a/src/client/src/components/(playground)/filter/visibility-columns.tsx+++ b/src/client/src/components/(playground)/filter/visibility-columns.tsx@@ -31,6 +31,7 @@ export default function VisibilityColumns({const onVisibilityChange = (key: string, value: boolean) => {updateFilter(pageName, `visibilityColumns.${key}`, value);};+ const isVisible = (key: string) => visibilityColumns[key] ?? true;return (<DropdownMenu>@@ -49,7 +50,7 @@ export default function VisibilityColumns({onClick={() =>onVisibilityChange(key,- !visibilityColumns[key]+ !isVisible(key))}disabled={!value?.enableHiding}@@ -57,7 +58,7 @@ export default function VisibilityColumns({><Checkboxchecked={- visibilityColumns[key]+ isVisible(key)}/>{convertKeyToLabel(key)}diff --git a/src/client/src/components/(playground)/observability/attribute-grid.tsx b/src/client/src/components/(playground)/observability/attribute-grid.tsxnew file mode 100644index 00000000..5f91a272--- /dev/null+++ b/src/client/src/components/(playground)/observability/attribute-grid.tsx@@ -0,0 +1,140 @@+"use client";++import { useMemo, useState } from "react";+import { isPlainObject } from "lodash";++function isEmptyValue(value: unknown) {+ return value === "" || value === null || value === undefined;+}++function stringifyValue(value: unknown) {+ if (isEmptyValue(value)) return "-";+ if (typeof value === "string") return value;+ if (typeof value === "number" || typeof value === "boolean") return String(value);+ try {+ return JSON.stringify(value, null, 2);+ } catch {+ return String(value);+ }+}++function shouldClamp(value: unknown, text: string) {+ return Array.isArray(value) || isPlainObject(value) || text.length > 180 || text.split("\n").length > 3;+}++function ValueCell({ value }: { value: unknown }) {+ const [expanded, setExpanded] = useState(false);+ const text = useMemo(() => stringifyValue(value), [value]);+ const clamp = shouldClamp(value, text);+ const isStructured = Array.isArray(value) || isPlainObject(value);+ const className = isStructured+ ? `max-w-full overflow-auto whitespace-pre-wrap break-words rounded border border-stone-200 bg-stone-50 p-2 font-mono text-xs leading-5 text-stone-800 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-200 ${+ expanded ? "max-h-96" : "max-h-[3.75rem]"+ }`+ : `max-w-full whitespace-pre-wrap break-words font-mono text-xs leading-5 text-stone-800 dark:text-stone-200 ${+ !expanded && clamp ? "line-clamp-3 overflow-hidden" : ""+ }`;++ return (+ <div className="min-w-0 max-w-full">+ <pre className={className}>{text}</pre>+ {clamp && (+ <button+ type="button"+ className="mt-1 text-xs font-medium text-primary hover:underline"+ onClick={() => setExpanded((value) => !value)}+ >+ {expanded ? "Show less" : "Show more"}+ </button>+ )}+ </div>+ );+}++function renderValue(value: unknown) {+ return <ValueCell value={value} />;+}++function getObjectEntries(data: unknown) {+ if (!isPlainObject(data)) return [];+ return Object.entries(data as Record<string, unknown>).filter(+ ([, value]) => !isEmptyValue(value)+ );+}++function KeyValueRows({ entries }: { entries: Array<[string, unknown]> }) {+ return (+ <div className="divide-y divide-stone-200 dark:divide-stone-800">+ {entries.map(([key, value], index) => (+ <div+ key={key}+ className={`grid min-w-0 grid-cols-1 gap-2 px-3 py-2 md:grid-cols-[minmax(180px,32%)_minmax(0,1fr)] ${+ index % 2 === 0+ ? "bg-white dark:bg-stone-950"+ : "bg-stone-50 dark:bg-stone-900/70"+ }`}+ >+ <div className="truncate font-mono text-xs font-medium text-stone-600 dark:text-stone-300">+ {key}+ </div>+ {renderValue(value)}+ </div>+ ))}+ </div>+ );+}++function ArrayGroups({ rows }: { rows: unknown[] }) {+ if (!rows.length) {+ return <div className="px-3 py-6 text-sm text-stone-400">No data.</div>;+ }++ return (+ <div className="space-y-3 p-3">+ {rows.map((row, index) => {+ const entries = isPlainObject(row)+ ? getObjectEntries(row)+ : [[`#${index + 1}`, row] as [string, unknown]];+ return (+ <div+ key={index}+ className="overflow-hidden rounded-md border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950"+ >+ <div className="border-b border-stone-200 bg-stone-100 px-3 py-2 font-mono text-xs font-semibold text-stone-500 dark:border-stone-800 dark:bg-stone-900 dark:text-stone-400">+ #{index + 1}+ </div>+ {entries.length ? (+ <KeyValueRows entries={entries} />+ ) : (+ <div className="px-3 py-4 text-sm text-stone-400">No data.</div>+ )}+ </div>+ );+ })}+ </div>+ );+}++export default function AttributeGrid({+ data,+ title,+}: {+ data?: unknown;+ title: string;+}) {+ const entries = getObjectEntries(data);+ return (+ <section className="rounded-md border border-stone-200 dark:border-stone-800 bg-stone-50 dark:bg-stone-900">+ <div className="border-b border-stone-200 dark:border-stone-800 px-3 py-2 text-sm font-medium text-stone-900 dark:text-stone-100">+ {title}+ </div>+ {Array.isArray(data) ? (+ <ArrayGroups rows={data} />+ ) : entries.length ? (+ <KeyValueRows entries={entries} />+ ) : (+ <div className="px-3 py-6 text-sm text-stone-400">No attributes.</div>+ )}+ </section>+ );+}diff --git a/src/client/src/components/(playground)/observability/columns.tsx b/src/client/src/components/(playground)/observability/columns.tsxnew file mode 100644index 00000000..27d70907--- /dev/null+++ b/src/client/src/components/(playground)/observability/columns.tsx@@ -0,0 +1,153 @@+import { Columns } from "@/components/data-table/columns";+import { CalendarDays } from "lucide-react";+import { format } from "date-fns";+import getMessage from "@/constants/messages";++const m = getMessage();++export type LogRow = {+ rowId: string | number;+ Timestamp: string;+ TraceId: string;+ SpanId: string;+ SeverityText: string;+ ServiceName: string;+ Body: string;+};++export type MetricRow = {+ metricName: string;+ metricType: string;+ serviceName: string;+ metricUnit?: string;+ latestValue?: number;+ avgValue?: number;+ minValue?: number;+ maxValue?: number;+ pointCount: number;+ lastSeen: string;+};++function formatDate(value?: string) {+ if (!value) return "-";+ try {+ return format(new Date(value), "MMM d, HH:mm:ss");+ } catch {+ return value;+ }+}++export const logColumns: Columns<string, LogRow> = {+ time: {+ header: () => m.OBSERVABILITY_TIME,+ cell: ({ row }) => (+ <div className="flex space-x-2 items-center" title={row.Timestamp}>+ <CalendarDays size="16" />+ <span className="truncate font-medium">{formatDate(row.Timestamp)}</span>+ </div>+ ),+ enableHiding: true,+ },+ severityText: {+ header: () => m.OBSERVABILITY_SEVERITY,+ cell: ({ row }) => (+ <span className="truncate" title={row.SeverityText || "-"}>+ {row.SeverityText || "-"}+ </span>+ ),+ enableHiding: true,+ },+ serviceName: {+ header: () => m.OBSERVABILITY_SERVICE,+ cell: ({ row }) => (+ <div className="truncate" title={row.ServiceName}>+ {row.ServiceName || "-"}+ </div>+ ),+ enableHiding: true,+ },+ body: {+ header: () => m.OBSERVABILITY_BODY,+ cell: ({ row }) => (+ <div className="truncate" title={row.Body}>+ {row.Body || "-"}+ </div>+ ),+ enableHiding: true,+ },+ traceId: {+ header: () => m.OBSERVABILITY_TRACE_ID,+ cell: ({ row }) => (+ <div className="truncate font-mono text-xs" title={row.TraceId}>+ {row.TraceId || "-"}+ </div>+ ),+ enableHiding: true,+ },+ spanId: {+ header: () => m.OBSERVABILITY_SPAN_ID,+ cell: ({ row }) => (+ <div className="truncate font-mono text-xs" title={row.SpanId}>+ {row.SpanId || "-"}+ </div>+ ),+ enableHiding: true,+ },+};++export const metricColumns: Columns<string, MetricRow> = {+ metricName: {+ header: () => m.OBSERVABILITY_METRIC,+ cell: ({ row }) => (+ <div className="truncate font-medium" title={row.metricName}>+ {row.metricName}+ </div>+ ),+ enableHiding: true,+ },+ metricType: {+ header: () => m.OBSERVABILITY_TYPE,+ cell: ({ row }) => <span className="truncate">{row.metricType}</span>,+ enableHiding: true,+ },+ serviceName: {+ header: () => m.OBSERVABILITY_SERVICE,+ cell: ({ row }) => (+ <div className="truncate" title={row.serviceName}>+ {row.serviceName || "-"}+ </div>+ ),+ enableHiding: true,+ },+ metricUnit: {+ header: () => m.OBSERVABILITY_UNIT,+ cell: ({ row }) => <span className="truncate">{row.metricUnit || "-"}</span>,+ enableHiding: true,+ },+ latestValue: {+ header: () => m.OBSERVABILITY_LATEST,+ cell: ({ row }) => (+ <span className="tabular-nums">+ {typeof row.latestValue === "number" ? row.latestValue.toFixed(4) : "-"}+ </span>+ ),+ enableHiding: true,+ },+ pointCount: {+ header: () => m.OBSERVABILITY_POINTS,+ cell: ({ row }) => (+ <span className="tabular-nums">{row.pointCount?.toLocaleString()}</span>+ ),+ enableHiding: true,+ },+ lastSeen: {+ header: () => m.OBSERVABILITY_LAST_SEEN,+ cell: ({ row }) => (+ <div className="flex space-x-2 items-center" title={row.lastSeen}>+ <CalendarDays size="16" />+ <span className="truncate font-medium">{formatDate(row.lastSeen)}</span>+ </div>+ ),+ enableHiding: true,+ },+};diff --git a/src/client/src/components/(playground)/observability/detail-object-tabs.tsx b/src/client/src/components/(playground)/observability/detail-object-tabs.tsxnew file mode 100644index 00000000..574071e3--- /dev/null+++ b/src/client/src/components/(playground)/observability/detail-object-tabs.tsx@@ -0,0 +1,173 @@+"use client";++import type { ReactNode } from "react";+import { isPlainObject } from "lodash";+import AttributeGrid from "./attribute-grid";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";++type DetailObjectTab = {+ id: string;+ label: string;+ data: unknown;+};++function humanizeKey(key: string) {+ return key+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")+ .replace(/[_-]+/g, " ")+ .replace(/\b\w/g, (char) => char.toUpperCase());+}++function isRenderableValue(value: unknown) {+ if (Array.isArray(value)) return value.length > 0;+ return isPlainObject(value) && Object.keys(value as Record<string, any>).length > 0;+}++function isEmptyValue(value: unknown) {+ if (Array.isArray(value)) return value.length === 0;+ if (isPlainObject(value)) return Object.keys(value as Record<string, any>).length === 0;+ return value === "" || value === null || value === undefined;+}++function buildDottedArrayTabs(+ source: Record<string, any>,+ exclude: Set<string>,+ labelOverrides?: Record<string, string>+) {+ const groups = new Map<string, Record<string, unknown[]>>();++ Object.entries(source).forEach(([key, value]) => {+ if (exclude.has(key) || !Array.isArray(value) || !key.includes(".")) return;+ const [group, ...fieldParts] = key.split(".");+ const field = fieldParts.join(".");+ if (!group || !field) return;+ if (!groups.has(group)) groups.set(group, {});+ groups.get(group)![field] = value;+ });++ const groupedKeys = new Set<string>();+ const tabs: DetailObjectTab[] = [];++ groups.forEach((fields, group) => {+ const maxRows = Math.max(...Object.values(fields).map((values) => values.length));+ const rows = Array.from({ length: maxRows }, (_, index) => {+ const row: Record<string, unknown> = {};+ Object.entries(fields).forEach(([field, values]) => {+ const value = values[index];+ if (!isEmptyValue(value)) row[field] = value;+ });+ return row;+ }).filter((row) => Object.keys(row).length > 0);++ if (!rows.length) return;+ Object.keys(fields).forEach((field) => groupedKeys.add(`${group}.${field}`));+ tabs.push({+ id: group,+ label: labelOverrides?.[group] || humanizeKey(group),+ data: rows,+ });+ });++ return { tabs, groupedKeys };+}++function buildRootProperties(+ source: Record<string, any>,+ exclude: Set<string>,+ groupedKeys: Set<string>+) {+ return Object.fromEntries(+ Object.entries(source).filter(+ ([key, value]) =>+ !exclude.has(key) &&+ !groupedKeys.has(key) &&+ !isEmptyValue(value) &&+ !Array.isArray(value) &&+ !isPlainObject(value)+ )+ );+}++export function buildObjectTabs(+ source?: Record<string, any>,+ options: {+ excludeKeys?: string[];+ labelOverrides?: Record<string, string>;+ rootLabel?: string;+ } = {}+): DetailObjectTab[] {+ const exclude = new Set(options.excludeKeys || []);+ const sourceObject = source || {};+ const { tabs: groupedTabs, groupedKeys } = buildDottedArrayTabs(+ sourceObject,+ exclude,+ options.labelOverrides+ );+ const directTabs = Object.entries(sourceObject)+ .filter(+ ([key, value]) =>+ !exclude.has(key) && !groupedKeys.has(key) && isRenderableValue(value)+ )+ .map(([key, value]) => ({+ id: key,+ label: options.labelOverrides?.[key] || humanizeKey(key),+ data: value,+ }));+ const rootProperties = buildRootProperties(sourceObject, exclude, groupedKeys);+ const rootTab = Object.keys(rootProperties).length+ ? [+ {+ id: "root",+ label: options.rootLabel || "Overview",+ data: rootProperties,+ },+ ]+ : [];++ return [...rootTab, ...directTabs, ...groupedTabs];+}++export default function DetailObjectTabs({+ tabs,+ extraTabs,+}: {+ tabs: DetailObjectTab[];+ extraTabs?: Array<{+ id: string;+ label: string;+ content: ReactNode;+ }>;+}) {+ const allTabs = [+ ...tabs.map((tab) => ({ ...tab, type: "object" as const })),+ ...(extraTabs || []).map((tab) => ({ ...tab, type: "custom" as const })),+ ];+ if (!allTabs.length) return null;++ return (+ <Tabs defaultValue={allTabs[0].id} className="min-w-0">+ <div className="max-w-full overflow-x-auto overflow-y-hidden pb-1">+ <TabsList className="h-9 w-max min-w-full justify-start rounded-md bg-stone-100 p-1 dark:bg-stone-900">+ {allTabs.map((tab) => (+ <TabsTrigger+ key={tab.id}+ value={tab.id}+ className="shrink-0 px-3 py-1 text-xs"+ >+ {tab.label}+ </TabsTrigger>+ ))}+ </TabsList>+ </div>+ {allTabs.map((tab) => (+ <TabsContent key={tab.id} value={tab.id} className="mt-3">+ {tab.type === "object" ? (+ <AttributeGrid title={tab.label} data={tab.data} />+ ) : (+ tab.content+ )}+ </TabsContent>+ ))}+ </Tabs>+ );+}diff --git a/src/client/src/components/(playground)/observability/detail-shell.tsx b/src/client/src/components/(playground)/observability/detail-shell.tsxnew file mode 100644index 00000000..78f51b2a--- /dev/null+++ b/src/client/src/components/(playground)/observability/detail-shell.tsx@@ -0,0 +1,37 @@+"use client";++export default function DetailShell({+ title,+ leadingActions,+ actions,+ headerMeta,+ children,+ compact = false,+}: {+ title: string;+ leadingActions?: React.ReactNode;+ actions?: React.ReactNode;+ headerMeta?: React.ReactNode;+ children: React.ReactNode;+ compact?: boolean;+}) {+ return (+ <div className="flex flex-col w-full h-full overflow-auto rounded-md border border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950">+ <div className={`sticky top-0 z-10 flex flex-col border-b border-stone-200 bg-white/95 shadow-sm shadow-stone-200/40 backdrop-blur dark:border-stone-800 dark:bg-stone-950/95 dark:shadow-black/20 ${compact ? "gap-2 px-3 py-2" : "gap-3 px-4 py-3"}`}>+ <div className={`flex flex-col md:flex-row md:items-start md:justify-between ${compact ? "gap-2" : "gap-3"}`}>+ <div className="flex min-w-0 grow items-start gap-2">+ {leadingActions && <div className="shrink-0">{leadingActions}</div>}+ <div className="min-w-0 grow">+ <h1 className={`truncate font-semibold text-stone-950 dark:text-stone-50 ${compact ? "text-base md:text-lg" : "text-lg md:text-xl"}`}>+ {title}+ </h1>+ </div>+ </div>+ {actions && <div className="shrink-0">{actions}</div>}+ </div>+ {headerMeta && <div>{headerMeta}</div>}+ </div>+ <div className={`flex flex-col ${compact ? "gap-2 p-2" : "gap-4 p-4"}`}>{children}</div>+ </div>+ );+}diff --git a/src/client/src/components/(playground)/observability/log-detail-page.tsx b/src/client/src/components/(playground)/observability/log-detail-page.tsxnew file mode 100644index 00000000..cb7d2f40--- /dev/null+++ b/src/client/src/components/(playground)/observability/log-detail-page.tsx@@ -0,0 +1,246 @@+"use client";++import { useCallback, useEffect, useMemo, type ReactNode } from "react";+import Link from "next/link";+import { useRouter, useSearchParams } from "next/navigation";+import {+ ArrowLeft,+ BadgeDollarSign,+ Clock,+ FileText,+ Gauge,+ GitBranch,+ Hash,+ MessageSquareText,+ Server,+ Siren,+ Zap,+} from "lucide-react";+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";+import DetailShell from "./detail-shell";+import { Button } from "@/components/ui/button";+import getMessage from "@/constants/messages";+import DetailObjectTabs, { buildObjectTabs } from "./detail-object-tabs";++function MetaTile({+ icon,+ label,+ value,+}: {+ icon: React.ReactNode;+ label: string;+ value?: string | number;+}) {+ return (+ <div className="rounded-md border border-stone-200 bg-stone-50 px-3 py-2 dark:border-stone-800 dark:bg-stone-900/50">+ <div className="flex items-center gap-1.5 text-xs text-stone-500 dark:text-stone-400">+ {icon}+ {label}+ </div>+ <div className="mt-1 truncate font-mono text-xs font-semibold text-stone-950 dark:text-stone-50">+ {value || "-"}+ </div>+ </div>+ );+}++function compactValue(value: unknown) {+ if (value === "" || value === null || value === undefined) return undefined;+ return String(value);+}++function formatNumber(value: unknown) {+ const numberValue = Number(value);+ if (!Number.isFinite(numberValue)) return compactValue(value);+ return numberValue.toLocaleString(undefined, { maximumFractionDigits: 4 });+}++function sumNumeric(values: unknown[]) {+ return values.reduce<number>((total, value) => {+ const numberValue = Number(value);+ return Number.isFinite(numberValue) ? total + numberValue : total;+ }, 0);+}++function ContextPill({ label, value }: { label: string; value?: unknown }) {+ const displayValue = compactValue(value);+ if (!displayValue) return null;+ return (+ <div className="min-w-0 rounded-md border border-stone-200 bg-white px-2.5 py-1.5 dark:border-stone-800 dark:bg-stone-950">+ <div className="text-[10px] uppercase tracking-wide text-stone-500 dark:text-stone-400">+ {label}+ </div>+ <div+ className="max-w-64 truncate font-mono text-xs text-stone-900 dark:text-stone-100"+ title={displayValue}+ >+ {displayValue}+ </div>+ </div>+ );+}++export function LogDetailView({+ id,+ from,+ variant = "page",+ extraActions,+}: {+ id: string;+ from?: string | null;+ variant?: "page" | "sheet";+ extraActions?: ReactNode;+}) {+ const m = getMessage();+ const router = useRouter();+ const { data, fireRequest } = useFetchWrapper();++ const fetchData = useCallback(() => {+ fireRequest({+ requestType: "GET",+ url: `/api/telemetry/logs/${id}`,+ });+ }, [fireRequest, id]);++ useEffect(() => {+ fetchData();+ }, [fetchData]);++ const record = (data as any)?.record;+ const logAttributes = record?.LogAttributes || {};+ const eventName = compactValue(logAttributes["event.name"]);+ const logTitle =+ [record?.Body, eventName].filter(Boolean).join(" / ") ||+ m.OBSERVABILITY_LOG_ENTRY;+ const totalTokens = sumNumeric([+ logAttributes.input_tokens,+ logAttributes.output_tokens,+ logAttributes.cache_read_tokens,+ logAttributes.cache_creation_tokens,+ ]);+ const severity = String(record?.SeverityText || "unknown severity");+ const normalizedSeverity = severity.toLowerCase();+ const severityClass =+ normalizedSeverity === "error" || normalizedSeverity === "fatal"+ ? "border-rose-200 bg-rose-50 text-rose-700 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-300"+ : normalizedSeverity === "warn" || normalizedSeverity === "warning"+ ? "border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-300"+ : "border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-900 dark:bg-sky-950/30 dark:text-sky-300";+ const detailTabs = useMemo(+ () => buildObjectTabs(record, {+ labelOverrides: {+ LogAttributes: "Log Attributes",+ ResourceAttributes: "Resource Attributes",+ ScopeAttributes: "Scope Attributes",+ },+ }),+ [record]+ );+ const tokenSummary = totalTokens+ ? `${totalTokens.toLocaleString()} total`+ : undefined;+ const goBack = () => router.push(from || "/telemetry?tab=logs");++ return (+ <DetailShell+ title={logTitle}+ leadingActions={+ variant === "page" ? (+ <Button+ variant="outline"+ size="sm"+ onClick={goBack}+ className="h-8 w-8 p-0"+ title={m.OBSERVABILITY_BACK}+ >+ <ArrowLeft className="h-3.5 w-3.5" />+ </Button>+ ) : undefined+ }+ actions={extraActions}+ headerMeta={+ record ? (+ <div className="grid grid-cols-2 gap-2 lg:grid-cols-4 xl:grid-cols-6">+ <div className={`rounded-md border px-3 py-2 ${severityClass}`}>+ <div className="flex items-center gap-1.5 text-xs font-medium">+ <Siren className="h-3.5 w-3.5" />+ {m.OBSERVABILITY_SEVERITY}+ </div>+ <div className="mt-1 truncate font-semibold">{severity}</div>+ </div>+ <MetaTile icon={<Clock className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_TIME} value={record.Timestamp} />+ <MetaTile icon={<Server className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_SERVICE} value={record.ServiceName} />+ <MetaTile icon={<MessageSquareText className="h-3.5 w-3.5" />} label="Event" value={eventName || record.Body} />+ <MetaTile icon={<BadgeDollarSign className="h-3.5 w-3.5" />} label="Cost" value={logAttributes.cost_usd ? `$${formatNumber(logAttributes.cost_usd)}` : undefined} />+ <MetaTile icon={<Zap className="h-3.5 w-3.5" />} label="Tokens" value={tokenSummary} />+ </div>+ ) : undefined+ }+ >+ {record && (+ <>+ <section className="rounded-md border border-stone-200 bg-stone-50 p-3 dark:border-stone-800 dark:bg-stone-900">+ <div className="flex items-center gap-2 text-xs font-medium uppercase tracking-wide text-stone-500 dark:text-stone-400">+ <FileText className="h-3.5 w-3.5" />+ Log Summary+ </div>+ <div className="mt-3 grid grid-cols-2 gap-2 md:grid-cols-4">+ <ContextPill label="Body" value={record.Body} />+ <ContextPill label="Duration" value={logAttributes.duration_ms ? `${formatNumber(logAttributes.duration_ms)} ms` : undefined} />+ <ContextPill label="Input" value={logAttributes.input_tokens ? `${formatNumber(logAttributes.input_tokens)} tokens` : undefined} />+ <ContextPill label="Output" value={logAttributes.output_tokens ? `${formatNumber(logAttributes.output_tokens)} tokens` : undefined} />+ <ContextPill label="Cache Read" value={logAttributes.cache_read_tokens ? `${formatNumber(logAttributes.cache_read_tokens)} tokens` : undefined} />+ </div>+ <div className="mt-3 flex flex-wrap gap-2">+ <ContextPill label="Request" value={logAttributes.request_id} />+ <ContextPill label="Model" value={logAttributes.model} />+ <ContextPill label="Source" value={logAttributes.query_source} />+ <ContextPill label="Session" value={logAttributes["session.id"]} />+ <ContextPill label="Prompt" value={logAttributes["prompt.id"]} />+ <ContextPill label="Terminal" value={logAttributes["terminal.type"]} />+ <ContextPill label="User" value={logAttributes["user.email"]} />+ </div>+ <div className="mt-3 flex flex-wrap gap-2 text-xs text-stone-500 dark:text-stone-400">+ {record.TraceId && (+ <Link+ className="rounded-md border border-stone-200 bg-white px-2 py-1 font-mono hover:text-primary dark:border-stone-800 dark:bg-stone-950"+ href={`/telemetry?tab=traces&traceId=${record.TraceId}`}+ >+ trace:{record.TraceId}+ </Link>+ )}+ {record.SpanId && (+ <Link+ className="rounded-md border border-stone-200 bg-white px-2 py-1 font-mono hover:text-primary dark:border-stone-800 dark:bg-stone-950"+ href={`/telemetry/traces/${record.SpanId}?from=${encodeURIComponent(from || "/telemetry?tab=logs")}`}+ >+ span:{record.SpanId}+ </Link>+ )}+ {record.TraceId && (+ <MetaTile icon={<GitBranch className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_TRACE_ID} value={record.TraceId} />+ )}+ {record.SpanId && (+ <MetaTile icon={<Hash className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_SPAN_ID} value={record.SpanId} />+ )}+ <MetaTile icon={<Gauge className="h-3.5 w-3.5" />} label="Scope" value={record.ScopeName} />+ </div>+ </section>+ <DetailObjectTabs tabs={detailTabs} />+ </>+ )}+ </DetailShell>+ );+}++export default function LogDetailPage({ id }: { id: string }) {+ const searchParams = useSearchParams();++ return (+ <LogDetailView+ id={id}+ from={searchParams.get("from")}+ variant="page"+ />+ );+}diff --git a/src/client/src/components/(playground)/observability/metric-detail-page.tsx b/src/client/src/components/(playground)/observability/metric-detail-page.tsxnew file mode 100644index 00000000..a474e05f--- /dev/null+++ b/src/client/src/components/(playground)/observability/metric-detail-page.tsx@@ -0,0 +1,275 @@+"use client";++import { useCallback, useEffect, useMemo, type ReactNode } from "react";+import { useRouter, useSearchParams } from "next/navigation";+import { ArrowLeft, Activity, Clock, Database, Sigma, TrendingUp } from "lucide-react";+import {+ Area,+ AreaChart,+ CartesianGrid,+ ResponsiveContainer,+ Tooltip,+ XAxis,+ YAxis,+} from "recharts";+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";+import { getFilterDetails } from "@/selectors/filter";+import { useRootStore } from "@/store";+import DetailShell from "./detail-shell";+import { Button } from "@/components/ui/button";+import getMessage from "@/constants/messages";+import DetailObjectTabs, { buildObjectTabs } from "./detail-object-tabs";++function SummaryItem({+ icon,+ label,+ value,+}: {+ icon: React.ReactNode;+ label: string;+ value?: string | number;+}) {+ return (+ <div className="rounded-md border border-stone-200 bg-stone-50 px-3 py-2 dark:border-stone-800 dark:bg-stone-900/50">+ <div className="flex items-center gap-1.5 text-xs text-stone-500 dark:text-stone-400">+ {icon}+ {label}+ </div>+ <div className="mt-1 truncate text-sm font-semibold tabular-nums text-stone-950 dark:text-stone-50">+ {value || "-"}+ </div>+ </div>+ );+}++function toNumber(value: unknown) {+ const numberValue = typeof value === "number" ? value : Number(value);+ return Number.isFinite(numberValue) ? numberValue : undefined;+}++function formatMetricValue(value: unknown, maximumFractionDigits = 4) {+ const numberValue = toNumber(value);+ if (numberValue === undefined) return value ? String(value) : "-";+ return numberValue.toLocaleString(undefined, { maximumFractionDigits });+}++function compactPoint(point: any) {+ const attributes = point?.Attributes || {};+ return {+ Time: point?.TimeUnix,+ Value: point?.metric_value,+ Unit: point?.MetricUnit,+ Type: point?.metric_type,+ Samples: point?.metric_sample_count,+ Service: point?.ServiceName,+ Model: attributes.model,+ Source: attributes.query_source,+ Session: attributes["session.id"],+ Terminal: attributes["terminal.type"],+ Attributes: point?.Attributes,+ ResourceAttributes: point?.ResourceAttributes,+ ScopeAttributes: point?.ScopeAttributes,+ };+}++export function MetricDetailView({+ name,+ metricType,+ serviceName,+ from,+ variant = "page",+ extraActions,+}: {+ name: string;+ metricType?: string;+ serviceName?: string;+ from?: string | null;+ variant?: "page" | "sheet";+ extraActions?: ReactNode;+}) {+ const m = getMessage();+ const router = useRouter();+ const filter = useRootStore(getFilterDetails);+ const { data, fireRequest } = useFetchWrapper();++ const fetchData = useCallback(() => {+ fireRequest({+ requestType: "POST",+ url: `/api/telemetry/metrics/${encodeURIComponent(name)}`,+ body: JSON.stringify({+ timeLimit: filter.timeLimit,+ selectedConfig: filter.selectedConfig,+ metricType,+ serviceName,+ }),+ });+ }, [filter, fireRequest, metricType, name, serviceName]);++ useEffect(() => {+ fetchData();+ }, [fetchData]);++ const points = ((data as any)?.points || []) as any[];+ const series = ((data as any)?.series || []) as any[];+ const latest = points[0];+ const latestValue = latest?.metric_value;+ const unit = latest?.MetricUnit || m.OBSERVABILITY_VALUE;+ const pointCount = points.length;+ const lastSeen = latest?.TimeUnix;+ const pointValues = useMemo(+ () => points.map((point) => toNumber(point?.metric_value)).filter((value): value is number => value !== undefined),+ [points]+ );+ const totalValue = pointValues.reduce((total, value) => total + value, 0);+ const averageValue = pointValues.length ? totalValue / pointValues.length : undefined;+ const maxValue = pointValues.length ? Math.max(...pointValues) : undefined;+ const chartData = useMemo(+ () =>+ series+ .map((point) => ({+ time: point?.request_time,+ value: toNumber(point?.value),+ }))+ .filter((point) => point.time && point.value !== undefined),+ [series]+ );+ const detailTabs = useMemo(+ () => [+ ...buildObjectTabs(latest, {+ labelOverrides: {+ Attributes: "Metric Attributes",+ ResourceAttributes: "Resource Attributes",+ ScopeAttributes: "Scope Attributes",+ },+ }),+ ...(points.length+ ? [{ id: "points", label: "Points", data: points.map(compactPoint) }]+ : []),+ ...(series.length ? [{ id: "series", label: "Series", data: series }] : []),+ ],+ [latest, points, series]+ );++ const goBack = () => {+ router.push(from || "/telemetry?tab=metrics");+ };++ return (+ <DetailShell+ title={name}+ leadingActions={+ variant === "page" ? (+ <Button+ variant="outline"+ size="sm"+ onClick={goBack}+ className="h-8 w-8 p-0"+ title={m.OBSERVABILITY_BACK}+ >+ <ArrowLeft className="h-3.5 w-3.5" />+ </Button>+ ) : undefined+ }+ actions={extraActions}+ headerMeta={+ <div className="grid grid-cols-2 gap-2 lg:grid-cols-5">+ <SummaryItem+ icon={<Activity className="h-3.5 w-3.5" />}+ label={m.OBSERVABILITY_LATEST}+ value={formatMetricValue(latestValue)}+ />+ <SummaryItem+ icon={<Sigma className="h-3.5 w-3.5" />}+ label="Total"+ value={pointValues.length ? formatMetricValue(totalValue) : "-"}+ />+ <SummaryItem+ icon={<TrendingUp className="h-3.5 w-3.5" />}+ label="Average"+ value={averageValue !== undefined ? formatMetricValue(averageValue) : "-"}+ />+ <SummaryItem+ icon={<Database className="h-3.5 w-3.5" />}+ label={`${m.OBSERVABILITY_LOADED_POINTS} (${unit})`}+ value={pointCount.toLocaleString()}+ />+ <SummaryItem+ icon={<Clock className="h-3.5 w-3.5" />}+ label={m.OBSERVABILITY_LAST_SEEN}+ value={lastSeen}+ />+ </div>+ }+ >+ {chartData.length > 0 && (+ <section className="rounded-md border border-stone-200 bg-white p-3 dark:border-stone-800 dark:bg-stone-950">+ <div className="mb-2 flex flex-wrap items-center justify-between gap-2">+ <div>+ <div className="text-sm font-semibold text-stone-950 dark:text-stone-50">+ Metric Trend+ </div>+ <div className="text-xs text-stone-500 dark:text-stone-400">+ {latest?.MetricDescription || latest?.MetricName || name}+ </div>+ </div>+ <div className="flex flex-wrap gap-2 text-xs">+ <span className="rounded-md border border-stone-200 px-2 py-1 font-mono text-stone-600 dark:border-stone-800 dark:text-stone-300">+ max {formatMetricValue(maxValue)}+ </span>+ <span className="rounded-md border border-stone-200 px-2 py-1 font-mono text-stone-600 dark:border-stone-800 dark:text-stone-300">+ unit {unit}+ </span>+ </div>+ </div>+ <div className="h-44 min-w-0">+ <ResponsiveContainer width="100%" height="100%">+ <AreaChart data={chartData} margin={{ top: 8, right: 12, bottom: 0, left: -18 }}>+ <defs>+ <linearGradient id="metric-detail-fill" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor="#0ea5e9" stopOpacity={0.32} />+ <stop offset="95%" stopColor="#0ea5e9" stopOpacity={0.02} />+ </linearGradient>+ </defs>+ <CartesianGrid strokeDasharray="3 3" stroke="currentColor" className="text-stone-200 dark:text-stone-800" />+ <XAxis dataKey="time" tick={{ fontSize: 11 }} tickLine={false} axisLine={false} minTickGap={24} />+ <YAxis tick={{ fontSize: 11 }} tickLine={false} axisLine={false} tickFormatter={(value) => formatMetricValue(value, 2)} />+ <Tooltip+ formatter={(value) => [formatMetricValue(value), unit]}+ labelClassName="text-stone-500"+ contentStyle={{+ borderRadius: 6,+ borderColor: "rgb(214 211 209)",+ fontSize: 12,+ }}+ />+ <Area+ type="monotone"+ dataKey="value"+ stroke="#0284c7"+ fill="url(#metric-detail-fill)"+ strokeWidth={2}+ dot={{ r: 2 }}+ activeDot={{ r: 4 }}+ />+ </AreaChart>+ </ResponsiveContainer>+ </div>+ </section>+ )}+ <DetailObjectTabs tabs={detailTabs} />+ </DetailShell>+ );+}++export default function MetricDetailPage({ name }: { name: string }) {+ const searchParams = useSearchParams();++ return (+ <MetricDetailView+ name={name}+ metricType={searchParams.get("metricType") || undefined}+ serviceName={searchParams.get("serviceName") || undefined}+ from={searchParams.get("from")}+ />+ );+}diff --git a/src/client/src/components/(playground)/observability/registry.tsx b/src/client/src/components/(playground)/observability/registry.tsxnew file mode 100644index 00000000..29d53f69--- /dev/null+++ b/src/client/src/components/(playground)/observability/registry.tsx@@ -0,0 +1,152 @@+import { Columns } from "@/components/data-table/columns";+import { columns as traceColumns } from "@/components/(playground)/request/columns";+import { columns as exceptionColumns } from "@/components/(playground)/exceptions/columns";+import { logColumns, metricColumns } from "./columns";+import { normalizeTrace } from "@/helpers/client/trace";+import {+ Activity,+ BarChart3,+ FileText,+ ShieldAlert,+ type LucideIcon,+} from "lucide-react";+import { CustomFilterAttributeType } from "@/types/store/filter";+import { PAGE } from "@/types/store/page";+import getMessage from "@/constants/messages";++const m = getMessage();++export type ObservabilitySignal = "traces" | "exceptions" | "metrics" | "logs";++export type ObservabilitySignalConfig = {+ key: ObservabilitySignal;+ label: string;+ shortLabel: string;+ tone: string;+ summary: string;+ icon: LucideIcon;+ listUrl: string;+ summaryUrl: string;+ configUrl: string;+ attributeKeysUrl: string;+ columns: Columns<any, any>;+ pageName: PAGE;+ visibilityPage: PAGE;+ supportGrouping?: boolean;+ groupedUrl?: string;+ includeOnlySorting?: string[];+ customAttributeTypes: CustomFilterAttributeType[];+ normalize?: (row: any) => any;+ getRowId: (row: any) => string;+ getDetailHref: (row: any, from: string) => string;+};++export const OBSERVABILITY_SIGNALS: ObservabilitySignalConfig[] = [+ {+ key: "traces",+ label: m.OBSERVABILITY_TRACES,+ shortLabel: m.OBSERVABILITY_TRACE_SHORT_LABEL,+ tone: "text-sky-600 dark:text-sky-400 bg-sky-50 dark:bg-sky-950/40 border-sky-200 dark:border-sky-900",+ summary: m.OBSERVABILITY_TRACE_SUMMARY,+ icon: Activity,+ listUrl: "/api/metrics/request",+ summaryUrl: "/api/telemetry/summary/traces",+ configUrl: "/api/metrics/request/config",+ attributeKeysUrl: "/api/metrics/request/attribute-keys",+ columns: traceColumns,+ pageName: "request",+ visibilityPage: "request",+ supportGrouping: true,+ groupedUrl: "/api/metrics/request/grouped",+ customAttributeTypes: ["SpanAttributes", "ResourceAttributes", "Field"],+ normalize: normalizeTrace,+ getRowId: (row) => row.spanId,+ getDetailHref: (row, from) =>+ `/telemetry/traces/${row.spanId}?from=${encodeURIComponent(from)}`,+ },+ {+ key: "exceptions",+ label: m.OBSERVABILITY_EXCEPTIONS,+ shortLabel: m.OBSERVABILITY_EXCEPTION_SHORT_LABEL,+ tone: "text-rose-600 dark:text-rose-400 bg-rose-50 dark:bg-rose-950/40 border-rose-200 dark:border-rose-900",+ summary: m.OBSERVABILITY_EXCEPTION_SUMMARY,+ icon: ShieldAlert,+ listUrl: "/api/metrics/exception",+ summaryUrl: "/api/telemetry/summary/exceptions",+ configUrl: "/api/metrics/request/config",+ attributeKeysUrl: "/api/metrics/request/attribute-keys",+ columns: exceptionColumns,+ pageName: "exception",+ visibilityPage: "exception",+ supportGrouping: true,+ groupedUrl: "/api/metrics/exception/grouped",+ includeOnlySorting: ["Timestamp"],+ customAttributeTypes: ["SpanAttributes", "ResourceAttributes", "Field"],+ normalize: normalizeTrace,+ getRowId: (row) => row.spanId,+ getDetailHref: (row, from) =>+ `/telemetry/exceptions/${row.spanId}?from=${encodeURIComponent(from)}`,+ },+ {+ key: "metrics",+ label: m.OBSERVABILITY_METRICS,+ shortLabel: m.OBSERVABILITY_METRIC_SHORT_LABEL,+ tone: "text-emerald-600 dark:text-emerald-400 bg-emerald-50 dark:bg-emerald-950/40 border-emerald-200 dark:border-emerald-900",+ summary: m.OBSERVABILITY_METRIC_SUMMARY,+ icon: BarChart3,+ listUrl: "/api/telemetry/metrics",+ summaryUrl: "/api/telemetry/summary/metrics",+ configUrl: "/api/telemetry/metrics/config",+ attributeKeysUrl: "/api/telemetry/metrics/attribute-keys",+ columns: metricColumns,+ pageName: "observabilityMetrics",+ visibilityPage: "observabilityMetrics",+ customAttributeTypes: [+ "Attributes",+ "ResourceAttributes",+ "ScopeAttributes",+ "Field",+ ],+ getRowId: (row) => `${row.metricType}:${row.serviceName}:${row.metricName}`,+ getDetailHref: (row, from) => {+ const query = new URLSearchParams({+ from,+ metricType: row.metricType || "",+ serviceName: row.serviceName || "",+ });+ return `/telemetry/metrics/${encodeURIComponent(row.metricName)}?${query.toString()}`;+ },+ },+ {+ key: "logs",+ label: m.OBSERVABILITY_LOGS,+ shortLabel: m.OBSERVABILITY_LOG_SHORT_LABEL,+ tone: "text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-950/40 border-amber-200 dark:border-amber-900",+ summary: m.OBSERVABILITY_LOG_SUMMARY,+ icon: FileText,+ listUrl: "/api/telemetry/logs",+ summaryUrl: "/api/telemetry/summary/logs",+ configUrl: "/api/telemetry/logs/config",+ attributeKeysUrl: "/api/telemetry/logs/attribute-keys",+ columns: logColumns,+ pageName: "observabilityLogs",+ visibilityPage: "observabilityLogs",+ includeOnlySorting: ["Timestamp", "SeverityNumber"],+ customAttributeTypes: [+ "LogAttributes",+ "ResourceAttributes",+ "ScopeAttributes",+ "Field",+ ],+ getRowId: (row) => String(row.rowId),+ getDetailHref: (row, from) =>+ `/telemetry/logs/${row.rowId}?from=${encodeURIComponent(from)}`,+ },+];++export function getSignalConfig(signal: string | null | undefined) {+ return (+ OBSERVABILITY_SIGNALS.find((item) => item.key === signal) ||+ OBSERVABILITY_SIGNALS[0]+ );+}diff --git a/src/client/src/components/(playground)/observability/signal-list.tsx b/src/client/src/components/(playground)/observability/signal-list.tsxnew file mode 100644index 00000000..7cea4668--- /dev/null+++ b/src/client/src/components/(playground)/observability/signal-list.tsx@@ -0,0 +1,494 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { usePathname, useRouter, useSearchParams } from "next/navigation";+import TracesFilter from "@/components/(playground)/filter/traces-filter";+import GroupBreadcrumb from "@/components/(playground)/request/group-breadcrumb";+import GroupedTable, {+ buildGroupValueFilter,+} from "@/components/(playground)/request/grouped-table";+import { getPingStatus } from "@/selectors/database-config";+import {+ getFilterDetails,+ getUpdateConfig,+ getUpdateFilter,+} from "@/selectors/filter";+import { getVisibilityColumnsOfPage } from "@/selectors/page";+import { useRootStore } from "@/store";+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";+import { toast } from "sonner";+import { ObservabilitySignalConfig } from "./registry";+import SignalSummary from "./signal-summary";+import SignalRecords from "./signal-records";+import { TraceDetailView } from "./trace-detail-page";+import { MetricDetailView } from "./metric-detail-page";+import { LogDetailView } from "./log-detail-page";+import { Button } from "@/components/ui/button";+import { Sheet, SheetContent } from "@/components/ui/sheet";+import { Maximize2, X } from "lucide-react";+import getMessage from "@/constants/messages";+import { prepareObservabilitySignalChange } from "@/helpers/client/observability";+import { ResizeablePanel } from "@/components/ui/resizeable-panel";++const DETAIL_SHEET_CONTENT_CLASS =+ "right-2 top-2 bottom-2 flex h-auto w-auto max-w-none flex-col gap-0 border-0 bg-transparent p-0 shadow-none focus-visible:outline-none sm:max-w-none";++function ResizableDetailSheet({+ children,+}: {+ children: ReactNode;+}) {+ const [maxWidth, setMaxWidth] = useState(1200);+ const [defaultWidth, setDefaultWidth] = useState(760);++ useEffect(() => {+ const updateBounds = () => {+ const viewportWidth = window.innerWidth;+ const nextMaxWidth = Math.max(420, viewportWidth - 32);+ setMaxWidth(nextMaxWidth);+ setDefaultWidth(Math.min(Math.max(viewportWidth * 0.68, 860), nextMaxWidth));+ };+ updateBounds();+ window.addEventListener("resize", updateBounds);+ return () => window.removeEventListener("resize", updateBounds);+ }, []);++ return (+ <ResizeablePanel+ defaultWidth={defaultWidth}+ minWidth={420}+ maxWidth={maxWidth}+ handlePosition="left"+ className="h-full max-w-[calc(100vw-1rem)] rounded-md bg-white shadow-2xl dark:bg-stone-950"+ handleClassName="opacity-100 border-stone-300 dark:border-stone-700 bg-white dark:bg-stone-900"+ >+ <div className="flex h-full min-h-0 flex-col overflow-hidden">+ {children}+ </div>+ </ResizeablePanel>+ );+}++export default function ObservabilitySignalList({+ config,+}: {+ config: ObservabilitySignalConfig;+}) {+ const m = getMessage();+ const router = useRouter();+ const pathname = usePathname();+ const searchParams = useSearchParams();+ const filter = useRootStore(getFilterDetails);+ const updateFilter = useRootStore(getUpdateFilter);+ const updateConfig = useRootStore(getUpdateConfig);+ const pingStatus = useRootStore(getPingStatus);+ const visibilityColumns = useRootStore((state) =>+ getVisibilityColumnsOfPage(state, config.visibilityPage)+ );+ const [previewSpanId, setPreviewSpanId] = useState<string | null>(null);+ const skipSelectedHydrationRef = useRef(false);+ const selectedParam = searchParams.get("selected");+ const { data, fireRequest, isFetched, isLoading } = useFetchWrapper();+ const {+ data: summaryData,+ fireRequest: fireSummaryRequest,+ isLoading: isSummaryLoading,+ } = useFetchWrapper();++ useEffect(() => {+ prepareObservabilitySignalChange(updateConfig, updateFilter);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [config.key]);++ const effectiveFilter = useMemo(() => {+ if (filter.groupBy && filter.groupValue) {+ return {+ ...filter,+ selectedConfig: buildGroupValueFilter(+ filter.groupBy,+ filter.groupValue,+ filter.selectedConfig+ ),+ };+ }+ return filter;+ }, [filter]);++ const showFlatList =+ !config.supportGrouping || !filter.groupBy || !!filter.groupValue;++ const fetchData = useCallback(() => {+ fireRequest({+ body: JSON.stringify(effectiveFilter),+ requestType: "POST",+ url: config.listUrl,+ failureCb: (err?: string) => {+ toast.error(err || m.OBSERVABILITY_NO_SERVER_CONNECTION, {+ id: `observability-${config.key}`,+ });+ },+ });+ }, [config.key, config.listUrl, effectiveFilter, fireRequest, m.OBSERVABILITY_NO_SERVER_CONNECTION]);++ const fetchSummary = useCallback(() => {+ fireSummaryRequest({+ body: JSON.stringify(effectiveFilter),+ requestType: "POST",+ url: config.summaryUrl,+ });+ }, [config.summaryUrl, effectiveFilter, fireSummaryRequest]);++ useEffect(() => {+ if (+ effectiveFilter.filterReady &&+ effectiveFilter.timeLimit.start &&+ effectiveFilter.timeLimit.end &&+ pingStatus === "success"+ ) {+ fetchSummary();+ if (showFlatList) fetchData();+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [effectiveFilter, pingStatus, showFlatList]);++ const rows = useMemo(() => {+ const records = (data as any)?.records || [];+ return config.normalize ? records.map(config.normalize) : records;+ }, [config, data]);+ const total = (data as any)?.total || 0;+ const isTraceSignal = config.key === "traces" || config.key === "exceptions";+ const isMetricSignal = config.key === "metrics";+ const isLogSignal = config.key === "logs";++ const setSelectedInUrl = useCallback(+ (id: string | null) => {+ const params = new URLSearchParams(searchParams.toString());+ if (id) {+ params.set("selected", id);+ } else {+ params.delete("selected");+ }+ const query = params.toString();+ router.replace(`${pathname}${query ? `?${query}` : ""}`, {+ scroll: false,+ });+ },+ [pathname, router, searchParams]+ );++ const closePreview = useCallback(() => {+ skipSelectedHydrationRef.current = true;+ setPreviewSpanId(null);+ setSelectedInUrl(null);+ }, [setSelectedInUrl]);++ useEffect(() => {+ if (!selectedParam) {+ skipSelectedHydrationRef.current = false;+ setPreviewSpanId(null);+ return;+ }+ if (isTraceSignal && !previewSpanId && !skipSelectedHydrationRef.current) {+ setPreviewSpanId(selectedParam);+ return;+ }+ if (!isTraceSignal) setPreviewSpanId(null);+ }, [isTraceSignal, previewSpanId, selectedParam]);++ const selectedMetricRow = useMemo(() => {+ if (!isMetricSignal || !selectedParam) return null;+ return (+ rows.find((row: any) => config.getRowId(row) === selectedParam) || null+ );+ }, [config, isMetricSignal, rows, selectedParam]);++ const selectedLogRow = useMemo(() => {+ if (!isLogSignal || !selectedParam) return null;+ return (+ rows.find((row: any) => config.getRowId(row) === selectedParam) || null+ );+ }, [config, isLogSignal, rows, selectedParam]);++ const openDetail = (row: any) => {+ if (isLoading) return;+ if (isTraceSignal) {+ skipSelectedHydrationRef.current = false;+ setPreviewSpanId(row.spanId);+ setSelectedInUrl(row.spanId);+ return;+ }+ if (isMetricSignal) {+ setSelectedInUrl(config.getRowId(row));+ return;+ }+ if (isLogSignal) {+ setSelectedInUrl(config.getRowId(row));+ return;+ }+ const from = `${window.location.pathname}${window.location.search}`;+ router.push(config.getDetailHref(row, from));+ };++ const previewHref = useMemo(() => {+ const activeSpanId = selectedParam || previewSpanId;+ if (!activeSpanId) return "";+ const from =+ typeof window !== "undefined"+ ? `${window.location.pathname}${window.location.search}`+ : "/telemetry";+ const prefix =+ config.key === "exceptions"+ ? "/telemetry/exceptions"+ : "/telemetry/traces";+ return `${prefix}/${activeSpanId}?from=${encodeURIComponent(from)}`;+ }, [config.key, previewSpanId, selectedParam]);++ const metricPreviewHref = useMemo(() => {+ if (!selectedMetricRow) return "";+ const from =+ typeof window !== "undefined"+ ? `${window.location.pathname}${window.location.search}`+ : "/telemetry?tab=metrics";+ return config.getDetailHref(selectedMetricRow, from);+ }, [config, selectedMetricRow]);++ const logPreviewHref = useMemo(() => {+ if (!selectedLogRow) return "";+ const from =+ typeof window !== "undefined"+ ? `${window.location.pathname}${window.location.search}`+ : "/telemetry?tab=logs";+ return config.getDetailHref(selectedLogRow, from);+ }, [config, selectedLogRow]);++ const updateTraceSelection = useCallback(+ (spanId: string) => {+ skipSelectedHydrationRef.current = false;+ setPreviewSpanId(spanId);+ setSelectedInUrl(spanId);+ },+ [setSelectedInUrl]+ );++ const updateActiveTraceSelection = useCallback(+ (spanId: string) => {+ setSelectedInUrl(spanId);+ },+ [setSelectedInUrl]+ );++ const updateTraceNavigationPage = useCallback(+ (offset: number) => {+ updateFilter("offset", offset);+ },+ [updateFilter]+ );++ return (+ <>+ <div className="mb-3">+ <SignalSummary+ key={`summary-${config.key}`}+ config={config}+ data={summaryData as any}+ isLoading={isSummaryLoading || pingStatus === "pending"}+ />+ </div>+ <TracesFilter+ total={showFlatList ? total : undefined}+ supportDynamicFilters+ includeOnlySorting={config.includeOnlySorting}+ pageName={config.pageName}+ columns={config.columns}+ configUrl={config.configUrl}+ attributeKeysUrl={config.attributeKeysUrl}+ customAttributeTypes={config.customAttributeTypes}+ filterStorageScope={config.key}+ showGroupBy={!!config.supportGrouping}+ showVisibilityColumns+ />++ {config.supportGrouping && filter.groupBy && (+ <GroupBreadcrumb+ groupBy={filter.groupBy}+ groupValue={filter.groupValue}+ rootLabel={`All ${config.label}`}+ updateFilter={updateFilter}+ />+ )}++ {config.supportGrouping && filter.groupBy && !filter.groupValue ? (+ <GroupedTable+ groupBy={filter.groupBy}+ apiUrl={config.groupedUrl}+ />+ ) : (+ <div className="flex min-h-0 flex-col gap-4">+ <SignalRecords+ key={`records-${config.key}`}+ config={config}+ rows={rows}+ visibilityColumns={visibilityColumns}+ isFetched={isFetched || pingStatus !== "pending"}+ isLoading={isLoading || pingStatus === "pending"}+ onOpen={openDetail}+ selectedId={selectedParam}+ />+ </div>+ )}+ <Sheet+ modal={false}+ open={isTraceSignal && !!previewSpanId}+ onOpenChange={(open) => !open && closePreview()}+ >+ <SheetContent+ side="right"+ className={DETAIL_SHEET_CONTENT_CLASS}+ displayOverlay={false}+ displayClose={false}+ >+ <ResizableDetailSheet>+ <div className="min-h-0 flex-1 overflow-hidden">+ {previewSpanId && (+ <TraceDetailView+ spanId={previewSpanId}+ type={config.key === "exceptions" ? "exceptions" : "traces"}+ variant="sheet"+ onSpanChange={updateTraceSelection}+ onActiveSpanChange={updateActiveTraceSelection}+ onNavigationPageChange={updateTraceNavigationPage}+ navigationRows={rows}+ navigationOffset={filter.offset}+ navigationTotal={total}+ navigationFilter={effectiveFilter}+ extraActions={+ <>+ <Button+ variant="outline"+ size="sm"+ className="h-7 gap-1.5"+ onClick={() => router.push(previewHref)}+ disabled={!previewHref}+ >+ <Maximize2 className="h-3.5 w-3.5" />+ {m.OBSERVABILITY_FULL_SCREEN}+ </Button>+ <Button+ variant="outline"+ size="sm"+ className="h-7 w-7 p-0 border-stone-200 bg-white text-stone-600 hover:bg-stone-100 hover:text-stone-950 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-300 dark:hover:bg-stone-800 dark:hover:text-stone-50"+ onClick={closePreview}+ title={m.OBSERVABILITY_CLOSE}+ >+ <X className="h-4 w-4" />+ </Button>+ </>+ }+ />+ )}+ </div>+ </ResizableDetailSheet>+ </SheetContent>+ </Sheet>+ <Sheet+ modal={false}+ open={isMetricSignal && !!selectedMetricRow}+ onOpenChange={(open) => !open && closePreview()}+ >+ <SheetContent+ side="right"+ className={DETAIL_SHEET_CONTENT_CLASS}+ displayOverlay={false}+ displayClose={false}+ >+ <ResizableDetailSheet>+ <div className="min-h-0 flex-1 overflow-hidden">+ {selectedMetricRow && (+ <MetricDetailView+ name={selectedMetricRow.metricName}+ metricType={selectedMetricRow.metricType}+ serviceName={selectedMetricRow.serviceName}+ variant="sheet"+ extraActions={+ <div className="flex items-center gap-2">+ <Button+ variant="outline"+ size="sm"+ className="h-7 gap-1.5"+ onClick={() => router.push(metricPreviewHref)}+ disabled={!metricPreviewHref}+ >+ <Maximize2 className="h-3.5 w-3.5" />+ {m.OBSERVABILITY_FULL_SCREEN}+ </Button>+ <Button+ variant="outline"+ size="sm"+ className="h-7 w-7 p-0 border-stone-200 bg-white text-stone-600 hover:bg-stone-100 hover:text-stone-950 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-300 dark:hover:bg-stone-800 dark:hover:text-stone-50"+ onClick={closePreview}+ title={m.OBSERVABILITY_CLOSE}+ >+ <X className="h-4 w-4" />+ </Button>+ </div>+ }+ />+ )}+ </div>+ </ResizableDetailSheet>+ </SheetContent>+ </Sheet>+ <Sheet+ modal={false}+ open={isLogSignal && !!selectedLogRow}+ onOpenChange={(open) => !open && closePreview()}+ >+ <SheetContent+ side="right"+ className={DETAIL_SHEET_CONTENT_CLASS}+ displayOverlay={false}+ displayClose={false}+ >+ <ResizableDetailSheet>+ <div className="min-h-0 flex-1 overflow-hidden">+ {selectedLogRow && (+ <LogDetailView+ id={config.getRowId(selectedLogRow)}+ from={+ typeof window !== "undefined"+ ? `${window.location.pathname}${window.location.search}`+ : "/telemetry?tab=logs"+ }+ variant="sheet"+ extraActions={+ <div className="flex items-center gap-2">+ <Button+ variant="outline"+ size="sm"+ className="h-7 gap-1.5"+ onClick={() => router.push(logPreviewHref)}+ disabled={!logPreviewHref}+ >+ <Maximize2 className="h-3.5 w-3.5" />+ {m.OBSERVABILITY_FULL_SCREEN}+ </Button>+ <Button+ variant="outline"+ size="sm"+ className="h-7 w-7 p-0 border-stone-200 bg-white text-stone-600 hover:bg-stone-100 hover:text-stone-950 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-300 dark:hover:bg-stone-800 dark:hover:text-stone-50"+ onClick={closePreview}+ title={m.OBSERVABILITY_CLOSE}+ >+ <X className="h-4 w-4" />+ </Button>+ </div>+ }+ />+ )}+ </div>+ </ResizableDetailSheet>+ </SheetContent>+ </Sheet>+ </>+ );+}diff --git a/src/client/src/components/(playground)/observability/signal-records.tsx b/src/client/src/components/(playground)/observability/signal-records.tsxnew file mode 100644index 00000000..0168f56c--- /dev/null+++ b/src/client/src/components/(playground)/observability/signal-records.tsx@@ -0,0 +1,414 @@+"use client";++import { format } from "date-fns";+import {+ BarChart3,+ Clock,+ Hash,+ Info,+ Zap,+} from "lucide-react";+import { ObservabilitySignalConfig } from "./registry";+import getMessage from "@/constants/messages";++const m = getMessage();++function formatDate(value?: string) {+ if (!value) return "-";+ try {+ return format(new Date(value), "MMM d, HH:mm:ss");+ } catch {+ return value;+ }+}++function attrValue(+ source: Record<string, any> | undefined,+ keys: string[]+) {+ for (const key of keys) {+ const value = source?.[key];+ if (value !== undefined && value !== null && String(value).length > 0) {+ return String(value);+ }+ }+ return "";+}++function compactText(value?: string, size = 12) {+ if (!value) return "-";+ return value.length > size ? `${value.slice(0, size)}...` : value;+}++function topAttributePairs(+ sources: Array<Record<string, any> | undefined>,+ limit = 3+) {+ const preferred = [+ "event.name",+ "log.iostream",+ "thread.name",+ "process.pid",+ "http.route",+ "url.path",+ "rpc.method",+ "db.system",+ "messaging.operation",+ "k8s.namespace.name",+ "k8s.deployment.name",+ "telemetry.sdk.name",+ ];+ const pairs: Array<[string, string]> = [];+ const pushPair = (key: string, value: unknown) => {+ if (pairs.length >= limit || value == null || String(value).length === 0) return;+ if (pairs.some(([existing]) => existing === key)) return;+ pairs.push([key, String(value)]);+ };++ for (const key of preferred) {+ for (const source of sources) {+ pushPair(key, source?.[key]);+ }+ }+ for (const source of sources) {+ for (const [key, value] of Object.entries(source || {})) {+ pushPair(key, value);+ if (pairs.length >= limit) break;+ }+ if (pairs.length >= limit) break;+ }+ return pairs;+}++function MiniMeta({+ icon,+ label,+ value,+}: {+ icon: React.ReactNode;+ label: string;+ value?: string | number;+}) {+ return (+ <span className="inline-flex min-w-0 items-center gap-1.5 rounded-md border border-stone-200 bg-white px-2 py-1 text-xs text-stone-600 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-300">+ {icon}+ <span className="text-stone-400 dark:text-stone-500">{label}</span>+ <span className="truncate font-medium tabular-nums text-stone-900 dark:text-stone-100">+ {value || "-"}+ </span>+ </span>+ );+}++function TraceRecord({+ row,+ config,+ visibilityColumns,+ isSelected,+ onOpen,+}: {+ row: any;+ config: ObservabilitySignalConfig;+ visibilityColumns: Record<string, boolean>;+ isSelected?: boolean;+ onOpen: (row: any) => void;+}) {+ const show = (key: string) => visibilityColumns[key] !== false;+ return (+ <button+ type="button"+ onClick={() => onOpen(row)}+ className={`group w-full rounded-md border p-3 text-left transition ${+ isSelected+ ? "border-primary bg-primary/10 shadow-sm ring-1 ring-primary/20 dark:border-primary dark:bg-primary/15"+ : "border-stone-200 bg-white hover:border-primary/50 hover:bg-primary/5 dark:border-stone-800 dark:bg-stone-950 dark:hover:border-primary/60 dark:hover:bg-primary/10"+ }`}+ >+ <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">+ <div className="min-w-0">+ <div className="flex min-w-0 items-center gap-2">+ <span className={`h-2 w-2 rounded-full ${config.key === "exceptions" ? "bg-rose-500" : "bg-sky-500"}`} />+ <h3 className="truncate text-sm font-semibold text-stone-950 dark:text-stone-50">+ {show("spanName") ? row.spanName || row.id : row.id}+ </h3>+ </div>+ <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-stone-500 dark:text-stone-400">+ {show("time") && <span>{row.time}</span>}+ {show("id") && <span className="font-mono">{row.spanId}</span>}+ {show("serviceName") && row.serviceName && <span>{row.serviceName}</span>}+ </div>+ </div>+ <div className="grid grid-cols-2 gap-1.5 sm:flex sm:flex-wrap sm:justify-end">+ {show("requestDuration") && <MiniMeta icon={<Clock className="h-3.5 w-3.5" />} label="duration" value={`${parseFloat(row.requestDuration || "0").toFixed(3)}s`} />}+ {show("totalTokens") && <MiniMeta icon={<Zap className="h-3.5 w-3.5" />} label="tokens" value={row.totalTokens} />}+ {show("model") && <MiniMeta icon={<Hash className="h-3.5 w-3.5" />} label="model" value={row.model || row.system} />}+ </div>+ </div>+ </button>+ );+}++function LogRecord({+ row,+ visibilityColumns,+ isSelected,+ onOpen,+}: {+ row: any;+ visibilityColumns: Record<string, boolean>;+ isSelected?: boolean;+ onOpen: (row: any) => void;+}) {+ const show = (key: string) => visibilityColumns[key] !== false;+ const severity = String(row.SeverityText || "INFO");+ const normalizedSeverity = severity.toLowerCase();+ const isError = ["error", "fatal"].includes(normalizedSeverity);+ const isWarn = ["warn", "warning"].includes(normalizedSeverity);+ const severityClass = isError+ ? "bg-rose-100 text-rose-700 dark:bg-rose-950 dark:text-rose-300"+ : isWarn+ ? "bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-300"+ : "bg-sky-100 text-sky-700 dark:bg-sky-950 dark:text-sky-300";+ const logAttrCount = row.LogAttributes ? Object.keys(row.LogAttributes).length : 0;+ const resourceAttrCount = row.ResourceAttributes ? Object.keys(row.ResourceAttributes).length : 0;+ const scopeAttrCount = row.ScopeAttributes ? Object.keys(row.ScopeAttributes).length : 0;+ const resourceAttrs = row.ResourceAttributes || {};+ const logAttrs = row.LogAttributes || {};+ const env = attrValue(resourceAttrs, ["deployment.environment", "service.namespace", "telemetry.sdk.language"]);+ const host = attrValue(resourceAttrs, ["host.name", "container.name", "k8s.pod.name"]);+ const http = [+ attrValue(logAttrs, ["http.request.method", "http.method"]),+ attrValue(logAttrs, ["http.response.status_code", "http.status_code"]),+ ].filter(Boolean).join(" ");+ const exceptionType = attrValue(logAttrs, ["exception.type", "error.type"]);+ const exceptionMessage = attrValue(logAttrs, ["exception.message", "error.message"]);+ const codeLocation = [+ attrValue(logAttrs, ["code.function"]),+ attrValue(logAttrs, ["code.filepath"]),+ attrValue(logAttrs, ["code.lineno"]),+ ].filter(Boolean).join(":");+ const primaryContext = exceptionType || http || codeLocation || env || host || row.ScopeName;+ const fallbackPairs = topAttributePairs([logAttrs, resourceAttrs, row.ScopeAttributes], 3);++ return (+ <button+ type="button"+ onClick={() => onOpen(row)}+ className={`w-full rounded-md border bg-white font-mono text-left transition dark:bg-stone-950 ${+ isSelected+ ? "border-amber-500 bg-amber-50 shadow-sm ring-1 ring-amber-200 dark:border-amber-500 dark:bg-amber-950/20 dark:ring-amber-900"+ : "border-stone-200 hover:border-amber-400 hover:bg-amber-50/50 dark:border-stone-800 dark:hover:border-amber-700 dark:hover:bg-amber-950/10"+ }`}+ >+ <div className="flex w-full items-center gap-2 px-3 py-2">+ <div className="grid min-w-0 grow grid-cols-[auto_auto_auto_1fr] items-center gap-2">+ {show("severityText") && <span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${severityClass}`}>+ {severity}+ </span>}+ {show("time") && <span className="whitespace-nowrap text-xs text-stone-500 dark:text-stone-400">+ {formatDate(row.Timestamp)}+ </span>}+ {show("serviceName") && <span className="max-w-36 truncate text-xs text-stone-500 dark:text-stone-400">+ {row.ServiceName || "unknown service"}+ </span>}+ {show("body") && <p className="truncate text-sm text-stone-900 dark:text-stone-100">+ {row.Body || "-"}+ </p>}+ </div>+ </div>+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-stone-100 px-3 py-1.5 text-[11px] text-stone-500 dark:border-stone-900 dark:text-stone-400">+ <span>sev#{row.SeverityNumber || "-"}</span>+ {primaryContext && <span title={primaryContext}>ctx:{compactText(primaryContext, 28)}</span>}+ {exceptionMessage && <span title={exceptionMessage}>msg:{compactText(exceptionMessage, 32)}</span>}+ {show("traceId") && <span className="font-mono" title={row.TraceId}>trace:{compactText(row.TraceId, 10)}</span>}+ {show("spanId") && <span className="font-mono" title={row.SpanId}>span:{compactText(row.SpanId, 10)}</span>}+ {host && <span title={host}>host:{compactText(host, 18)}</span>}+ {env && <span title={env}>env:{compactText(env, 18)}</span>}+ {fallbackPairs.map(([key, value]) => (+ <span key={`${key}-${value}`} title={`${key}: ${value}`}>+ {compactText(key, 16)}:{compactText(value, 20)}+ </span>+ ))}+ <span>attrs:{logAttrCount}/{resourceAttrCount}/{scopeAttrCount}</span>+ </div>+ </button>+ );+}++function MetricRecord({+ row,+ visibilityColumns,+ isSelected,+ onOpen,+}: {+ row: any;+ visibilityColumns: Record<string, boolean>;+ isSelected?: boolean;+ onOpen: (row: any) => void;+}) {+ const show = (key: string) => visibilityColumns[key] !== false;+ const value = typeof row.latestValue === "number" ? row.latestValue : Number(row.latestValue || 0);+ const maxValue = Math.abs(Number(row.maxValue || 0));+ const minValue = Number(row.minValue || 0);+ const avgValue = Number(row.avgValue || 0);+ const observationCount = Number(row.observationCount || 0);+ const width = `${Math.max(8, Math.min(100, maxValue > 0 ? (Math.abs(value) / maxValue) * 100 : 0))}%`;+ const unit = row.metricUnit || "unitless";++ return (+ <button+ type="button"+ onClick={() => onOpen(row)}+ className={`group w-full rounded-md border p-3 text-left transition ${+ isSelected+ ? "border-emerald-500 bg-emerald-50 shadow-sm ring-1 ring-emerald-200 dark:border-emerald-500 dark:bg-emerald-950/30 dark:ring-emerald-900"+ : "border-stone-200 bg-white hover:border-emerald-400 hover:bg-emerald-50/60 dark:border-stone-800 dark:bg-stone-950 dark:hover:border-emerald-700 dark:hover:bg-emerald-950/20"+ }`}+ >+ <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">+ <div className="min-w-0">+ <div className="flex min-w-0 items-center gap-2">+ <span className="h-2 w-2 rounded-full bg-emerald-500" />+ <h3 className="truncate text-sm font-semibold text-stone-950 dark:text-stone-50">+ {show("metricName") ? row.metricName : m.OBSERVABILITY_METRIC}+ </h3>+ </div>+ <div className="mt-1 flex flex-wrap items-center gap-1.5">+ {show("metricType") && <span className="rounded bg-emerald-100 px-1.5 py-0.5 text-[11px] font-medium text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300">+ {row.metricType}+ </span>}+ {show("serviceName") && <span className="rounded bg-stone-100 px-1.5 py-0.5 text-[11px] text-stone-600 dark:bg-stone-900 dark:text-stone-300">+ {row.serviceName || "all services"}+ </span>}+ {show("lastSeen") && <span className="text-xs text-stone-500 dark:text-stone-400">{formatDate(row.lastSeen)}</span>}+ </div>+ </div>+ <div className="grid grid-cols-2 gap-1.5 sm:flex sm:flex-wrap sm:justify-end">+ {show("latestValue") && (+ <MiniMeta+ icon={<BarChart3 className="h-3.5 w-3.5" />}+ label="latest"+ value={`${Number.isFinite(value) ? value.toLocaleString(undefined, { maximumFractionDigits: 4 }) : "-"} ${unit}`}+ />+ )}+ {show("pointCount") && (+ <MiniMeta+ icon={<Info className="h-3.5 w-3.5" />}+ label="points"+ value={row.pointCount?.toLocaleString?.() || row.pointCount || 0}+ />+ )}+ <MiniMeta+ icon={<BarChart3 className="h-3.5 w-3.5" />}+ label="avg"+ value={Number.isFinite(avgValue) ? avgValue.toLocaleString(undefined, { maximumFractionDigits: 4 }) : "-"}+ />+ <MiniMeta+ icon={<BarChart3 className="h-3.5 w-3.5" />}+ label="range"+ value={`${Number.isFinite(minValue) ? minValue.toLocaleString(undefined, { maximumFractionDigits: 3 }) : "-"} - ${Number.isFinite(maxValue) ? maxValue.toLocaleString(undefined, { maximumFractionDigits: 3 }) : "-"}`}+ />+ {observationCount > row.pointCount && (+ <MiniMeta+ icon={<Info className="h-3.5 w-3.5" />}+ label="obs"+ value={observationCount.toLocaleString()}+ />+ )}+ </div>+ </div>+ <div className="mt-3">+ <div className="h-1.5 rounded-full bg-stone-100 dark:bg-stone-900">+ <div className="h-full rounded-full bg-emerald-500" style={{ width }} />+ </div>+ <div className="mt-1 flex items-center justify-between text-[11px] text-stone-400 dark:text-stone-500">+ <span>latest compared to max in this window</span>+ <div className="flex gap-2">+ <span>min {Number.isFinite(minValue) ? minValue.toLocaleString(undefined, { maximumFractionDigits: 4 }) : "-"}</span>+ <span>max {Number.isFinite(maxValue) ? maxValue.toLocaleString(undefined, { maximumFractionDigits: 4 }) : "-"}</span>+ </div>+ </div>+ </div>+ </button>+ );+}++export default function SignalRecords({+ config,+ rows,+ visibilityColumns,+ isFetched,+ isLoading,+ onOpen,+ selectedId,+}: {+ config: ObservabilitySignalConfig;+ rows: any[];+ visibilityColumns: Record<string, boolean>;+ isFetched: boolean;+ isLoading: boolean;+ onOpen: (row: any) => void;+ selectedId?: string | null;+}) {+ if (isLoading) {+ return (+ <div className="grid gap-2">+ {Array.from({ length: 6 }).map((_, index) => (+ <div+ key={index}+ className="h-20 animate-pulse rounded-md border border-stone-200 bg-stone-100 dark:border-stone-800 dark:bg-stone-900"+ />+ ))}+ </div>+ );+ }++ if (isFetched && rows.length === 0) {+ return (+ <div className="rounded-md border border-dashed border-stone-300 p-8 text-center text-sm text-stone-500 dark:border-stone-700 dark:text-stone-400">+ No {config.label.toLowerCase()} found for the selected filters.+ </div>+ );+ }++ if (config.key === "metrics") {+ return (+ <div className="grid gap-2">+ {rows.map((row) => (+ <MetricRecord+ key={config.getRowId(row)}+ row={row}+ visibilityColumns={visibilityColumns}+ isSelected={selectedId === config.getRowId(row)}+ onOpen={onOpen}+ />+ ))}+ </div>+ );+ }++ return (+ <div className="grid gap-2">+ {rows.map((row) =>+ config.key === "logs" ? (+ <LogRecord+ key={config.getRowId(row)}+ row={row}+ visibilityColumns={visibilityColumns}+ isSelected={selectedId === config.getRowId(row)}+ onOpen={onOpen}+ />+ ) : (+ <TraceRecord+ key={config.getRowId(row)}+ row={row}+ config={config}+ visibilityColumns={visibilityColumns}+ isSelected={selectedId === row.spanId}+ onOpen={onOpen}+ />+ )+ )}+ </div>+ );+}diff --git a/src/client/src/components/(playground)/observability/signal-summary.tsx b/src/client/src/components/(playground)/observability/signal-summary.tsxnew file mode 100644index 00000000..827c3125--- /dev/null+++ b/src/client/src/components/(playground)/observability/signal-summary.tsx@@ -0,0 +1,90 @@+"use client";++import {+ Bar,+ BarChart,+ CartesianGrid,+ ResponsiveContainer,+ Tooltip,+ XAxis,+ YAxis,+} from "recharts";+import { ObservabilitySignalConfig } from "./registry";+import getMessage from "@/constants/messages";++const m = getMessage();++type SummaryData = {+ bucket?: string;+ total?: number;+ peak?: number;+ buckets?: Array<Record<string, any>>;+};++function formatBucket(bucket?: string) {+ if (!bucket) return m.OBSERVABILITY_AUTO;+ return bucket.charAt(0).toUpperCase() + bucket.slice(1);+}++function chartColor(signal: ObservabilitySignalConfig["key"]) {+ if (signal === "exceptions") return "#e11d48";+ if (signal === "logs") return "#d97706";+ if (signal === "metrics") return "#059669";+ return "#0284c7";+}++export default function SignalSummary({+ config,+ data,+ isLoading,+}: {+ config: ObservabilitySignalConfig;+ data?: SummaryData;+ isLoading?: boolean;+}) {+ const buckets = data?.buckets || [];+ const metricLabel =+ config.key === "metrics"+ ? m.OBSERVABILITY_METRIC_POINTS+ : config.key === "logs"+ ? m.OBSERVABILITY_LOG_EVENTS+ : m.OBSERVABILITY_SPANS;++ return (+ <section className="rounded-md border border-stone-200 bg-stone-50/80 p-3 dark:border-stone-800 dark:bg-stone-900/40">+ <div className="min-w-0">+ <div className="mb-2 flex flex-wrap items-center justify-between gap-2">+ <div>+ <p className="text-xs uppercase tracking-wide text-stone-500 dark:text-stone-400">+ {formatBucket(data?.bucket)} volume+ </p>+ <h2 className="text-sm font-semibold text-stone-950 dark:text-stone-50">+ {metricLabel}+ </h2>+ </div>+ <span className={`rounded-full border px-2 py-1 text-xs font-medium ${config.tone}`}>+ {isLoading ? m.OBSERVABILITY_LOADING : `${buckets.length} buckets`}+ </span>+ </div>+ <div className="h-28 min-w-0">+ <ResponsiveContainer width="100%" height="100%">+ <BarChart data={buckets} margin={{ top: 2, right: 8, bottom: 0, left: -22 }}>+ <CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-stone-200 dark:stroke-stone-800" />+ <XAxis dataKey="label" tickLine={false} axisLine={false} className="text-[10px] fill-stone-500" />+ <YAxis tickLine={false} axisLine={false} className="text-[10px] fill-stone-500" />+ <Tooltip+ cursor={{ fill: "rgba(120, 113, 108, 0.12)" }}+ contentStyle={{+ borderRadius: 6,+ borderColor: "rgb(214 211 209)",+ fontSize: 12,+ }}+ />+ <Bar dataKey="count" radius={[4, 4, 0, 0]} fill={chartColor(config.key)} />+ </BarChart>+ </ResponsiveContainer>+ </div>+ </div>+ </section>+ );+}diff --git a/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsx b/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsxnew file mode 100644index 00000000..f38436e7--- /dev/null+++ b/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsx@@ -0,0 +1,214 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import type { ReactNode } from "react";+import { BarChart3, DollarSign, GitBranch, MessageSquareText, Network } from "lucide-react";+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";+import { TraceHeirarchySpan } from "@/types/trace";+import {+ RequestProvider,+ useRequest,+} from "@/components/(playground)/request/request-context";+import TreeNode from "@/components/(playground)/request/components/tree-node";+import TimelineView from "@/components/(playground)/request/components/timeline-view";+import NodeGraph from "@/components/(playground)/request/components/node-graph";+import ChatView from "@/components/(playground)/request/components/chat-view";+import getMessage from "@/constants/messages";+import { cn } from "@/lib/utils";++type ViewMode = "tree" | "chat" | "timeline" | "graph";++const VIEW_MODES: { key: ViewMode; labelKey: "OBSERVABILITY_TREE" | "OBSERVABILITY_CHAT" | "OBSERVABILITY_TIMELINE" | "OBSERVABILITY_GRAPH"; icon: ReactNode }[] = [+ { key: "tree", labelKey: "OBSERVABILITY_TREE", icon: <GitBranch className="h-3.5 w-3.5" /> },+ { key: "chat", labelKey: "OBSERVABILITY_CHAT", icon: <MessageSquareText className="h-3.5 w-3.5" /> },+ { key: "timeline", labelKey: "OBSERVABILITY_TIMELINE", icon: <BarChart3 className="h-3.5 w-3.5" /> },+ { key: "graph", labelKey: "OBSERVABILITY_GRAPH", icon: <Network className="h-3.5 w-3.5" /> },+];++function sumCostRecursive(span: TraceHeirarchySpan): number {+ const cost = span.Cost != null && span.Cost > 0 ? span.Cost : 0;+ const childrenCost = (span.children || []).reduce(+ (acc, child) => acc + sumCostRecursive(child),+ 0+ );+ return cost + childrenCost;+}++function countSpans(span?: TraceHeirarchySpan): number {+ if (!span) return 0;+ return 1 + (span.children || []).reduce((acc, child) => acc + countSpans(child), 0);+}++function SelectionBridge({+ onSelectSpan,+ selectedSpanId,+}: {+ onSelectSpan?: (spanId: string) => void;+ selectedSpanId: string;+}) {+ const [request] = useRequest();+ const lastSelectedSpanId = useRef(selectedSpanId);++ useEffect(() => {+ if (lastSelectedSpanId.current !== selectedSpanId) {+ lastSelectedSpanId.current = selectedSpanId;+ return;+ }+ if (request?.spanId && request.spanId !== selectedSpanId) {+ onSelectSpan?.(request.spanId);+ }+ }, [onSelectSpan, request?.spanId, selectedSpanId]);++ return null;+}++function SpanHierarchyExplorerInner({+ hierarchySpanId,+ selectedSpanId,+ onSelectSpan,+ fill = false,+}: {+ hierarchySpanId: string;+ selectedSpanId: string;+ onSelectSpan?: (spanId: string) => void;+ fill?: boolean;+}) {+ const m = getMessage();+ const [, updateRequest] = useRequest();+ const [viewMode, setViewMode] = useState<ViewMode>("tree");+ const { data, fireRequest, isLoading } = useFetchWrapper();++ useEffect(() => {+ updateRequest({ spanId: selectedSpanId } as any);+ }, [selectedSpanId, updateRequest]);++ useEffect(() => {+ fireRequest({+ requestType: "GET",+ url: `/api/metrics/request/span/${hierarchySpanId}/heirarchy`,+ });+ }, [fireRequest, hierarchySpanId]);++ const typedData = (data as { record?: TraceHeirarchySpan; err?: string }) || {};+ const record = typedData.record;+ const aggregateCost = useMemo(+ () => (record ? sumCostRecursive(record) : 0),+ [record]+ );+ const spanCount = useMemo(() => countSpans(record), [record]);++ return (+ <section+ className={cn(+ "rounded-md border border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950 overflow-hidden",+ fill && "flex h-full min-h-0 flex-col"+ )}+ >+ <SelectionBridge+ selectedSpanId={selectedSpanId}+ onSelectSpan={onSelectSpan}+ />+ <div className="flex flex-wrap items-center gap-2 border-b border-stone-200 bg-stone-50 px-2 py-1.5 dark:border-stone-800 dark:bg-stone-900">++ <div className="flex rounded-md border border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950 p-0.5">+ {VIEW_MODES.map((mode) => (+ <button+ key={mode.key}+ onClick={() => setViewMode(mode.key)}+ className={`inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs font-medium transition-colors ${+ viewMode === mode.key+ ? "bg-primary text-white"+ : "text-stone-500 hover:bg-stone-100 dark:text-stone-400 dark:hover:bg-stone-800"+ }`}+ >+ {mode.icon}+ {m[mode.labelKey]}+ </button>+ ))}+ </div>+ <div className="ml-auto flex min-w-0 items-center gap-2">+ <span className="rounded border border-stone-200 bg-white px-1.5 py-0.5 text-[11px] text-stone-500 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-400">+ {isLoading+ ? m.OBSERVABILITY_LOADING_SPANS+ : m.OBSERVABILITY_SPAN_COUNT(spanCount.toLocaleString())}+ </span>+ </div>+ </div>++ {isLoading ? (+ <div className="grid gap-2 p-3">+ {[0, 1, 2, 3].map((item) => (+ <div+ key={item}+ className="h-9 animate-pulse rounded bg-stone-100 dark:bg-stone-900"+ />+ ))}+ </div>+ ) : !record || typedData.err ? (+ <div className="px-3 py-8 text-sm text-stone-400">+ {m.OBSERVABILITY_HIERARCHY_UNAVAILABLE}+ </div>+ ) : (+ <div+ className={cn(+ "bg-stone-50/60 dark:bg-stone-950",+ fill+ ? viewMode === "graph"+ ? "min-h-0 flex-1 overflow-hidden overscroll-contain"+ : "min-h-0 flex-1 overflow-auto"+ : viewMode === "graph"+ ? "h-[520px] overflow-hidden overscroll-contain"+ : "max-h-[520px] overflow-auto"+ )}+ >+ {viewMode === "tree" && (+ <div className="min-w-fit p-3">+ <TreeNode span={record} level={0} />+ </div>+ )}+ {viewMode === "chat" && <ChatView record={record} />}+ {viewMode === "timeline" && (+ <div className="min-w-fit p-3">+ <TimelineView record={record} />+ </div>+ )}+ {viewMode === "graph" && <NodeGraph record={record} />}+ </div>+ )}+ {aggregateCost > 0 && (+ <div className="flex shrink-0 items-center gap-2 border-t border-stone-200 bg-stone-50 px-3 py-2 dark:border-stone-800 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="font-mono text-xs font-semibold text-stone-900 dark:text-stone-100">+ ${aggregateCost.toFixed(10)}+ </span>+ </div>+ )}+ </section>+ );+}++export default function SpanHierarchyExplorer({+ hierarchySpanId,+ selectedSpanId,+ onSelectSpan,+ fill,+}: {+ hierarchySpanId: string;+ selectedSpanId: string;+ onSelectSpan?: (spanId: string) => void;+ fill?: boolean;+}) {+ return (+ <RequestProvider syncUrl={false}>+ <SpanHierarchyExplorerInner+ hierarchySpanId={hierarchySpanId}+ selectedSpanId={selectedSpanId}+ onSelectSpan={onSelectSpan}+ fill={fill}+ />+ </RequestProvider>+ );+}diff --git a/src/client/src/components/(playground)/observability/trace-detail-page.tsx b/src/client/src/components/(playground)/observability/trace-detail-page.tsxnew file mode 100644index 00000000..aea4f747--- /dev/null+++ b/src/client/src/components/(playground)/observability/trace-detail-page.tsx@@ -0,0 +1,574 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import type { ReactNode } from "react";+import { useRouter, useSearchParams } from "next/navigation";+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";+import DetailShell from "./detail-shell";+import { getExtraTabsContentTypes, normalizeTrace } from "@/helpers/client/trace";+import { getTimeLimitObject } from "@/store/filter";+import { FilterConfig, FilterType, TIME_RANGES } from "@/types/store/filter";+import { useCustomBreadcrumbs } from "@/utils/hooks/useBreadcrumbs";+import { AlertTriangle, ArrowLeft, ChevronLeft, ChevronRight, Clock, Cpu, DollarSign, RefreshCw, Zap } from "lucide-react";+import SpanHierarchyExplorer from "./span-hierarchy-explorer";+import { Button } from "@/components/ui/button";+import getMessage from "@/constants/messages";+import Evaluations from "@/components/(playground)/request/components/evaluations";+import DetailObjectTabs, { buildObjectTabs } from "./detail-object-tabs";+import {+ ResizableHandle,+ ResizablePanel,+ ResizablePanelGroup,+} from "@/components/ui/resizable";+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";+import { toast } from "sonner";++function Stat({ icon, label, value }: { icon: ReactNode; label: string; value?: string }) {+ return (+ <div className="rounded-md bg-stone-100 px-2.5 py-1.5 dark:bg-stone-900">+ <div className="flex items-center gap-1.5 text-[11px] text-stone-500 dark:text-stone-400">+ {icon}+ {label}+ </div>+ <div className="mt-0.5 truncate text-xs font-semibold text-stone-900 dark:text-stone-100">+ {value || "-"}+ </div>+ </div>+ );+}++function CostStat({+ costValue,+ spanId,+ hasModel,+ onRecalculated,+}: {+ costValue?: string;+ spanId?: string;+ hasModel: boolean;+ onRecalculated: () => void;+}) {+ const m = getMessage();+ const hasCost = !!costValue && costValue !== "-";+ const canRecalculate = hasModel && !!spanId;+ const { fireRequest, isLoading } = useFetchWrapper<{+ success: boolean;+ err?: string;+ data?: { spanId: string; cost: number };+ }>();++ const handleRecalculate = (event: React.MouseEvent) => {+ event.stopPropagation();+ if (!spanId || isLoading) return;+ fireRequest({+ requestType: "POST",+ url: `/api/pricing/${spanId}`,+ successCb: (response) => {+ if (response?.success) {+ toast.success(+ `${m.RECALCULATE_COST_SUCCESS}: $${(response.data?.cost ?? 0).toFixed(10)}`,+ { id: "pricing-update" }+ );+ onRecalculated();+ } else {+ toast.error(response?.err || m.RECALCULATE_COST_FAILURE, {+ id: "pricing-update",+ });+ }+ },+ failureCb: (err?: string) => {+ toast.error(err || m.RECALCULATE_COST_REQUEST_FAILED, {+ id: "pricing-update",+ });+ },+ });+ };++ return (+ <div className="rounded-md bg-stone-100 px-2.5 py-1.5 dark:bg-stone-900">+ <div className="flex items-center gap-1.5 text-[11px] text-stone-500 dark:text-stone-400">+ <DollarSign className="h-3.5 w-3.5" />+ {m.OBSERVABILITY_COST}+ {canRecalculate && (+ <TooltipProvider delayDuration={200}>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ onClick={handleRecalculate}+ disabled={isLoading}+ className="relative ml-auto rounded p-0.5 transition-colors hover:bg-stone-200 disabled:opacity-50 dark:hover:bg-stone-700"+ >+ <RefreshCw className={`h-3 w-3 ${isLoading ? "animate-spin" : ""}`} />+ {!hasCost && !isLoading && (+ <span className="absolute -right-0.5 -top-0.5 h-2 w-2 animate-ping rounded-full bg-primary" />+ )}+ </button>+ </TooltipTrigger>+ <TooltipContent side="bottom" className="max-w-[220px] text-xs">+ {m.RECALCULATE_COST_TITLE}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ )}+ </div>+ <div className="mt-0.5 truncate text-xs font-semibold text-stone-900 dark:text-stone-100">+ {costValue || "-"}+ </div>+ </div>+ );+}++function MetaPill({ label, value }: { label: string; value?: string }) {+ if (!value) return null;+ return (+ <div className="min-w-0 rounded-md border border-stone-200 bg-white px-2 py-1 dark:border-stone-800 dark:bg-stone-950">+ <div className="text-[10px] uppercase tracking-wide text-stone-500 dark:text-stone-400">+ {label}+ </div>+ <div className="max-w-72 truncate font-mono text-[11px] font-medium text-stone-900 dark:text-stone-100" title={value}>+ {value}+ </div>+ </div>+ );+}++const CF_SEP = "|";++function paramsToSelectedConfig(params: URLSearchParams): Partial<FilterConfig> {+ const config: Partial<FilterConfig> = {};+ const assignList = (param: string, key: keyof FilterConfig) => {+ const value = params.get(param);+ if (value) (config as any)[key] = value.split(",").filter(Boolean);+ };+ assignList("models", "models");+ assignList("providers", "providers");+ assignList("traceTypes", "traceTypes");+ assignList("appNames", "applicationNames");+ assignList("spanNames", "spanNames");+ assignList("envs", "environments");+ assignList("services", "services");+ assignList("severities", "severities");+ assignList("metricNames", "metricNames");+ assignList("metricTypes", "metricTypes");+ 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 any,+ key: key || "",+ value: rest.join(CF_SEP),+ };+ })+ .filter((filter) => filter.key && filter.value);+ }+ return config;+}++function filterFromSource(from: string | null, offsetOverride?: number): FilterType {+ const params = new URLSearchParams();+ if (from && typeof window !== "undefined") {+ const url = new URL(from, window.location.origin);+ url.searchParams.forEach((value, key) => params.append(key, value));+ }++ const range = (params.get("tr") || "24H") as TIME_RANGES;+ const customStart = params.get("ts");+ const customEnd = params.get("te");+ const timeLimit =+ range === "CUSTOM" && customStart && customEnd+ ? { type: range, start: new Date(customStart), end: new Date(customEnd) }+ : {+ type: range,+ ...(getTimeLimitObject(range, "") as { start: Date; end: Date }),+ };++ return {+ timeLimit,+ limit: parseInt(params.get("limit") || "25", 10),+ offset: offsetOverride ?? parseInt(params.get("offset") || "0", 10),+ selectedConfig: paramsToSelectedConfig(params),+ sorting: { type: "Timestamp", direction: "desc" },+ refreshRate: "1m",+ filterReady: true,+ groupBy: params.get("gb") || undefined,+ groupValue: params.get("gbv") || undefined,+ };+}++function sourceWithOffset(from: string | null, offset: number) {+ if (!from || typeof window === "undefined") return from;+ const url = new URL(from, window.location.origin);+ url.searchParams.set("offset", String(offset));+ return `${url.pathname}${url.search}`;+}++export function TraceDetailView({+ spanId,+ type,+ variant = "page",+ onSpanChange,+ onActiveSpanChange,+ extraActions,+ navigationRows,+ navigationOffset,+ navigationTotal,+ navigationFilter,+ onNavigationPageChange,+}: {+ spanId: string;+ type: "traces" | "exceptions";+ variant?: "page" | "sheet";+ onSpanChange?: (spanId: string) => void;+ onActiveSpanChange?: (spanId: string) => void;+ extraActions?: ReactNode;+ navigationRows?: any[];+ navigationOffset?: number;+ navigationTotal?: number;+ navigationFilter?: FilterType;+ onNavigationPageChange?: (offset: number) => void;+}) {+ const m = getMessage();+ const router = useRouter();+ const searchParams = useSearchParams();+ const from = searchParams.get("from");+ const [selectedSpanId, setSelectedSpanId] = useState(spanId);+ const [activeListSpanId, setActiveListSpanId] = useState(spanId);+ const hierarchySpanIdRef = useRef(spanId);+ const [listOffset, setListOffset] = useState(() => filterFromSource(from).offset);+ const [navigationPageOverride, setNavigationPageOverride] = useState<{+ rows: any[];+ offset: number;+ total?: number;+ } | null>(null);+ const fromRef = useRef(from);+ const listUrlRef = useRef(type === "exceptions" ? "/api/metrics/exception" : "/api/metrics/request");+ const detailBasePathRef = useRef(+ type === "exceptions" ? "/telemetry/exceptions" : "/telemetry/traces"+ );+ const { data, fireRequest, isLoading } = useFetchWrapper();+ const {+ data: listData,+ fireRequest: fireListRequest,+ isLoading: isListLoading,+ } = useFetchWrapper<any>();+ const fetchData = useCallback(() => {+ fireRequest({+ requestType: "GET",+ url: `/api/metrics/request/span/${selectedSpanId}`,+ });+ }, [fireRequest, selectedSpanId]);++ useEffect(() => {+ hierarchySpanIdRef.current = spanId;+ setSelectedSpanId(spanId);+ setActiveListSpanId(spanId);+ setNavigationPageOverride((currentPage) =>+ currentPage?.rows.some((row: any) => row.spanId === spanId)+ ? currentPage+ : null+ );+ }, [spanId]);++ useEffect(() => {+ fetchData();+ }, [fetchData]);++ const navigateToListSpan = useCallback(+ (nextSpanId: string) => {+ hierarchySpanIdRef.current = nextSpanId;+ setActiveListSpanId(nextSpanId);+ setSelectedSpanId(nextSpanId);+ const source = fromRef.current;+ const qs = source ? `?from=${encodeURIComponent(source)}` : "";+ if (variant === "page") {+ router.replace(`${detailBasePathRef.current}/${nextSpanId}${qs}`, { scroll: false });+ }+ onSpanChange?.(nextSpanId);+ },+ [onSpanChange, router, variant]+ );++ const selectSpanInCurrentTrace = useCallback(+ (nextSpanId: string) => {+ setSelectedSpanId(nextSpanId);+ onActiveSpanChange?.(nextSpanId);+ },+ [onActiveSpanChange]+ );++ const fetchList = useCallback(+ (offset: number, direction?: -1 | 1) => {+ const listFilter = fromRef.current+ ? filterFromSource(fromRef.current, offset)+ : navigationFilter+ ? { ...navigationFilter, offset }+ : filterFromSource(fromRef.current, offset);+ fireListRequest({+ body: JSON.stringify(listFilter),+ requestType: "POST",+ url: listUrlRef.current,+ successCb: (response) => {+ if (!direction) return;+ const records = ((response as any)?.records || []).map(normalizeTrace);+ const target =+ direction === 1 ? records[0] : records[records.length - 1];+ if (target?.spanId) {+ const nextSource = sourceWithOffset(fromRef.current, offset);+ fromRef.current = nextSource;+ setListOffset(offset);+ setNavigationPageOverride({+ rows: records,+ offset,+ total: (response as any)?.total,+ });+ onNavigationPageChange?.(offset);+ navigateToListSpan(target.spanId);+ }+ },+ });+ },+ [fireListRequest, navigateToListSpan, navigationFilter, onNavigationPageChange]+ );++ useEffect(() => {+ fetchList(listOffset);+ // Only hydrate the neighboring list once. Explicit page-boundary navigation+ // fetches another page on demand; making this reactive causes route updates+ // to cascade into repeated list fetches.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const raw = (data as any)?.record;+ const trace = raw ? normalizeTrace(raw) : null;+ const resourceAttributes = raw?.ResourceAttributes || {};+ const serviceNamespace = resourceAttributes["service.namespace"];+ const deploymentEnvironment =+ resourceAttributes["deployment.environment"] ||+ (trace as any)?.environment ||+ (trace as any)?.deploymentType;+ const statusValue =+ raw?.StatusMessage || raw?.StatusCode+ ? [raw?.StatusCode, raw?.StatusMessage].filter(Boolean).join(" / ")+ : undefined;+ const hasEvaluationPanel = trace+ ? getExtraTabsContentTypes(trace).includes("Evaluation")+ : false;+ const detailTabs = useMemo(+ () => buildObjectTabs(raw, {+ labelOverrides: {+ SpanAttributes: "Span Attributes",+ ResourceAttributes: "Resource Attributes",+ },+ }),+ [raw]+ );+ const title = trace?.spanName || (isLoading ? m.OBSERVABILITY_TRACE_LOADING : selectedSpanId);+ const resultsHref =+ from || `/telemetry?tab=${type === "exceptions" ? "exceptions" : "traces"}`;+ const breadcrumbTitle = trace?.spanName || (isLoading ? m.OBSERVABILITY_LOADING : m.OBSERVABILITY_TRACE_DETAILS);++ const customHeader = useMemo(+ () => ({+ title: breadcrumbTitle,+ description: selectedSpanId,+ breadcrumbs: [+ { title: m.OBSERVABILITY_TITLE, href: resultsHref },+ ],+ }),+ [breadcrumbTitle, m.OBSERVABILITY_TITLE, resultsHref, selectedSpanId]+ );+ useCustomBreadcrumbs(customHeader, [selectedSpanId, resultsHref], variant === "page");+ const listRows = useMemo(+ () => (((listData as any)?.records || []).map(normalizeTrace)),+ [listData]+ );+ const effectiveListRows = navigationPageOverride?.rows?.length+ ? navigationRows?.some((row: any) => row.spanId === activeListSpanId)+ ? navigationRows+ : navigationPageOverride.rows+ : navigationRows?.length+ ? navigationRows+ : listRows;+ const effectiveListOffset =+ navigationPageOverride?.rows?.length &&+ !navigationRows?.some((row: any) => row.spanId === activeListSpanId)+ ? navigationPageOverride.offset+ : navigationOffset ?? listOffset;+ const total =+ navigationPageOverride?.rows?.length &&+ !navigationRows?.some((row: any) => row.spanId === activeListSpanId)+ ? navigationPageOverride.total ?? navigationTotal ?? (listData as any)?.total ?? 0+ : navigationTotal ?? (listData as any)?.total ?? 0;+ const currentIndex = effectiveListRows.findIndex((row: any) => row.spanId === activeListSpanId);+ const navigationLimit =+ navigationFilter?.limit ?? filterFromSource(fromRef.current).limit;+ const canPrev = currentIndex > 0 || effectiveListOffset > 0;+ const canNext =+ currentIndex >= 0 &&+ (currentIndex < effectiveListRows.length - 1 || effectiveListOffset + effectiveListRows.length < total);++ const selectPrev = () => {+ if (currentIndex > 0) {+ navigateToListSpan(effectiveListRows[currentIndex - 1].spanId);+ } else if (effectiveListOffset > 0) {+ fetchList(Math.max(0, effectiveListOffset - navigationLimit), -1);+ }+ };++ const selectNext = () => {+ if (currentIndex >= 0 && currentIndex < effectiveListRows.length - 1) {+ navigateToListSpan(effectiveListRows[currentIndex + 1].spanId);+ } else if (effectiveListOffset + effectiveListRows.length < total) {+ fetchList(effectiveListOffset + navigationLimit, 1);+ }+ };++ const goBack = () => {+ router.push(resultsHref);+ };++ return (+ <DetailShell+ title={title}+ compact+ leadingActions={+ variant === "page" ? (+ <Button+ variant="outline"+ size="sm"+ onClick={goBack}+ className="h-8 w-8 p-0"+ title={m.OBSERVABILITY_BACK}+ >+ <ArrowLeft className="h-3.5 w-3.5" />+ </Button>+ ) : undefined+ }+ headerMeta={+ trace ? (+ <div className="grid grid-cols-2 gap-1.5 md:grid-cols-3 xl:grid-cols-5">+ {statusValue && (+ <Stat icon={<AlertTriangle className="h-3.5 w-3.5" />} label="Status" value={statusValue} />+ )}+ <Stat icon={<Clock className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_DURATION} value={`${parseFloat(trace.requestDuration).toFixed(3)}s`} />+ <Stat icon={<Zap className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_TOKENS} value={trace.totalTokens} />+ <CostStat+ costValue={trace.cost && trace.cost !== "-" ? `$${trace.cost}` : undefined}+ spanId={trace.spanId}+ hasModel={!!trace.model}+ onRecalculated={fetchData}+ />+ <Stat icon={<Cpu className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_MODEL} value={trace.model || trace.serviceName} />+ </div>+ ) : undefined+ }+ actions={+ <div className="flex flex-wrap items-center justify-end gap-2">+ <div className="flex items-center gap-1 rounded-md border border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950 p-0.5">+ <button+ onClick={selectPrev}+ disabled={!canPrev || isListLoading}+ className="rounded p-1 text-stone-500 hover:bg-stone-100 hover:text-stone-900 disabled:cursor-not-allowed disabled:opacity-30 dark:text-stone-400 dark:hover:bg-stone-800 dark:hover:text-stone-100"+ title={m.OBSERVABILITY_PREVIOUS_SPAN}+ >+ <ChevronLeft className="h-4 w-4" />+ </button>+ <span className="min-w-[4.5rem] px-1 text-center text-xs tabular-nums text-stone-500 dark:text-stone-400">+ {currentIndex >= 0 ? `${effectiveListOffset + currentIndex + 1} / ${total || effectiveListRows.length}` : "-"}+ </span>+ <button+ onClick={selectNext}+ disabled={!canNext || isListLoading}+ className="rounded p-1 text-stone-500 hover:bg-stone-100 hover:text-stone-900 disabled:cursor-not-allowed disabled:opacity-30 dark:text-stone-400 dark:hover:bg-stone-800 dark:hover:text-stone-100"+ title={m.OBSERVABILITY_NEXT_SPAN}+ >+ <ChevronRight className="h-4 w-4" />+ </button>+ </div>+ {extraActions}+ </div>+ }+ >+ {trace && (+ <>+ <div className="flex flex-wrap gap-1.5">+ <MetaPill label={m.OBSERVABILITY_TRACE_ID} value={trace.id} />+ <MetaPill label={m.OBSERVABILITY_SPAN_ID} value={trace.spanId} />+ <MetaPill label={m.OBSERVABILITY_SERVICE} value={trace.serviceName} />+ <MetaPill label="Service Namespace" value={serviceNamespace} />+ <MetaPill label="Deployment Environment" value={deploymentEnvironment} />+ </div>+ <div className="hidden h-[min(860px,calc(100vh-12rem))] min-h-[620px] overflow-hidden rounded-md border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950 lg:block">+ <ResizablePanelGroup direction="horizontal" className="h-full">+ <ResizablePanel defaultSize={48} minSize={32} maxSize={68}>+ <div className="h-full min-h-0 p-2">+ <SpanHierarchyExplorer+ hierarchySpanId={hierarchySpanIdRef.current}+ selectedSpanId={selectedSpanId}+ onSelectSpan={selectSpanInCurrentTrace}+ fill+ />+ </div>+ </ResizablePanel>+ <ResizableHandle withHandle />+ <ResizablePanel defaultSize={52} minSize={32}>+ <div className="h-full min-h-0 overflow-auto p-2">+ <DetailObjectTabs+ tabs={detailTabs}+ extraTabs={+ hasEvaluationPanel && trace+ ? [+ {+ id: "evaluations",+ label: "Evaluations",+ content: <Evaluations trace={trace} surface="observability" />,+ },+ ]+ : undefined+ }+ />+ </div>+ </ResizablePanel>+ </ResizablePanelGroup>+ </div>+ <div className="grid gap-3 lg:hidden">+ <SpanHierarchyExplorer+ hierarchySpanId={hierarchySpanIdRef.current}+ selectedSpanId={selectedSpanId}+ onSelectSpan={selectSpanInCurrentTrace}+ />+ <DetailObjectTabs+ tabs={detailTabs}+ extraTabs={+ hasEvaluationPanel && trace+ ? [+ {+ id: "evaluations",+ label: "Evaluations",+ content: <Evaluations trace={trace} surface="observability" />,+ },+ ]+ : undefined+ }+ />+ </div>+ </>+ )}+ </DetailShell>+ );+}++export default function TraceDetailPage({+ spanId,+ type,+}: {+ spanId: string;+ type: "traces" | "exceptions";+}) {+ return <TraceDetailView spanId={spanId} type={type} variant="page" />;+}diff --git a/src/client/src/components/(playground)/request/components/chat-view.tsx b/src/client/src/components/(playground)/request/components/chat-view.tsxindex c37d4262..4e91a80b 100644--- a/src/client/src/components/(playground)/request/components/chat-view.tsx+++ b/src/client/src/components/(playground)/request/components/chat-view.tsx@@ -284,25 +284,25 @@ function ToolIndicator({return (<div- className={`mx-3 rounded-lg border cursor-pointer transition-colors ${+ className={`mx-2 cursor-pointer rounded-md border transition-colors ${isSelected? "border-primary/40 bg-primary/5"- : "border-stone-200 dark:border-stone-700 bg-stone-50 dark:bg-stone-900/50 hover:bg-stone-100 dark:hover:bg-stone-800"+ : "border-stone-200 bg-white hover:bg-stone-50 dark:border-stone-800 dark:bg-stone-950 dark:hover:bg-stone-900"}`}onClick={onClick}>{/* Header row */}- <div className="flex items-center gap-2 px-3 py-2">- <div className="flex items-center justify-center h-6 w-6 rounded-md bg-violet-100 dark:bg-violet-900/40 shrink-0">- <Wrench className="h-3.5 w-3.5 text-violet-600 dark:text-violet-400" />+ <div className="flex items-center gap-2 px-2.5 py-1.5">+ <div className="flex h-5 w-5 shrink-0 items-center justify-center rounded border border-stone-200 bg-stone-50 dark:border-stone-800 dark:bg-stone-900">+ <Wrench className="h-3 w-3 text-stone-500 dark:text-stone-400" /></div><div className="flex flex-col min-w-0 flex-1"><div className="flex items-center gap-1.5">- <span className="text-[11px] font-semibold text-violet-700 dark:text-violet-300">+ <span className="text-[11px] font-semibold text-stone-700 dark:text-stone-300">{item.label}</span>{item.toolType && (- <span className="text-[9px] px-1.5 py-0.5 rounded-full bg-violet-100 dark:bg-violet-900/30 text-violet-600 dark:text-violet-400 font-medium">+ <span className="rounded border border-stone-200 px-1.5 py-0.5 text-[9px] font-medium text-stone-500 dark:border-stone-800 dark:text-stone-400">{item.toolType}</span>)}@@ -322,7 +322,7 @@ function ToolIndicator({{displayArgs && (<div className="border-t border-stone-200 dark:border-stone-700"><button- className="flex items-center gap-1 px-3 py-1 text-[10px] text-stone-400 dark:text-stone-500 hover:text-stone-600 dark:hover:text-stone-300 w-full"+ className="flex items-center gap-1 px-2.5 py-1 text-[10px] text-stone-400 dark:text-stone-500 hover:text-stone-600 dark:hover:text-stone-300 w-full"onClick={(e) => {e.stopPropagation();setExpanded(!expanded);@@ -336,7 +336,7 @@ function ToolIndicator({Arguments</button>{expanded && (- <pre className="px-3 pb-2 text-[10px] leading-relaxed text-stone-600 dark:text-stone-400 font-mono overflow-x-auto max-h-48 overflow-y-auto">+ <pre className="px-2.5 pb-2 text-[10px] leading-relaxed text-stone-600 dark:text-stone-400 font-mono overflow-x-auto max-h-48 overflow-y-auto">{displayArgs}</pre>)}@@ -354,28 +354,28 @@ const roleConfig = {label: "User",align: "items-end" as const,bubble:- "bg-primary/10 dark:bg-primary/15 text-stone-800 dark:text-stone-200 rounded-2xl rounded-br-md",+ "border border-primary/20 bg-primary/5 dark:bg-primary/10 text-stone-800 dark:text-stone-200 rounded-md",},assistant: {icon: <Bot className="h-3.5 w-3.5" />,label: "Assistant",align: "items-start" as const,bubble:- "bg-stone-200 dark:bg-stone-800 text-stone-800 dark:text-stone-200 rounded-2xl rounded-bl-md",+ "border border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950 text-stone-800 dark:text-stone-200 rounded-md",},system: {icon: <Cog className="h-3.5 w-3.5" />,label: "System",align: "items-start" as const,bubble:- "bg-amber-50 dark:bg-amber-950/30 text-amber-900 dark:text-amber-200 rounded-2xl rounded-bl-md border border-amber-200 dark:border-amber-800",+ "bg-amber-50/70 dark:bg-amber-950/20 text-amber-900 dark:text-amber-200 rounded-md border border-amber-200 dark:border-amber-900",},tool: {icon: <Wrench className="h-3.5 w-3.5" />,label: "Tool Result",align: "items-start" as const,bubble:- "bg-violet-50 dark:bg-violet-950/30 text-violet-900 dark:text-violet-200 rounded-2xl rounded-bl-md border border-violet-200 dark:border-violet-800",+ "bg-stone-50 dark:bg-stone-900/50 text-stone-800 dark:text-stone-200 rounded-md border border-stone-200 dark:border-stone-800",},};@@ -459,7 +459,7 @@ export default function ChatView({}return (- <div className="flex flex-col gap-2.5 py-3">+ <div className="flex flex-col gap-2 py-2">{dedupedItems.map((item, i) => {const isSelected = request?.spanId === item.span.SpanId;@@ -482,10 +482,10 @@ export default function ChatView({return (<divkey={`${item.span.SpanId}-span-${i}`}- className={`flex items-center gap-2 mx-3 px-3 py-1.5 rounded-md border cursor-pointer transition-colors ${+ className={`mx-2 flex cursor-pointer items-center gap-2 rounded-md border px-2.5 py-1.5 transition-colors ${isSelected? "border-primary/40 bg-primary/5"- : "border-dashed border-stone-200 dark:border-stone-700 hover:bg-stone-100 dark:hover:bg-stone-800"+ : "border-stone-200 bg-white hover:bg-stone-50 dark:border-stone-800 dark:bg-stone-950 dark:hover:bg-stone-900"}`}onClick={() =>updateRequest({ spanId: item.span.SpanId })@@ -516,11 +516,11 @@ export default function ChatView({return (<divkey={`${item.span.SpanId}-${role}-${i}`}- className={`flex flex-col gap-0.5 px-3 ${config.align}`}+ className={`flex flex-col gap-0.5 px-2 ${config.align}`}>{/* Role label + span name */}<div- className={`flex items-center gap-1.5 text-[10px] text-stone-400 dark:text-stone-500 px-1 ${+ className={`flex items-center gap-1.5 px-1 text-[10px] text-stone-400 dark:text-stone-500 ${role === "user" ? "flex-row-reverse" : ""}`}>@@ -536,12 +536,12 @@ export default function ChatView({{/* Bubble */}<div- className={`max-w-[85%] px-3 py-2 text-[12px] leading-relaxed whitespace-pre-wrap break-words cursor-pointer transition-shadow ${+ className={`max-w-[92%] cursor-pointer whitespace-pre-wrap break-words px-2.5 py-2 text-[12px] leading-relaxed transition-colors ${config.bubble} ${isSelected- ? "ring-2 ring-primary ring-offset-1 dark:ring-offset-stone-900"- : "hover:shadow-md"+ ? "ring-1 ring-primary/60"+ : "hover:border-stone-300 dark:hover:border-stone-700"}`}onClick={() =>updateRequest({ spanId: item.span.SpanId })diff --git a/src/client/src/components/(playground)/request/components/evaluations.tsx b/src/client/src/components/(playground)/request/components/evaluations.tsxindex 087c1feb..f3568424 100644--- a/src/client/src/components/(playground)/request/components/evaluations.tsx+++ b/src/client/src/components/(playground)/request/components/evaluations.tsx@@ -9,7 +9,7 @@ import {import { TransformedTraceRow } from "@/types/trace";import useFetchWrapper from "@/utils/hooks/useFetchWrapper";import Link from "next/link";-import { useEffect, useState } from "react";+import { useEffect, useState, type ReactNode } from "react";import { toast } from "sonner";import { Badge } from "@/components/ui/badge";import {@@ -42,14 +42,32 @@ function getScoreColor(score: number): string {return "bg-red-100 dark:bg-red-900 text-red-900 dark:text-red-50";}-function EvaluationCard({ evaluation }: { evaluation: Evaluation }) {+function EvaluationCard({+ evaluation,+ surface = "default",+}: {+ evaluation: Evaluation;+ surface?: "default" | "observability";+}) {+ const m = getMessage();+ const isObservabilitySurface = surface === "observability";const [isExpanded, setIsExpanded] = useState(false);return (- <div className="rounded-lg border border-stone-200 dark:border-stone-700 overflow-hidden">+ <div+ className={`overflow-hidden rounded-md border ${+ isObservabilitySurface+ ? "border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950"+ : "border-stone-200 dark:border-stone-700"+ }`}+ ><buttontype="button"- className="w-full flex items-center justify-between gap-3 px-3 py-2.5 text-left bg-stone-50 dark:bg-stone-800/80 hover:bg-stone-100 dark:hover:bg-stone-800 transition-colors cursor-pointer"+ className={`w-full flex items-center justify-between gap-3 px-3 text-left transition-colors cursor-pointer ${+ isObservabilitySurface+ ? "py-2 bg-white hover:bg-stone-50 dark:bg-stone-950 dark:hover:bg-stone-900"+ : "py-2.5 bg-stone-50 dark:bg-stone-800/80 hover:bg-stone-100 dark:hover:bg-stone-800"+ }`}onClick={() => setIsExpanded(!isExpanded)}><span className="text-sm font-medium text-stone-700 dark:text-stone-300">@@ -70,17 +88,23 @@ function EvaluationCard({ evaluation }: { evaluation: Evaluation }) {</div></button>{isExpanded && (- <div className="px-3 py-2.5 space-y-2 text-xs bg-white dark:bg-stone-900/50 border-t border-stone-200 dark:border-stone-700">+ <div className="px-3 py-2.5 space-y-2 text-xs bg-stone-50/70 dark:bg-stone-900/40 border-t border-stone-200 dark:border-stone-800"><div>- <span className="font-medium text-stone-500 dark:text-stone-400">Classification: </span>+ <span className="font-medium text-stone-500 dark:text-stone-400">+ {m.EVALUATION_CLASSIFICATION}:{" "}+ </span><span className="text-stone-700 dark:text-stone-300">{evaluation.classification}</span></div><div>- <span className="font-medium text-stone-500 dark:text-stone-400">Explanation: </span>+ <span className="font-medium text-stone-500 dark:text-stone-400">+ {m.EVALUATION_EXPLANATION}:{" "}+ </span><span className="text-stone-700 dark:text-stone-300">{evaluation.explanation}</span></div><div>- <span className="font-medium text-stone-500 dark:text-stone-400">Verdict: </span>+ <span className="font-medium text-stone-500 dark:text-stone-400">+ {m.EVALUATION_VERDICT}:{" "}+ </span><span className="text-stone-700 dark:text-stone-300">{evaluation.verdict}</span></div></div>@@ -115,14 +139,14 @@ function ManualFeedbackForm({onSuccess();},failureCb: () => {- toast.error("Failed to save feedback");+ toast.error(getMessage().EVALUATION_FEEDBACK_SAVE_FAILURE);},});};return (- <div className="rounded-lg border border-stone-200 dark:border-stone-700 overflow-hidden">- <div className="px-3 py-2.5 border-b border-stone-200 dark:border-stone-700">+ <div className="rounded-lg border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950 overflow-hidden">+ <div className="px-3 py-2.5 border-b border-stone-200 dark:border-stone-800"><h4 className="text-xs font-medium text-stone-500 dark:text-stone-400">{getMessage().EVALUATION_MANUAL_FEEDBACK}</h4>@@ -248,24 +272,33 @@ function RuleEngineInfo({<div className="px-3 py-2.5 border-b border-stone-200 dark:border-stone-700 flex items-center gap-1.5"><Zap className="size-3.5 text-stone-500" /><span className="text-xs font-medium text-stone-500 dark:text-stone-400">- Rule Engine & Run Details+ {getMessage().EVALUATION_RULE_ENGINE_DETAILS}</span></div><div className="px-3 py-2.5 text-xs space-y-2 text-stone-600 dark:text-stone-400">{source && (<p>- <span className="font-medium">Source:</span>{" "}- {source === "manual" ? "Manual" : "Auto"}+ <span className="font-medium">+ {getMessage().EVALUATION_SOURCE}:+ </span>{" "}+ {source === "manual"+ ? getMessage().EVALUATION_SOURCE_MANUAL+ : getMessage().EVALUATION_SOURCE_AUTO}</p>)}{model && (<p>- <span className="font-medium">Engine:</span> {model}+ <span className="font-medium">+ {getMessage().EVALUATION_ENGINE}:+ </span>{" "}+ {model}</p>)}{matchingRuleIds.length > 0 && (<div className="flex flex-wrap items-center gap-1">- <span className="font-medium shrink-0">Rules applied:</span>+ <span className="font-medium shrink-0">+ {getMessage().EVALUATION_RULES_APPLIED}:+ </span>{matchingRuleIds.map((rid) => (<Linkkey={rid}@@ -279,7 +312,9 @@ function RuleEngineInfo({)}{contextApplied && contextEntityIds.length > 0 && (<div className="flex flex-wrap items-center gap-1">- <span className="font-medium shrink-0">Context:</span>+ <span className="font-medium shrink-0">+ {getMessage().EVALUATION_CONTEXT}:+ </span>{contextEntityIds.map((cid) => (<Linkkey={cid}@@ -293,8 +328,10 @@ function RuleEngineInfo({)}{contextApplied && contextEntityIds.length === 0 && (<p>- <span className="font-medium">Context:</span> Applied from context- entities+ <span className="font-medium">+ {getMessage().EVALUATION_CONTEXT}:+ </span>{" "}+ {getMessage().EVALUATION_CONTEXT_APPLIED}</p>)}</div>@@ -305,10 +342,13 @@ function RuleEngineInfo({function EvaluationRunCard({run,ruleContext,+ surface = "default",}: {run: EvaluationRun;ruleContext?: { matchingRuleIds: string[]; contextApplied: boolean };+ surface?: "default" | "observability";}) {+ const isObservabilitySurface = surface === "observability";const source = run.meta?.source;const model = run.meta?.model;const cost = run.cost ?? (run.meta?.cost ? parseFloat(run.meta.cost) : undefined);@@ -317,14 +357,28 @@ function EvaluationRunCard({const dateStr = runDate ? format(runDate, "MMM d, yyyy HH:mm:ss") : "—";return (- <div className="rounded-lg border border-stone-200 dark:border-stone-700 overflow-hidden">- <div className="flex items-center justify-between gap-3 px-3 py-2.5 bg-stone-50 dark:bg-stone-800/80 border-b border-stone-200 dark:border-stone-700">+ <div+ className={`overflow-hidden rounded-md border ${+ isObservabilitySurface+ ? "border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950"+ : "border-stone-200 dark:border-stone-700"+ }`}+ >+ <div+ className={`flex items-center justify-between gap-3 border-b px-3 ${+ isObservabilitySurface+ ? "py-2 border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950"+ : "py-2.5 bg-stone-50 dark:bg-stone-800/80 border-stone-200 dark:border-stone-700"+ }`}+ ><div className="flex items-center gap-2 min-w-0"><Badgevariant="outline"className="text-[10px] font-medium shrink-0 border-stone-300 dark:border-stone-600">- {source === "manual" ? "Manual" : "Auto"}+ {source === "manual"+ ? getMessage().EVALUATION_SOURCE_MANUAL+ : getMessage().EVALUATION_SOURCE_AUTO}</Badge><span className="text-xs text-stone-600 dark:text-stone-400 truncate">{dateStr}@@ -341,12 +395,18 @@ function EvaluationRunCard({</span>)}</div>- <div className="p-3 space-y-2">+ <div className={isObservabilitySurface ? "space-y-2 bg-stone-50/60 p-2.5 dark:bg-stone-950" : "p-3 space-y-2"}>{evals.length === 0 ? (- <p className="text-xs text-stone-500 dark:text-stone-400">No evaluations</p>+ <p className="text-xs text-stone-500 dark:text-stone-400">+ {getMessage().EVALUATION_NO_RESULTS}+ </p>) : (evals.map((evaluation, index) => (- <EvaluationCard key={index} evaluation={evaluation} />+ <EvaluationCard+ key={index}+ evaluation={evaluation}+ surface={surface}+ />)))}</div>@@ -354,7 +414,14 @@ function EvaluationRunCard({);}-export default function Evaluations({ trace }: { trace: TransformedTraceRow }) {+export default function Evaluations({+ trace,+ surface = "default",+}: {+ trace: TransformedTraceRow;+ surface?: "default" | "observability";+}) {+ const isObservabilitySurface = surface === "observability";const [error, setError] = useState<string | null>(null);const {data: responseData,@@ -413,18 +480,54 @@ export default function Evaluations({ trace }: { trace: TransformedTraceRow }) {);const hasLegacyEvals = !hasRuns && (legacyEvals?.length ?? 0) > 0;- if (isLoading || !isFetched || isRunEvaluationLoading) {+ const renderShell = (+ children: ReactNode,+ options?: { status?: string; showRunAction?: boolean }+ ) => {+ if (!isObservabilitySurface) return children;+return (+ <section className="overflow-hidden rounded-md border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950">+ <div className="flex flex-wrap items-center gap-2 border-b border-stone-200 bg-stone-50 px-3 py-2 dark:border-stone-800 dark:bg-stone-900">+ <div className="mr-auto min-w-0">+ <h2 className="text-sm font-semibold text-stone-900 dark:text-stone-100">+ {getMessage().OBSERVABILITY_EVALUATION_PANEL}+ </h2>+ <p className="text-xs text-stone-500 dark:text-stone-400">+ {options?.status || getMessage().EVALUATION_MANUAL_AND_AUTO}+ </p>+ </div>+ {options?.showRunAction && hasConfig && (+ <Button+ variant="default"+ size="sm"+ className="h-7 gap-1.5 bg-primary px-2.5 text-xs"+ onClick={runEvaluation}+ disabled={isRunEvaluationLoading}+ >+ <Play className="size-3.5" />+ {getMessage().EVALUATION_RUN}+ </Button>+ )}+ </div>+ <div className="bg-stone-50/60 p-3 dark:bg-stone-950">{children}</div>+ </section>+ );+ };++ if (isLoading || !isFetched || isRunEvaluationLoading) {+ return renderShell(<div className="flex flex-col gap-3 px-4 py-2"><div className="text-sm text-stone-500 dark:text-stone-300">{getMessage().EVALUATION_DATA_LOADING}</div>- </div>+ </div>,+ { status: getMessage().EVALUATION_DATA_LOADING });}if (responseData?.configErr) {- return (+ return renderShell(<div className="flex flex-col gap-3 px-4 py-2"><div className="text-sm text-stone-500 dark:text-stone-300">{getMessage().EVALUATION_CONFIG_NOT_SET}@@ -434,14 +537,15 @@ export default function Evaluations({ trace }: { trace: TransformedTraceRow }) {{getMessage().EVALUATION_CONFIG_SET}</Link></Button>- </div>+ </div>,+ { status: getMessage().EVALUATION_CONFIG_NOT_SET });}- return (- <div className="flex flex-col gap-3 px-3 py-2">+ return renderShell(+ <div className={isObservabilitySurface ? "flex flex-col gap-3" : "flex flex-col gap-3 px-3 py-2"}>{/* Actions bar */}- <div className="flex flex-wrap items-center gap-2 pb-2 border-b border-stone-200 dark:border-stone-700">+ <div className={`${isObservabilitySurface ? "hidden" : "flex"} flex-wrap items-center gap-2 pb-2 border-b border-stone-200 dark:border-stone-700`}>{hasConfig && (<Buttonvariant="default"@@ -459,7 +563,7 @@ export default function Evaluations({ trace }: { trace: TransformedTraceRow }) {href="/evaluations/types"className="text-xs text-stone-500 dark:text-stone-400 hover:text-primary inline-flex items-center gap-1">- {runs.length} run{runs.length !== 1 ? "s" : ""}+ {getMessage().EVALUATION_RUN_COUNT(runs.length)}<ExternalLink className="size-3" /></Link>)}@@ -481,7 +585,7 @@ export default function Evaluations({ trace }: { trace: TransformedTraceRow }) {{hasRuns ? (<div className="space-y-3"><h4 className="text-xs font-medium text-stone-500 dark:text-stone-400 uppercase tracking-wide">- Runs+ {getMessage().EVALUATION_RUNS}</h4><div className="space-y-2">{runs.map((run) => (@@ -489,6 +593,7 @@ export default function Evaluations({ trace }: { trace: TransformedTraceRow }) {key={run.id}run={run}ruleContext={ruleContext}+ surface={surface}/>))}</div>@@ -496,11 +601,15 @@ export default function Evaluations({ trace }: { trace: TransformedTraceRow }) {) : hasLegacyEvals && legacyEvals ? (<div className="space-y-3"><h4 className="text-xs font-medium text-stone-500 dark:text-stone-400 uppercase tracking-wide">- Evaluations+ {getMessage().EVALUATION_RESULTS}</h4><div className="space-y-2">{legacyEvals.map((evaluation, index) => (- <EvaluationCard key={index} evaluation={evaluation} />+ <EvaluationCard+ key={index}+ evaluation={evaluation}+ surface={surface}+ />))}</div></div>@@ -511,10 +620,18 @@ export default function Evaluations({ trace }: { trace: TransformedTraceRow }) {) : null}{/* Manual feedback */}- <div className="space-y-3 pt-3 border-t border-stone-200 dark:border-stone-700">+ <div className="space-y-3 pt-3"><FeedbackList feedbacks={feedbacks} /><ManualFeedbackForm spanId={trace.spanId} onSuccess={getEvaluations} /></div>- </div>+ </div>,+ {+ showRunAction: true,+ status: hasRuns+ ? getMessage().EVALUATION_RUN_COUNT(runs.length)+ : hasConfig+ ? getMessage().EVALUATION_NOT_RUN_YET+ : getMessage().EVALUATION_MANUAL_AND_AUTO,+ });}diff --git a/src/client/src/components/(playground)/request/components/node-graph.tsx b/src/client/src/components/(playground)/request/components/node-graph.tsxindex 2085af11..f9bdb456 100644--- a/src/client/src/components/(playground)/request/components/node-graph.tsx+++ b/src/client/src/components/(playground)/request/components/node-graph.tsx@@ -124,34 +124,33 @@ export default function NodeGraph({ record }: { record: TraceHeirarchySpan }) {const onMouseUp = useCallback(() => setPanning(false), []);return (- <div className="relative flex-1 w-full min-h-0 h-full">-- {/* 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" 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" title="Fit to view"><Maximize className="h-3.5 w-3.5 text-primary" /></button>- </div>-- {/* 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 className="relative flex flex-col flex-1 w-full min-h-0 h-full overflow-hidden overscroll-contain">+ <div className="shrink-0 flex flex-wrap items-center gap-2 justify-between border-b border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950 px-2 py-1.5">+ <div className="flex flex-wrap items-center gap-3 text-[10px] text-stone-500 dark:text-stone-400">+ <span className="font-semibold text-stone-700 dark:text-stone-300">+ Edge Types+ </span>+ <span className="flex items-center gap-1.5">+ <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-1.5">+ <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>+ <div className="flex items-center gap-1 rounded-md border border-stone-200 dark:border-stone-700 bg-stone-50 dark:bg-stone-900 p-0.5">+ <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" title="Fit to view"><Maximize className="h-3.5 w-3.5 text-primary" /></button>+ </div></div>- {/* Canvas */}<divref={containerRef}- className="absolute inset-0"+ className="relative flex-1 min-h-0 overflow-hidden overscroll-contain"style={{ cursor: panning ? "grabbing" : "grab" }}onWheel={onWheel}onMouseDown={onMouseDown}diff --git a/src/client/src/components/(playground)/request/request-context.tsx b/src/client/src/components/(playground)/request/request-context.tsxindex 2b46a7d6..2c6b0d66 100644--- a/src/client/src/components/(playground)/request/request-context.tsx+++ b/src/client/src/components/(playground)/request/request-context.tsx@@ -55,7 +55,13 @@ function syncUrlParams(request: RequestProps) {window.history.replaceState({}, "", url.toString());}-export function RequestProvider({ children }: { children: ReactNode }) {+export function RequestProvider({+ children,+ syncUrl = true,+}: {+ children: ReactNode;+ syncUrl?: boolean;+}) {const [request, setRequest] = useState<RequestProps>(null);const [items, setItemsState] = useState<TransformedTraceRow[]>([]);const [total, setTotalState] = useState(0);@@ -77,8 +83,8 @@ export function RequestProvider({ children }: { children: ReactNode }) {const updateRequest = useCallback((value: RequestProps) => {setRequest(value);- syncUrlParams(value);- }, []);+ if (syncUrl) syncUrlParams(value);+ }, [syncUrl]);const setItems = useCallback((newItems: TransformedTraceRow[]) => {setItemsState(newItems);@@ -109,6 +115,7 @@ export function RequestProvider({ children }: { children: ReactNode }) {// On mount, check URL for spanId to restore the open traceuseEffect(() => {+ if (!syncUrl) return;if (typeof window === "undefined") return;const params = new URLSearchParams(window.location.search);const spanId = params.get("spanId");@@ -117,7 +124,7 @@ export function RequestProvider({ children }: { children: ReactNode }) {// Create a minimal placeholder to trigger the detail sheet fetchsetRequest({ spanId, id: traceId || "" } as TransformedTraceRow);}- }, []);+ }, [syncUrl]);const navigatePrev = useCallback(() => {const idx = itemsRef.current.findIndex(@@ -126,7 +133,7 @@ export function RequestProvider({ children }: { children: ReactNode }) {if (idx > 0) {const prev = itemsRef.current[idx - 1];setRequest(prev);- syncUrlParams(prev);+ if (syncUrl) syncUrlParams(prev);} else if (idx === 0 && offsetRef.current > 0 && onPageChangeRef.current) {// At first item of current page — trigger previous pagependingNavDirection.current = -1;@@ -141,7 +148,7 @@ export function RequestProvider({ children }: { children: ReactNode }) {if (idx >= 0 && idx < itemsRef.current.length - 1) {const next = itemsRef.current[idx + 1];setRequest(next);- syncUrlParams(next);+ if (syncUrl) syncUrlParams(next);} else if (idx === itemsRef.current.length - 1 &&offsetRef.current + itemsRef.current.length < totalRef.current &&diff --git a/src/client/src/components/(playground)/route-breadcrumbs.tsx b/src/client/src/components/(playground)/route-breadcrumbs.tsxindex 4bdd7c43..f38324bf 100644--- a/src/client/src/components/(playground)/route-breadcrumbs.tsx+++ b/src/client/src/components/(playground)/route-breadcrumbs.tsx@@ -8,6 +8,7 @@ import {} from "@/components/ui/breadcrumb";import { usePageHeader } from "@/selectors/page";import { usePathname } from "next/navigation";+import Link from "next/link";import React, { useEffect } from "react";import { generatePageHeader } from "@/utils/breadcrumbs";@@ -29,8 +30,8 @@ export default function RouteBreadcrumbs() {<BreadcrumbList className="text-xs">{showHomeBreadcrumb && (<BreadcrumbItem>- <BreadcrumbLink href="/home">- Home+ <BreadcrumbLink asChild>+ <Link href="/home">Home</Link></BreadcrumbLink></BreadcrumbItem>)}@@ -40,8 +41,8 @@ export default function RouteBreadcrumbs() {{header.breadcrumbs.map(({ title, href }, index) => (<React.Fragment key={href}><BreadcrumbItem>- <BreadcrumbLink href={href}>- {title}+ <BreadcrumbLink asChild>+ <Link href={href}>{title}</Link></BreadcrumbLink></BreadcrumbItem>{index < header.breadcrumbs.length - 1 && <BreadcrumbSeparator />}diff --git a/src/client/src/components/(playground)/sidebar/index.tsx b/src/client/src/components/(playground)/sidebar/index.tsxindex e62f868d..035d4b1f 100644--- a/src/client/src/components/(playground)/sidebar/index.tsx+++ b/src/client/src/components/(playground)/sidebar/index.tsx@@ -27,7 +27,7 @@ const getIfSidebarItemClasses = (pathname: string, item: SidebarItemProps) => {return `${inactiveClasses}${commonClasses}`;if(item.link) {- if (["/home", "/dashboard", "/requests", "/exceptions", "/prompt-hub", "/vault", "/openground", "/settings"].includes(item.link)) {+ if (["/home", "/dashboard", "/telemetry", "/requests", "/exceptions", "/prompt-hub", "/vault", "/openground", "/settings"].includes(item.link)) {return pathname.startsWith(item.link) ? `${activeClasses}${commonClasses}` : `${inactiveClasses}${commonClasses}`;}@@ -50,9 +50,11 @@ const getIfSidebarItemClasses = (pathname: string, item: SidebarItemProps) => {case "/dashboard":return pathname.startsWith("/dashboard") && !pathname.startsWith("/dashboards") ? `${activeClasses}${commonClasses}` : `${inactiveClasses}${commonClasses}`;case "/requests":- return pathname.startsWith("/requests") ? `${activeClasses}${commonClasses}` : `${inactiveClasses}${commonClasses}`;+ return pathname.startsWith("/requests") || pathname.startsWith("/telemetry") ? `${activeClasses}${commonClasses}` : `${inactiveClasses}${commonClasses}`;case "/exceptions":- return pathname.startsWith("/exceptions") ? `${activeClasses}${commonClasses}` : `${inactiveClasses}${commonClasses}`;+ return pathname.startsWith("/exceptions") || pathname.startsWith("/telemetry") ? `${activeClasses}${commonClasses}` : `${inactiveClasses}${commonClasses}`;+ case "/telemetry":+ return pathname.startsWith("/telemetry") ? `${activeClasses}${commonClasses}` : `${inactiveClasses}${commonClasses}`;case "/prompt-hub":return pathname.startsWith("/prompt-hub") ? `${activeClasses}${commonClasses}` : `${inactiveClasses}${commonClasses}`;case "/vault":diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.tsindex 693a0aa9..edaab938 100644--- a/src/client/src/constants/messages/en.ts+++ b/src/client/src/constants/messages/en.ts@@ -35,9 +35,13 @@ export const EVALUATION_CONFIG_NOT_SET ="Evaluation config not set! Please set the config first to run evaluations.";export const EVALUATION_CONFIG_SET = "Setup Evaluation!";export const EVALUATION_NOT_RUN_YET =- "Evaluation not run yet! Please run the evaluation to get results.";+ "AI Evaluation has not run yet! Please run the evaluation to get results.";export const EVALUATION_RUN = "Run Evaluation";export const EVALUATION_RUN_AGAIN = "Run Evaluation Again";+export const EVALUATION_RUN_COUNT = (count: number) =>+ `${count} run${count !== 1 ? "s" : ""}`;+export const EVALUATION_RUNS = "Runs";+export const EVALUATION_RESULTS = "Evaluations";export const EVALUATION_DATA_LOADING = "Loading evaluation data...";export const EVALUATION_CREATED = "Evaluation created successfully!";export const EVALUATION_UPDATED = "Evaluation updated successfully!";@@ -46,6 +50,19 @@ export const EVALUATION_CONFIG_INVALID = "Invalid evaluation config!";export const EVALUATION_CONFIG_UPDATING_FAILED ="Evaluation config updation failed!";export const EVALUATION_RUN_FAILURE = "Evaluation run failed!";+export const EVALUATION_FEEDBACK_SAVE_FAILURE = "Failed to save feedback";+export const EVALUATION_CLASSIFICATION = "Classification";+export const EVALUATION_EXPLANATION = "Explanation";+export const EVALUATION_VERDICT = "Verdict";+export const EVALUATION_RULE_ENGINE_DETAILS = "Rule Engine & Run Details";+export const EVALUATION_SOURCE = "Source";+export const EVALUATION_SOURCE_MANUAL = "Manual";+export const EVALUATION_SOURCE_AUTO = "Auto";+export const EVALUATION_ENGINE = "Engine";+export const EVALUATION_RULES_APPLIED = "Rules applied";+export const EVALUATION_CONTEXT = "Context";+export const EVALUATION_CONTEXT_APPLIED = "Applied from context entities";+export const EVALUATION_NO_RESULTS = "No evaluations";// Evaluation Settings pageexport const EVALUATION_VAULT_KEY_NOT_FOUND = "Unable to find the vault key.";@@ -93,7 +110,7 @@ export const EVALUATION_MANUAL_AND_AUTO_DESCRIPTION ="Manual and Auto evaluations use the Rule Engine context applied in evaluation types when rules match the trace. Manual runs are stored with source=manual; Auto runs are stored with source=auto.";// Manual feedback-export const EVALUATION_MANUAL_FEEDBACK = "Manual Feedback";+export const EVALUATION_MANUAL_FEEDBACK = "Feedback";export const EVALUATION_MANUAL_FEEDBACK_DESCRIPTION ="Add your feedback on this response";export const EVALUATION_FEEDBACK_POSITIVE = "Good";@@ -107,6 +124,113 @@ export const EVALUATION_FEEDBACK_SAVED = "Feedback saved!";export const TRACE_NOT_FOUND = "Trace not found!";export const TRACE_FETCHING_ERROR = "Error fetching trace!";+// Observability+export const OBSERVABILITY_TITLE = "Telemetry";+export const OBSERVABILITY_TRACE_LOADING = "Loading trace...";+export const OBSERVABILITY_LOADING = "Loading...";+export const OBSERVABILITY_TRACE_DETAILS = "Trace Details";+export const OBSERVABILITY_TRACES = "Traces";+export const OBSERVABILITY_EXCEPTIONS = "Exceptions";+export const OBSERVABILITY_METRICS = "Metrics";+export const OBSERVABILITY_LOGS = "Logs";+export const OBSERVABILITY_TRACE_SHORT_LABEL = "Latency, cost, tokens";+export const OBSERVABILITY_EXCEPTION_SHORT_LABEL = "Failures and error spans";+export const OBSERVABILITY_METRIC_SHORT_LABEL = "Gauges, sums, histograms";+export const OBSERVABILITY_LOG_SHORT_LABEL = "Events and correlated context";+export const OBSERVABILITY_TRACE_SUMMARY = "Span flow";+export const OBSERVABILITY_EXCEPTION_SUMMARY = "Failure path";+export const OBSERVABILITY_METRIC_SUMMARY = "Signal shape";+export const OBSERVABILITY_LOG_SUMMARY = "Event stream";+export const OBSERVABILITY_BACK = "Back";+export const OBSERVABILITY_DURATION = "Duration";+export const OBSERVABILITY_TOKENS = "Tokens";+export const OBSERVABILITY_COST = "Cost";+export const OBSERVABILITY_MODEL = "Model";+export const OBSERVABILITY_TRACE_ID = "Trace ID";+export const OBSERVABILITY_SPAN_ID = "Span ID";+export const OBSERVABILITY_SERVICE = "Service";+export const OBSERVABILITY_APPLICATION = "Application";+export const OBSERVABILITY_SYSTEM = "System";+export const OBSERVABILITY_UNKNOWN_SERVICE = "unknown service";+export const OBSERVABILITY_UNKNOWN_APP = "unknown app";+export const OBSERVABILITY_PREVIOUS_SPAN = "Previous span";+export const OBSERVABILITY_NEXT_SPAN = "Next span";+export const OBSERVABILITY_SPAN_ATTRIBUTES = "Span Attributes";+export const OBSERVABILITY_RESOURCE_ATTRIBUTES = "Resource Attributes";+export const OBSERVABILITY_SCOPE_ATTRIBUTES = "Scope Attributes";+export const OBSERVABILITY_LOG_ATTRIBUTES = "Log Attributes";+export const OBSERVABILITY_METRIC_ATTRIBUTES = "Metric Attributes";+export const OBSERVABILITY_RAW_RECORD = "Raw Record";+export const OBSERVABILITY_RAW_LOG = "Raw Log";+export const OBSERVABILITY_FIELD = "Field";+export const OBSERVABILITY_VALUE = "Value";+export const OBSERVABILITY_TYPES = "Types";+export const OBSERVABILITY_MODELS = "Models";+export const OBSERVABILITY_PROVIDERS = "Providers";+export const OBSERVABILITY_MAX_COST = "Max Cost";+export const OBSERVABILITY_APPLICATION_NAMES = "Application Names";+export const OBSERVABILITY_SPAN_NAMES = "Span Names";+export const OBSERVABILITY_ENVIRONMENTS = "Environments";+export const OBSERVABILITY_SERVICES = "Services";+export const OBSERVABILITY_SEVERITIES = "Severities";+export const OBSERVABILITY_METRIC_NAMES = "Metric Names";+export const OBSERVABILITY_METRIC_TYPES = "Metric Types";+export const OBSERVABILITY_COPY_UNSUPPORTED =+ "Copy to clipboard is not supported in this browser";+export const OBSERVABILITY_LINK_COPIED = "Link copied to clipboard";+export const OBSERVABILITY_LINK_COPY_FAILED = "Could not copy link";+export const OBSERVABILITY_COPY_SHARE_LINK = "Copy shareable link";+export const OBSERVABILITY_TIME = "Time";+export const OBSERVABILITY_SEVERITY = "Severity";+export const OBSERVABILITY_BODY = "Body";+export const OBSERVABILITY_METRIC = "Metric";+export const OBSERVABILITY_TYPE = "Type";+export const OBSERVABILITY_UNIT = "Unit";+export const OBSERVABILITY_LATEST = "Latest";+export const OBSERVABILITY_POINTS = "Points";+export const OBSERVABILITY_LAST_SEEN = "Last Seen";+export const OBSERVABILITY_LOG_ENTRY = "Log entry";+export const OBSERVABILITY_LATEST_METRIC_ATTRIBUTES =+ "Latest Metric Attributes";+export const OBSERVABILITY_LATEST_RESOURCE_ATTRIBUTES =+ "Latest Resource Attributes";+export const OBSERVABILITY_LATEST_SCOPE_ATTRIBUTES = "Latest Scope Attributes";+export const OBSERVABILITY_LATEST_METRIC_POINT = "Latest Metric Point";+export const OBSERVABILITY_LOADED_POINTS = "Loaded Points";+export const OBSERVABILITY_CLOSE = "Close";+export const OBSERVABILITY_FIELDS = "Fields";+export const OBSERVABILITY_LOG_ATTRS = "Log Attrs";+export const OBSERVABILITY_RESOURCE = "Resource";+export const OBSERVABILITY_SCOPE = "Scope";+export const OBSERVABILITY_RAW = "Raw";+export const OBSERVABILITY_AUTO = "Auto";+export const OBSERVABILITY_METRIC_POINTS = "Metric points";+export const OBSERVABILITY_LOG_EVENTS = "Log events";+export const OBSERVABILITY_SPANS = "Spans";+export const OBSERVABILITY_TOTAL = "Total";+export const OBSERVABILITY_PEAK = "Peak";+export const OBSERVABILITY_SPAN_HIERARCHY = "Span Hierarchy";+export const OBSERVABILITY_LOADING_SPANS = "Loading spans";+export const OBSERVABILITY_SPAN_COUNT = (count: string) => `${count} spans`;+export const OBSERVABILITY_SPAN_COUNT_WITH_COST = (count: string, cost: string) =>+ `${count} spans / $${cost}`;+export const OBSERVABILITY_HIERARCHY_UNAVAILABLE =+ "Span hierarchy is not available for this span.";+export const OBSERVABILITY_TREE = "Tree";+export const OBSERVABILITY_CHAT = "Chat";+export const OBSERVABILITY_TIMELINE = "Timeline";+export const OBSERVABILITY_GRAPH = "Graph";+export const OBSERVABILITY_NO_SERVER_CONNECTION = "Cannot connect to server!";+export const OBSERVABILITY_ADD = "Add";+export const OBSERVABILITY_SPAN_NAME_EXAMPLE = "e.g. SpanName";+export const OBSERVABILITY_ATTRIBUTE_KEY_EXAMPLE = "e.g. gen_ai.system";+export const OBSERVABILITY_FULL_SCREEN = "Full screen";+export const OBSERVABILITY_EVALUATION_PANEL = "Evaluation";+export const OBSERVABILITY_ROW = "row";+export const OBSERVABILITY_TRACE = "trace";+export const OBSERVABILITY_SPAN = "span";+export const OBSERVABILITY_SCOPE_META = "scope";+// Cronexport const CRON_RECURRING_TIME_INVALID ="Invalid cron schedule. Please check the format.";@@ -1289,4 +1413,4 @@ export const CHAT_TOKENS = "tokens";export const CHAT_ERROR_PREFIX = "Error:";export const CHAT_SOMETHING_WENT_WRONG = "Something went wrong. Please try again.";export const CHAT_FAILED_TO_GET_RESPONSE = "Failed to get response";-export const CHAT_NO_RESPONSE_STREAM = "No response stream";\ No newline at end of file+export const CHAT_NO_RESPONSE_STREAM = "No response stream";diff --git a/src/client/src/constants/sidebar.tsx b/src/client/src/constants/sidebar.tsxindex 83bfdc06..31da1edf 100644--- a/src/client/src/constants/sidebar.tsx+++ b/src/client/src/constants/sidebar.tsx@@ -5,17 +5,14 @@ import {BookText,CircleDollarSign,Component,+ Activity,Home,Key,LayoutDashboard,- MessageSquare,MonitorCog,MonitorPlay,- Radar,SettingsIcon,- ShieldAlert,SlidersHorizontal,- TextQuote} from "lucide-react";import DatabaseConfigSwitch from "@/components/(playground)/sidebar/database-config-switch";import OpenTelemetrySvg from "@/components/svg/opentelemetry";@@ -44,7 +41,7 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [},{icon: <Otter className={ICON_CLASSES} />,- text: "Otter Chat",+ text: "Otter",link: "/chat",type: "action",},@@ -57,16 +54,10 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [{title: "Monitoring",type: "section",- children: [{- icon: <TextQuote className={ICON_CLASSES} />,- text: "Requests",- link: "/requests",- type: "action",- },- {- icon: <ShieldAlert className={ICON_CLASSES} />,- text: "Exceptions",- link: "/exceptions",+ children: [{+ icon: <Activity className={ICON_CLASSES} />,+ text: "Telemetry",+ link: "/telemetry",type: "action",},// {@@ -166,4 +157,4 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [icon: <BookText className={ICON_CLASSES} />,type: "action",}-];\ No newline at end of file+];diff --git a/src/client/src/constants/traces.ts b/src/client/src/constants/traces.tsindex 87853d84..c3c1ab5e 100644--- a/src/client/src/constants/traces.ts+++ b/src/client/src/constants/traces.ts@@ -40,6 +40,7 @@ import { objectKeys } from "@/utils/object";import { isArray } from "lodash";import {SPAN_KIND_TYPE,+ TraceMappingPathType,TraceMappingKeyType,TraceMappingValueType,} from "@/types/trace";@@ -185,6 +186,12 @@ export const TraceMapping: Record<TraceMappingKeyType, TraceMappingValueType> =label: "Prompt Tokens",type: "integer",path: "usage.input_tokens",+ paths: [+ "usage.input_tokens",+ "client.token.usage.input",+ { path: "input_tokens", prefix: null },+ { path: "prompt_tokens", prefix: null },+ ],prefix: SpanAttributesGenAIPrefix,icon: Braces,defaultValue: "-",@@ -193,6 +200,12 @@ export const TraceMapping: Record<TraceMappingKeyType, TraceMappingValueType> =label: "Completion Tokens",type: "integer",path: "usage.output_tokens",+ paths: [+ "usage.output_tokens",+ "client.token.usage.output",+ { path: "output_tokens", prefix: null },+ { path: "completion_tokens", prefix: null },+ ],prefix: SpanAttributesGenAIPrefix,defaultValue: "-",},@@ -200,6 +213,11 @@ export const TraceMapping: Record<TraceMappingKeyType, TraceMappingValueType> =label: "Total Tokens",type: "integer",path: "usage.total_tokens",+ paths: [+ "usage.total_tokens",+ "client.token.usage",+ { path: "total_tokens", prefix: null },+ ],prefix: SpanAttributesGenAIPrefix,icon: TicketPlus,defaultValue: "-",@@ -688,13 +706,32 @@ export const TraceMapping: Record<TraceMappingKeyType, TraceMappingValueType> =},};+function getReverseTraceMappingPath(pathConfig: TraceMappingPathType): string {+ if (+ typeof pathConfig === "object" &&+ !isArray(pathConfig) &&+ "path" in pathConfig+ ) {+ return isArray(pathConfig.path)+ ? (pathConfig.path as string[]).join(",")+ : (pathConfig.path as string);+ }++ return isArray(pathConfig)+ ? (pathConfig as string[]).join(",")+ : (pathConfig as string);+}+function getReverseTraceMapping(): Record<string, TraceMappingKeyType> {return objectKeys(TraceMapping).reduce((acc: Record<string, TraceMappingKeyType>, key) => {- const path: string = isArray(TraceMapping[key].path)- ? (TraceMapping[key].path as string[]).join(",")- : (TraceMapping[key].path as string);- acc[path] = key;+ const paths = TraceMapping[key].paths?.length+ ? TraceMapping[key].paths!+ : [TraceMapping[key].path];++ paths.forEach((pathConfig) => {+ acc[getReverseTraceMappingPath(pathConfig)] = key;+ });return acc;},{}diff --git a/src/client/src/helpers/client/filter-persistence.ts b/src/client/src/helpers/client/filter-persistence.tsnew file mode 100644index 00000000..8d9f1a51--- /dev/null+++ b/src/client/src/helpers/client/filter-persistence.ts@@ -0,0 +1,33 @@+const FILTER_STORAGE_KEY_PREFIX = "openlit_filter_v1";++export const FILTER_PARAM_KEYS = [+ "tr",+ "ts",+ "te",+ "limit",+ "offset",+ "models",+ "providers",+ "traceTypes",+ "appNames",+ "spanNames",+ "envs",+ "maxCost",+ "services",+ "severities",+ "metricNames",+ "metricTypes",+ "cf",+ "gb",+ "gbv",+];++export function getFilterStorageKey(scope?: string) {+ return scope+ ? `${FILTER_STORAGE_KEY_PREFIX}:${scope}`+ : FILTER_STORAGE_KEY_PREFIX;+}++export function stripFilterParams(params: URLSearchParams) {+ FILTER_PARAM_KEYS.forEach((key) => params.delete(key));+}diff --git a/src/client/src/helpers/client/observability.ts b/src/client/src/helpers/client/observability.tsnew file mode 100644index 00000000..1a6844d6--- /dev/null+++ b/src/client/src/helpers/client/observability.ts@@ -0,0 +1,18 @@+import { FilterConfig } from "@/types/store/filter";++export type UpdateFilterFn = (+ key: string,+ value: any,+ extraParams?: any+) => void;++export type UpdateConfigFn = (config?: FilterConfig) => void;++export function prepareObservabilitySignalChange(+ updateConfig: UpdateConfigFn,+ updateFilter: UpdateFilterFn+) {+ updateConfig(undefined);+ updateFilter("groupBy", null);+ updateFilter("groupValue", null);+}diff --git a/src/client/src/helpers/client/trace.ts b/src/client/src/helpers/client/trace.tsindex 632e741a..956f3fdc 100644--- a/src/client/src/helpers/client/trace.ts+++ b/src/client/src/helpers/client/trace.ts@@ -1,5 +1,6 @@import { SUPPORTED_EVALUATION_OPERATIONS, TraceMapping } from "@/constants/traces";import {+ TraceMappingPathType,TraceMappingKeyType,TransformedTraceRow,TraceRow,@@ -93,15 +94,23 @@ export const getNormalizedTraceAttribute = (}};+function getNumberOrNull(value: unknown): number | null {+ if (value === undefined || value === null || value === "" || value === "-") {+ return null;+ }++ const numericValue = Number(value);+ return Number.isFinite(numericValue) ? numericValue : null;+}+export const normalizeTrace = (item: TraceRow): TransformedTraceRow => {const spanAttrs = item?.SpanAttributes ?? {};const resourceAttrs = (item as any)?.ResourceAttributes ?? {};- return objectKeys(TraceMapping).reduce(+ const normalizedTrace = objectKeys(TraceMapping).reduce((acc: TransformedTraceRow, traceKey: TraceMappingKeyType) => {- let value: unknown;const mapping = TraceMapping[traceKey];+ let value = getTraceMappingValue(item, traceKey);if (mapping.isRoot) {- value = get(item, mapping.path);// applicationName and environment live in ResourceAttributes, not at rootif (value == null && traceKey === "applicationName") {value = resourceAttrs["service.name"];@@ -120,16 +129,6 @@ export const normalizeTrace = (item: TraceRow): TransformedTraceRow => {} else if (value == null && traceKey === "revisedPrompt") {value = spanAttrs["gen_ai.content.revised_prompt"];}- } else {- value = get(spanAttrs, getTraceMappingKeyFullPath(traceKey));- // Backward compatibility: new OTel convention for token usage- if (value == null && traceKey === "totalTokens") {- value = spanAttrs["gen_ai.client.token.usage"];- } else if (value == null && traceKey === "promptTokens") {- value = spanAttrs["gen_ai.client.token.usage.input"];- } else if (value == null && traceKey === "completionTokens") {- value = spanAttrs["gen_ai.client.token.usage.output"];- }}acc[traceKey] = getNormalizedTraceAttribute(traceKey, value);@@ -137,53 +136,104 @@ export const normalizeTrace = (item: TraceRow): TransformedTraceRow => {},{} as TransformedTraceRow);++ if (getNumberOrNull(normalizedTrace.totalTokens) === null) {+ const promptTokens = getNumberOrNull(normalizedTrace.promptTokens);+ const completionTokens = getNumberOrNull(normalizedTrace.completionTokens);++ if (promptTokens !== null || completionTokens !== null) {+ normalizedTrace.totalTokens = (promptTokens ?? 0) + (completionTokens ?? 0);+ }+ }++ return normalizedTrace;};-export const getTraceMappingKeyFullPath = (+function normalizeMappingPath(pathConfig: TraceMappingPathType) {+ if (+ typeof pathConfig === "object" &&+ !Array.isArray(pathConfig) &&+ "path" in pathConfig+ ) {+ return pathConfig;+ }++ return { path: pathConfig };+}++function joinPathSegments(path: string | string[]) {+ return Array.isArray(path) ? path.join(".") : path;+}++function getTraceMappingPathFullPath(key: TraceMappingKeyType,+ pathConfig: TraceMappingPathType,shouldReturnArray: boolean = false-) => {- if (!TraceMapping[key].prefix) {- if (!shouldReturnArray) {- if (typeof TraceMapping[key].path !== "string") {- return (TraceMapping[key].path as string[]).join(".");- }- }- return TraceMapping[key].path;- }- if (shouldReturnArray) {- let returnArr: string[] = [];- if (typeof TraceMapping[key].prefix === "string") {- returnArr = returnArr.concat([TraceMapping[key].prefix as string]);- } else {- returnArr = returnArr.concat(TraceMapping[key].prefix as string[]);- }+) {+ const mapping = TraceMapping[key];+ const normalizedPath = normalizeMappingPath(pathConfig);+ const prefix =+ "prefix" in normalizedPath ? normalizedPath.prefix : mapping.prefix;- if (typeof TraceMapping[key].path === "string") {- returnArr = returnArr.concat([TraceMapping[key].path as string]);- } else {- returnArr = returnArr.concat(TraceMapping[key].path as string[]);+ if (!prefix) {+ if (shouldReturnArray) {+ return Array.isArray(normalizedPath.path)+ ? normalizedPath.path+ : [normalizedPath.path];}- return returnArr;+ return joinPathSegments(normalizedPath.path);}- let returnString = "";- if (typeof TraceMapping[key].prefix === "string") {- returnString = TraceMapping[key].prefix as string;- } else {- returnString = (TraceMapping[key].prefix as string[]).join(".");+ if (shouldReturnArray) {+ const prefixParts = Array.isArray(prefix) ? prefix : [prefix];+ const pathParts = Array.isArray(normalizedPath.path)+ ? normalizedPath.path+ : [normalizedPath.path];+ return prefixParts.concat(pathParts);}- if (typeof TraceMapping[key].path === "string") {- returnString = [returnString, TraceMapping[key].path as string].join(".");- } else {- returnString = [- returnString,- (TraceMapping[key].path as string[]).join("."),- ].join(".");+ return [joinPathSegments(prefix), joinPathSegments(normalizedPath.path)].join(".");+}++export const getTraceMappingKeyFullPath = (+ key: TraceMappingKeyType,+ shouldReturnArray: boolean = false+) => {+ return getTraceMappingPathFullPath(+ key,+ TraceMapping[key].path,+ shouldReturnArray+ );+};++export const getTraceMappingKeyFullPaths = (+ key: TraceMappingKeyType,+ shouldReturnArray: boolean = false+) => {+ const mapping = TraceMapping[key];+ const paths = mapping.paths?.length ? mapping.paths : [mapping.path];+ return paths.map((pathConfig) =>+ getTraceMappingPathFullPath(key, pathConfig, shouldReturnArray)+ );+};++export const getTraceMappingValue = (+ item: TraceRow | Record<string, unknown>,+ key: TraceMappingKeyType+) => {+ const mapping = TraceMapping[key];+ const source = mapping.isRoot+ ? item+ : ((item as TraceRow)?.SpanAttributes ?? {});++ for (const path of getTraceMappingKeyFullPaths(key)) {+ const value = get(source, path as string);+ if (value !== undefined && value !== null && value !== "") {+ return value;+ }}- return returnString;+ return undefined;};export const CODE_ITEM_DISPLAY_KEYS: TraceMappingKeyType[] = [@@ -255,10 +305,11 @@ export const SPAN_ATTR_INFO_PILL_KEYS: TraceMappingKeyType[] = [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);- })+ .flatMap((key) =>+ getTraceMappingKeyFullPaths(key).map((path) =>+ Array.isArray(path) ? path.join(".") : (path as string)+ )+ ));/**diff --git a/src/client/src/helpers/server/trace.ts b/src/client/src/helpers/server/trace.tsindex bfc2f222..4493db79 100644--- a/src/client/src/helpers/server/trace.ts+++ b/src/client/src/helpers/server/trace.ts@@ -1,4 +1,8 @@-export { getTraceMappingKeyFullPath } from "../client/trace";+export {+ getTraceMappingKeyFullPath,+ getTraceMappingKeyFullPaths,+ getTraceMappingValue,+} from "../client/trace";export const buildHierarchy = (data: any[]) => {// Create a map for quick lookup of nodes by SpanIddiff --git a/src/client/src/lib/platform/common.ts b/src/client/src/lib/platform/common.tsindex cdc308c9..74c6d80e 100644--- a/src/client/src/lib/platform/common.ts+++ b/src/client/src/lib/platform/common.ts@@ -14,6 +14,12 @@ import { OPERATION_TYPE } from "@/types/platform";export const OTEL_TRACES_TABLE_NAME = "otel_traces";export const OTEL_LOGS_TABLE_NAME = "otel_logs";export const OTEL_GPUS_TABLE_NAME = "otel_metrics_gauge";+export const OTEL_METRICS_GAUGE_TABLE_NAME = "otel_metrics_gauge";+export const OTEL_METRICS_SUM_TABLE_NAME = "otel_metrics_sum";+export const OTEL_METRICS_HISTOGRAM_TABLE_NAME = "otel_metrics_histogram";+export const OTEL_METRICS_SUMMARY_TABLE_NAME = "otel_metrics_summary";+export const OTEL_METRICS_EXPONENTIAL_HISTOGRAM_TABLE_NAME =+ "otel_metrics_exponential_histogram";export type TimeLimit = {start: Date | string;diff --git a/src/client/src/lib/platform/llm/token.ts b/src/client/src/lib/platform/llm/token.tsindex 3a72f95a..f6750600 100644--- a/src/client/src/lib/platform/llm/token.ts+++ b/src/client/src/lib/platform/llm/token.ts@@ -1,5 +1,5 @@import { MetricParams, dataCollector, OTEL_TRACES_TABLE_NAME } from "../common";-import { getTraceMappingKeyFullPath } from "@/helpers/server/trace";+import { getTraceMappingKeyFullPaths } from "@/helpers/server/trace";import {dateTruncGroupingLogic,getFilterPreviousParams,@@ -12,27 +12,30 @@ export type TokenParams = MetricParams & {type: TOKEN_TYPE;};+function getSpanAttributePaths(key: "totalTokens" | "promptTokens" | "completionTokens") {+ return (getTraceMappingKeyFullPaths(key) as string[]).map(+ (path) => `SpanAttributes['${path}']`+ );+}++function getFirstNonEmptyPath(paths: string[]) {+ return paths.reduce((expression, path) => `if(${expression} != '', ${expression}, ${path})`);+}+export async function getAverageTokensPerRequest(params: TokenParams) {- const primaryPath = `SpanAttributes['${getTraceMappingKeyFullPath(+ const tokenKey =params.type === "total"? "totalTokens": params.type === "prompt"? "promptTokens"- : "completionTokens"- )}']`;-- // Backward compatibility: fall back to new OTel convention attributes- const fallbackAttr =- params.type === "total"- ? "gen_ai.client.token.usage"- : params.type === "prompt"- ? "gen_ai.client.token.usage.input"- : "gen_ai.client.token.usage.output";- const fallbackPath = `SpanAttributes['${fallbackAttr}']`;-- const keyPath = `if(${primaryPath} != '', ${primaryPath}, ${fallbackPath})`;+ : "completionTokens";+ const tokenPaths = getSpanAttributePaths(tokenKey);+ const keyPath = getFirstNonEmptyPath(tokenPaths);- const currentWhereParams = { ...params, notOrEmpty: [{ key: primaryPath }, { key: fallbackPath }] };+ const currentWhereParams = {+ ...params,+ notOrEmpty: tokenPaths.map((key) => ({ key })),+ };let query;@@ -70,26 +73,16 @@ export async function getTokensPerTime(params: MetricParams) {const { start, end } = params.timeLimit;const dateTrunc = dateTruncGroupingLogic(end as Date, start as Date);- const primaryPaths = [- `SpanAttributes['${getTraceMappingKeyFullPath("totalTokens")}']`,- `SpanAttributes['${getTraceMappingKeyFullPath("promptTokens")}']`,- `SpanAttributes['${getTraceMappingKeyFullPath("completionTokens")}']`,+ const tokenPaths = [+ getSpanAttributePaths("totalTokens"),+ getSpanAttributePaths("promptTokens"),+ getSpanAttributePaths("completionTokens"),];- // Backward compatibility: fall back to new OTel convention attributes- const fallbackPaths = [- `SpanAttributes['gen_ai.client.token.usage']`,- `SpanAttributes['gen_ai.client.token.usage.input']`,- `SpanAttributes['gen_ai.client.token.usage.output']`,- ];-- const coalesced = primaryPaths.map(- (p, i) => `if(${p} != '', ${p}, ${fallbackPaths[i]})`- );+ const coalesced = tokenPaths.map((paths) => getFirstNonEmptyPath(paths));const filterPaths: { key: string }[] = [- ...primaryPaths.map((key) => ({ key })),- ...fallbackPaths.map((key) => ({ key })),+ ...tokenPaths.flatMap((paths) => paths.map((key) => ({ key }))),];const query = `SELECTdiff --git a/src/client/src/lib/platform/observability.ts b/src/client/src/lib/platform/observability.tsnew file mode 100644index 00000000..82c11c07--- /dev/null+++ b/src/client/src/lib/platform/observability.ts@@ -0,0 +1,465 @@+import {+ MetricParams,+ OTEL_LOGS_TABLE_NAME,+ OTEL_TRACES_TABLE_NAME,+ OTEL_METRICS_EXPONENTIAL_HISTOGRAM_TABLE_NAME,+ OTEL_METRICS_GAUGE_TABLE_NAME,+ OTEL_METRICS_HISTOGRAM_TABLE_NAME,+ OTEL_METRICS_SUMMARY_TABLE_NAME,+ OTEL_METRICS_SUM_TABLE_NAME,+ dataCollector,+} from "./common";+import {+ dateTruncGroupingLogic,+ getFilterWhereCondition,+} from "@/helpers/server/platform";+import { CustomFilterAttributeType } from "@/types/store/filter";++type FilterTable = "logs" | "metrics";+type SummarySignal = "traces" | "exceptions" | "logs" | "metrics";++const METRIC_TABLES = [+ { table: OTEL_METRICS_GAUGE_TABLE_NAME, type: "gauge", valueExpr: "Value", countExpr: "1" },+ { table: OTEL_METRICS_SUM_TABLE_NAME, type: "sum", valueExpr: "Value", countExpr: "1" },+ { table: OTEL_METRICS_HISTOGRAM_TABLE_NAME, type: "histogram", valueExpr: "Sum", countExpr: "Count" },+ { table: OTEL_METRICS_SUMMARY_TABLE_NAME, type: "summary", valueExpr: "Sum", countExpr: "Count" },+ {+ table: OTEL_METRICS_EXPONENTIAL_HISTOGRAM_TABLE_NAME,+ type: "exponential_histogram",+ valueExpr: "Sum",+ countExpr: "Count",+ },+];++const LOG_FIELD_GROUP_BY = new Set([+ "Timestamp",+ "TraceId",+ "SpanId",+ "SeverityText",+ "SeverityNumber",+ "ServiceName",+ "Body",+ "ScopeName",+ "ScopeVersion",+]);++const METRIC_FIELD_GROUP_BY = new Set([+ "ServiceName",+ "MetricName",+ "MetricDescription",+ "MetricUnit",+ "ScopeName",+ "ScopeVersion",+ "TimeUnix",+]);++function escapeClickHouseString(value: string) {+ return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");+}++function getSummaryBucket(params: MetricParams) {+ const start = new Date(params.timeLimit.start as Date | string);+ const end = new Date(params.timeLimit.end as Date | string);+ const days = Math.max(1, (end.getTime() - start.getTime()) / 86400000);++ if (days <= 2) return "hour";+ if (days <= 45) return "day";+ if (days <= 370) return "week";+ return "month";+}++function bucketLabelFormat(bucket: string) {+ if (bucket === "hour") return "%m/%d %H:00";+ if (bucket === "month") return "%Y/%m";+ return "%Y/%m/%d";+}++function inList(values: string[]) {+ return values.map((value) => `'${escapeClickHouseString(value)}'`).join(", ");+}++function customFilterExpression(+ table: FilterTable,+ attributeType: CustomFilterAttributeType,+ key: string,+ value: string+) {+ const safeValue = escapeClickHouseString(value);+ const safeKey = escapeClickHouseString(key);+ const safeField = key.replace(/[^A-Za-z0-9_.]/g, "");++ if (attributeType === "ResourceAttributes") {+ return `ResourceAttributes['${safeKey}'] = '${safeValue}'`;+ }+ if (attributeType === "ScopeAttributes") {+ return `ScopeAttributes['${safeKey}'] = '${safeValue}'`;+ }+ if (attributeType === "LogAttributes" && table === "logs") {+ return `LogAttributes['${safeKey}'] = '${safeValue}'`;+ }+ if (attributeType === "Attributes" && table === "metrics") {+ return `Attributes['${safeKey}'] = '${safeValue}'`;+ }+ if (attributeType === "Field" && safeField) {+ const allowed = table === "logs" ? LOG_FIELD_GROUP_BY : METRIC_FIELD_GROUP_BY;+ if (allowed.has(safeField)) return `${safeField} = '${safeValue}'`;+ }+ return "";+}++function buildWhere(params: MetricParams, table: FilterTable) {+ const where: string[] = [];+ const timeColumn = table === "logs" ? "Timestamp" : "TimeUnix";+ const { start, end } = params.timeLimit || {};+ if (start && end) {+ where.push(+ `${timeColumn} >= parseDateTimeBestEffort('${start}') AND ${timeColumn} <= parseDateTimeBestEffort('${end}')`+ );+ }++ const selected = params.selectedConfig || {};+ if (selected.services?.length) {+ where.push(`ServiceName IN (${inList(selected.services)})`);+ }+ if (table === "logs" && selected.severities?.length) {+ const severities = selected.severities.map((severity: string) => severity.toLowerCase());+ where.push(`lower(SeverityText) IN (${inList(severities)})`);+ }+ if (table === "metrics") {+ if (selected.metricNames?.length) {+ where.push(`MetricName IN (${inList(selected.metricNames)})`);+ }+ }+ if (selected.customFilters?.length) {+ selected.customFilters.forEach(+ ({+ attributeType,+ key,+ value,+ }: {+ attributeType: CustomFilterAttributeType;+ key: string;+ value: string;+ }) => {+ if (!key || !value) return;+ const expr = customFilterExpression(table, attributeType, key, value);+ if (expr) where.push(expr);+ }+ );+ }++ if (table === "logs" && selected.traceIds?.length) {+ where.push(`TraceId IN (${inList(selected.traceIds)})`);+ }+ if (table === "logs" && selected.spanIds?.length) {+ where.push(`SpanId IN (${inList(selected.spanIds)})`);+ }++ return where.length ? where.join(" AND ") : "1 = 1";+}++function metricUnionSelect(params: MetricParams, selectSql: string) {+ const where = buildWhere(params, "metrics");+ const selectedTypes = params.selectedConfig?.metricTypes as string[] | undefined;+ const tables = selectedTypes?.length+ ? METRIC_TABLES.filter(({ type }) => selectedTypes.includes(type))+ : METRIC_TABLES;+ return tables.map(+ ({ table, type, valueExpr, countExpr }) => `+ SELECT+ '${type}' AS metric_type,+ ${valueExpr} AS metric_value,+ ${countExpr} AS metric_sample_count,+ ${selectSql}+ FROM ${table}+ WHERE ${where}+ `+ ).join(" UNION ALL ");+}++export async function getLogsConfig(params: MetricParams) {+ const query = `+ SELECT+ arrayFilter(x -> x != '', ARRAY_AGG(DISTINCT ServiceName)) AS services,+ arrayFilter(x -> x != '', ARRAY_AGG(DISTINCT SeverityText)) AS severities,+ CAST(COUNT(*) AS INTEGER) AS totalRows+ FROM ${OTEL_LOGS_TABLE_NAME}+ WHERE ${buildWhere(params, "logs")}+ `;+ return dataCollector({ query });+}++export async function getLogAttributeKeys(params: MetricParams) {+ const where = buildWhere(params, "logs");+ const queries = [+ {+ key: "logAttributeKeys",+ query: `SELECT DISTINCT arrayJoin(mapKeys(LogAttributes)) AS key FROM ${OTEL_LOGS_TABLE_NAME} WHERE ${where} ORDER BY key LIMIT 500`,+ },+ {+ key: "resourceAttributeKeys",+ query: `SELECT DISTINCT arrayJoin(mapKeys(ResourceAttributes)) AS key FROM ${OTEL_LOGS_TABLE_NAME} WHERE ${where} ORDER BY key LIMIT 500`,+ },+ {+ key: "scopeAttributeKeys",+ query: `SELECT DISTINCT arrayJoin(mapKeys(ScopeAttributes)) AS key FROM ${OTEL_LOGS_TABLE_NAME} WHERE ${where} ORDER BY key LIMIT 500`,+ },+ ];+ const results = await Promise.all(queries.map(({ query }) => dataCollector({ query })));+ return {+ err: results.find((result) => result.err)?.err ?? null,+ spanAttributeKeys: [],+ resourceAttributeKeys:+ (results[1].data as { key: string }[] | undefined)?.map((row) => row.key) ?? [],+ logAttributeKeys:+ (results[0].data as { key: string }[] | undefined)?.map((row) => row.key) ?? [],+ scopeAttributeKeys:+ (results[2].data as { key: string }[] | undefined)?.map((row) => row.key) ?? [],+ };+}++export async function getLogs(params: MetricParams) {+ const { limit = 25, offset = 0 } = params;+ const where = buildWhere(params, "logs");+ const countQuery = `SELECT CAST(COUNT(*) AS INTEGER) AS total FROM ${OTEL_LOGS_TABLE_NAME} WHERE ${where}`;+ const { data: countData, err: countErr } = await dataCollector({ query: countQuery });+ if (countErr) return { err: countErr };++ const orderBy = params.sorting?.type+ ? `${params.sorting.type.replace(/[^A-Za-z0-9_.]/g, "")} ${params.sorting.direction}`+ : "Timestamp desc";+ const query = `+ SELECT+ cityHash64(toString(Timestamp), TraceId, SpanId, SeverityText, Body) AS rowId,+ *+ FROM ${OTEL_LOGS_TABLE_NAME}+ WHERE ${where}+ ORDER BY ${orderBy}+ LIMIT ${limit}+ OFFSET ${offset}+ `;+ const { data, err } = await dataCollector({ query });+ return {+ err,+ records: data,+ total: (countData as any[])?.[0]?.total || 0,+ };+}++export async function getSignalSummary(+ params: MetricParams,+ signal: SummarySignal+) {+ const bucket = getSummaryBucket(params);+ const labelFormat = bucketLabelFormat(bucket);+ let query = "";++ if (signal === "traces" || signal === "exceptions") {+ const traceParams: MetricParams = {+ ...params,+ ...(signal === "exceptions"+ ? { statusCode: ["STATUS_CODE_ERROR", "Error"] }+ : {}),+ };+ const where = getFilterWhereCondition(traceParams, true);+ query = `+ SELECT+ formatDateTime(DATE_TRUNC('${bucket}', Timestamp), '${labelFormat}') AS label,+ CAST(COUNT(*) AS INTEGER) AS count,+ CAST(avg(Duration) * 1e-9 AS FLOAT) AS avgDuration,+ CAST(SUM(toFloat64OrZero(SpanAttributes['gen_ai.usage.cost'])) AS FLOAT) AS cost,+ CAST(SUM(toInt64OrZero(SpanAttributes['gen_ai.usage.total_tokens'])) AS INTEGER) AS tokens+ FROM ${OTEL_TRACES_TABLE_NAME}+ WHERE ${where}+ GROUP BY label+ ORDER BY min(Timestamp)+ `;+ } else if (signal === "logs") {+ const where = buildWhere(params, "logs");+ query = `+ SELECT+ formatDateTime(DATE_TRUNC('${bucket}', Timestamp), '${labelFormat}') AS label,+ CAST(COUNT(*) AS INTEGER) AS count,+ CAST(countIf(SeverityText IN ('ERROR', 'Error', 'error', 'FATAL', 'Fatal', 'fatal')) AS INTEGER) AS errors,+ CAST(uniqExact(ServiceName) AS INTEGER) AS services+ FROM ${OTEL_LOGS_TABLE_NAME}+ WHERE ${where}+ GROUP BY label+ ORDER BY min(Timestamp)+ `;+ } else {+ const union = metricUnionSelect(params, "ServiceName, MetricName, TimeUnix");+ query = `+ SELECT+ formatDateTime(DATE_TRUNC('${bucket}', TimeUnix), '${labelFormat}') AS label,+ CAST(COUNT(*) AS INTEGER) AS count,+ CAST(uniqExact(MetricName) AS INTEGER) AS metrics,+ CAST(uniqExact(ServiceName) AS INTEGER) AS services+ FROM (${union})+ GROUP BY label+ ORDER BY min(TimeUnix)+ `;+ }++ const { data, err } = await dataCollector({ query });+ const buckets = (data as any[]) || [];+ const total = buckets.reduce((sum, row) => sum + Number(row.count || 0), 0);++ return {+ err,+ bucket,+ buckets,+ total,+ peak: buckets.reduce((max, row) => Math.max(max, Number(row.count || 0)), 0),+ };+}++export async function getLogByRowId(rowId: string) {+ const safeRowId = rowId.replace(/[^0-9]/g, "");+ const query = `+ SELECT+ cityHash64(toString(Timestamp), TraceId, SpanId, SeverityText, Body) AS rowId,+ *+ FROM ${OTEL_LOGS_TABLE_NAME}+ WHERE cityHash64(toString(Timestamp), TraceId, SpanId, SeverityText, Body) = ${safeRowId || "0"}+ LIMIT 1+ `;+ const { data, err } = await dataCollector({ query });+ return { err, record: (data as any[])?.[0] };+}++export async function getMetricsConfig(params: MetricParams) {+ const query = `+ SELECT+ arrayFilter(x -> x != '', ARRAY_AGG(DISTINCT ServiceName)) AS services,+ arrayFilter(x -> x != '', ARRAY_AGG(DISTINCT MetricName)) AS metricNames,+ arrayFilter(x -> x != '', ARRAY_AGG(DISTINCT metric_type)) AS metricTypes,+ CAST(COUNT(*) AS INTEGER) AS totalRows+ FROM (${metricUnionSelect(params, "ServiceName, MetricName")})+ `;+ return dataCollector({ query });+}++export async function getMetricAttributeKeys(params: MetricParams) {+ const queries = METRIC_TABLES.map(({ table }) => ({+ metric: `SELECT DISTINCT arrayJoin(mapKeys(Attributes)) AS key FROM ${table} WHERE ${buildWhere(params, "metrics")}`,+ resource: `SELECT DISTINCT arrayJoin(mapKeys(ResourceAttributes)) AS key FROM ${table} WHERE ${buildWhere(params, "metrics")}`,+ scope: `SELECT DISTINCT arrayJoin(mapKeys(ScopeAttributes)) AS key FROM ${table} WHERE ${buildWhere(params, "metrics")}`,+ }));+ const [metricResult, resourceResult, scopeResult] = await Promise.all([+ dataCollector({+ query: `${queries.map((q) => q.metric).join(" UNION DISTINCT ")} ORDER BY key LIMIT 500`,+ }),+ dataCollector({+ query: `${queries.map((q) => q.resource).join(" UNION DISTINCT ")} ORDER BY key LIMIT 500`,+ }),+ dataCollector({+ query: `${queries.map((q) => q.scope).join(" UNION DISTINCT ")} ORDER BY key LIMIT 500`,+ }),+ ]);+ return {+ err: metricResult.err || resourceResult.err || scopeResult.err,+ spanAttributeKeys: [],+ resourceAttributeKeys:+ (resourceResult.data as { key: string }[] | undefined)?.map((row) => row.key) ?? [],+ metricAttributeKeys:+ (metricResult.data as { key: string }[] | undefined)?.map((row) => row.key) ?? [],+ scopeAttributeKeys:+ (scopeResult.data as { key: string }[] | undefined)?.map((row) => row.key) ?? [],+ };+}++export async function getMetrics(params: MetricParams) {+ const { limit = 25, offset = 0 } = params;+ const union = metricUnionSelect(+ params,+ "ServiceName, MetricName, MetricDescription, MetricUnit, TimeUnix, Attributes, ResourceAttributes, ScopeName, ScopeVersion, ScopeAttributes"+ );+ const countQuery = `+ SELECT CAST(COUNT(*) AS INTEGER) AS total+ FROM (+ SELECT MetricName, metric_type, ServiceName+ FROM (${union})+ GROUP BY MetricName, metric_type, ServiceName+ )+ `;+ const { data: countData, err: countErr } = await dataCollector({ query: countQuery });+ if (countErr) return { err: countErr };++ const query = `+ SELECT+ MetricName AS metricName,+ metric_type AS metricType,+ ServiceName AS serviceName,+ anyLast(MetricDescription) AS metricDescription,+ anyLast(MetricUnit) AS metricUnit,+ CAST(argMax(metric_value, TimeUnix) AS FLOAT) AS latestValue,+ CAST(avg(metric_value) AS FLOAT) AS avgValue,+ CAST(min(metric_value) AS FLOAT) AS minValue,+ CAST(max(metric_value) AS FLOAT) AS maxValue,+ CAST(COUNT(*) AS INTEGER) AS pointCount,+ CAST(SUM(metric_sample_count) AS INTEGER) AS observationCount,+ max(TimeUnix) AS lastSeen+ FROM (${union})+ GROUP BY MetricName, metric_type, ServiceName+ ORDER BY lastSeen DESC+ LIMIT ${limit}+ OFFSET ${offset}+ `;+ const { data, err } = await dataCollector({ query });+ return {+ err,+ records: data,+ total: (countData as any[])?.[0]?.total || 0,+ };+}++export async function getMetricDetail(metricName: string, metricType?: string, serviceName?: string, params?: MetricParams) {+ const safeMetricName = escapeClickHouseString(metricName);+ const selectedConfig = {+ ...(params?.selectedConfig || {}),+ metricNames: [metricName],+ ...(metricType ? { metricTypes: [metricType] } : {}),+ ...(serviceName ? { services: [serviceName] } : {}),+ };+ const effectiveParams: MetricParams = {+ timeLimit: params?.timeLimit || {+ type: "24H",+ start: new Date(Date.now() - 24 * 60 * 60 * 1000),+ end: new Date(),+ },+ selectedConfig,+ };+ const start = new Date(effectiveParams.timeLimit.start as Date | string);+ const end = new Date(effectiveParams.timeLimit.end as Date | string);+ const dateTrunc = dateTruncGroupingLogic(end, start);+ const union = metricUnionSelect(+ effectiveParams,+ "ServiceName, MetricName, MetricDescription, MetricUnit, TimeUnix, Attributes, ResourceAttributes, ScopeName, ScopeVersion, ScopeAttributes"+ );+ const seriesQuery = `+ SELECT+ formatDateTime(DATE_TRUNC('${dateTrunc}', TimeUnix), '%Y/%m/%d %R') AS request_time,+ CAST(avg(metric_value) AS FLOAT) AS value+ FROM (${union})+ WHERE MetricName = '${safeMetricName}'+ GROUP BY request_time+ ORDER BY request_time+ `;+ const pointsQuery = `+ SELECT *+ FROM (${union})+ WHERE MetricName = '${safeMetricName}'+ ORDER BY TimeUnix DESC+ LIMIT 100+ `;+ const [series, points] = await Promise.all([+ dataCollector({ query: seriesQuery }),+ dataCollector({ query: pointsQuery }),+ ]);+ return {+ err: series.err || points.err,+ series: series.data ?? [],+ points: points.data ?? [],+ };+}diff --git a/src/client/src/lib/platform/pricing/index.ts b/src/client/src/lib/platform/pricing/index.tsindex 51e373e0..0f5c0266 100644--- a/src/client/src/lib/platform/pricing/index.ts+++ b/src/client/src/lib/platform/pricing/index.ts@@ -2,7 +2,10 @@ import getMessage from "@/constants/messages";import { getCurrentUser } from "@/lib/session";import { throwIfError } from "@/utils/error";import { dataCollector, OTEL_TRACES_TABLE_NAME } from "@/lib/platform/common";-import { getTraceMappingKeyFullPath } from "@/helpers/server/trace";+import {+ getTraceMappingKeyFullPath,+ getTraceMappingKeyFullPaths,+} from "@/helpers/server/trace";import { SUPPORTED_EVALUATION_OPERATIONS } from "@/constants/traces";import { getDBConfigById } from "@/lib/db-config";import { getRequestViaSpanId } from "@/lib/platform/request";@@ -17,9 +20,11 @@ import asaw from "@/utils/asaw";const COST_KEY = getTraceMappingKeyFullPath("cost") as string; // gen_ai.usage.costconst MODEL_KEY = getTraceMappingKeyFullPath("model") as string; // gen_ai.request.modelconst PROVIDER_KEY = getTraceMappingKeyFullPath("provider") as string; // gen_ai.system-const PROMPT_TOKENS_KEY = getTraceMappingKeyFullPath("promptTokens") as string; // gen_ai.usage.input_tokens-const COMPLETION_TOKENS_KEY = getTraceMappingKeyFullPath("completionTokens") as string; // gen_ai.usage.output_tokensconst TYPE_KEY = getTraceMappingKeyFullPath("type") as string; // gen_ai.operation.name+const PROMPT_TOKENS_KEYS = getTraceMappingKeyFullPaths("promptTokens") as string[];+const COMPLETION_TOKENS_KEYS = getTraceMappingKeyFullPaths(+ "completionTokens"+) as string[];interface TraceRow {SpanId: string;@@ -31,6 +36,24 @@ function getAttr(trace: TraceRow, key: string): string {return (trace.SpanAttributes || {})[key] ?? "";}+function getNumericAttr(trace: TraceRow, keys: string[]): number {+ const attributes = trace.SpanAttributes || {};++ for (const key of keys) {+ const value = attributes[key];+ if (value === undefined || value === null || value === "") {+ continue;+ }++ const numericValue = Number(value);+ if (Number.isFinite(numericValue)) {+ return numericValue;+ }+ }++ return 0;+}+/*** Compute the cost for a single trace by looking up the model in* openlit_provider_models and applying token-based pricing.@@ -42,11 +65,8 @@ async function computeCostForTrace(): Promise<{ cost: number | null; reason?: string }> {const provider = getAttr(trace, PROVIDER_KEY);const model = getAttr(trace, MODEL_KEY);- const promptTokens = Number(getAttr(trace, PROMPT_TOKENS_KEY)) || 0;- const completionTokens = Number(getAttr(trace, COMPLETION_TOKENS_KEY)) || 0;-- const allKeys = Object.keys(trace.SpanAttributes || {});- const genAiKeys = allKeys.filter((k) => k.startsWith("gen_ai"));+ const promptTokens = getNumericAttr(trace, PROMPT_TOKENS_KEYS);+ const completionTokens = getNumericAttr(trace, COMPLETION_TOKENS_KEYS);if (!provider || !model) {const reason = `Missing ${!provider ? "provider" : ""}${diff --git a/src/client/src/lib/platform/request/index.ts b/src/client/src/lib/platform/request/index.tsindex a4c8bfd6..768f0c92 100644--- a/src/client/src/lib/platform/request/index.ts+++ b/src/client/src/lib/platform/request/index.ts@@ -269,13 +269,11 @@ export async function getHeirarchyViaSpanId(spanId: string) {});if (traceIdErr || !Array.isArray(traceIdData) || traceIdData.length === 0) {- console.error(`[heirarchy] Failed to find TraceId for spanId=${spanId}:`, traceIdErr);return { err: "Span not found", record: {} };}const traceId = traceIdData[0].TraceId;if (!traceId) {- console.error(`[heirarchy] TraceId is empty for spanId=${spanId}. Row:`, traceIdData[0]);return { err: "TraceId not found for span", record: {} };}@@ -300,7 +298,6 @@ export async function getHeirarchyViaSpanId(spanId: string) {});if (allSpansErr || !Array.isArray(allSpans) || allSpans.length === 0) {- console.error(`[heirarchy] Failed to fetch spans for traceId=${traceId}:`, allSpansErr);return { err: "Failed to fetch trace spans", record: {} };}@@ -308,7 +305,6 @@ export async function getHeirarchyViaSpanId(spanId: string) {const heirarchy = buildHierarchy(allSpans as any[]);if (!heirarchy) {- console.error(`[heirarchy] buildHierarchy returned null for traceId=${traceId}, ${allSpans.length} spans`);return { err: "Error building hierarchy", record: {} };}diff --git a/src/client/src/middleware.ts b/src/client/src/middleware.tsindex 8cb1165d..4ca78bb1 100644--- a/src/client/src/middleware.ts+++ b/src/client/src/middleware.ts@@ -17,6 +17,10 @@ export const config = {"/register","/getting-started","/dashboard",+ "/telemetry",+ "/telemetry/:path*",+ "/observability",+ "/observability/:path*","/requests","/openground","/exceptions",diff --git a/src/client/src/store/filter.ts b/src/client/src/store/filter.tsindex fcb17798..0d5858fb 100644--- a/src/client/src/store/filter.ts+++ b/src/client/src/store/filter.ts@@ -163,7 +163,7 @@ export const filterStoreSlice: FilterStore = lens((setStore, getStore) => ({config: resetConfig ? undefined : getStore().config,});},- updateConfig: (config: FilterConfig) => {+ updateConfig: (config?: FilterConfig) => {setStore({ config });},updateAttributeKeys: (attributeKeys: AttributeKeys) => {diff --git a/src/client/src/store/page.ts b/src/client/src/store/page.tsindex 6455fc61..1890230a 100644--- a/src/client/src/store/page.ts+++ b/src/client/src/store/page.ts@@ -25,6 +25,27 @@ export const pageStoreSlice: PageStore = lens((setStore, getStore) => ({exceptionType: true,},},+ observabilityLogs: {+ visibilityColumns: {+ time: true,+ severityText: true,+ serviceName: true,+ body: true,+ traceId: true,+ spanId: false,+ },+ },+ observabilityMetrics: {+ visibilityColumns: {+ metricName: true,+ metricType: true,+ serviceName: true,+ metricUnit: true,+ latestValue: true,+ pointCount: true,+ lastSeen: true,+ },+ },fleethub: {visibilityColumns: {id: true,diff --git a/src/client/src/types/store/filter.ts b/src/client/src/types/store/filter.tsindex 94145982..8595c5d8 100644--- a/src/client/src/types/store/filter.ts+++ b/src/client/src/types/store/filter.ts@@ -23,7 +23,13 @@ export interface FilterType {filterReady?: boolean;}-export type CustomFilterAttributeType = "SpanAttributes" | "ResourceAttributes" | "Field";+export type CustomFilterAttributeType =+ | "SpanAttributes"+ | "ResourceAttributes"+ | "LogAttributes"+ | "ScopeAttributes"+ | "Attributes"+ | "Field";export type CustomFilter = {attributeType: CustomFilterAttributeType;@@ -57,6 +63,10 @@ export interface FilterConfig {serviceNames: string[];spanNames: string[];environments: string[];+ services: string[];+ severities: string[];+ metricNames: string[];+ metricTypes: string[];customFilters?: CustomFilter[];/** Locked agent version scope used by the agent detail page. */versionFilter?: VersionFilter;@@ -65,6 +75,9 @@ export interface FilterConfig {export type AttributeKeys = {spanAttributeKeys: string[];resourceAttributeKeys: string[];+ logAttributeKeys?: string[];+ scopeAttributeKeys?: string[];+ metricAttributeKeys?: string[];};export type FilterStore = {@@ -72,6 +85,6 @@ export type FilterStore = {config?: FilterConfig;attributeKeys?: AttributeKeys;updateFilter: (key: string, value: any, extraParams?: any) => void;- updateConfig: (config: FilterConfig) => void;+ updateConfig: (config?: FilterConfig) => void;updateAttributeKeys: (keys: AttributeKeys) => void;};diff --git a/src/client/src/types/store/page.ts b/src/client/src/types/store/page.tsindex a3b3310e..ca429a78 100644--- a/src/client/src/types/store/page.ts+++ b/src/client/src/types/store/page.ts@@ -13,7 +13,13 @@ export type REQUEST_VISIBILITY_COLUMNS = Record<boolean>;-export type PAGE = "dashboard" | "request" | "exception" | "fleethub";+export type PAGE =+ | "dashboard"+ | "request"+ | "exception"+ | "observabilityLogs"+ | "observabilityMetrics"+ | "fleethub";export type PageHeader = {title: string;@@ -34,10 +40,16 @@ export type PageStore = {exception: {visibilityColumns: Record<string, boolean>;};+ observabilityLogs: {+ visibilityColumns: Record<string, boolean>;+ };+ observabilityMetrics: {+ visibilityColumns: Record<string, boolean>;+ };fleethub: {visibilityColumns: Record<string, boolean>;};setData: (p: PAGE, keyPath: string, value: unknown) => void;header: PageHeader,setHeader: (header: PageHeader) => void;-};\ No newline at end of file+};diff --git a/src/client/src/types/trace.ts b/src/client/src/types/trace.tsindex b4908c6e..f596ed05 100644--- a/src/client/src/types/trace.ts+++ b/src/client/src/types/trace.ts@@ -1,6 +1,13 @@import { type LucideIcon } from "lucide-react";export type TraceKeyType = "string" | "integer" | "float" | "round" | "date";+export type TraceMappingPathType =+ | string+ | string[]+ | {+ path: string | string[];+ prefix?: string | string[] | null;+ };export type TraceMappingKeyType =| "time"@@ -103,6 +110,7 @@ export type TraceMappingValueType = {label: string;type: TraceKeyType;path: string | string[];+ paths?: TraceMappingPathType[];prefix?: string | string[];isRoot?: boolean;offset?: number;diff --git a/src/client/src/utils/breadcrumbs.ts b/src/client/src/utils/breadcrumbs.tsindex b113e8f4..7e58c0b5 100644--- a/src/client/src/utils/breadcrumbs.ts+++ b/src/client/src/utils/breadcrumbs.ts@@ -119,6 +119,33 @@ export const ROUTE_CONFIGS: RouteConfig[] = [getTitle: () => "Requests",getBreadcrumbs: () => [],},++ // Telemetry+ {+ regex: /^\/telemetry$/,+ getTitle: () => "Telemetry",+ getBreadcrumbs: () => [],+ },+ {+ regex: /^\/telemetry\/traces\/[^/]+$/,+ getTitle: () => "Trace Details",+ getBreadcrumbs: () => [{ title: "Telemetry", href: "/telemetry?tab=traces" }],+ },+ {+ regex: /^\/telemetry\/exceptions\/[^/]+$/,+ getTitle: () => "Exception Details",+ getBreadcrumbs: () => [{ title: "Telemetry", href: "/telemetry?tab=exceptions" }],+ },+ {+ regex: /^\/telemetry\/logs\/[^/]+$/,+ getTitle: () => "Log Details",+ getBreadcrumbs: () => [{ title: "Telemetry", href: "/telemetry?tab=logs" }],+ },+ {+ regex: /^\/telemetry\/metrics\/[^/]+$/,+ getTitle: () => "Metric Details",+ getBreadcrumbs: () => [{ title: "Telemetry", href: "/telemetry?tab=metrics" }],+ },// Exceptions{diff --git a/src/client/src/utils/hooks/useBreadcrumbs.ts b/src/client/src/utils/hooks/useBreadcrumbs.tsindex 6d710e21..20b0e006 100644--- a/src/client/src/utils/hooks/useBreadcrumbs.ts+++ b/src/client/src/utils/hooks/useBreadcrumbs.ts@@ -52,13 +52,15 @@ export function useDynamicBreadcrumbs(*/export function useCustomBreadcrumbs(customHeader: PageHeader,- deps: React.DependencyList = []+ deps: React.DependencyList = [],+ enabled = true) {const { header, setHeader } = usePageHeader();useEffect(() => {+ if (!enabled) return;setHeader(customHeader);- }, [setHeader, customHeader.title, customHeader.description, ...deps]);+ }, [enabled, setHeader, customHeader.title, customHeader.description, customHeader.breadcrumbs, ...deps]);return { header, setHeader };}