Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(web): system table view preset category chips (#14774)

Trang Nguyena0def57ff75f
diff --git a/packages/shared/src/domain/table-view-presets.ts b/packages/shared/src/domain/table-view-presets.ts
index f6a0ae8828..6e2f3fbc81 100644
--- a/packages/shared/src/domain/table-view-presets.ts
+++ b/packages/shared/src/domain/table-view-presets.ts
@@ -14,6 +14,46 @@ export enum TableViewPresetTableName {
ExperimentItems = "experiment-items",
}
+/**
+ * Categories used to group system table view presets into the quick-access
+ * chip row rendered beneath the search bar (v4 events table). This enum is the
+ * single source of truth for grouping and display order; the frontend maps
+ * each category to an icon locally (lucide icons are not available in shared).
+ */
+export enum SystemTableViewPresetCategory {
+ SlowCalls = "slow-calls",
+ Errors = "errors",
+ CostRegression = "cost-regression",
+}
+
+export const SYSTEM_TABLE_VIEW_PRESET_CATEGORY_META: Record<
+ SystemTableViewPresetCategory,
+ { label: string; order: number }
+> = {
+ // The Errors category is surfaced to users as "Quality" β€” it groups error,
+ // output-review, and (coming-soon) eval-score / feedback presets.
+ [SystemTableViewPresetCategory.Errors]: {
+ label: "Quality",
+ order: 1,
+ },
+ [SystemTableViewPresetCategory.SlowCalls]: { label: "Slow", order: 2 },
+ [SystemTableViewPresetCategory.CostRegression]: {
+ label: "Cost",
+ order: 3,
+ },
+};
+
+/** Categories in their defined display order. */
+export const SYSTEM_TABLE_VIEW_PRESET_CATEGORIES_ORDERED = (
+ Object.keys(
+ SYSTEM_TABLE_VIEW_PRESET_CATEGORY_META,
+ ) as SystemTableViewPresetCategory[]
+).sort(
+ (a, b) =>
+ SYSTEM_TABLE_VIEW_PRESET_CATEGORY_META[a].order -
+ SYSTEM_TABLE_VIEW_PRESET_CATEGORY_META[b].order,
+);
+
export const TableViewPresetDomainSchema = z.object({
id: z.string(),
projectId: z.string().nullable(),
diff --git a/packages/shared/src/server/services/DefaultViewService/DefaultViewService.ts b/packages/shared/src/server/services/DefaultViewService/DefaultViewService.ts
index 863f6d2771..5901625b09 100644
--- a/packages/shared/src/server/services/DefaultViewService/DefaultViewService.ts
+++ b/packages/shared/src/server/services/DefaultViewService/DefaultViewService.ts
@@ -1,5 +1,9 @@
import { prisma } from "../../../db";
import { TableViewPresetTableName } from "../../../domain/table-view-presets";
+import {
+ getSystemTableViewPresetById,
+ isSystemTableViewPresetId,
+} from "../TableViewService/systemPresets";
import type {
DefaultViewAssignments,
DefaultViewScope,
@@ -103,11 +107,27 @@ export class DefaultViewService {
userId,
});
- if (assignments.userDefaultViewId) {
+ // A default may point at a system preset (view_id has no FK on purpose),
+ // and system presets are code-defined β€” a catalog iteration can retire an
+ // id. Treat a retired system-preset default as absent and FALL THROUGH to
+ // the next scope, instead of handing the client an id whose fetch errors
+ // on every visit. The row is deliberately left in place: ignoring it is
+ // reversible, deleting it is not.
+ const isResolvable = (viewId: string) =>
+ !isSystemTableViewPresetId(viewId) ||
+ getSystemTableViewPresetById(viewId) !== null;
+
+ if (
+ assignments.userDefaultViewId &&
+ isResolvable(assignments.userDefaultViewId)
+ ) {
return { viewId: assignments.userDefaultViewId, scope: "user" };
}
- if (assignments.projectDefaultViewId) {
+ if (
+ assignments.projectDefaultViewId &&
+ isResolvable(assignments.projectDefaultViewId)
+ ) {
return { viewId: assignments.projectDefaultViewId, scope: "project" };
}
diff --git a/packages/shared/src/server/services/TableViewService/TableViewService.ts b/packages/shared/src/server/services/TableViewService/TableViewService.ts
index 7d80356133..320ac6e6d3 100644
--- a/packages/shared/src/server/services/TableViewService/TableViewService.ts
+++ b/packages/shared/src/server/services/TableViewService/TableViewService.ts
@@ -222,6 +222,7 @@ export class TableViewService {
name: preset.name,
description: preset.description,
isSystem: true,
+ category: preset.category,
tableName: preset.tableName,
createdBy: null,
createdByUser: null,
@@ -258,7 +259,13 @@ export class TableViewService {
// Non-system presets should take precedence over system presets
(!preset.isSystem && existingPreset.isSystem)
) {
- presetsByName.set(preset.name, preset);
+ presetsByName.set(preset.name, {
+ ...preset,
+ // A user view displacing a same-named system preset inherits its
+ // category, so the category chip keeps the entry (now applying
+ // the user's customized version) instead of silently dropping it.
+ category: preset.category ?? existingPreset?.category,
+ });
}
}
diff --git a/packages/shared/src/server/services/TableViewService/systemPresets.ts b/packages/shared/src/server/services/TableViewService/systemPresets.ts
index 2cf1966c31..583c850b58 100644
--- a/packages/shared/src/server/services/TableViewService/systemPresets.ts
+++ b/packages/shared/src/server/services/TableViewService/systemPresets.ts
@@ -1,4 +1,5 @@
import {
+ SystemTableViewPresetCategory,
type TableViewPresetState,
TableViewPresetTableName,
} from "../../../domain/table-view-presets";
@@ -14,56 +15,79 @@ export interface SystemTableViewPreset {
name: string;
description?: string;
tableName: TableViewPresetTableName;
+ /**
+ * When set, the preset is surfaced as a quick-access chip beneath the search
+ * bar, grouped under this category. Uncategorized presets appear only in the
+ * views drawer.
+ */
+ category?: SystemTableViewPresetCategory;
state: TableViewPresetState;
}
-const buildFilterOnlySystemPreset = ({
+const buildSystemPreset = ({
id,
name,
description,
tableName,
+ category,
filters,
+ orderBy = null,
}: {
id: string;
name: string;
description?: string;
tableName: TableViewPresetTableName;
+ category?: SystemTableViewPresetCategory;
filters: TableViewPresetState["filters"];
+ orderBy?: TableViewPresetState["orderBy"];
}): SystemTableViewPreset => ({
id,
name,
description,
tableName,
+ category,
state: {
filters,
columnOrder: [],
columnVisibility: {},
- orderBy: null,
+ orderBy,
searchQuery: "",
},
});
const OBSERVATIONS_EVENTS_SYSTEM_TABLE_VIEW_PRESETS: SystemTableViewPreset[] = [
- buildFilterOnlySystemPreset({
- id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}trace_root_observations`,
- name: "Root Observations",
- description:
- "See top-level observations only, good for trace-level analysis",
+ buildSystemPreset({
+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}errors_only`,
+ name: "Errors Only",
+ description: "Focus on observations that failed",
tableName: TableViewPresetTableName.ObservationsEvents,
+ category: SystemTableViewPresetCategory.Errors,
filters: [
{
- column: "isRootObservation",
- type: "boolean",
- operator: "=",
- value: true,
+ column: "level",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["ERROR"],
},
],
}),
- buildFilterOnlySystemPreset({
- id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}generations_only`,
- name: "Generations Only",
- description: "Focus on LLM generation observations",
+
+ // --- Slow calls -----------------------------------------------------------
+ buildSystemPreset({
+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}latency_over_10s`,
+ name: "Latency over 10s",
+ description: "Observations taking longer than 10 seconds",
tableName: TableViewPresetTableName.ObservationsEvents,
+ category: SystemTableViewPresetCategory.SlowCalls,
+ filters: [{ column: "latency", type: "number", operator: ">", value: 10 }],
+ orderBy: { column: "latency", order: "DESC" },
+ }),
+ buildSystemPreset({
+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}slow_generations`,
+ name: "Slow generations",
+ description: "Generation calls slower than 5 seconds",
+ tableName: TableViewPresetTableName.ObservationsEvents,
+ category: SystemTableViewPresetCategory.SlowCalls,
filters: [
{
column: "type",
@@ -71,35 +95,94 @@ const OBSERVATIONS_EVENTS_SYSTEM_TABLE_VIEW_PRESETS: SystemTableViewPreset[] = [
operator: "any of",
value: ["GENERATION"],
},
+ { column: "latency", type: "number", operator: ">", value: 5 },
],
+ orderBy: { column: "latency", order: "DESC" },
}),
- buildFilterOnlySystemPreset({
- id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}errors_only`,
- name: "Errors Only",
- description: "Focus on observations that failed",
+
+ // --- Errors ---------------------------------------------------------------
+ buildSystemPreset({
+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}warnings_and_errors`,
+ name: "Warnings & errors",
+ description: "Observations logged at WARNING or ERROR level",
tableName: TableViewPresetTableName.ObservationsEvents,
+ category: SystemTableViewPresetCategory.Errors,
filters: [
{
column: "level",
type: "stringOptions",
operator: "any of",
- value: ["ERROR"],
+ value: ["ERROR", "WARNING"],
},
],
}),
- buildFilterOnlySystemPreset({
- id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}agent_workflow`,
- name: "Agent Workflow",
- description: "Follow agent steps, tool calls, and retrievals",
+ buildSystemPreset({
+ // Shipped-id stability: this is the pre-chips "Generations Only" preset
+ // (identical filters) renamed and categorized. Its id already lives in
+ // bookmarked `?viewId=` URLs and `default_views` rows (view_id has no FK
+ // on purpose), so the rename keeps the id β€” retiring it would strand
+ // those references. Never mint a new id for a preset whose meaning
+ // survives a catalog iteration β€” and conversely, the FILTER SEMANTICS
+ // under this id are frozen: tightening this preset (e.g. adding score or
+ // output filters) would silently morph every old bookmark/default, so a
+ // preset with a different meaning must get a new id.
+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}generations_only`,
+ name: "Review output (generations)",
+ description: "LLM generation outputs, for reviewing response quality",
tableName: TableViewPresetTableName.ObservationsEvents,
+ category: SystemTableViewPresetCategory.Errors,
filters: [
{
column: "type",
type: "stringOptions",
operator: "any of",
- value: ["AGENT", "CHAIN", "TOOL", "RETRIEVER"],
+ value: ["GENERATION"],
+ },
+ ],
+ }),
+ buildSystemPreset({
+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}missed_tool_calls`,
+ name: "Missed tool calls",
+ description: "LLM calls that had tools available but didn't call any",
+ tableName: TableViewPresetTableName.ObservationsEvents,
+ category: SystemTableViewPresetCategory.Errors,
+ filters: [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["GENERATION"],
+ },
+ { column: "toolDefinitions", type: "number", operator: ">", value: 0 },
+ { column: "toolCalls", type: "number", operator: "=", value: 0 },
+ ],
+ }),
+
+ // --- Cost regression ------------------------------------------------------
+ buildSystemPreset({
+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}high_cost`,
+ name: "High cost (> $1)",
+ description: "Observations costing more than $1",
+ tableName: TableViewPresetTableName.ObservationsEvents,
+ category: SystemTableViewPresetCategory.CostRegression,
+ filters: [{ column: "totalCost", type: "number", operator: ">", value: 1 }],
+ orderBy: { column: "totalCost", order: "DESC" },
+ }),
+ buildSystemPreset({
+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}high_token_usage`,
+ name: "High token usage",
+ description: "Observations using more than 50k tokens",
+ tableName: TableViewPresetTableName.ObservationsEvents,
+ category: SystemTableViewPresetCategory.CostRegression,
+ filters: [
+ {
+ column: "totalTokens",
+ type: "number",
+ operator: ">",
+ value: 50000,
},
],
+ orderBy: { column: "totalTokens", order: "DESC" },
}),
];
diff --git a/packages/shared/src/server/services/TableViewService/types.ts b/packages/shared/src/server/services/TableViewService/types.ts
index 76b2f56ef8..98e35b411e 100644
--- a/packages/shared/src/server/services/TableViewService/types.ts
+++ b/packages/shared/src/server/services/TableViewService/types.ts
@@ -1,5 +1,10 @@
import z from "zod";
-import { orderBy, singleFilter, TableViewPresetTableName } from "../../..";
+import {
+ orderBy,
+ singleFilter,
+ SystemTableViewPresetCategory,
+ TableViewPresetTableName,
+} from "../../..";
export const CreateTableViewPresetsInput = z.object({
projectId: z.string(),
@@ -40,6 +45,9 @@ export const TableViewPresetsNamesCreatorListSchema = z.array(
tableName: z.enum(TableViewPresetTableName),
description: z.string().optional(),
isSystem: z.boolean().optional(),
+ // Present on categorized system presets that surface as quick-access chips
+ // beneath the search bar; undefined for user views and uncategorized presets.
+ category: z.enum(SystemTableViewPresetCategory).optional(),
createdBy: z.string().nullable(),
createdByUser: z
.object({
diff --git a/web/src/__tests__/server/table-view-preset-retirement.servertest.ts b/web/src/__tests__/server/table-view-preset-retirement.servertest.ts
new file mode 100644
index 0000000000..2034e7c4dc
--- /dev/null
+++ b/web/src/__tests__/server/table-view-preset-retirement.servertest.ts
@@ -0,0 +1,115 @@
+/** @jest-environment node */
+
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ createOrgProjectAndApiKey,
+ DefaultViewService,
+ getSystemTableViewPresets,
+} from "@langfuse/shared/src/server";
+import { randomUUID } from "crypto";
+import { TableViewPresetTableName } from "@langfuse/shared";
+
+// System preset ids are part of the persisted contract: they live in
+// bookmarked `?viewId=` URLs and in `default_views` rows (view_id has no FK
+// on purpose). A catalog iteration may RENAME a preset β€” keeping its id so
+// existing references resolve to the new content β€” or RETIRE an id entirely,
+// in which case references must degrade gracefully (no default applied, no
+// error), never surface a recurring failure to the user.
+
+// Shipped in v3.206.0 and removed by the category-chips catalog iteration.
+const RETIRED_ID = "__langfuse_trace_root_observations";
+
+const createDefault = ({
+ projectId,
+ userId = null,
+ viewId,
+}: {
+ projectId: string;
+ userId?: string | null;
+ viewId: string;
+}) =>
+ prisma.defaultView.create({
+ data: {
+ projectId,
+ userId,
+ viewName: TableViewPresetTableName.ObservationsEvents,
+ viewId,
+ },
+ });
+
+describe("system preset retirement", () => {
+ it("keeps the shipped ids for presets whose meaning survived the iteration", () => {
+ const ids = getSystemTableViewPresets(
+ TableViewPresetTableName.ObservationsEvents,
+ ).map((preset) => preset.id);
+
+ // Shipped pre-chips (v3.206.0): "Errors Only" kept as-is;
+ // "Generations Only" renamed to "Review output (generations)" with
+ // identical filters β€” the id must stay so bookmarks/defaults keep working.
+ expect(ids).toContain("__langfuse_errors_only");
+ expect(ids).toContain("__langfuse_generations_only");
+ });
+
+ it("treats a project default pointing at a retired system preset as no default", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ await createDefault({ projectId, viewId: RETIRED_ID });
+
+ await expect(
+ DefaultViewService.getResolvedDefault({
+ projectId,
+ viewName: TableViewPresetTableName.ObservationsEvents,
+ }),
+ ).resolves.toBeNull();
+ });
+
+ it("falls through a retired user default to a live project default", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const user = await prisma.user.create({
+ data: { email: `retired-default-${randomUUID()}@example.com` },
+ });
+ await createDefault({ projectId, userId: user.id, viewId: RETIRED_ID });
+ await createDefault({ projectId, viewId: "__langfuse_errors_only" });
+
+ await expect(
+ DefaultViewService.getResolvedDefault({
+ projectId,
+ viewName: TableViewPresetTableName.ObservationsEvents,
+ userId: user.id,
+ }),
+ ).resolves.toMatchObject({
+ viewId: "__langfuse_errors_only",
+ scope: "project",
+ });
+ });
+
+ it("still resolves a default pointing at a live system preset", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ await createDefault({ projectId, viewId: "__langfuse_generations_only" });
+
+ await expect(
+ DefaultViewService.getResolvedDefault({
+ projectId,
+ viewName: TableViewPresetTableName.ObservationsEvents,
+ }),
+ ).resolves.toMatchObject({
+ viewId: "__langfuse_generations_only",
+ scope: "project",
+ });
+ });
+
+ it("leaves user views out of the retirement check", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ // A dangling reference to a DELETED user view is not the retirement
+ // path: getResolvedDefault must still return it (the client surfaces the
+ // failure), because silently skipping it would mask real data loss.
+ const danglingUserViewId = `deleted-user-view-${randomUUID()}`;
+ await createDefault({ projectId, viewId: danglingUserViewId });
+
+ await expect(
+ DefaultViewService.getResolvedDefault({
+ projectId,
+ viewName: TableViewPresetTableName.ObservationsEvents,
+ }),
+ ).resolves.toMatchObject({ viewId: danglingUserViewId });
+ });
+});
diff --git a/web/src/__tests__/server/unit/system-table-view-presets.servertest.ts b/web/src/__tests__/server/unit/system-table-view-presets.servertest.ts
new file mode 100644
index 0000000000..508428c449
--- /dev/null
+++ b/web/src/__tests__/server/unit/system-table-view-presets.servertest.ts
@@ -0,0 +1,70 @@
+/** @jest-environment node */
+
+import { getSystemTableViewPresets } from "@langfuse/shared/src/server";
+import {
+ eventsTableCols,
+ eventsTableFilterState,
+ orderBy as orderBySchema,
+ SystemTableViewPresetCategory,
+ TableViewPresetTableName,
+} from "@langfuse/shared";
+
+// Column ids that are valid targets for a filter or an orderBy on the events
+// table. Presets that reference an unknown column, or use a filter type/operator
+// that does not match the column contract, would be silently dropped at apply
+// time β€” so we assert the whole preset catalog is well-formed here.
+const eventsColumnIds = new Set(eventsTableCols.map((col) => col.id));
+
+describe("observations-events system table view presets", () => {
+ const presets = getSystemTableViewPresets(
+ TableViewPresetTableName.ObservationsEvents,
+ );
+
+ it("ships at least the categorized presets", () => {
+ expect(presets.length).toBeGreaterThan(0);
+ const categorized = presets.filter((preset) => preset.category);
+ expect(categorized.length).toBeGreaterThan(0);
+ });
+
+ it.each(presets.map((preset) => [preset.name, preset] as const))(
+ "preset %s has a valid filter state",
+ (_name, preset) => {
+ const parsed = eventsTableFilterState.safeParse(preset.state.filters);
+ expect(parsed.success).toBe(true);
+
+ for (const filter of preset.state.filters) {
+ expect(eventsColumnIds).toContain(filter.column);
+ }
+ },
+ );
+
+ it.each(presets.map((preset) => [preset.name, preset] as const))(
+ "preset %s has a valid orderBy referencing a known column",
+ (_name, preset) => {
+ const parsed = orderBySchema.safeParse(preset.state.orderBy);
+ expect(parsed.success).toBe(true);
+
+ if (preset.state.orderBy) {
+ expect(eventsColumnIds).toContain(preset.state.orderBy.column);
+ }
+ },
+ );
+
+ it("only uses known categories", () => {
+ const validCategories = new Set<string>(
+ Object.values(SystemTableViewPresetCategory),
+ );
+ for (const preset of presets) {
+ if (preset.category) {
+ expect(validCategories).toContain(preset.category);
+ }
+ }
+ });
+
+ it("uses unique preset ids and names", () => {
+ const ids = presets.map((preset) => preset.id);
+ const names = presets.map((preset) => preset.name);
+ expect(new Set(ids).size).toBe(ids.length);
+ expect(new Set(names).size).toBe(names.length);
+ });
+});
diff --git a/web/src/__tests__/table-view-presets.clienttest.ts b/web/src/__tests__/table-view-presets.clienttest.ts
index 08a4bcd803..45ebccf958 100644
--- a/web/src/__tests__/table-view-presets.clienttest.ts
+++ b/web/src/__tests__/table-view-presets.clienttest.ts
@@ -75,6 +75,35 @@ describe("table view presets validation functions", () => {
const orderBy: OrderByState = { column: "age", order: "ASC" };
expect(validateOrderBy(orderBy, mockColumns)).toBeNull();
});
+
+ it("should find a sortable column nested inside a column group", () => {
+ // e.g. the events table nests totalTokens under a "Usage" group def; a
+ // flat lookup dropped the saved orderBy of any view sorting by it.
+ const groupedColumns = [
+ { id: "name", enableSorting: true, accessorKey: "name" },
+ {
+ id: "usage",
+ accessorKey: "usage",
+ columns: [
+ {
+ id: "totalTokens",
+ enableSorting: true,
+ accessorKey: "totalTokens",
+ },
+ { id: "inputTokens", enableSorting: false, accessorKey: "input" },
+ ],
+ },
+ ];
+ const orderBy: OrderByState = { column: "totalTokens", order: "DESC" };
+ expect(validateOrderBy(orderBy, groupedColumns)).toEqual(orderBy);
+ // A nested column that opts out of sorting still returns null.
+ expect(
+ validateOrderBy(
+ { column: "inputTokens", order: "DESC" },
+ groupedColumns,
+ ),
+ ).toBeNull();
+ });
});
describe("validateFilters", () => {
diff --git a/web/src/components/table/data-table-toolbar.tsx b/web/src/components/table/data-table-toolbar.tsx
index 79e43d395e..c9f2e48e35 100644
--- a/web/src/components/table/data-table-toolbar.tsx
+++ b/web/src/components/table/data-table-toolbar.tsx
@@ -151,6 +151,10 @@ interface DataTableToolbarProps<TData, TValue> {
className?: string;
rowClassName?: string;
viewModeToggle?: React.ReactNode;
+ /** Rendered at the start of the toolbar's control row (left-aligned), before
+ * the filter toggle β€” e.g. the v4 events category-preset chips, so they
+ * share the row with the right-aligned Columns/Export controls. */
+ leadingControls?: React.ReactNode;
}
// Helper function to get the description for DocPopup
@@ -217,6 +221,7 @@ export function DataTableToolbar<TData, TValue>({
viewConfig,
filterWithAI = false,
viewModeToggle,
+ leadingControls,
}: DataTableToolbarProps<TData, TValue>) {
const [searchString, setSearchString] = useState(
searchConfig?.currentQuery ?? "",
@@ -266,6 +271,7 @@ export function DataTableToolbar<TData, TValue>({
rowClassName,
)}
>
+ {leadingControls}
{/* Desktop uses the sidebar's own header toggle + collapsed rail; this
toolbar toggle only remains for the mobile stacked layout. */}
{hasNewSidebar && (
diff --git a/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx b/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx
index 88c0c15bca..5154408bb7 100644
--- a/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx
+++ b/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx
@@ -222,35 +222,37 @@ export function TableViewPresetsDrawer({
const [isEditPopoverOpen, setIsEditPopoverOpen] = useState<boolean>(false);
const [dropdownId, setDropdownId] = useState<string | null>(null);
- const selectedViewName = useMemo(() => {
- // Check system filter presets first
- const systemPreset = systemFilterPresets?.find(
- (p) => p.id === selectedViewId,
- );
- if (systemPreset) {
- // Normalize both to handle missing vs undefined property mismatch
- const normalizedCurrent = normalizeForComparison(currentState.filters);
- const normalizedPreset = normalizeForComparison(systemPreset.filters);
- // If filters have been modified from the preset, show the generic trigger label instead
- if (!isEqual(normalizedCurrent, normalizedPreset)) {
- return undefined;
- }
- return systemPreset.name;
- }
- // Then check user presets
- return TableViewPresetsList?.find((v) => v.id === selectedViewId)?.name;
- }, [
- selectedViewId,
- systemFilterPresets,
- TableViewPresetsList,
- currentState.filters,
- ]);
-
const allViewNames = useMemo(
() => TableViewPresetsList?.map((view) => ({ value: view.name })) ?? [],
[TableViewPresetsList],
);
+ // Categorized system presets are surfaced by the category chip row beneath
+ // the search bar, so they are excluded from the drawer list to avoid showing
+ // the same preset in two places. Name lookups and uniqueness checks above
+ // still use the full list. Two exceptions stay in the drawer:
+ // - a categorized USER view (the name-dedup lets a same-named user view
+ // displace a system preset into the chips) β€” a personal view must never
+ // vanish from "My Views", it is its only management surface (rename,
+ // delete, defaults, permalink);
+ // - a categorized system preset that IS the current user/project default
+ // (assignable pre-chips; the row still exists in default_views) β€” this
+ // row is the only place carrying the default badge and the "Remove as
+ // my/project default" menu, so hiding it would leave the assignment
+ // auto-applying on every load with no UI to inspect or clear it. Once
+ // the default is removed, the row leaves the drawer again.
+ const drawerPresetList = useMemo(
+ () =>
+ TableViewPresetsList?.filter(
+ (view) =>
+ !view.category ||
+ !view.isSystem ||
+ view.id === defaultAssignments?.userDefaultViewId ||
+ view.id === defaultAssignments?.projectDefaultViewId,
+ ),
+ [TableViewPresetsList, defaultAssignments],
+ );
+
useUniqueNameValidation({
currentName: form.watch("name"),
allNames: allViewNames,
@@ -445,19 +447,13 @@ export function TableViewPresetsDrawer({
}}
>
<DrawerTrigger asChild>
- <Button
- variant="outline"
- id={triggerId}
- title={selectedViewName ? `View: ${selectedViewName}` : "Views"}
- >
- <span>
- {selectedViewName ? `View: ${selectedViewName}` : "Views"}
- </span>
+ <Button variant="outline" id={triggerId} title="My Views">
+ <span>My Views</span>
{selectedViewId ? (
<ChevronDown className="ml-1 h-4 w-4" />
) : (
<div className="bg-input ml-1 rounded-sm px-1 text-xs">
- {TableViewPresetsList?.length ?? 0}
+ {drawerPresetList?.length ?? 0}
</div>
)}
</Button>
@@ -545,13 +541,12 @@ export function TableViewPresetsDrawer({
))}
{/* Separator between system and user presets */}
- {systemFilterPresets?.length &&
- TableViewPresetsList?.length ? (
+ {systemFilterPresets?.length && drawerPresetList?.length ? (
<Separator className="my-2" />
) : null}
{/* User Presets */}
- {TableViewPresetsList?.map((view) => {
+ {drawerPresetList?.map((view) => {
const isUserDefault =
defaultAssignments?.userDefaultViewId === view.id;
const isProjectDefault =
diff --git a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
index 7ec940dd99..ec7347b600 100644
--- a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
+++ b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
@@ -335,13 +335,24 @@ export function useTableViewManager({
// has run (the migration is one-shot and this is a separate persistence path).
// Run the table's opt-in columnOrder migration on the payload first so the
// same "only reposition a stale default" rule applies here too.
- if (viewData.columnOrder) {
+ //
+ // EMPTY payloads carry no column opinion and must not touch the user's
+ // layout: system presets (and the chips' cleared state) ship
+ // `columnOrder: []` / `columnVisibility: {}`, and writing those through
+ // would reconcile the table back to default columns and PERSIST that to
+ // localStorage β€” silently wiping per-user reordering/visibility on every
+ // preset apply. User-saved views always persist a full non-empty
+ // snapshot, so gating on non-empty only skips the no-opinion payloads.
+ if (viewData.columnOrder && viewData.columnOrder.length > 0) {
const migratedColumnOrder = validationContext.migrateColumnOrder
? validationContext.migrateColumnOrder(viewData.columnOrder)
: viewData.columnOrder;
setColumnOrder(migratedColumnOrder);
}
- if (viewData.columnVisibility)
+ if (
+ viewData.columnVisibility &&
+ Object.keys(viewData.columnVisibility).length > 0
+ )
setColumnVisibility(viewData.columnVisibility);
// Unlock as soon as the view is applied. Earlier versions kept the table
@@ -382,6 +393,12 @@ export function useTableViewManager({
// mutation on a link open) β€” so there is nothing to fetch.
!hasExplicitTableStateInUrl(router.query) &&
(!isSystemPresetId(selectedViewId) || allowBackendSystemPresets),
+ // A 404 is an expected outcome, not an incident: system presets are
+ // code-defined and a catalog iteration can retire an id that still
+ // lives in bookmarks/session storage. Silence the GLOBAL query-cache
+ // error toast for it β€” the error effect below owns the messaging
+ // (friendly retirement notice vs. real error).
+ meta: { silentHttpCodes: [404] },
},
);
@@ -446,13 +463,45 @@ export function useTableViewManager({
setIsInitialized(true);
setIsLoading(false);
handleSetViewId(null, { updateType: "replaceIn" });
- showErrorToast("Error applying view", selectedViewError.message, "WARNING");
+ // A 404 on a system-preset id means the catalog retired it (system
+ // presets are code-defined); stale references live on in bookmarks and
+ // session storage. Stale DEFAULTS never reach here (getDefault
+ // self-heals them server-side), so this is an explicit-ish reference β€”
+ // tell the user once why they landed on the default table (a dead
+ // bookmark is fixable), in a friendlier voice than the real error kept
+ // for dangling user views and for transient failures (which must stay
+ // loud β€” a network blip is not a retirement).
+ if (
+ isSystemPresetId(requestedViewId) &&
+ selectedViewError.data?.httpStatus === 404
+ ) {
+ // How many users still follow "the older way" (a retired preset
+ // reference) and get redirected β€” sizes the cost of each catalog
+ // iteration.
+ capture("saved_views:retired_view_redirect", {
+ tableName,
+ viewId: requestedViewId,
+ });
+ showErrorToast(
+ "View no longer available",
+ "This suggested view was retired β€” showing the default view instead.",
+ "WARNING",
+ );
+ } else {
+ showErrorToast(
+ "Error applying view",
+ selectedViewError.message,
+ "WARNING",
+ );
+ }
}, [
disabled,
isSelectedViewError,
selectedViewError,
selectedViewId,
handleSetViewId,
+ capture,
+ tableName,
]);
if (disabled) {
diff --git a/web/src/components/table/table-view-presets/validation.ts b/web/src/components/table/table-view-presets/validation.ts
index 77e1981b9d..a0edb4482f 100644
--- a/web/src/components/table/table-view-presets/validation.ts
+++ b/web/src/components/table/table-view-presets/validation.ts
@@ -18,8 +18,19 @@ export function validateOrderBy(
): OrderByState | null {
if (!orderBy || !columns || columns.length === 0) return null;
+ // Flatten group columns: a sortable column can live inside a group def
+ // (e.g. the events table's totalTokens under "Usage"), and a flat lookup
+ // would silently drop a saved orderBy that references it.
+ const flatColumns = columns.flatMap(function flatten(
+ col: LangfuseColumnDef<any, any>,
+ ): LangfuseColumnDef<any, any>[] {
+ return [col, ...(col.columns?.flatMap(flatten) ?? [])];
+ });
+
const isSortableColumn = (columnId: string) =>
- columns.some((col) => col.id === columnId && col.enableSorting !== false);
+ flatColumns.some(
+ (col) => col.id === columnId && col.enableSorting !== false,
+ );
// If the column already exists in the active table, keep it.
if (isSortableColumn(orderBy.column)) {
diff --git a/web/src/features/events/components/CategoryPresetChips.tsx b/web/src/features/events/components/CategoryPresetChips.tsx
new file mode 100644
index 0000000000..5f6f4237d9
--- /dev/null
+++ b/web/src/features/events/components/CategoryPresetChips.tsx
@@ -0,0 +1,341 @@
+import { useMemo, useRef } from "react";
+import { DollarSign, ThumbsDown, Timer, type LucideIcon } from "lucide-react";
+import {
+ SYSTEM_TABLE_VIEW_PRESET_CATEGORIES_ORDERED,
+ SYSTEM_TABLE_VIEW_PRESET_CATEGORY_META,
+ SystemTableViewPresetCategory,
+ TableViewPresetTableName,
+ type TableViewPresetState,
+} from "@langfuse/shared";
+import { Button } from "@/src/components/ui/button";
+import {
+ Popover,
+ PopoverClose,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import { cn } from "@/src/utils/tailwind";
+import { useViewData } from "@/src/components/table/table-view-presets/hooks/useViewData";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+
+const CATEGORY_ICONS: Record<SystemTableViewPresetCategory, LucideIcon> = {
+ [SystemTableViewPresetCategory.SlowCalls]: Timer,
+ [SystemTableViewPresetCategory.Errors]: ThumbsDown,
+ [SystemTableViewPresetCategory.CostRegression]: DollarSign,
+};
+
+type PresetItem = {
+ id: string;
+ name: string;
+ description?: string;
+ // The filters/orderBy this preset applies. Absent for the disabled
+ // coming-soon placeholder.
+ state?: TableViewPresetState;
+ // A non-interactive "coming soon" placeholder (e.g. Low quality), rendered
+ // greyed with a "Soon" badge and no apply behavior.
+ disabled?: boolean;
+};
+
+// Applied on toggle-off: clears the preset's filters and sort back to the
+// table's unfiltered default (mirrors an empty system preset).
+const CLEARED_VIEW_STATE: TableViewPresetState = {
+ filters: [],
+ orderBy: null,
+ columnOrder: [],
+ columnVisibility: {},
+ searchQuery: "",
+};
+
+// Coming-soon placeholder shown under "Quality & Errors". Real, project-scoped
+// quality presets (eval scores + feedback) are a follow-up; this signals intent
+// without doing anything.
+const LOW_QUALITY_COMING_SOON: PresetItem = {
+ id: "__coming_soon_low_quality",
+ name: "Low quality",
+ description:
+ "Surface low eval scores & negative feedback β€” e.g. faithfulness < 0.7, CSAT ≀ 3",
+ disabled: true,
+};
+
+type CategoryPresetChipsProps = {
+ projectId: string;
+ /** The currently applied view id, used to render the active chip/row state. */
+ activeViewId: string | null;
+ /** Sets `?viewId` (deep-link/provenance); pass null to deselect. */
+ onApplyView: (viewId: string | null) => void;
+ /** Applies the preset's filters/orderBy to the live table. */
+ applyViewState: (viewData: TableViewPresetState) => void;
+ /**
+ * Non-destructive preview of a preset's filters in the search bar while
+ * hovering/focusing its row; pass null to restore. No-op when the search bar
+ * isn't active.
+ */
+ onPreviewView?: (viewData: TableViewPresetState | null) => void;
+};
+
+/**
+ * Quick-access preset chips grouped by category, rendered beneath the search
+ * bar on the v4 observations/events table. Each chip opens a popover listing
+ * the category's system presets; selecting one applies it through the shared
+ * table-view manager (which sets `?viewId` for deep-linkable state).
+ */
+export function CategoryPresetChips({
+ projectId,
+ activeViewId,
+ onApplyView,
+ applyViewState,
+ onPreviewView,
+}: CategoryPresetChipsProps) {
+ const capture = usePostHogClientCapture();
+ const { TableViewPresetsList } = useViewData({
+ tableName: TableViewPresetTableName.ObservationsEvents,
+ projectId,
+ });
+ // Pointer opens suppress Radix's focus-first-row so clicking a chip doesn't
+ // instantly fire the first row's focus-preview; keyboard opens keep it, or
+ // Tab would exit the (portaled) popover and rows would be unreachable.
+ // Two refs because the pointerdown flag must survive until onOpenChange(true)
+ // consumes it: switching chip→chip, the OLD popover's close (an outside-
+ // pointerdown dismiss) happens between the new trigger's pointerdown and its
+ // open, so clearing on close would drop the flag. Shared across the chips β€”
+ // only one popover interaction happens at a time.
+ const pointerDownRef = useRef(false);
+ const openedByPointerRef = useRef(false);
+
+ // Explore β†’ activate funnel: one close event carries how long the popover
+ // was open and how the interaction ended, so dwell time and conversion read
+ // without stitching opens to applies. Shared across the chips β€” only one
+ // popover interaction happens at a time; chip→chip switching closes the old
+ // popover (capturing ITS outcome via its own closure) before the new opens.
+ const openedAtRef = useRef<number | null>(null);
+ const outcomeRef = useRef<
+ "no_interaction" | "previewed_only" | "applied" | "cleared"
+ >("no_interaction");
+ const markExplored = () => {
+ if (outcomeRef.current === "no_interaction")
+ outcomeRef.current = "previewed_only";
+ };
+
+ const presetsByCategory = useMemo(() => {
+ // While the preset list is loading, render no chips at all (null below)
+ // rather than a lone Quality chip holding just the coming-soon placeholder
+ // β€” the other chips popping in on response would shift the toolbar row.
+ if (!TableViewPresetsList) return null;
+ const grouped = new Map<SystemTableViewPresetCategory, PresetItem[]>();
+ for (const view of TableViewPresetsList) {
+ if (!view.category) continue;
+ const list = grouped.get(view.category) ?? [];
+ list.push({
+ id: view.id,
+ name: view.name,
+ description: view.description,
+ state: {
+ filters: view.filters,
+ orderBy: view.orderBy,
+ columnOrder: view.columnOrder,
+ columnVisibility: view.columnVisibility,
+ searchQuery: view.searchQuery,
+ },
+ });
+ grouped.set(view.category, list);
+ }
+ // Quality lives under the Errors ("Quality & Errors") chip as a
+ // coming-soon placeholder for now β€” but only alongside real presets, so a
+ // catalog without categorized presets renders no chips (guard below).
+ const errorsList = grouped.get(SystemTableViewPresetCategory.Errors);
+ if (errorsList) {
+ grouped.set(SystemTableViewPresetCategory.Errors, [
+ ...errorsList,
+ LOW_QUALITY_COMING_SOON,
+ ]);
+ }
+ return grouped;
+ }, [TableViewPresetsList]);
+
+ const categories = presetsByCategory
+ ? SYSTEM_TABLE_VIEW_PRESET_CATEGORIES_ORDERED.filter(
+ (category) => (presetsByCategory.get(category)?.length ?? 0) > 0,
+ )
+ : [];
+
+ if (!presetsByCategory || categories.length === 0) return null;
+
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ {categories.map((category) => {
+ const presets = presetsByCategory.get(category) ?? [];
+ const Icon = CATEGORY_ICONS[category];
+ const { label } = SYSTEM_TABLE_VIEW_PRESET_CATEGORY_META[category];
+ const isCategoryActive = presets.some(
+ (preset) => preset.id === activeViewId,
+ );
+
+ return (
+ <Popover
+ key={category}
+ onOpenChange={(open) => {
+ if (open) {
+ openedByPointerRef.current = pointerDownRef.current;
+ pointerDownRef.current = false;
+ openedAtRef.current = Date.now();
+ outcomeRef.current = "no_interaction";
+ capture("saved_views:category_chip_open", {
+ category,
+ tableName: TableViewPresetTableName.ObservationsEvents,
+ });
+ } else {
+ // The popover can close without a row leave/blur firing
+ // (select a preset, click outside, Escape) β€” always end the
+ // preview so it can't outlive the popover.
+ onPreviewView?.(null);
+ if (openedAtRef.current !== null) {
+ capture("saved_views:category_chip_close", {
+ category,
+ outcome: outcomeRef.current,
+ durationMs: Date.now() - openedAtRef.current,
+ tableName: TableViewPresetTableName.ObservationsEvents,
+ });
+ openedAtRef.current = null;
+ }
+ }
+ }}
+ >
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ onPointerDown={() => {
+ pointerDownRef.current = true;
+ }}
+ onKeyDown={(event) => {
+ // Keyboard activation explicitly marks a non-pointer open,
+ // clearing a stale flag from a pointer toggle-close.
+ if (event.key === "Enter" || event.key === " ")
+ pointerDownRef.current = false;
+ }}
+ className={cn("gap-1.5", isCategoryActive && "bg-primary/5")}
+ >
+ <Icon className="h-4 w-4" aria-hidden />
+ {label}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ className="w-72 p-1"
+ onOpenAutoFocus={(event) => {
+ // See openedByPointerRef: a pointer open keeps focus on the
+ // trigger (no instant first-row focus-preview); a keyboard
+ // open lets Radix focus the first row so the presets stay
+ // keyboard-reachable β€” previewing the row focus lands on is
+ // then the expected behavior.
+ if (openedByPointerRef.current) event.preventDefault();
+ }}
+ >
+ <div className="text-muted-foreground px-2 py-1.5 text-xs font-medium">
+ {label}
+ </div>
+ <div className="max-h-72 overflow-y-auto">
+ {presets.map((preset) => {
+ const isPresetActive =
+ !preset.disabled && preset.id === activeViewId;
+ const row = (
+ <button
+ type="button"
+ // aria-disabled (not disabled) so the coming-soon row
+ // still receives clicks β€” captured below as a demand
+ // signal for the follow-up quality presets.
+ aria-disabled={preset.disabled || undefined}
+ onMouseEnter={() => {
+ if (!preset.state) return;
+ markExplored();
+ onPreviewView?.(preset.state);
+ capture("saved_views:category_preset_preview", {
+ category,
+ presetId: preset.id,
+ presetName: preset.name,
+ tableName:
+ TableViewPresetTableName.ObservationsEvents,
+ });
+ }}
+ onMouseLeave={() =>
+ !preset.disabled && onPreviewView?.(null)
+ }
+ onFocus={() => {
+ if (!preset.state) return;
+ markExplored();
+ onPreviewView?.(preset.state);
+ }}
+ onBlur={() => !preset.disabled && onPreviewView?.(null)}
+ onClick={() => {
+ if (!preset.state) {
+ markExplored();
+ capture(
+ "saved_views:category_preset_coming_soon_click",
+ {
+ category,
+ presetId: preset.id,
+ presetName: preset.name,
+ tableName:
+ TableViewPresetTableName.ObservationsEvents,
+ },
+ );
+ return;
+ }
+ // Set ?viewId for deep-link/provenance, then apply the
+ // preset's filters/orderBy (or clear on toggle-off).
+ const next = isPresetActive ? null : preset.id;
+ outcomeRef.current = next ? "applied" : "cleared";
+ onApplyView(next);
+ applyViewState(
+ next ? preset.state : CLEARED_VIEW_STATE,
+ );
+ capture("saved_views:category_chip_apply", {
+ category,
+ presetId: preset.id,
+ presetName: preset.name,
+ action: next ? "apply" : "clear",
+ tableName:
+ TableViewPresetTableName.ObservationsEvents,
+ });
+ }}
+ className={cn(
+ "flex w-full items-start justify-between gap-2 rounded-sm px-2 py-1.5 text-left text-sm",
+ preset.disabled
+ ? "cursor-default opacity-60"
+ : "hover:bg-accent",
+ )}
+ >
+ <span className="flex flex-col">
+ <span className="flex items-center gap-1.5 font-medium">
+ {preset.name}
+ {preset.disabled && (
+ <span className="text-muted-foreground rounded-sm border px-1 text-[10px] font-normal uppercase">
+ Soon
+ </span>
+ )}
+ </span>
+ {preset.description && (
+ <span className="text-muted-foreground text-xs">
+ {preset.description}
+ </span>
+ )}
+ </span>
+ </button>
+ );
+ // The disabled placeholder never applies, so it isn't wrapped
+ // in PopoverClose (clicking it should not close the popover).
+ return preset.disabled ? (
+ <div key={preset.id}>{row}</div>
+ ) : (
+ <PopoverClose asChild key={preset.id}>
+ {row}
+ </PopoverClose>
+ );
+ })}
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index 5eda820220..cbd474ea89 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -31,10 +31,12 @@ import {
BatchExportTableName,
type ObservationType,
TableViewPresetTableName,
+ type TableViewPresetState,
BatchActionType,
ActionId,
RESOURCE_LIMIT_ERROR_MESSAGE,
} from "@langfuse/shared";
+import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";
import { cn } from "@/src/utils/tailwind";
import { LevelColors } from "@/src/components/level-colors";
import { numberFormatter, usdFormatter } from "@/src/utils/numbers";
@@ -107,6 +109,8 @@ import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSea
import { EventsSearchBarRow } from "@/src/features/search-bar/components/EventsSearchBarRow";
import { buildAiContext } from "@/src/features/search-bar/lib/ai-context";
import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";
+import { CategoryPresetChips } from "@/src/features/events/components/CategoryPresetChips";
+import { TableViewPresetsDrawer } from "@/src/components/table/table-view-presets/components/data-table-view-presets-drawer";
import { withMetadataPathOptions } from "@/src/features/search-bar/lib/metadata-paths";
import {
useObservedMetadataPaths,
@@ -540,6 +544,24 @@ export default function ObservationsEventsTable({
setSearchType,
});
+ // Non-destructive preview: while a category-chip preset row is hovered or
+ // focused, show the query it would apply as the store's preview overlay. The
+ // draft is never touched, so ending the preview cannot lose in-progress
+ // typing. Clicking still applies for real via applyViewState. No-op outside
+ // search-bar mode.
+ const previewViewInSearchBar = useCallback(
+ (state: TableViewPresetState | null) => {
+ if (!searchBarMode) return;
+ const { actions } = searchBarStore.getState();
+ if (state) {
+ actions.setPreview(filterStateToQueryText(state.filters).text);
+ } else {
+ actions.clearPreview();
+ }
+ },
+ [searchBarMode, searchBarStore],
+ );
+
// Disabled for now because perhaps confusing
// const viewModeFilter: FilterState =
// viewMode === "trace"
@@ -1639,11 +1661,6 @@ export default function ObservationsEventsTable({
currentSearchQuery={
searchBarMode ? (searchQuery ?? "") : undefined
}
- viewConfig={{
- tableName: TableViewPresetTableName.ObservationsEvents,
- projectId,
- controllers: viewControllers,
- }}
columnsWithCustomSelect={[
"providedModelName",
"name",
@@ -1719,6 +1736,37 @@ export default function ObservationsEventsTable({
// In bar mode AI filtering lives in the search bar ("Ask AI"),
// so the legacy wand is only offered when the bar is absent.
filterWithAI={!searchBarMode}
+ // Category-preset chips + "My Views" pill share the toolbar row,
+ // left-aligned, so they sit on the same line as the right-aligned
+ // Columns/Export controls.
+ leadingControls={
+ <div className="flex flex-wrap items-center gap-2">
+ <CategoryPresetChips
+ projectId={projectId}
+ activeViewId={
+ viewControllers.appliedViewId ??
+ viewControllers.selectedViewId
+ }
+ onApplyView={viewControllers.handleSetViewId}
+ applyViewState={viewControllers.applyViewState}
+ onPreviewView={previewViewInSearchBar}
+ />
+ <TableViewPresetsDrawer
+ viewConfig={{
+ tableName: TableViewPresetTableName.ObservationsEvents,
+ projectId,
+ controllers: viewControllers,
+ }}
+ currentState={{
+ orderBy: orderByState ?? null,
+ filters: queryFilter.explicitFilterState ?? [],
+ columnOrder,
+ columnVisibility,
+ searchQuery: searchQuery ?? "",
+ }}
+ />
+ </div>
+ }
/>
</div>
)}
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 00e8511b67..8a0972bf5b 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -52,6 +52,17 @@ export const events = {
"update_name",
"search_views",
"system_preset_selected",
+ "category_chip_open",
+ "category_chip_apply",
+ "category_preset_preview",
+ "category_preset_coming_soon_click",
+ // Fired when a chip popover closes; carries durationMs + outcome
+ // ("applied" | "cleared" | "previewed_only" | "no_interaction") so the
+ // explore β†’ activate funnel and dwell time read from one event.
+ "category_chip_close",
+ // A bookmarked/stored system-preset id that the catalog retired β€” the
+ // user was shown the one-time notice and landed on the default view.
+ "retired_view_redirect",
],
score: [
"create",
diff --git a/web/src/features/search-bar/README.md b/web/src/features/search-bar/README.md
index b54e429498..bd2772b8ab 100644
--- a/web/src/features/search-bar/README.md
+++ b/web/src/features/search-bar/README.md
@@ -127,6 +127,14 @@ committedText ──resetTo──▢ store.draft ──(type/pick/remove)──
changes) and it never writes back, so the cycle cannot loop. No
reconciliation signature, no two-way sync β€” a commit's own echo settles
because `resetTo` no-ops when the draft already matches.
+- **Previews are an overlay, not a draft write.** `previewText` (store) is
+ display-only state for "show the query this preset would apply" affordances
+ (the events-table category-preset chips). `ComposerWithPreview` stacks a
+ read-only preview surface over the (mounted, hidden) editor while it is
+ active β€” SearchComposer itself knows nothing about previews and its DOM is
+ never reprojected by one. The preview never merges into the draft, never
+ commits, and any real draft write clears it β€” so ending a preview can never
+ lose in-progress typing, by construction rather than by restore logic.
- This mirrors the prototype's ADR-006 ("URL is canonical; everything derives
from it") and "no write loops".
diff --git a/web/src/features/search-bar/components/ComposerWithPreview.tsx b/web/src/features/search-bar/components/ComposerWithPreview.tsx
new file mode 100644
index 0000000000..0e8af1bf65
--- /dev/null
+++ b/web/src/features/search-bar/components/ComposerWithPreview.tsx
@@ -0,0 +1,76 @@
+// Composition wrapper: the real SearchComposer plus a read-only preview
+// surface, stacked in the same grid cell. While `previewText` (store) is
+// active β€” a category-preset row being hovered/focused β€” the preview fades in
+// ON TOP and the editor is hidden underneath.
+//
+// Why composition instead of teaching SearchComposer about previews: the
+// composer is the most invariant-dense component in the feature (contenteditable
+// projection, undo history, selection mirroring), and a preview never needs any
+// of that. Stacking keeps the editor MOUNTED β€” unmounting would wipe its
+// undo/selection/autocomplete refs β€” and never reprojects its DOM, so a preview
+// cannot interact with editing state by construction. The grid cell sizes to
+// max(editor, preview), so a wrapping preview grows the band instead of
+// clipping. Both surfaces share their chrome via composer-chrome.ts so the
+// overlay renders pixel-identical.
+
+import * as React from "react";
+
+import { cn } from "@/src/utils/tailwind";
+
+import { scoreTypeContextFromObserved } from "@/src/features/search-bar/lib/observed-options";
+import { SearchComposer } from "@/src/features/search-bar/components/SearchComposer";
+import { ComposerTokens } from "@/src/features/search-bar/components/ComposerTokens";
+import { useSearchBarStore } from "@/src/features/search-bar/store/SearchBarStoreProvider";
+import {
+ COMPOSER_SURFACE_CLASSES,
+ COMPOSER_TEXT_CLASSES,
+} from "@/src/features/search-bar/components/composer-chrome";
+
+export function ComposerWithPreview(
+ props: React.ComponentProps<typeof SearchComposer>,
+) {
+ const previewText = useSearchBarStore((s) => s.previewText);
+ const previewActive = previewText !== null;
+
+ // Same score-type routing the composer uses, so preview pills type-classify
+ // (numeric vs categorical scores) identically to the real query.
+ const scoreTypes = React.useMemo(
+ () => scoreTypeContextFromObserved(props.observed),
+ [props.observed],
+ );
+
+ return (
+ <div className="grid">
+ <div
+ className={cn(
+ "col-start-1 row-start-1 min-w-0",
+ // visibility (not display) keeps the editor's height contributing
+ // to the cell, so the band never collapses under a shorter preview.
+ previewActive && "invisible",
+ )}
+ >
+ <SearchComposer {...props} />
+ </div>
+ {previewActive && (
+ <div
+ data-testid="search-bar-preview"
+ data-composer-preview-text={previewText}
+ className={cn(
+ "col-start-1 row-start-1 min-w-0",
+ "animate-in fade-in-0 duration-150",
+ )}
+ >
+ <div className={COMPOSER_SURFACE_CLASSES}>
+ <div className={COMPOSER_TEXT_CLASSES}>
+ <ComposerTokens
+ draft={previewText}
+ showDiagnostics={false}
+ scoreTypes={scoreTypes}
+ />
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/features/search-bar/components/EventsSearchBarRow.tsx b/web/src/features/search-bar/components/EventsSearchBarRow.tsx
index 40b5b9adfe..bb13aedc25 100644
--- a/web/src/features/search-bar/components/EventsSearchBarRow.tsx
+++ b/web/src/features/search-bar/components/EventsSearchBarRow.tsx
@@ -20,7 +20,7 @@ import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
import { useQueryProject } from "@/src/features/projects/hooks";
import type { ObservedOptions } from "@/src/features/search-bar/lib/observed-options";
import { AI_GROUNDING_COLUMNS } from "@/src/features/search-bar/lib/ai-context";
-import { SearchComposer } from "@/src/features/search-bar/components/SearchComposer";
+import { ComposerWithPreview } from "@/src/features/search-bar/components/ComposerWithPreview";
import { SearchBarAiPrompt } from "@/src/features/search-bar/components/SearchBarAiPrompt";
import { SearchBarStoreProvider } from "@/src/features/search-bar/store/SearchBarStoreProvider";
import type { SearchBarStore } from "@/src/features/search-bar/store/searchBarStore";
@@ -86,7 +86,7 @@ export function EventsSearchBarRow({
/>
) : (
<SearchBarStoreProvider store={store} commit={commit}>
- <SearchComposer
+ <ComposerWithPreview
projectId={projectId}
observed={observed}
erroredColumns={erroredColumns}
diff --git a/web/src/features/search-bar/components/SearchComposer.tsx b/web/src/features/search-bar/components/SearchComposer.tsx
index 864f3b070a..ee274fa40c 100644
--- a/web/src/features/search-bar/components/SearchComposer.tsx
+++ b/web/src/features/search-bar/components/SearchComposer.tsx
@@ -52,6 +52,10 @@ import {
COMPOSER_PLACEHOLDER,
optionDomId,
} from "@/src/features/search-bar/components/presentation";
+import {
+ COMPOSER_SURFACE_CLASSES,
+ COMPOSER_TEXT_CLASSES,
+} from "@/src/features/search-bar/components/composer-chrome";
const LISTBOX_ID = "search-bar-listbox";
// Word joiners (shared with ComposerTokens) give the DOM caret boundaries
@@ -1267,7 +1271,9 @@ export function SearchComposer({
// centers a single line near min-h-9 and the box grows when wrapped.
// Right gutter keeps the last token clear of the top-right control:
// the "Ask AI" button (pr-20), or the error icon (pr-8).
- "border-input bg-background relative min-h-9 rounded-md border px-2 py-1.5",
+ // Box + text metrics are shared with the preview surface
+ // (composer-chrome.ts) so the overlay renders pixel-identical.
+ COMPOSER_SURFACE_CLASSES,
onActivateAi !== undefined && !showGlobalDiagnostics
? "pr-20"
: "pr-8",
@@ -1316,7 +1322,10 @@ export function SearchComposer({
// below the ~24px pills ("too big"). 24px matches the pill height so
// the caret aligns with the pills. Trade-off: tighter gap between
// wrapped lines of pills (single-line is unaffected).
- className="min-h-6 font-mono text-xs leading-6 break-words whitespace-pre-wrap caret-[hsl(var(--foreground))] outline-none"
+ className={cn(
+ COMPOSER_TEXT_CLASSES,
+ "caret-[hsl(var(--foreground))] outline-none",
+ )}
onInput={(event) => {
if (!(event.nativeEvent as InputEvent).isComposing) syncFromDom();
}}
diff --git a/web/src/features/search-bar/components/composer-chrome.ts b/web/src/features/search-bar/components/composer-chrome.ts
new file mode 100644
index 0000000000..d5f195edaf
--- /dev/null
+++ b/web/src/features/search-bar/components/composer-chrome.ts
@@ -0,0 +1,12 @@
+// Shared chrome between the real composer (SearchComposer) and the read-only
+// preview surface (ComposerWithPreview). Both must render pixel-identical β€”
+// the preview overlays the editor in the same grid cell β€” so the box and the
+// text metrics live here instead of being duplicated and drifting apart.
+
+/** The bar's box: border, background, radius, padding, min height. */
+export const COMPOSER_SURFACE_CLASSES =
+ "border-input bg-background relative min-h-9 rounded-md border px-2 py-1.5";
+
+/** The query text metrics: mono font, pill-matched line height, wrapping. */
+export const COMPOSER_TEXT_CLASSES =
+ "min-h-6 font-mono text-xs leading-6 break-words whitespace-pre-wrap";
diff --git a/web/src/features/search-bar/store/searchBarStore.clienttest.ts b/web/src/features/search-bar/store/searchBarStore.clienttest.ts
index 0742901c28..f4d76c564a 100644
--- a/web/src/features/search-bar/store/searchBarStore.clienttest.ts
+++ b/web/src/features/search-bar/store/searchBarStore.clienttest.ts
@@ -162,6 +162,51 @@ describe("searchBarStore (draft-only)", () => {
expect(store.getState().draft).toBe("level:ERROR refund");
});
+ it("preview overlays without touching the draft and clears on end", () => {
+ // The preview lane is display-only state: while a preset row is hovered
+ // the bar shows previewText, but the draft β€” including in-progress typing
+ // that was never committed β€” must survive untouched.
+ const store = createSearchBarStore();
+ store.getState().actions.setDraft("level:ERROR name:foo");
+ store.getState().actions.setPreview("latency:>10 ");
+ expect(store.getState().previewText).toBe("latency:>10 ");
+ expect(store.getState().draft).toBe("level:ERROR name:foo");
+ store.getState().actions.clearPreview();
+ expect(store.getState().previewText).toBeNull();
+ expect(store.getState().draft).toBe("level:ERROR name:foo");
+ });
+
+ it("clearPreview is a no-op when no preview is active (no churn re-render)", () => {
+ // Row leave/blur and the popover's close handler can all end the same
+ // preview; the extra calls must not notify subscribers.
+ const store = createSearchBarStore();
+ let notified = 0;
+ const unsub = store.subscribe(() => notified++);
+ store.getState().actions.clearPreview();
+ expect(notified).toBe(0);
+ store.getState().actions.setPreview("level:ERROR ");
+ store.getState().actions.setPreview("level:ERROR ");
+ expect(notified).toBe(1);
+ unsub();
+ });
+
+ it("a draft write ends the preview (edit always wins over overlay)", () => {
+ const store = createSearchBarStore();
+ store.getState().actions.setPreview("latency:>10 ");
+ store.getState().actions.setDraft("env:prod");
+ expect(store.getState().previewText).toBeNull();
+
+ store.getState().actions.setPreview("latency:>10 ");
+ store.getState().actions.resetTo("level:ERROR");
+ expect(store.getState().previewText).toBeNull();
+
+ const chip = createSearchBarStore();
+ chip.getState().actions.setDraft("level:ERROR env:dev");
+ chip.getState().actions.setPreview("latency:>10 ");
+ chip.getState().actions.removeChipSpan(0, 11);
+ expect(chip.getState().previewText).toBeNull();
+ });
+
it("revealInvalid marks the current draft; setDraft clears it", () => {
const store = createSearchBarStore();
store.getState().actions.setDraft("level:ERROR OR env:dev");
diff --git a/web/src/features/search-bar/store/searchBarStore.ts b/web/src/features/search-bar/store/searchBarStore.ts
index f7706ef188..34fafb86d6 100644
--- a/web/src/features/search-bar/store/searchBarStore.ts
+++ b/web/src/features/search-bar/store/searchBarStore.ts
@@ -1,4 +1,4 @@
-// Per-mount search-bar store β€” DRAFT ONLY.
+// Per-mount search-bar store β€” DRAFT ONLY (plus an ephemeral preview overlay).
//
// Data direction is deliberately dumb and one-way: the table's URL filter
// state (FilterState + searchQuery/searchType) is the single source of truth.
@@ -8,6 +8,12 @@
// and nothing here ever writes back to the filter state (that happens in the
// container's commit workflow). This removes the reconciliation/loop-guard the
// old two-source design needed.
+//
+// `previewText` is a display-only overlay on top of that model (a hovered
+// preset row shows the query it would apply). It is rendered instead of the
+// draft while active but is not an edit buffer: it never merges into the
+// draft, never commits, and any real draft write clears it β€” so previews are
+// non-destructive by construction, not by careful restore logic.
import { createStore, type StoreApi } from "zustand/vanilla";
@@ -44,6 +50,14 @@ export function draftsSemanticallyEqual(
export type SearchBarStoreState = {
/** Live editing buffer. */
draft: string;
+ /**
+ * Ephemeral preview overlay (a preset row being hovered/focused shows the
+ * query it would apply). Rendered INSTEAD of the draft while non-null; it
+ * never merges into the draft, so ending a preview cannot lose in-progress
+ * typing β€” the draft was simply never touched. Any real draft write clears
+ * it (an edit always ends a preview).
+ */
+ previewText: string | null;
/** Pure derivations of `draft`, cached on write to avoid re-parsing. */
draftDiagnostics: Diagnostic[];
draftValid: boolean;
@@ -73,6 +87,10 @@ export type SearchBarStoreState = {
* after the draft was typed, so `draftValid` doesn't stay stale.
*/
revalidate: () => void;
+ /** Show `text` in the bar as a non-destructive preview overlay. */
+ setPreview: (text: string) => void;
+ /** End the preview; the untouched draft shows again. Safe to call twice. */
+ clearPreview: () => void;
};
};
@@ -102,6 +120,9 @@ export function createSearchBarStore(
const res = validateQuery(next, scoreTypes);
set({
draft: next,
+ // A real edit always ends a preview β€” the overlay must never sit over
+ // a draft that changed underneath it.
+ previewText: null,
draftDiagnostics: res.diagnostics,
draftValid: res.valid,
invalidRevealDraft: null,
@@ -110,6 +131,7 @@ export function createSearchBarStore(
return {
draft: "",
+ previewText: null,
draftDiagnostics: [],
draftValid: true,
invalidRevealDraft: null,
@@ -143,6 +165,14 @@ export function createSearchBarStore(
return next;
},
revealInvalid: () => set({ invalidRevealDraft: get().draft }),
+ setPreview: (text) => {
+ if (get().previewText === text) return;
+ set({ previewText: text });
+ },
+ clearPreview: () => {
+ if (get().previewText === null) return;
+ set({ previewText: null });
+ },
revalidate: () => {
const scoreTypes = resolveScoreTypes?.();
// Nothing to refresh: the draft was already validated against an