🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(dashboard): 'View as table' — navigate from a widget to the traces/observations table (LFE-11021) (#15194)
Nikita Kabardinc9da58d93242
diff --git a/web/src/features/dashboard/lib/buildTableFilterHref.clienttest.ts b/web/src/features/dashboard/lib/buildTableFilterHref.clienttest.tsnew file mode 100644index 0000000000..553c249fc7--- /dev/null+++ b/web/src/features/dashboard/lib/buildTableFilterHref.clienttest.ts@@ -0,0 +1,292 @@+import {+ type FilterState,+ observationsTableCols,+ tracesTableCols,+} from "@langfuse/shared";+import {+ buildTableFilterHref,+ buildViewAsTableHint,+} from "./buildTableFilterHref";+import {+ decodeFiltersGeneric,+ MAX_URL_FILTER_QUERY_LENGTH,+} from "@/src/features/filters/lib/filter-query-encoding";++const DATE_RANGE = {+ from: new Date("2026-07-01T00:00:00.000Z"),+ to: new Date("2026-07-02T00:00:00.000Z"),+};++// Parse the ?filter= value the way the destination table does: the URL layer+// decodes the transport-encoding once, then decodeFiltersGeneric parses the+// semicolon/comma format.+const decodeHrefFilters = (href: string): FilterState => {+ const url = new URL("http://localhost" + href);+ const filterParam = url.searchParams.get("filter");+ return filterParam ? decodeFiltersGeneric(filterParam) : [];+};++describe("buildTableFilterHref", () => {+ it("links a traces-view widget to the traces table with translated column ids", () => {+ const uiFilters: FilterState = [+ {+ column: "traceName",+ type: "stringOptions",+ operator: "any of",+ value: ["checkout"],+ },+ { column: "user", type: "string", operator: "=", value: "u-1" },+ {+ column: "traceTags",+ type: "arrayOptions",+ operator: "any of",+ value: ["prod"],+ },+ ];++ const { href, notApplicable } = buildTableFilterHref(+ "proj-1",+ "traces",+ uiFilters,+ DATE_RANGE,+ );++ expect(href.startsWith("/project/proj-1/traces?")).toBe(true);++ const decoded = decodeHrefFilters(href);+ expect(decoded.map((f) => f.column)).toEqual([+ "traceName",+ "userId",+ "traceTags",+ ]);+ // every emitted id is a real traces table column+ const ids = new Set(tracesTableCols.map((c) => c.id));+ decoded.forEach((f) => expect(ids.has(f.column)).toBe(true));+ expect(notApplicable.size).toBe(0);+ });++ it("links an observations-view widget to the observations table (model rename, tags kept)", () => {+ const uiFilters: FilterState = [+ {+ column: "model",+ type: "stringOptions",+ operator: "any of",+ value: ["gpt-4"],+ },+ { column: "user", type: "string", operator: "=", value: "u-1" },+ {+ column: "traceTags",+ type: "arrayOptions",+ operator: "any of",+ value: ["a"],+ },+ ];++ const { href } = buildTableFilterHref(+ "proj-1",+ "observations",+ uiFilters,+ DATE_RANGE,+ );++ expect(href.startsWith("/project/proj-1/observations?")).toBe(true);++ const decoded = decodeHrefFilters(href);+ expect(decoded.map((f) => f.column)).toEqual(["model", "userId", "tags"]);+ const ids = new Set(observationsTableCols.map((c) => c.id));+ decoded.forEach((f) => expect(ids.has(f.column)).toBe(true));+ });++ it("drops a sessionId filter for an observations widget and reports it", () => {+ const uiFilters: FilterState = [+ { column: "session", type: "string", operator: "=", value: "s-1" },+ { column: "user", type: "string", operator: "=", value: "u-1" },+ ];++ const { href, notApplicable } = buildTableFilterHref(+ "proj-1",+ "observations",+ uiFilters,+ DATE_RANGE,+ );++ const decoded = decodeHrefFilters(href);+ expect(decoded.map((f) => f.column)).toEqual(["userId"]);+ expect(notApplicable.get("sessionId")).toMatch(/session/i);+ });++ it('drops a dashboard-global "Version" filter on an observations widget (parity with the widget query, which maps it to the dropped traceVersion)', () => {+ // The "stored" mapping variant the widget query uses resolves the legacy+ // "Version" alias to `traceVersion`, which the observations table can't+ // express. The builder must match: no observation `version` filter leaks in.+ const uiFilters: FilterState = [+ { column: "Version", type: "string", operator: "=", value: "v1" },+ { column: "user", type: "string", operator: "=", value: "u-1" },+ ];++ const { href, notApplicable } = buildTableFilterHref(+ "proj-1",+ "observations",+ uiFilters,+ DATE_RANGE,+ );++ const decoded = decodeHrefFilters(href);+ expect(decoded.map((f) => f.column)).toEqual(["userId"]);+ expect(decoded.some((f) => f.column === "version")).toBe(false);+ expect(notApplicable.has("traceVersion")).toBe(true);+ });++ it("encodes the widget time range as a custom dateRange", () => {+ const { href } = buildTableFilterHref("proj-1", "traces", [], DATE_RANGE);+ const url = new URL("http://localhost" + href);+ expect(url.searchParams.get("dateRange")).toBe(+ `${DATE_RANGE.from.getTime()}-${DATE_RANGE.to.getTime()}`,+ );+ });++ it("omits filter/dateRange params when there is nothing to encode", () => {+ const { href } = buildTableFilterHref("proj-1", "traces", [], undefined);+ expect(href).toBe("/project/proj-1/traces");+ });++ it("survives operators with spaces through URL transport", () => {+ const uiFilters: FilterState = [+ {+ column: "traceName",+ type: "stringOptions",+ operator: "any of",+ value: ["a b", "c"],+ },+ ];+ const { href } = buildTableFilterHref(+ "proj-1",+ "traces",+ uiFilters,+ undefined,+ );+ const decoded = decodeHrefFilters(href);+ expect(decoded[0]).toMatchObject({+ column: "traceName",+ operator: "any of",+ value: ["a b", "c"],+ });+ });++ it("drops the largest filters to stay within the URL length budget, still navigating", () => {+ const huge = Array.from(+ { length: 800 },+ (_, i) => `value-${i}-${"x".repeat(20)}`,+ );+ const uiFilters: FilterState = [+ { column: "user", type: "string", operator: "=", value: "keep-me" },+ {+ column: "traceTags",+ type: "arrayOptions",+ operator: "any of",+ value: huge,+ },+ ];++ const { href, droppedForLength } = buildTableFilterHref(+ "proj-1",+ "traces",+ uiFilters,+ DATE_RANGE,+ );++ expect(droppedForLength).toBe(1);+ const url = new URL("http://localhost" + href);+ const filterParam = url.searchParams.get("filter") ?? "";+ expect(filterParam.length).toBeLessThanOrEqual(MAX_URL_FILTER_QUERY_LENGTH);+ // the small, high-value filter is retained+ const decoded = decodeHrefFilters(href);+ expect(decoded.map((f) => f.column)).toEqual(["userId"]);+ });+});++describe("buildViewAsTableHint", () => {+ it("returns null when nothing was dropped", () => {+ const result = buildTableFilterHref(+ "proj-1",+ "traces",+ [{ column: "user", type: "string", operator: "=", value: "u-1" }],+ DATE_RANGE,+ );+ expect(result.notApplicable.size).toBe(0);+ expect(result.droppedForLength).toBe(0);+ expect(buildViewAsTableHint(result)).toBeNull();+ });++ it("counts not-applicable dimensions with their reasons in the tooltip", () => {+ const result = buildTableFilterHref(+ "proj-1",+ "observations",+ [{ column: "session", type: "string", operator: "=", value: "s-1" }],+ DATE_RANGE,+ );+ const hint = buildViewAsTableHint(result);+ expect(hint?.count).toBe(1);+ expect(hint?.title).toMatch(/session/i);+ });++ // Regression: a filter dropped purely for URL length must still surface in+ // the hint. A hint keyed only on notApplicable would be silently zero here,+ // landing the user on a table quietly missing a filter they configured.+ it("surfaces length-dropped filters even when notApplicable is empty", () => {+ const huge = Array.from(+ { length: 800 },+ (_, i) => `value-${i}-${"x".repeat(20)}`,+ );+ const result = buildTableFilterHref(+ "proj-1",+ "traces",+ [+ { column: "user", type: "string", operator: "=", value: "keep-me" },+ {+ column: "traceTags",+ type: "arrayOptions",+ operator: "any of",+ value: huge,+ },+ ],+ DATE_RANGE,+ );++ expect(result.notApplicable.size).toBe(0);+ expect(result.droppedForLength).toBe(1);++ const hint = buildViewAsTableHint(result);+ expect(hint).not.toBeNull();+ expect(hint?.count).toBe(1); // not silently zero+ expect(hint?.title).toMatch(/dropped to keep the table URL/i);+ });++ it("sums not-applicable and length-dropped filters into one count", () => {+ const huge = Array.from(+ { length: 800 },+ (_, i) => `value-${i}-${"x".repeat(20)}`,+ );+ const result = buildTableFilterHref(+ "proj-1",+ "observations",+ [+ // sessionId -> not-applicable on observations+ { column: "session", type: "string", operator: "=", value: "s-1" },+ { column: "user", type: "string", operator: "=", value: "keep-me" },+ // huge applicable tags filter -> dropped for length+ {+ column: "traceTags",+ type: "arrayOptions",+ operator: "any of",+ value: huge,+ },+ ],+ DATE_RANGE,+ );++ expect(result.notApplicable.size).toBe(1);+ expect(result.droppedForLength).toBe(1);+ expect(buildViewAsTableHint(result)?.count).toBe(2);+ });+});diff --git a/web/src/features/dashboard/lib/buildTableFilterHref.ts b/web/src/features/dashboard/lib/buildTableFilterHref.tsnew file mode 100644index 0000000000..0ecaab9c9f--- /dev/null+++ b/web/src/features/dashboard/lib/buildTableFilterHref.ts@@ -0,0 +1,154 @@+import { type FilterState } from "@langfuse/shared";+import { type views } from "@langfuse/shared/query";+import { type z } from "zod";+import { mapLegacyUiTableFilterToView } from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";+import {+ classifyViewFiltersForTable,+ tableTargetForView,+} from "@/src/features/dashboard/lib/viewFilterToTableFilter";+import {+ encodeFiltersGeneric,+ MAX_URL_FILTER_QUERY_LENGTH,+} from "@/src/features/filters/lib/filter-query-encoding";+import { rangeToString } from "@/src/utils/date-range-utils";++type ViewName = z.infer<typeof views>;++export interface TableFilterHrefResult {+ /** `/project/<id>/<table>?filter=...&dateRange=...` ready for `router.push`. */+ href: string;+ /**+ * Widget dimensions the target table can't express, dropped from the filter.+ * Keyed by view dimension -> human reason. Non-empty means the table shows a+ * superset of the widget's data.+ */+ notApplicable: Map<string, string>;+ /**+ * Applicable filters additionally dropped so the `?filter=` value stays+ * within `MAX_URL_FILTER_QUERY_LENGTH` (avoids a 431 on the round-trip).+ */+ droppedForLength: number;+}++/**+ * Encode `filters` for the URL, dropping the largest-serialized filters first+ * until the value fits `MAX_URL_FILTER_QUERY_LENGTH`. Runaway high-cardinality+ * filters are the usual budget hogs (LFE-10717), so removing the biggest keeps+ * the most individual filters intact while guaranteeing the link still loads.+ */+function encodeFiltersWithinBudget(filters: FilterState): {+ encoded: string;+ droppedForLength: number;+} {+ let kept = filters;+ let encoded = encodeFiltersGeneric(kept);+ let droppedForLength = 0;++ while (kept.length > 0 && encoded.length > MAX_URL_FILTER_QUERY_LENGTH) {+ let biggestIdx = 0;+ let biggestLen = -1;+ for (let i = 0; i < kept.length; i++) {+ const len = encodeFiltersGeneric([kept[i]]).length;+ if (len > biggestLen) {+ biggestLen = len;+ biggestIdx = i;+ }+ }+ kept = kept.filter((_, i) => i !== biggestIdx);+ droppedForLength += 1;+ encoded = encodeFiltersGeneric(kept);+ }++ return { encoded, droppedForLength };+}++/**+ * Build the traces/observations-table link that shows the same data as a+ * widget: the widget's filters translated to the table's applicable filters+ * (filters the table can't express are dropped, not errored) plus the widget's+ * time range.+ *+ * `filters` are the widget's raw ui-table filters (widget config + dashboard+ * global filters); they are normalized to view space here before classifying.+ * `dateRange` is the dashboard's absolute range; when absent the table keeps+ * its own stored/default range.+ *+ * Normalization uses `mapLegacyUiTableFilterToView` (the "stored" variant), the+ * SAME mapping DashboardWidget's own query build applies to widget ++ * dashboard-global filters. This matters where the two variants diverge on a+ * legacy alias: e.g. a dashboard-global "Version" filter on an observations+ * widget maps to `traceVersion` (which the observations table correctly drops)+ * under the stored variant, but to the observation `version` column under the+ * editor variant — which would filter a different field than the chart did.+ */+export function buildTableFilterHref(+ projectId: string,+ view: ViewName,+ filters: FilterState,+ dateRange: { from: Date; to: Date } | undefined,+): TableFilterHrefResult {+ const table = tableTargetForView(view);++ const viewFilters = mapLegacyUiTableFilterToView(view, filters);+ const { applicable, notApplicable } = classifyViewFiltersForTable(+ view,+ viewFilters,+ );++ const { encoded, droppedForLength } = encodeFiltersWithinBudget(applicable);++ // Encode each param value with encodeURIComponent so the space in operators+ // like "any of" becomes %20 (unambiguous across the query-string parser the+ // destination table uses — a "+" would depend on form-encoding semantics).+ // encodeFiltersGeneric already percent-encodes the value layer, so this is+ // the single outer transport-encoding the parser reverses once.+ const queryParts: string[] = [];+ if (encoded.length > 0) {+ queryParts.push(`filter=${encodeURIComponent(encoded)}`);+ }+ if (dateRange) {+ queryParts.push(+ `dateRange=${encodeURIComponent(rangeToString(dateRange))}`,+ );+ }++ const query = queryParts.join("&");+ const href = `/project/${projectId}/${table}${query ? `?${query}` : ""}`;++ return { href, notApplicable, droppedForLength };+}++export interface ViewAsTableHint {+ /**+ * Total widget filters not reflected in the table: dimensions the table+ * can't express plus applicable filters dropped to fit the URL budget.+ */+ count: number;+ /** Newline-joined reasons, suitable for a tooltip. */+ title: string;+}++/**+ * Build the "N filters not shown" hint for a View-as-table result. Combines+ * the not-applicable dimensions with the filters dropped purely for URL length+ * so a length-drop is never silent — landing on a table quietly missing a+ * configured filter would break the "dropped with a hint, never mis-applied"+ * guarantee. Returns null when nothing was dropped.+ */+export function buildViewAsTableHint(+ result: TableFilterHrefResult,+): ViewAsTableHint | null {+ const count = result.notApplicable.size + result.droppedForLength;+ if (count === 0) return null;++ const reasons = Array.from(result.notApplicable.values());+ if (result.droppedForLength > 0) {+ reasons.push(+ `${result.droppedForLength} filter${+ result.droppedForLength === 1 ? "" : "s"+ } dropped to keep the table URL within limits.`,+ );+ }++ return { count, title: reasons.join("\n") };+}diff --git a/web/src/features/dashboard/lib/viewFilterToTableFilter.clienttest.ts b/web/src/features/dashboard/lib/viewFilterToTableFilter.clienttest.tsnew file mode 100644index 0000000000..46830ae166--- /dev/null+++ b/web/src/features/dashboard/lib/viewFilterToTableFilter.clienttest.ts@@ -0,0 +1,246 @@+import {+ type FilterState,+ observationsTableCols,+ tracesTableCols,+} from "@langfuse/shared";+import { type views } from "@langfuse/shared/query";+import { type z } from "zod";+import {+ classifyViewFiltersForTable,+ tableTargetForView,+} from "./viewFilterToTableFilter";++type ViewName = z.infer<typeof views>;++const tableColIds = {+ traces: new Set(tracesTableCols.map((c) => c.id)),+ observations: new Set(observationsTableCols.map((c) => c.id)),+} as const;++const stringFilter = (column: string): FilterState[number] => ({+ column,+ type: "string",+ operator: "=",+ value: "x",+});++const stringOptionsFilter = (column: string): FilterState[number] => ({+ column,+ type: "stringOptions",+ operator: "any of",+ value: ["gpt-4"],+});++const arrayOptionsFilter = (column: string): FilterState[number] => ({+ column,+ type: "arrayOptions",+ operator: "any of",+ value: ["a"],+});++describe("tableTargetForView", () => {+ it("routes observations to the observations table", () => {+ expect(tableTargetForView("observations")).toBe("observations");+ });++ it("routes traces and every scores-* view to the traces table", () => {+ expect(tableTargetForView("traces")).toBe("traces");+ expect(tableTargetForView("scores-numeric")).toBe("traces");+ expect(tableTargetForView("scores-categorical")).toBe("traces");+ });+});++describe("classifyViewFiltersForTable", () => {+ it("maps trace-view dimensions to real traces table column ids (with renames)", () => {+ const filters: FilterState = [+ stringOptionsFilter("name"),+ arrayOptionsFilter("tags"),+ stringFilter("userId"),+ stringFilter("sessionId"),+ stringFilter("release"),+ stringFilter("version"),+ stringFilter("environment"),+ ];+ const { applicable, notApplicable } = classifyViewFiltersForTable(+ "traces",+ filters,+ );++ expect(applicable.map((f) => f.column)).toEqual([+ "traceName", // name -> traceName (rename)+ "traceTags", // tags -> traceTags (rename)+ "userId",+ "sessionId",+ "release",+ "version",+ "environment",+ ]);+ expect(notApplicable.size).toBe(0);+ });++ it("maps observation-view dimensions to real observations table column ids", () => {+ const filters: FilterState = [+ stringOptionsFilter("providedModelName"),+ arrayOptionsFilter("tags"),+ stringFilter("userId"),+ stringOptionsFilter("type"),+ stringOptionsFilter("level"),+ stringOptionsFilter("name"),+ ];+ const { applicable, notApplicable } = classifyViewFiltersForTable(+ "observations",+ filters,+ );++ expect(applicable.map((f) => f.column)).toEqual([+ "model", // providedModelName -> model (rename)+ "tags", // tags stays tags on the observations table+ "userId",+ "type",+ "level",+ "name",+ ]);+ expect(notApplicable.size).toBe(0);+ });++ it("drops sessionId on observations (no session column) with a reason", () => {+ const { applicable, notApplicable } = classifyViewFiltersForTable(+ "observations",+ [stringFilter("sessionId")],+ );++ expect(applicable).toHaveLength(0);+ expect(notApplicable.get("sessionId")).toMatch(/session/i);+ });++ it("maps only trace-derived score dimensions to the traces table, dropping score-specific ones", () => {+ const filters: FilterState = [+ stringOptionsFilter("traceName"),+ arrayOptionsFilter("tags"),+ stringFilter("userId"),+ stringFilter("traceRelease"),+ stringFilter("traceVersion"),+ stringOptionsFilter("name"), // score name+ stringOptionsFilter("source"), // score source+ ];+ const { applicable, notApplicable } = classifyViewFiltersForTable(+ "scores-numeric",+ filters,+ );++ expect(applicable.map((f) => f.column)).toEqual([+ "traceName",+ "traceTags", // tags -> traceTags (rename)+ "userId",+ "release", // traceRelease -> release (rename)+ "version", // traceVersion -> version (rename)+ ]);+ expect(notApplicable.get("name")).toMatch(/score name/i);+ expect(notApplicable.get("source")).toMatch(/score source/i);+ });++ it("preserves filter type/operator/value and only rewrites the column", () => {+ const original = stringOptionsFilter("providedModelName");+ const { applicable } = classifyViewFiltersForTable("observations", [+ original,+ ]);++ expect(applicable[0]).toEqual({+ column: "model",+ type: "stringOptions",+ operator: "any of",+ value: ["gpt-4"],+ });+ // pure: input untouched+ expect(original.column).toBe("providedModelName");+ });++ it("reports unknown columns as not-applicable with a generic reason instead of throwing", () => {+ const { applicable, notApplicable } = classifyViewFiltersForTable(+ "traces",+ [stringFilter("totallyMadeUpDimension")],+ );++ expect(applicable).toHaveLength(0);+ expect(notApplicable.get("totallyMadeUpDimension")).toContain(+ "totallyMadeUpDimension",+ );+ });++ it("collapses repeated drops of the same dimension into a single reason", () => {+ const { notApplicable } = classifyViewFiltersForTable("observations", [+ stringFilter("sessionId"),+ {+ column: "sessionId",+ type: "string",+ operator: "contains",+ value: "y",+ },+ ]);+ expect(notApplicable.size).toBe(1);+ });++ // Guards against invented / drifted column ids: every applicable target id+ // must be a real column on the view's target table.+ it("only ever emits real target-table column ids", () => {+ const probesByView: Record<ViewName, FilterState> = {+ traces: [+ stringOptionsFilter("name"),+ arrayOptionsFilter("tags"),+ stringFilter("userId"),+ stringFilter("sessionId"),+ stringFilter("metadata"),+ stringFilter("release"),+ stringFilter("version"),+ stringFilter("environment"),+ stringFilter("id"),+ ],+ observations: [+ stringOptionsFilter("traceName"),+ stringOptionsFilter("name"),+ stringFilter("userId"),+ stringFilter("metadata"),+ stringOptionsFilter("type"),+ arrayOptionsFilter("tags"),+ stringOptionsFilter("providedModelName"),+ stringOptionsFilter("level"),+ arrayOptionsFilter("toolNames"),+ arrayOptionsFilter("calledToolNames"),+ stringFilter("environment"),+ stringFilter("version"),+ stringOptionsFilter("promptName"),+ stringFilter("promptVersion"),+ stringFilter("id"),+ stringFilter("traceId"),+ stringFilter("parentObservationId"),+ ],+ "scores-numeric": [+ stringOptionsFilter("traceName"),+ arrayOptionsFilter("tags"),+ stringFilter("userId"),+ stringFilter("sessionId"),+ stringFilter("traceRelease"),+ stringFilter("traceVersion"),+ ],+ "scores-categorical": [+ stringOptionsFilter("traceName"),+ arrayOptionsFilter("tags"),+ stringFilter("userId"),+ stringFilter("sessionId"),+ stringFilter("traceRelease"),+ stringFilter("traceVersion"),+ ],+ };++ (Object.keys(probesByView) as ViewName[]).forEach((view) => {+ const target = tableTargetForView(view);+ const { applicable } = classifyViewFiltersForTable(+ view,+ probesByView[view],+ );+ applicable.forEach((f) => {+ expect(tableColIds[target].has(f.column)).toBe(true);+ });+ });+ });+});diff --git a/web/src/features/dashboard/lib/viewFilterToTableFilter.ts b/web/src/features/dashboard/lib/viewFilterToTableFilter.tsnew file mode 100644index 0000000000..978d220782--- /dev/null+++ b/web/src/features/dashboard/lib/viewFilterToTableFilter.ts@@ -0,0 +1,205 @@+import { type FilterState } from "@langfuse/shared";+import { type views } from "@langfuse/shared/query";+import { type z } from "zod";++/**+ * Translate a dashboard/widget query-view filter set into the best-possible+ * filter set for the traces / observations data table, so a "View as table"+ * action can open the row-level data behind a widget.+ *+ * This module is the single source of truth for the view -> table filter+ * direction. It is authored as a sibling of the table -> query-dimension+ * `classifyChartFilters` (chart-view/lib/chartFilterCompatibility.ts): same+ * `{ applicable, notApplicable }` shape with per-column reasons, but pointing+ * the opposite way, so the two are intentionally NOT shared.+ *+ * It is a pure module (no React, no server imports) so a later monitor-alert+ * feature can reuse it server-side.+ *+ * Input filters are expected in *view space* — i.e. their `column`s are the+ * canonical view dimension names the query engine uses (e.g. `providedModelName`,+ * `tags`, `sessionId`). Callers that hold widget/ui-table filters must first+ * normalize them via `mapWidgetUiTableFilterToView`.+ */++type ViewName = z.infer<typeof views>;++/** The data table a widget view opens into. */+export type TableTarget = "traces" | "observations";++export interface ClassifiedViewFilters {+ /**+ * Widget filters that the target table can express, rewritten so each+ * `column` carries the target table's column **id** (the value the table's+ * `?filter=` decoder matches against — see `getColumnName` in+ * useFilterState). Filter `type`/`operator`/`value` are preserved verbatim.+ */+ applicable: FilterState;+ /** Dropped view dimension -> human-readable reason it can't be expressed. */+ notApplicable: Map<string, string>;+}++/**+ * Which data table a widget view maps to. Mirrors `buildDataWindowPermalink`+ * in packages/shared/.../monitors/processor/processor.ts: an `observations`+ * view links to the observations table; `traces` and every `scores-*` view+ * link to the traces table (the row-level data users expect to inspect).+ */+export function tableTargetForView(view: ViewName): TableTarget {+ return view === "observations" ? "observations" : "traces";+}++/**+ * Per-view map from a canonical view dimension to the target data-table column+ * **id**. Only dimensions the target table can genuinely express are listed;+ * every other dimension is reported as not-applicable. Column ids are the real+ * ids from `tracesTableCols` / `observationsTableCols` (cross-checked by the+ * unit tests, which fail if an id is invented or drifts).+ */+const VIEW_DIMENSION_TO_TABLE_COL: Record<+ ViewName,+ Readonly<Record<string, string>>+> = {+ // traces view -> traces table+ traces: {+ name: "traceName",+ tags: "traceTags",+ userId: "userId",+ sessionId: "sessionId",+ metadata: "metadata",+ release: "release",+ version: "version",+ environment: "environment",+ id: "id",+ },+ // observations view -> observations table+ observations: {+ traceName: "traceName",+ name: "name",+ userId: "userId",+ metadata: "metadata",+ type: "type",+ // Observations table keeps the `tags` id (it exposes trace tags as "Trace+ // Tags", id `tags`); traces table renames the same dimension to `traceTags`.+ tags: "tags",+ providedModelName: "model",+ level: "level",+ toolNames: "toolNames",+ calledToolNames: "calledToolNames",+ environment: "environment",+ version: "version",+ promptName: "promptName",+ promptVersion: "promptVersion",+ id: "id",+ traceId: "traceId",+ parentObservationId: "parentObservationId",+ },+ // scores-numeric view -> traces table. Only the dimensions that resolve from+ // the parent TRACE (traces.* in the scores view) map to a real traces column;+ // score-specific dimensions (name/source/value/dataType/...) have no trace+ // column and are dropped.+ "scores-numeric": {+ traceName: "traceName",+ tags: "traceTags",+ userId: "userId",+ sessionId: "sessionId",+ traceRelease: "release",+ traceVersion: "version",+ },+ // scores-categorical view -> traces table (same trace-derived dimensions).+ "scores-categorical": {+ traceName: "traceName",+ tags: "traceTags",+ userId: "userId",+ sessionId: "sessionId",+ traceRelease: "release",+ traceVersion: "version",+ },+};++/**+ * Specific, human reasons for notable dropped dimensions. Any dimension not+ * covered here falls back to `defaultReason`.+ */+const DROPPED_REASONS: Partial<+ Record<ViewName, Readonly<Record<string, string>>>+> = {+ traces: {+ timestampMonth:+ "Timestamp grouping has no filter column on the traces table.",+ },+ observations: {+ sessionId: "The observations table has no session filter column.",+ traceRelease:+ "Trace release is not a filterable column on the observations table.",+ traceVersion:+ "Trace version is not a filterable column on the observations table.",+ release:+ "Observation release is not a filterable column on the observations table.",+ startTimeMonth:+ "Timestamp grouping has no filter column on the observations table.",+ experimentName:+ "Experiment filters are not available on the observations table.",+ experimentId:+ "Experiment filters are not available on the observations table.",+ experimentDatasetId:+ "Experiment filters are not available on the observations table.",+ },+ "scores-numeric": {+ name: "Score name has no equivalent column on the traces table.",+ source: "Score source has no equivalent column on the traces table.",+ value: "Score value has no equivalent column on the traces table.",+ dataType: "Score data type has no equivalent column on the traces table.",+ metadata: "Score metadata does not map to trace metadata.",+ environment:+ "Score environment does not map to the trace environment column.",+ observationName:+ "Observation name has no equivalent column on the traces table.",+ },+ "scores-categorical": {+ name: "Score name has no equivalent column on the traces table.",+ source: "Score source has no equivalent column on the traces table.",+ stringValue: "Score value has no equivalent column on the traces table.",+ dataType: "Score data type has no equivalent column on the traces table.",+ metadata: "Score metadata does not map to trace metadata.",+ environment:+ "Score environment does not map to the trace environment column.",+ observationName:+ "Observation name has no equivalent column on the traces table.",+ },+};++function reasonFor(view: ViewName, column: string): string {+ return (+ DROPPED_REASONS[view]?.[column] ??+ `The "${column}" filter is not available on the ${tableTargetForView(+ view,+ )} table.`+ );+}++/**+ * Partition a view-space filter set into the filters the target data table can+ * express (rewritten to table column ids) and the dropped dimensions with a+ * reason each. Never throws: unknown columns degrade to not-applicable rather+ * than erroring, so navigation always proceeds.+ */+export function classifyViewFiltersForTable(+ view: ViewName,+ filters: FilterState,+): ClassifiedViewFilters {+ const columnMap = VIEW_DIMENSION_TO_TABLE_COL[view] ?? {};+ const applicable: FilterState = [];+ const notApplicable = new Map<string, string>();++ for (const filter of filters) {+ const tableColId = columnMap[filter.column];+ if (tableColId) {+ applicable.push({ ...filter, column: tableColId });+ } else if (!notApplicable.has(filter.column)) {+ notApplicable.set(filter.column, reasonFor(view, filter.column));+ }+ }++ return { applicable, notApplicable };+}diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex de57a1b20c..407435ff12 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -173,6 +173,7 @@ export const events = {"widget_copied_to_project","widget_json_downloaded","widget_copied_to_clipboard",+ "widget_view_as_table","widget_pasted","widget_paste_rejected","widget_duplicated",diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsxindex 9da5d46125..a9189e75d7 100644--- a/web/src/features/widgets/components/DashboardWidget.tsx+++ b/web/src/features/widgets/components/DashboardWidget.tsx@@ -27,8 +27,13 @@ import {CopyPlusIcon,FileJsonIcon,DownloadIcon,+ TableIcon,} from "lucide-react";import { useRouter } from "next/router";+import {+ buildTableFilterHref,+ buildViewAsTableHint,+} from "@/src/features/dashboard/lib/buildTableFilterHref";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { showErrorToast } from "@/src/features/notifications/showErrorToast";import { downloadChartDataCsv } from "@/src/features/widgets/chart-library/downloadChartDataCsv";@@ -459,6 +464,46 @@ export function DashboardWidget({[chartPresentation],);+ // "View as table" navigation: the widget's own filters (config + dashboard+ // global) translated to the traces/observations table's applicable filters,+ // plus the widget's time range. Filters the table can't express are dropped+ // (surfaced as a hint), never errored. The widget-filter merge mirrors the+ // query build above (widget.data.filters + dashboard filterState).+ const tableView = useMemo(() => {+ const view = widget.data?.view;+ if (!view) return undefined;+ const mergedFilters: FilterState = [+ ...(widget.data?.filters ?? []),+ ...filterState,+ ];+ return buildTableFilterHref(+ projectId,+ view as z.infer<typeof views>,+ mergedFilters,+ dateRange,+ );+ }, [projectId, widget.data, filterState, dateRange]);++ const handleViewAsTable = () => {+ if (!tableView) return;+ capture("dashboard:widget_view_as_table", {+ widget_id: placement.widgetId,+ dashboard_id: dashboardId,+ view: widget.data?.view,+ filters_not_applicable: tableView.notApplicable.size,+ filters_dropped_for_length: tableView.droppedForLength,+ });+ router.push(tableView.href);+ };++ // Hint combines both reasons a widget filter can be missing from the table:+ // dimensions the table can't express AND applicable filters dropped to keep+ // the ?filter= URL within budget. A length-drop must never be silent.+ const viewAsTableHint = useMemo(+ () => (tableView ? buildViewAsTableHint(tableView) : null),+ [tableView],+ );+const handleEdit = () => {router.push(`/project/${projectId}/widgets/${placement.widgetId}?dashboardId=${dashboardId}`,@@ -646,6 +691,27 @@ export function DashboardWidget({</button></DropdownMenuTrigger><DropdownMenuContent align="end">+ {tableView && (+ <>+ <DropdownMenuItem+ onClick={handleViewAsTable}+ title={viewAsTableHint?.title}+ >+ <TableIcon className="mr-2 h-4 w-4" />+ <span className="flex flex-col">+ <span>View as table</span>+ {viewAsTableHint && (+ <span className="text-muted-foreground text-xs">+ {viewAsTableHint.count} filter+ {viewAsTableHint.count === 1 ? "" : "s"} not shown in+ the table+ </span>+ )}+ </span>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ </>+ )}<DropdownMenuItem onClick={handleCopyToClipboard}><CopyIcon className="mr-2 h-4 w-4" />Copy to clipboard