Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat: introduce sidebar filtering UI (#9561)

Leo Weigand689dc1630751
diff --git a/web/src/__tests__/filter-query-encoding-decoding.clienttest.ts b/web/src/__tests__/filter-query-encoding-decoding.clienttest.ts
new file mode 100644
index 0000000000..d1dda9d8f0
--- /dev/null
+++ b/web/src/__tests__/filter-query-encoding-decoding.clienttest.ts
@@ -0,0 +1,1067 @@
+import {
+ encodeFiltersGeneric,
+ decodeFiltersGeneric,
+} from "@/src/features/filters/lib/filter-query-encoding";
+import type { FilterState } from "@langfuse/shared";
+
+// Test-specific dinosaur-themed column mapping
+const TEST_COLUMN_TO_QUERY_KEY = {
+ species: "species",
+ diet: "diet",
+ period: "period",
+ habitat: "habitat",
+ extinct: "extinct",
+ length: "length",
+ name: "name",
+ ratings: "ratings",
+};
+
+const TEST_COLUMN_DEFS = [
+ { id: "species", name: "species", type: "stringOptions" as const },
+ { id: "diet", name: "diet", type: "stringOptions" as const },
+ { id: "period", name: "period", type: "stringOptions" as const },
+ { id: "habitat", name: "habitat", type: "arrayOptions" as const },
+ { id: "extinct", name: "extinct", type: "boolean" as const },
+ { id: "length", name: "length", type: "number" as const },
+ { id: "name", name: "name", type: "string" as const },
+ { id: "ratings", name: "ratings", type: "categoryOptions" as const },
+];
+
+type FilterQueryOptions = Record<
+ keyof typeof TEST_COLUMN_TO_QUERY_KEY,
+ string[]
+>;
+
+// Wrapper functions for tests
+const encodeFilters = (filters: FilterState, options: FilterQueryOptions) =>
+ encodeFiltersGeneric(filters, TEST_COLUMN_TO_QUERY_KEY, options);
+
+const decodeFilters = (query: string, options: FilterQueryOptions) => {
+ return decodeFiltersGeneric(
+ query,
+ TEST_COLUMN_TO_QUERY_KEY,
+ options,
+ (column) => {
+ const columnDef = TEST_COLUMN_DEFS.find((col) => col.id === column);
+ return columnDef?.type || "stringOptions";
+ },
+ );
+};
+
+describe("Filter Query Encoding & Decoding", () => {
+ const mockOptions: FilterQueryOptions = {
+ species: [
+ "t-rex",
+ "triceratops",
+ "velociraptor",
+ "brachiosaurus",
+ "stegosaurus",
+ "t-rex:variant",
+ "triceratops:variant",
+ ],
+ diet: ["carnivore", "herbivore", "omnivore", "diet:special"],
+ period: ["triassic", "jurassic", "cretaceous"],
+ habitat: ["forest", "plains", "swamp", "desert"],
+ extinct: ["Extinct", "Not extinct"],
+ length: [],
+ name: [],
+ ratings: [],
+ };
+
+ describe("Encoding", () => {
+ it("should encode empty filter state to empty string", () => {
+ const filters: FilterState = [];
+ expect(encodeFilters(filters, mockOptions)).toBe("");
+ });
+
+ it("should encode single categorical filter", () => {
+ const filters: FilterState = [
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["jurassic"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("period:jurassic");
+ });
+
+ it("should encode multiple values in categorical filter", () => {
+ const filters: FilterState = [
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["jurassic", "cretaceous"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "period:jurassic,cretaceous",
+ );
+ });
+
+ it("should encode another categorical filter", () => {
+ const filters: FilterState = [
+ {
+ column: "species",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["t-rex"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("species:t-rex");
+ });
+
+ it("should encode categorical filter with lowercase conversion", () => {
+ const filters: FilterState = [
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["carnivore"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("diet:carnivore");
+ });
+
+ it("should handle colons in filter values by quoting", () => {
+ const filters: FilterState = [
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["diet:special", "carnivore"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ 'diet:"diet:special",carnivore',
+ );
+ });
+
+ it("should encode multiple filters", () => {
+ const filters: FilterState = [
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["jurassic"],
+ },
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["carnivore", "omnivore"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "period:jurassic diet:carnivore,omnivore",
+ );
+ });
+
+ it("should serialize filter even when all values are selected", () => {
+ const filters: FilterState = [
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic", "jurassic", "cretaceous"], // All available
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "period:triassic,jurassic,cretaceous",
+ );
+ });
+
+ it("should serialize level filter even when all levels are selected", () => {
+ const filters: FilterState = [
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["herbivore", "omnivore", "herbivore", "carnivore"], // All available
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "diet:herbivore,omnivore,herbivore,carnivore",
+ );
+ });
+
+ it("should handle mixed filters with all and specific values", () => {
+ const filters: FilterState = [
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic", "jurassic", "cretaceous"], // All - now included
+ },
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["carnivore"], // Specific - should be included
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "period:triassic,jurassic,cretaceous diet:carnivore",
+ );
+ });
+
+ it("should ignore non-stringOptions filters", () => {
+ const filters: FilterState = [
+ {
+ column: "Timestamp",
+ type: "datetime",
+ operator: ">=",
+ value: new Date("2024-01-01"),
+ },
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("period:triassic");
+ });
+
+ it("should encode exclusive filters with minus prefix", () => {
+ const filters: FilterState = [
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["triassic"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("-period:triassic");
+ });
+
+ it("should encode multiple exclusive filter values", () => {
+ const filters: FilterState = [
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["carnivore", "herbivore"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "-diet:carnivore,herbivore",
+ );
+ });
+
+ it("should encode mixed inclusive and exclusive filters", () => {
+ const filters: FilterState = [
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic"],
+ },
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["omnivore"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "period:triassic -diet:omnivore",
+ );
+ });
+
+ it("should encode numeric >= filter", () => {
+ const filters: FilterState = [
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 5,
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("length:>=5");
+ });
+
+ it("should encode numeric <= filter", () => {
+ const filters: FilterState = [
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 10,
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("length:<=10");
+ });
+
+ it("should encode numeric range with both >= and <= as bracket notation", () => {
+ const filters: FilterState = [
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 5,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 10,
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("length:[5,10]");
+ });
+
+ it("should encode numeric filter with decimal values", () => {
+ const filters: FilterState = [
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 2.5,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 7.8,
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("length:[2.5,7.8]");
+ });
+
+ it("should encode numeric range with negative numbers", () => {
+ const filters: FilterState = [
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: -5,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 10,
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("length:[-5,10]");
+ });
+
+ it("should encode string filter with contains operator", () => {
+ const filters: FilterState = [
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "rex",
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("name:*rex*");
+ });
+
+ it("should encode string filter and escape spaces with backslashes", () => {
+ const filters: FilterState = [
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "tyrannosaurus rex",
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "name:*tyrannosaurus\\ rex*",
+ );
+ });
+
+ it("should encode string filter and escape asterisks", () => {
+ const filters: FilterState = [
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "t*rex",
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("name:*t\\*rex*");
+ });
+
+ it("should skip empty string filters", () => {
+ const filters: FilterState = [
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "",
+ },
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["jurassic"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("period:jurassic");
+ });
+
+ it("should encode categoryOptions filter with single value", () => {
+ const filters: FilterState = [
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "danger",
+ value: ["high"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("ratings.danger:high");
+ });
+
+ it("should encode categoryOptions filter with multiple values", () => {
+ const filters: FilterState = [
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "danger",
+ value: ["high", "medium"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "ratings.danger:high,medium",
+ );
+ });
+
+ it("should encode categoryOptions filter with none of operator", () => {
+ const filters: FilterState = [
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "none of",
+ key: "danger",
+ value: ["low"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("-ratings.danger:low");
+ });
+
+ it("should encode categoryOptions filter with special characters in values", () => {
+ const filters: FilterState = [
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "accuracy",
+ value: ["excellent", "good"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "ratings.accuracy:excellent,good",
+ );
+ });
+
+ it("should skip categoryOptions filter with empty key", () => {
+ const filters: FilterState = [
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "",
+ value: ["high"],
+ },
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["jurassic"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("period:jurassic");
+ });
+
+ it("should skip categoryOptions filter with empty values", () => {
+ const filters: FilterState = [
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "danger",
+ value: [],
+ },
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["jurassic"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("period:jurassic");
+ });
+
+ it("should encode multiple categoryOptions filters", () => {
+ const filters: FilterState = [
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "danger",
+ value: ["high"],
+ },
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "accuracy",
+ value: ["excellent", "good"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "ratings.danger:high ratings.accuracy:excellent,good",
+ );
+ });
+ });
+
+ describe("Decoding", () => {
+ it("should decode empty string to empty filter state", () => {
+ expect(decodeFilters("", mockOptions)).toEqual([]);
+ });
+
+ it("should decode single environment filter", () => {
+ const result = decodeFilters("period:triassic", mockOptions);
+ expect(result).toEqual([
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic"],
+ },
+ ]);
+ });
+
+ it("should decode quoted values with colons", () => {
+ const result = decodeFilters(
+ 'species:"t-rex:variant","triceratops:variant"',
+ mockOptions,
+ );
+ expect(result).toEqual([
+ {
+ column: "species",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["t-rex:variant", "triceratops:variant"],
+ },
+ ]);
+ });
+
+ it("should decode multiple environment values", () => {
+ const result = decodeFilters("period:triassic,jurassic", mockOptions);
+ expect(result).toEqual([
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic", "jurassic"],
+ },
+ ]);
+ });
+
+ it("should decode multiple filters", () => {
+ const result = decodeFilters(
+ "period:triassic diet:carnivore,herbivore",
+ mockOptions,
+ );
+ expect(result).toEqual([
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic"],
+ },
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["carnivore", "herbivore"],
+ },
+ ]);
+ });
+
+ it("should ignore empty filter values (malformed query)", () => {
+ const result = decodeFilters("period:", mockOptions);
+ expect(result).toEqual([]);
+ });
+
+ it("should ignore unknown filter types", () => {
+ const result = decodeFilters(
+ "period:triassic unknown:value diet:carnivore",
+ mockOptions,
+ );
+ expect(result).toEqual([
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic"],
+ },
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["carnivore"],
+ },
+ ]);
+ });
+
+ it("should filter out invalid values for known filters", () => {
+ const result = decodeFilters(
+ "period:triassic,invalid,jurassic",
+ mockOptions,
+ );
+ expect(result).toEqual([
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic", "jurassic"], // 'invalid' filtered out
+ },
+ ]);
+ });
+
+ it("should handle malformed syntax gracefully", () => {
+ // Missing colon
+ expect(decodeFilters("period", mockOptions)).toEqual([]);
+
+ // Multiple colons
+ expect(decodeFilters("period:triassic:extra", mockOptions)).toEqual([]);
+
+ // Empty parts
+ expect(
+ decodeFilters("period:triassic diet:carnivore", mockOptions),
+ ).toEqual([
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic"],
+ },
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["carnivore"],
+ },
+ ]);
+ });
+
+ it("should decode exclusive filters with minus prefix", () => {
+ const result = decodeFilters("-period:triassic", mockOptions);
+ expect(result).toEqual([
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["triassic"],
+ },
+ ]);
+ });
+
+ it("should decode multiple exclusive filter values", () => {
+ const result = decodeFilters("-diet:carnivore,herbivore", mockOptions);
+ expect(result).toEqual([
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["carnivore", "herbivore"],
+ },
+ ]);
+ });
+
+ it("should decode mixed inclusive and exclusive filters", () => {
+ const result = decodeFilters(
+ "period:triassic -diet:omnivore",
+ mockOptions,
+ );
+ expect(result).toEqual([
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic"],
+ },
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["omnivore"],
+ },
+ ]);
+ });
+
+ it("should handle exclusive filters with quoted values", () => {
+ const result = decodeFilters('-species:"t-rex:variant"', mockOptions);
+ expect(result).toEqual([
+ {
+ column: "species",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["t-rex:variant"],
+ },
+ ]);
+ });
+
+ it("should decode numeric >= filter", () => {
+ const query = "length:>=5";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 5,
+ },
+ ]);
+ });
+
+ it("should decode numeric <= filter", () => {
+ const query = "length:<=10";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 10,
+ },
+ ]);
+ });
+
+ it("should decode bracket notation range [min,max]", () => {
+ const query = "length:[5,10]";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 5,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 10,
+ },
+ ]);
+ });
+
+ it("should decode bracket notation with decimal values", () => {
+ const query = "length:[2.5,7.8]";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 2.5,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 7.8,
+ },
+ ]);
+ });
+
+ it("should decode bracket notation with negative numbers", () => {
+ const query = "length:[-5,10]";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: -5,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 10,
+ },
+ ]);
+ });
+
+ it("should decode separate >= and <= operators as individual filters", () => {
+ const query = "length:>=5 length:<=10";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 5,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 10,
+ },
+ ]);
+ });
+
+ it("should decode string filter with asterisks", () => {
+ const query = "name:*rex*";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "rex",
+ },
+ ]);
+ });
+
+ it("should decode string filter with escaped spaces", () => {
+ const query = "name:*tyrannosaurus\\ rex*";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "tyrannosaurus rex",
+ },
+ ]);
+ });
+
+ it("should decode string filter with escaped asterisks", () => {
+ const query = "name:*t\\*rex*";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "t*rex",
+ },
+ ]);
+ });
+
+ it("should decode categoryOptions filter with single value", () => {
+ const query = "ratings.danger:high";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "danger",
+ value: ["high"],
+ },
+ ]);
+ });
+
+ it("should decode categoryOptions filter with multiple values", () => {
+ const query = "ratings.danger:high,medium";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "danger",
+ value: ["high", "medium"],
+ },
+ ]);
+ });
+
+ it("should decode categoryOptions filter with none of operator", () => {
+ const query = "-ratings.danger:low";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "none of",
+ key: "danger",
+ value: ["low"],
+ },
+ ]);
+ });
+
+ it("should decode multiple categoryOptions filters", () => {
+ const query = "ratings.danger:high ratings.accuracy:excellent,good";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "danger",
+ value: ["high"],
+ },
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "accuracy",
+ value: ["excellent", "good"],
+ },
+ ]);
+ });
+ });
+
+ describe("Round-trip consistency", () => {
+ it("should maintain consistency through encode -> decode", () => {
+ const originalFilters: FilterState = [
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "tyrannosaurus rex",
+ },
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic", "jurassic"],
+ },
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["carnivore"],
+ },
+ {
+ column: "habitat",
+ type: "arrayOptions",
+ operator: "any of",
+ value: ["forest"],
+ },
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic"],
+ },
+ ];
+
+ const serialized = encodeFilters(originalFilters, mockOptions);
+ const deserialized = decodeFilters(serialized, mockOptions);
+
+ expect(deserialized).toEqual(originalFilters);
+ });
+
+ it("should maintain consistency for values with colons through encode -> decode", () => {
+ const originalFilters: FilterState = [
+ {
+ column: "species",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["t-rex:variant", "triceratops:variant"],
+ },
+ ];
+
+ const serialized = encodeFilters(originalFilters, mockOptions);
+ const deserialized = decodeFilters(serialized, mockOptions);
+
+ expect(deserialized).toEqual(originalFilters);
+ });
+
+ it("should handle all values selected correctly in round-trip", () => {
+ // All environments selected should now be encoded and round-trip consistently
+ const allEnvironmentsFilter: FilterState = [
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic", "jurassic", "cretaceous"],
+ },
+ ];
+
+ const serialized = encodeFilters(allEnvironmentsFilter, mockOptions);
+ expect(serialized).toBe("period:triassic,jurassic,cretaceous"); // Should encode all values
+
+ const deserialized = decodeFilters(serialized, mockOptions);
+ expect(deserialized).toEqual(allEnvironmentsFilter); // Should decode to original
+ });
+
+ it("should maintain consistency for exclusive filters through encode -> decode", () => {
+ const exclusiveFilters: FilterState = [
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["triassic"],
+ },
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["carnivore", "herbivore"],
+ },
+ ];
+
+ const serialized = encodeFilters(exclusiveFilters, mockOptions);
+ const deserialized = decodeFilters(serialized, mockOptions);
+
+ expect(deserialized).toEqual(exclusiveFilters);
+ });
+
+ it("should maintain consistency for mixed inclusive/exclusive filters", () => {
+ const mixedFilters: FilterState = [
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic", "jurassic"],
+ },
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["omnivore"],
+ },
+ {
+ column: "species",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["t-rex:variant"], // With colon
+ },
+ {
+ column: "habitat",
+ type: "arrayOptions",
+ operator: "none of",
+ value: ["swamp"],
+ },
+ {
+ column: "extinct",
+ type: "boolean",
+ operator: "=",
+ value: true,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 0.5,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 15.2,
+ },
+ ];
+
+ const serialized = encodeFilters(mixedFilters, mockOptions);
+ const deserialized = decodeFilters(serialized, mockOptions);
+
+ expect(deserialized).toEqual(mixedFilters);
+ });
+ });
+});
diff --git a/web/src/components/table/data-table-ai-filters.tsx b/web/src/components/table/data-table-ai-filters.tsx
new file mode 100644
index 0000000000..a4a8d58b21
--- /dev/null
+++ b/web/src/components/table/data-table-ai-filters.tsx
@@ -0,0 +1,155 @@
+import { useState } from "react";
+import { Button } from "@/src/components/ui/button";
+import { Textarea } from "@/src/components/ui/textarea";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
+import { Info, ExternalLink } from "lucide-react";
+import { useQueryProject } from "@/src/features/projects/hooks";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
+import { api } from "@/src/utils/api";
+import { type FilterState } from "@langfuse/shared";
+
+interface DataTableAIFiltersProps {
+ onFiltersGenerated: (filters: FilterState) => void;
+}
+
+export function DataTableAIFilters({
+ onFiltersGenerated,
+}: DataTableAIFiltersProps) {
+ const [aiPrompt, setAiPrompt] = useState("");
+ const [aiError, setAiError] = useState<string | null>(null);
+ const projectId = useProjectIdFromURL();
+ const { organization } = useQueryProject();
+
+ const hasAdminAccess = useHasOrganizationAccess({
+ organizationId: organization?.id ?? undefined,
+ scope: "organization:update",
+ });
+
+ const createFilterMutation =
+ api.naturalLanguageFilters.createCompletion.useMutation();
+
+ const handleAiFilterSubmit = async () => {
+ if (aiPrompt.trim() && !createFilterMutation.isPending && projectId) {
+ setAiError(null);
+ try {
+ const result = await createFilterMutation.mutateAsync({
+ projectId,
+ prompt: aiPrompt.trim(),
+ });
+
+ if (result && Array.isArray(result.filters)) {
+ if (result.filters.length === 0) {
+ setAiError("Failed to generate filters, try again");
+ return;
+ }
+
+ // Set the filters from the API response
+ onFiltersGenerated(result.filters as FilterState);
+ setAiPrompt("");
+ } else {
+ console.error(result);
+ setAiError("Invalid response format from API");
+ }
+ } catch (error) {
+ console.error("Error calling tRPC API:", error);
+ setAiError(
+ error instanceof Error ? error.message : "Failed to generate filters",
+ );
+ }
+ }
+ };
+
+ // When AI features are not enabled
+ if (!organization?.aiFeaturesEnabled) {
+ return (
+ <div className="flex flex-col gap-3">
+ <p className="text-sm text-muted-foreground">
+ AI-powered filters use natural language to generate deterministic
+ filters.
+ {!hasAdminAccess &&
+ " Ask your organization administrator to enable AI features in organization settings."}
+ </p>
+ {hasAdminAccess && organization?.id && (
+ <Button
+ onClick={() => {
+ window.open(
+ `/organization/${organization.id}/settings`,
+ "_blank",
+ );
+ }}
+ variant="outline"
+ size="sm"
+ className="w-fit"
+ >
+ Enable in Organization Settings
+ <ExternalLink className="ml-2 h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ );
+ }
+
+ // When AI features are enabled
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">Filter with AI</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info className="h-4 w-4 text-muted-foreground" />
+ </TooltipTrigger>
+ <TooltipContent>
+ <p className="text-xs">
+ We convert natural language into deterministic filters which you
+ can adjust afterwards
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ <Textarea
+ autoFocus
+ value={aiPrompt}
+ onChange={(e) => {
+ setAiPrompt(e.target.value);
+ if (aiError) setAiError(null);
+ }}
+ placeholder="Describe the filters you want to apply..."
+ className="min-h-[80px] resize-none"
+ disabled={createFilterMutation.isPending}
+ onKeyDown={(e) => {
+ if (
+ e.key === "Enter" &&
+ !e.shiftKey &&
+ !createFilterMutation.isPending
+ ) {
+ e.preventDefault();
+ handleAiFilterSubmit();
+ }
+ }}
+ />
+ <Button
+ onClick={handleAiFilterSubmit}
+ type="button"
+ variant="default"
+ size="sm"
+ disabled={createFilterMutation.isPending || !aiPrompt.trim()}
+ className="w-fit"
+ >
+ {createFilterMutation.isPending ? "Loading..." : "Generate"}
+ </Button>
+ {aiError && (
+ <div className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
+ {aiError}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/components/table/data-table-controls.tsx b/web/src/components/table/data-table-controls.tsx
new file mode 100644
index 0000000000..8916f62818
--- /dev/null
+++ b/web/src/components/table/data-table-controls.tsx
@@ -0,0 +1,946 @@
+import {
+ createContext,
+ useContext,
+ useState,
+ useEffect,
+ useRef,
+ useCallback,
+} from "react";
+import useLocalStorage from "@/src/components/useLocalStorage";
+import { cn } from "@/src/utils/tailwind";
+import { compactNumberFormatter } from "@/src/utils/numbers";
+import { Accordion } from "@/src/components/ui/accordion";
+import * as AccordionPrimitive from "@radix-ui/react-accordion";
+import { ChevronDown } from "lucide-react";
+import { Checkbox } from "@/src/components/ui/checkbox";
+import { Button } from "@/src/components/ui/button";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
+import { Slider } from "@/src/components/ui/slider";
+import { Input } from "@/src/components/ui/input";
+import { Label } from "@/src/components/ui/label";
+import { X as IconX, Search, WandSparkles } from "lucide-react";
+import type {
+ UIFilter,
+ KeyValueFilterEntry,
+ NumericKeyValueFilterEntry,
+ StringKeyValueFilterEntry,
+} from "@/src/features/filters/hooks/useSidebarFilterState";
+import { KeyValueFilterBuilder } from "@/src/components/table/key-value-filter-builder";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import { DataTableAIFilters } from "@/src/components/table/data-table-ai-filters";
+import { type FilterState } from "@langfuse/shared";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
+
+interface ControlsContextType {
+ open: boolean;
+ setOpen: React.Dispatch<React.SetStateAction<boolean>>;
+}
+
+export const ControlsContext = createContext<ControlsContextType | null>(null);
+
+export function DataTableControlsProvider({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const [open, setOpen] = useLocalStorage("data-table-controls", true);
+
+ return (
+ <ControlsContext.Provider value={{ open, setOpen }}>
+ <div
+ // access the data-expanded state with tailwind via `group-data-[expanded=true]/controls`
+ className="group/controls contents"
+ data-expanded={open}
+ >
+ {children}
+ </div>
+ </ControlsContext.Provider>
+ );
+}
+
+export function useDataTableControls() {
+ const context = useContext(ControlsContext);
+
+ if (!context) {
+ // Return default values when not in a provider (e.g., tables without the new sidebar)
+ return { open: false, setOpen: () => {} };
+ }
+
+ return context as ControlsContextType;
+}
+
+export interface QueryFilter {
+ filters: UIFilter[];
+ expanded: string[];
+ onExpandedChange: (value: string[]) => void;
+ clearAll: () => void;
+ isFiltered: boolean;
+ setFilterState: (filters: FilterState) => void;
+}
+
+interface DataTableControlsProps {
+ queryFilter: QueryFilter;
+ filterWithAI?: boolean;
+}
+
+export function DataTableControls({
+ queryFilter,
+ filterWithAI,
+}: DataTableControlsProps) {
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
+ const [aiPopoverOpen, setAiPopoverOpen] = useState(false);
+
+ const handleFiltersGenerated = useCallback(
+ (filters: FilterState) => {
+ // Apply filters
+ queryFilter.setFilterState(filters);
+
+ // Extract unique column names from filters
+ const columnsToExpand = [...new Set(filters.map((f) => f.column))];
+
+ // Get current expanded state and merge with new columns
+ const currentExpanded = queryFilter.expanded;
+ const newExpanded = Array.from(
+ new Set([...currentExpanded, ...columnsToExpand]),
+ );
+ queryFilter.onExpandedChange(newExpanded);
+
+ // Close popover
+ setAiPopoverOpen(false);
+ },
+ [queryFilter],
+ );
+
+ return (
+ <div
+ className={cn(
+ "h-full w-full border-r border-t bg-background sm:block sm:min-w-52 sm:max-w-52 md:min-w-64 md:max-w-64",
+ "group-data-[expanded=false]/controls:hidden",
+ )}
+ >
+ <div className="flex h-full flex-col overflow-auto">
+ <div className="mb-2 flex h-10 shrink-0 items-center justify-between border-b px-3">
+ <span className="text-sm font-medium">Filters</span>
+ {filterWithAI && isLangfuseCloud && (
+ <Popover open={aiPopoverOpen} onOpenChange={setAiPopoverOpen}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <PopoverTrigger asChild>
+ <Button variant="ghost" size="icon" className="h-8 w-8">
+ <WandSparkles className="h-4 w-4" />
+ </Button>
+ </PopoverTrigger>
+ </TooltipTrigger>
+ <TooltipContent>Filter with AI</TooltipContent>
+ </Tooltip>
+ <PopoverContent align="center" className="w-[400px]">
+ <DataTableAIFilters
+ onFiltersGenerated={handleFiltersGenerated}
+ />
+ </PopoverContent>
+ </Popover>
+ )}
+ </div>
+ <Accordion
+ type="multiple"
+ className="w-full"
+ value={queryFilter.expanded}
+ onValueChange={queryFilter.onExpandedChange}
+ >
+ {queryFilter.filters.map((filter) => {
+ if (filter.type === "categorical") {
+ return (
+ <CategoricalFacet
+ key={filter.column}
+ filterKey={filter.column}
+ filterKeyShort={filter.shortKey}
+ label={filter.label}
+ expanded={filter.expanded}
+ options={filter.options}
+ counts={filter.counts}
+ loading={filter.loading}
+ value={filter.value}
+ onChange={filter.onChange}
+ onOnlyChange={filter.onOnlyChange}
+ isActive={filter.isActive}
+ onReset={filter.onReset}
+ />
+ );
+ }
+
+ if (filter.type === "numeric") {
+ return (
+ <NumericFacet
+ key={filter.column}
+ filterKey={filter.column}
+ filterKeyShort={filter.shortKey}
+ label={filter.label}
+ expanded={filter.expanded}
+ loading={filter.loading}
+ min={filter.min}
+ max={filter.max}
+ value={filter.value}
+ onChange={filter.onChange}
+ unit={filter.unit}
+ isActive={filter.isActive}
+ onReset={filter.onReset}
+ />
+ );
+ }
+
+ if (filter.type === "string") {
+ return (
+ <StringFacet
+ key={filter.column}
+ filterKey={filter.column}
+ filterKeyShort={filter.shortKey}
+ label={filter.label}
+ expanded={filter.expanded}
+ loading={filter.loading}
+ value={filter.value}
+ onChange={filter.onChange}
+ isActive={filter.isActive}
+ onReset={filter.onReset}
+ />
+ );
+ }
+
+ if (filter.type === "keyValue") {
+ return (
+ <KeyValueFacet
+ key={filter.column}
+ filterKey={filter.column}
+ filterKeyShort={filter.shortKey}
+ label={filter.label}
+ expanded={filter.expanded}
+ loading={filter.loading}
+ keyOptions={filter.keyOptions}
+ availableValues={filter.availableValues}
+ value={filter.value}
+ onChange={filter.onChange}
+ isActive={filter.isActive}
+ onReset={filter.onReset}
+ />
+ );
+ }
+
+ if (filter.type === "numericKeyValue") {
+ return (
+ <NumericKeyValueFacet
+ key={filter.column}
+ filterKey={filter.column}
+ filterKeyShort={filter.shortKey}
+ label={filter.label}
+ expanded={filter.expanded}
+ loading={filter.loading}
+ keyOptions={filter.keyOptions}
+ value={filter.value}
+ onChange={filter.onChange}
+ isActive={filter.isActive}
+ onReset={filter.onReset}
+ />
+ );
+ }
+
+ if (filter.type === "stringKeyValue") {
+ return (
+ <StringKeyValueFacet
+ key={filter.column}
+ filterKey={filter.column}
+ filterKeyShort={filter.shortKey}
+ label={filter.label}
+ expanded={filter.expanded}
+ loading={filter.loading}
+ keyOptions={filter.keyOptions}
+ value={filter.value}
+ onChange={filter.onChange}
+ isActive={filter.isActive}
+ onReset={filter.onReset}
+ />
+ );
+ }
+
+ return null;
+ })}
+ </Accordion>
+ </div>
+ </div>
+ );
+}
+
+interface BaseFacetProps {
+ label: string;
+ children?: React.ReactNode;
+ filterKey: string;
+ filterKeyShort?: string | null;
+ expanded?: boolean;
+ loading?: boolean;
+ isActive?: boolean;
+ onReset?: () => void;
+}
+
+interface CategoricalFacetProps extends BaseFacetProps {
+ options: string[];
+ counts: Map<string, number>;
+ value: string[];
+ onChange: (values: string[]) => void;
+ onOnlyChange?: (value: string) => void;
+}
+
+interface NumericFacetProps extends BaseFacetProps {
+ min: number;
+ max: number;
+ value: [number, number];
+ onChange: (value: [number, number]) => void;
+ unit?: string;
+}
+
+interface StringFacetProps extends BaseFacetProps {
+ value: string;
+ onChange: (value: string) => void;
+}
+
+interface KeyValueFacetProps extends BaseFacetProps {
+ keyOptions?: string[];
+ availableValues: Record<string, string[]>;
+ value: KeyValueFilterEntry[];
+ onChange: (filters: KeyValueFilterEntry[]) => void;
+}
+
+interface NumericKeyValueFacetProps extends BaseFacetProps {
+ keyOptions?: string[];
+ value: NumericKeyValueFilterEntry[];
+ onChange: (filters: NumericKeyValueFilterEntry[]) => void;
+}
+
+interface StringKeyValueFacetProps extends BaseFacetProps {
+ keyOptions?: string[];
+ value: StringKeyValueFilterEntry[];
+ onChange: (filters: StringKeyValueFilterEntry[]) => void;
+}
+
+// Non-animated accordion components for filters
+const FilterAccordionItemPrimitive = AccordionPrimitive.Item;
+
+const FilterAccordionTrigger = ({
+ className,
+ children,
+ ...props
+}: React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>) => (
+ <AccordionPrimitive.Header className="flex">
+ <AccordionPrimitive.Trigger
+ className={cn(
+ "flex flex-1 items-center justify-between font-medium hover:underline [&[data-state=open]>svg]:rotate-180",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronDown className="h-4 w-4 shrink-0" />
+ </AccordionPrimitive.Trigger>
+ </AccordionPrimitive.Header>
+);
+
+const FilterAccordionContent = ({
+ className,
+ children,
+ ...props
+}: React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>) => (
+ <AccordionPrimitive.Content className="overflow-hidden text-sm" {...props}>
+ <div className={cn("pb-2 pt-1", className)}>{children}</div>
+ </AccordionPrimitive.Content>
+);
+
+interface FilterAccordionItemProps {
+ label: string;
+ filterKey: string;
+ filterKeyShort?: string | null;
+ children: React.ReactNode;
+ isActive?: boolean;
+ onReset?: () => void;
+}
+
+export function FilterAccordionItem({
+ label,
+ filterKey,
+ filterKeyShort,
+ children,
+ isActive,
+ onReset,
+}: FilterAccordionItemProps) {
+ return (
+ <FilterAccordionItemPrimitive value={filterKey} className="border-none">
+ <FilterAccordionTrigger className="px-4 py-2 text-sm font-normal text-muted-foreground hover:text-foreground hover:no-underline">
+ <div className="flex grow items-center gap-1.5 pr-2">
+ <span className="flex grow items-baseline gap-1">
+ {label}
+ {filterKeyShort && (
+ <code className="hidden font-mono text-xs text-muted-foreground/70">
+ {filterKeyShort}
+ </code>
+ )}
+ </span>
+ {isActive && onReset && (
+ <div
+ role="button"
+ tabIndex={0}
+ onClick={(e) => {
+ e.stopPropagation();
+ onReset();
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.stopPropagation();
+ e.preventDefault();
+ onReset();
+ }
+ }}
+ className="inline-flex h-5 cursor-pointer items-center gap-1 rounded-full border bg-background px-2 text-xs hover:bg-accent hover:text-accent-foreground"
+ aria-label={`Clear ${label} filter`}
+ >
+ <span>Clear</span>
+ <IconX className="h-3 w-3" />
+ </div>
+ )}
+ </div>
+ </FilterAccordionTrigger>
+ <FilterAccordionContent className="pb-2">
+ {children}
+ </FilterAccordionContent>
+ </FilterAccordionItemPrimitive>
+ );
+}
+
+export function CategoricalFacet({
+ label,
+ filterKey,
+ filterKeyShort,
+ expanded,
+ loading,
+ options,
+ counts,
+ value,
+ onChange,
+ onOnlyChange,
+ isActive,
+ onReset,
+}: CategoricalFacetProps) {
+ const [showAll, setShowAll] = useState(false);
+ const [searchQuery, setSearchQuery] = useState("");
+
+ // Reset showAll and searchQuery state when accordion is collapsed
+ useEffect(() => {
+ if (!expanded) {
+ setShowAll(false);
+ setSearchQuery("");
+ }
+ }, [expanded]);
+
+ const MAX_VISIBLE_OPTIONS = 12;
+ const hasMoreOptions = options.length > MAX_VISIBLE_OPTIONS;
+
+ // Filter options by search query
+ const filteredOptions = searchQuery
+ ? options.filter((option) =>
+ option.toLowerCase().includes(searchQuery.toLowerCase()),
+ )
+ : options;
+
+ const hasMoreFilteredOptions = filteredOptions.length > MAX_VISIBLE_OPTIONS;
+ const visibleOptions = showAll
+ ? filteredOptions
+ : filteredOptions.slice(0, MAX_VISIBLE_OPTIONS);
+
+ return (
+ <FilterAccordionItem
+ label={label}
+ filterKey={filterKey}
+ filterKeyShort={filterKeyShort}
+ isActive={isActive}
+ onReset={onReset}
+ >
+ <div className="flex flex-col px-2">
+ {loading ? (
+ <div className="pl-4 text-sm text-muted-foreground">Loading...</div>
+ ) : options.length === 0 ? (
+ <div className="py-1 text-center text-sm text-muted-foreground">
+ No options found
+ </div>
+ ) : (
+ <>
+ {hasMoreOptions && (
+ <div className="mb-2 px-2">
+ <div className="relative">
+ <Search className="absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ placeholder="Filter values"
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="h-8 pl-7 text-xs"
+ />
+ </div>
+ </div>
+ )}
+ {filteredOptions.length === 0 ? (
+ <div className="py-1 text-center text-sm text-muted-foreground">
+ No matches found
+ </div>
+ ) : (
+ <>
+ {visibleOptions.map((option: string) => (
+ <FilterValueCheckbox
+ key={option}
+ id={`${filterKey}-${option}`}
+ label={option}
+ count={counts.get(option) || 0}
+ checked={value.includes(option)}
+ onCheckedChange={(checked) => {
+ const newValues = checked
+ ? [...value, option]
+ : value.filter((v: string) => v !== option);
+ onChange(newValues);
+ }}
+ onLabelClick={
+ onOnlyChange ? () => onOnlyChange(option) : undefined
+ }
+ totalSelected={value.length}
+ />
+ ))}
+ {hasMoreFilteredOptions && !showAll && (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => setShowAll(true)}
+ className="text-normal mt-1 h-auto justify-start px-2 py-1 pl-8 text-xs"
+ >
+ Show more values
+ </Button>
+ )}
+ </>
+ )}
+ </>
+ )}
+ </div>
+ </FilterAccordionItem>
+ );
+}
+
+export function NumericFacet({
+ label,
+ filterKey,
+ filterKeyShort,
+ expanded: _expanded,
+ loading,
+ min,
+ max,
+ value,
+ onChange,
+ unit,
+ isActive,
+ onReset,
+}: NumericFacetProps) {
+ const [localValue, setLocalValue] = useState<[number, number]>(value);
+ const timeoutRef = useRef<NodeJS.Timeout | null>(null);
+
+ useEffect(() => {
+ setLocalValue(value);
+ }, [value]);
+
+ // Cleanup timeout on unmount
+ useEffect(() => {
+ return () => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ }
+ };
+ }, []);
+
+ const updateWithDebounce = (newValue: [number, number]) => {
+ setLocalValue(newValue);
+
+ // Clear existing timeout
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ }
+
+ // Set new timeout
+ timeoutRef.current = setTimeout(() => {
+ onChange(newValue);
+ }, 120);
+ };
+
+ const handleSliderChange = (values: number[]) => {
+ if (values.length === 2) {
+ const newValue: [number, number] = [values[0], values[1]];
+ updateWithDebounce(newValue);
+ }
+ };
+
+ const handleMinInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const inputValue = e.target.value;
+ // If input is cleared, reset to default min
+ if (inputValue === "") {
+ const newValue: [number, number] = [min, localValue[1]];
+ updateWithDebounce(newValue);
+ return;
+ }
+ const newMin = parseFloat(inputValue);
+ if (isNaN(newMin)) return;
+ const newValue: [number, number] = [newMin, localValue[1]];
+ updateWithDebounce(newValue);
+ };
+
+ const handleMaxInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const inputValue = e.target.value;
+ // If input is cleared, reset to default max
+ if (inputValue === "") {
+ const newValue: [number, number] = [localValue[0], max];
+ updateWithDebounce(newValue);
+ return;
+ }
+ const newMax = parseFloat(inputValue);
+ if (isNaN(newMax)) return;
+ const newValue: [number, number] = [localValue[0], newMax];
+ updateWithDebounce(newValue);
+ };
+
+ return (
+ <FilterAccordionItem
+ label={label}
+ filterKey={filterKey}
+ filterKeyShort={filterKeyShort}
+ isActive={isActive}
+ onReset={onReset}
+ >
+ <div className="px-4 py-2">
+ {loading ? (
+ <div className="text-sm text-muted-foreground">Loading...</div>
+ ) : (
+ <div className="grid gap-4">
+ <div className="flex items-center gap-4">
+ <div className="grid w-full gap-1.5">
+ <Label
+ htmlFor={`min-${filterKey}`}
+ className="text-xs text-muted-foreground"
+ >
+ Min.
+ </Label>
+ <div className="flex items-center gap-1">
+ <Input
+ type="number"
+ id={`min-${filterKey}`}
+ value={isActive ? localValue[0] : ""}
+ placeholder={String(min)}
+ min={min}
+ step="any"
+ onChange={handleMinInputChange}
+ className="h-8"
+ />
+ {unit && (
+ <span className="text-xs text-muted-foreground">
+ {unit}
+ </span>
+ )}
+ </div>
+ </div>
+ <div className="grid w-full gap-1.5">
+ <Label
+ htmlFor={`max-${filterKey}`}
+ className="text-xs text-muted-foreground"
+ >
+ Max.
+ </Label>
+ <div className="flex items-center gap-1">
+ <Input
+ type="number"
+ id={`max-${filterKey}`}
+ value={isActive ? localValue[1] : ""}
+ placeholder={String(max)}
+ min={min}
+ step="any"
+ onChange={handleMaxInputChange}
+ className="h-8"
+ />
+ {unit && (
+ <span className="text-xs text-muted-foreground">
+ {unit}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ <Slider
+ min={min}
+ max={max}
+ step={1}
+ value={localValue}
+ onValueChange={handleSliderChange}
+ />
+ </div>
+ )}
+ </div>
+ </FilterAccordionItem>
+ );
+}
+
+export function StringFacet({
+ label,
+ filterKey,
+ filterKeyShort,
+ expanded: _expanded,
+ loading,
+ value,
+ onChange,
+ isActive,
+ onReset,
+}: StringFacetProps) {
+ const [localValue, setLocalValue] = useState<string>(value);
+ const timeoutRef = useRef<NodeJS.Timeout | null>(null);
+
+ useEffect(() => {
+ setLocalValue(value);
+ }, [value]);
+
+ // Cleanup timeout on unmount
+ useEffect(() => {
+ return () => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ }
+ };
+ }, []);
+
+ const updateWithDebounce = (newValue: string) => {
+ setLocalValue(newValue);
+
+ // Clear existing timeout
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ }
+
+ // Set new timeout
+ timeoutRef.current = setTimeout(() => {
+ onChange(newValue);
+ }, 500);
+ };
+
+ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ updateWithDebounce(e.target.value);
+ };
+
+ return (
+ <FilterAccordionItem
+ label={label}
+ filterKey={filterKey}
+ filterKeyShort={filterKeyShort}
+ isActive={isActive}
+ onReset={onReset}
+ >
+ <div className="px-4">
+ {loading ? (
+ <div className="text-sm text-muted-foreground">Loading...</div>
+ ) : (
+ <Input
+ type="text"
+ id={`string-${filterKey}`}
+ value={localValue}
+ placeholder="Search"
+ onChange={handleInputChange}
+ className="h-8"
+ />
+ )}
+ </div>
+ </FilterAccordionItem>
+ );
+}
+
+export function KeyValueFacet({
+ label,
+ filterKey,
+ filterKeyShort,
+ expanded: _expanded,
+ loading,
+ keyOptions,
+ availableValues,
+ value,
+ onChange,
+ isActive,
+ onReset,
+}: KeyValueFacetProps) {
+ return (
+ <FilterAccordionItem
+ label={label}
+ filterKey={filterKey}
+ filterKeyShort={filterKeyShort}
+ isActive={isActive}
+ onReset={onReset}
+ >
+ {loading ? (
+ <div className="px-4 py-2 text-sm text-muted-foreground">
+ Loading...
+ </div>
+ ) : (
+ <KeyValueFilterBuilder
+ mode="categorical"
+ keyOptions={keyOptions}
+ availableValues={availableValues}
+ activeFilters={value}
+ onChange={onChange}
+ />
+ )}
+ </FilterAccordionItem>
+ );
+}
+
+export function NumericKeyValueFacet({
+ label,
+ filterKey,
+ filterKeyShort,
+ expanded: _expanded,
+ loading,
+ keyOptions,
+ value,
+ onChange,
+ isActive,
+ onReset,
+}: NumericKeyValueFacetProps) {
+ return (
+ <FilterAccordionItem
+ label={label}
+ filterKey={filterKey}
+ filterKeyShort={filterKeyShort}
+ isActive={isActive}
+ onReset={onReset}
+ >
+ {loading ? (
+ <div className="px-4 py-2 text-sm text-muted-foreground">
+ Loading...
+ </div>
+ ) : (
+ <KeyValueFilterBuilder
+ mode="numeric"
+ keyOptions={keyOptions}
+ activeFilters={value}
+ onChange={onChange}
+ />
+ )}
+ </FilterAccordionItem>
+ );
+}
+
+export function StringKeyValueFacet({
+ label,
+ filterKey,
+ filterKeyShort,
+ expanded: _expanded,
+ loading,
+ keyOptions,
+ value,
+ onChange,
+ isActive,
+ onReset,
+}: StringKeyValueFacetProps) {
+ return (
+ <FilterAccordionItem
+ label={label}
+ filterKey={filterKey}
+ filterKeyShort={filterKeyShort}
+ isActive={isActive}
+ onReset={onReset}
+ >
+ {loading ? (
+ <div className="px-4 py-2 text-sm text-muted-foreground">
+ Loading...
+ </div>
+ ) : (
+ <KeyValueFilterBuilder
+ mode="string"
+ keyOptions={keyOptions}
+ activeFilters={value}
+ onChange={onChange}
+ />
+ )}
+ </FilterAccordionItem>
+ );
+}
+
+interface FilterValueCheckboxProps {
+ id: string;
+ label: string;
+ count: number;
+ checked?: boolean;
+ onCheckedChange?: (checked: boolean) => void;
+ onLabelClick?: () => void; // For "only this" behavior
+ totalSelected?: number;
+}
+
+export function FilterValueCheckbox({
+ id,
+ label,
+ count,
+ checked = false,
+ onCheckedChange,
+ onLabelClick,
+ totalSelected,
+}: FilterValueCheckboxProps) {
+ // Show "All" when clicking would reverse selection (only one item selected)
+ const labelText = checked && totalSelected === 1 ? "All" : "Only";
+
+ return (
+ <div className="relative flex items-center px-2">
+ {/* Checkbox hover area */}
+ <div className="group/checkbox flex items-center rounded-sm p-1 transition-colors hover:bg-accent">
+ <Checkbox
+ id={id}
+ checked={checked}
+ onCheckedChange={onCheckedChange}
+ className="pointer-events-auto"
+ />
+ </div>
+
+ {/* Label hover area */}
+ <div
+ className="group/label flex min-w-0 flex-1 cursor-pointer items-center rounded-sm px-1 py-1 transition-colors hover:bg-accent"
+ onClick={onLabelClick}
+ >
+ <span className="min-w-0 flex-1 truncate text-xs">{label}</span>
+
+ {/* "Only" or "All" indicator when hovering label */}
+ {onLabelClick && (
+ <span className="hidden pl-1 text-xs text-muted-foreground group-hover/label:block">
+ {labelText}
+ </span>
+ )}
+
+ {count > 0 ? (
+ <span className="ml-auto w-7 pl-1 text-right text-xs text-muted-foreground">
+ {compactNumberFormatter(count, 0)}
+ </span>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+export function DataTableControlsSection({
+ title,
+ children,
+}: {
+ title: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="space-y-3">
+ <h3 className="text-sm font-medium text-foreground">{title}</h3>
+ <div>{children}</div>
+ </div>
+ );
+}
diff --git a/web/src/components/table/data-table-toolbar.tsx b/web/src/components/table/data-table-toolbar.tsx
index 25719721b6..27da735666 100644
--- a/web/src/components/table/data-table-toolbar.tsx
+++ b/web/src/components/table/data-table-toolbar.tsx
@@ -21,7 +21,13 @@ import {
DataTableRowHeightSwitch,
type RowHeight,
} from "@/src/components/table/data-table-row-height-switch";
-import { Search, ChevronDown } from "lucide-react";
+import {
+ Search,
+ ChevronDown,
+ PanelLeftClose,
+ PanelLeftOpen,
+} from "lucide-react";
+import { Badge } from "@/src/components/ui/badge";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { TimeRangePicker } from "@/src/components/date-picker";
import {
@@ -29,7 +35,6 @@ import {
TABLE_AGGREGATION_OPTIONS,
} from "@/src/utils/date-range-utils";
import { DataTableSelectAllBanner } from "@/src/components/table/data-table-multi-select-actions/data-table-select-all-banner";
-import { MultiSelect } from "@/src/features/filters/components/multi-select";
import { cn } from "@/src/utils/tailwind";
import DocPopup from "@/src/components/layouts/doc-popup";
import { TableViewPresetsDrawer } from "@/src/components/table/table-view-presets/components/data-table-view-presets-drawer";
@@ -40,6 +45,8 @@ import {
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from "@/src/components/ui/dropdown-menu";
+import { useDataTableControls } from "@/src/components/table/data-table-controls";
+import { MultiSelect as MultiSelectFilter } from "@/src/features/filters/components/multi-select";
export interface MultiSelect {
selectAll: boolean;
@@ -135,12 +142,36 @@ export function DataTableToolbar<TData, TValue>({
);
const capture = usePostHogClientCapture();
+ const { open: controlsPanelOpen, setOpen: setControlsPanelOpen } =
+ useDataTableControls();
+ // Only show the toggle button when we're using the new sidebar
+ const hasNewSidebar = !filterColumnDefinition && filterState !== undefined;
return (
<div className={cn("grid h-fit w-full gap-0 px-2", className)}>
<div className="my-2 flex flex-wrap items-center gap-2 @container">
+ {hasNewSidebar && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setControlsPanelOpen(!controlsPanelOpen)}
+ className="flex h-8 items-center gap-2 text-sm"
+ >
+ {controlsPanelOpen ? (
+ <PanelLeftClose className="h-4 w-4" />
+ ) : (
+ <PanelLeftOpen className="h-4 w-4" />
+ )}
+ <span>{controlsPanelOpen ? "Hide" : "Show"} filters</span>
+ {filterState && filterState.length > 0 && (
+ <Badge variant="secondary" className="ml-1 h-5 px-1.5 text-xs">
+ {filterState.length}
+ </Badge>
+ )}
+ </Button>
+ )}
{searchConfig && (
- <div className="flex min-w-0 max-w-64 flex-shrink-0 items-stretch">
+ <div className="flex max-w-[30rem] flex-shrink-0 items-stretch md:min-w-[24rem]">
<div
className={cn(
"flex h-8 flex-1 items-center border border-input bg-background pl-2",
@@ -265,7 +296,7 @@ export function DataTableToolbar<TData, TValue>({
/>
)}
{environmentFilter && (
- <MultiSelect
+ <MultiSelectFilter
title="Environment"
label="Env"
values={environmentFilter.values}
diff --git a/web/src/components/table/key-value-filter-builder.tsx b/web/src/components/table/key-value-filter-builder.tsx
new file mode 100644
index 0000000000..1b02169dd3
--- /dev/null
+++ b/web/src/components/table/key-value-filter-builder.tsx
@@ -0,0 +1,412 @@
+import { useState, useEffect } from "react";
+import { Button } from "@/src/components/ui/button";
+import { Input } from "@/src/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import {
+ InputCommand,
+ InputCommandEmpty,
+ InputCommandGroup,
+ InputCommandInput,
+ InputCommandItem,
+ InputCommandList,
+} from "@/src/components/ui/input-command";
+import { MultiSelect } from "@/src/features/filters/components/multi-select";
+import { Plus, X, Check, ChevronDown } from "lucide-react";
+import { cn } from "@/src/utils/tailwind";
+import type {
+ KeyValueFilterEntry,
+ NumericKeyValueFilterEntry,
+ StringKeyValueFilterEntry,
+} from "@/src/features/filters/hooks/useSidebarFilterState";
+
+type KeyValueFilterBuilderProps =
+ | {
+ mode: "categorical";
+ keyOptions?: string[];
+ availableValues: Record<string, string[]>;
+ activeFilters: KeyValueFilterEntry[];
+ onChange: (filters: KeyValueFilterEntry[]) => void;
+ }
+ | {
+ mode: "numeric";
+ keyOptions?: string[];
+ activeFilters: NumericKeyValueFilterEntry[];
+ onChange: (filters: NumericKeyValueFilterEntry[]) => void;
+ }
+ | {
+ mode: "string";
+ keyOptions?: string[];
+ activeFilters: StringKeyValueFilterEntry[];
+ onChange: (filters: StringKeyValueFilterEntry[]) => void;
+ };
+
+// Map operators to human-readable labels
+const NUMERIC_OPERATOR_LABELS = {
+ "=": "equals",
+ ">": "greater than",
+ "<": "less than",
+ ">=": "greater than or equals",
+ "<=": "less than or equals",
+} as const;
+
+const STRING_OPERATOR_LABELS = {
+ "=": "equals",
+ contains: "contains",
+ "does not contain": "does not contain",
+} as const;
+
+export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
+ const { mode, keyOptions, activeFilters, onChange } = props;
+ const availableValues = mode === "categorical" ? props.availableValues : {};
+
+ // Local UI state for filter rows (includes incomplete filters)
+ const [localFilters, setLocalFilters] = useState<
+ | KeyValueFilterEntry[]
+ | NumericKeyValueFilterEntry[]
+ | StringKeyValueFilterEntry[]
+ >([]);
+
+ // Track which popover is open (by index)
+ const [openPopoverIndex, setOpenPopoverIndex] = useState<number | null>(null);
+
+ // Initialize from activeFilters (which only has complete filters)
+ useEffect(() => {
+ setLocalFilters(activeFilters.length > 0 ? activeFilters : []);
+ }, [activeFilters]);
+
+ const handleFilterChange = (
+ index: number,
+ updates:
+ | Partial<KeyValueFilterEntry>
+ | Partial<NumericKeyValueFilterEntry>
+ | Partial<StringKeyValueFilterEntry>,
+ ) => {
+ // TypeScript can't narrow the union array type automatically, so we narrow explicitly based on mode
+ if (mode === "categorical") {
+ const filters = localFilters as KeyValueFilterEntry[];
+ const newFilters = [...filters];
+ newFilters[index] = {
+ ...newFilters[index],
+ ...updates,
+ } as KeyValueFilterEntry;
+ setLocalFilters(newFilters);
+ (onChange as (filters: KeyValueFilterEntry[]) => void)(newFilters);
+ } else if (mode === "numeric") {
+ const filters = localFilters as NumericKeyValueFilterEntry[];
+ const newFilters = [...filters];
+ newFilters[index] = {
+ ...newFilters[index],
+ ...updates,
+ } as NumericKeyValueFilterEntry;
+ setLocalFilters(newFilters);
+ (onChange as (filters: NumericKeyValueFilterEntry[]) => void)(newFilters);
+ } else {
+ const filters = localFilters as StringKeyValueFilterEntry[];
+ const newFilters = [...filters];
+ newFilters[index] = {
+ ...newFilters[index],
+ ...updates,
+ } as StringKeyValueFilterEntry;
+ setLocalFilters(newFilters);
+ (onChange as (filters: StringKeyValueFilterEntry[]) => void)(newFilters);
+ }
+ };
+
+ const handleAddFilter = () => {
+ if (mode === "categorical") {
+ const newFilter: KeyValueFilterEntry = {
+ key: "",
+ operator: "any of" as const,
+ value: [],
+ };
+ const filters = localFilters as KeyValueFilterEntry[];
+ const newFilters = [...filters, newFilter];
+ setLocalFilters(newFilters);
+ } else if (mode === "numeric") {
+ const newFilter: NumericKeyValueFilterEntry = {
+ key: "",
+ operator: "=" as const,
+ value: "",
+ };
+ const filters = localFilters as NumericKeyValueFilterEntry[];
+ const newFilters = [...filters, newFilter];
+ setLocalFilters(newFilters);
+ } else {
+ const newFilter: StringKeyValueFilterEntry = {
+ key: "",
+ operator: "=" as const,
+ value: "",
+ };
+ const filters = localFilters as StringKeyValueFilterEntry[];
+ const newFilters = [...filters, newFilter];
+ setLocalFilters(newFilters);
+ }
+ };
+
+ const handleRemoveFilter = (index: number) => {
+ if (mode === "categorical") {
+ const filters = localFilters as KeyValueFilterEntry[];
+ const newFilters = filters.filter((_, i) => i !== index);
+ setLocalFilters(newFilters);
+ (onChange as (filters: KeyValueFilterEntry[]) => void)(newFilters);
+ } else if (mode === "numeric") {
+ const filters = localFilters as NumericKeyValueFilterEntry[];
+ const newFilters = filters.filter((_, i) => i !== index);
+ setLocalFilters(newFilters);
+ (onChange as (filters: NumericKeyValueFilterEntry[]) => void)(newFilters);
+ } else {
+ const filters = localFilters as StringKeyValueFilterEntry[];
+ const newFilters = filters.filter((_, i) => i !== index);
+ setLocalFilters(newFilters);
+ (onChange as (filters: StringKeyValueFilterEntry[]) => void)(newFilters);
+ }
+ };
+
+ return (
+ <div className="flex flex-col gap-4 px-4 py-1">
+ {/* Filter rows */}
+ {localFilters.map((filter, index) => {
+ const availableValuesForKey = filter.key
+ ? (availableValues[filter.key] ?? [])
+ : [];
+
+ return (
+ <div
+ key={index}
+ className="flex flex-col gap-2 border-b pb-3 last:border-b-0 last:pb-0"
+ >
+ {/* Key input and delete button row */}
+ <div className="flex items-center gap-2">
+ {keyOptions ? (
+ // Combobox for known keys
+ <Popover
+ open={openPopoverIndex === index}
+ onOpenChange={(open) =>
+ setOpenPopoverIndex(open ? index : null)
+ }
+ >
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ className="flex-1 justify-between text-left font-normal"
+ >
+ <span
+ className={cn(!filter.key && "text-muted-foreground")}
+ >
+ {filter.key || "Key"}
+ </span>
+ <ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[200px] p-0" align="start">
+ <InputCommand>
+ <InputCommandInput placeholder="Search keys..." />
+ <InputCommandList>
+ <InputCommandEmpty>No keys found.</InputCommandEmpty>
+ <InputCommandGroup>
+ {keyOptions.map((option) => (
+ <InputCommandItem
+ key={option}
+ value={option}
+ onSelect={(value) => {
+ if (mode === "categorical") {
+ handleFilterChange(index, {
+ key: value,
+ value: [],
+ });
+ } else {
+ handleFilterChange(index, {
+ key: value,
+ value: "",
+ });
+ }
+ setOpenPopoverIndex(null); // Close after selection
+ }}
+ >
+ <Check
+ className={cn(
+ "mr-2 h-4 w-4",
+ option === filter.key
+ ? "visible"
+ : "invisible",
+ )}
+ />
+ {option}
+ </InputCommandItem>
+ ))}
+ </InputCommandGroup>
+ </InputCommandList>
+ </InputCommand>
+ </PopoverContent>
+ </Popover>
+ ) : (
+ // Text input for free-form keys
+ <Input
+ placeholder="Key"
+ value={filter.key}
+ onChange={(e) => {
+ if (mode === "categorical") {
+ handleFilterChange(index, {
+ key: e.target.value,
+ value: [],
+ });
+ } else {
+ handleFilterChange(index, {
+ key: e.target.value,
+ value: "",
+ });
+ }
+ }}
+ className="flex-1"
+ />
+ )}
+
+ {/* Delete button */}
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => handleRemoveFilter(index)}
+ className="h-8 w-8 p-0"
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
+
+ {mode === "categorical" ? (
+ <>
+ {/* Operator select */}
+ <Select
+ value={filter.operator}
+ onValueChange={(value) =>
+ handleFilterChange(index, {
+ operator: value as "any of" | "none of",
+ })
+ }
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="any of">any of</SelectItem>
+ <SelectItem value="none of">none of</SelectItem>
+ </SelectContent>
+ </Select>
+
+ {/* Values multi-select */}
+ <MultiSelect
+ title="Values"
+ options={availableValuesForKey.map((v) => ({ value: v }))}
+ values={filter.value as string[]}
+ onValueChange={(values) =>
+ handleFilterChange(index, { value: values })
+ }
+ disabled={!filter.key}
+ />
+ </>
+ ) : mode === "numeric" ? (
+ <>
+ {/* Numeric operator select */}
+ <Select
+ value={filter.operator}
+ onValueChange={(value) =>
+ handleFilterChange(index, {
+ operator: value as "=" | ">" | "<" | ">=" | "<=",
+ })
+ }
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {Object.entries(NUMERIC_OPERATOR_LABELS).map(
+ ([op, label]) => (
+ <SelectItem key={op} value={op}>
+ {label}
+ </SelectItem>
+ ),
+ )}
+ </SelectContent>
+ </Select>
+
+ {/* Numeric value input */}
+ <Input
+ type="number"
+ placeholder="Value"
+ value={filter.value}
+ onChange={(e) =>
+ handleFilterChange(index, {
+ value:
+ e.target.value === "" ? "" : parseFloat(e.target.value),
+ })
+ }
+ disabled={!filter.key}
+ />
+ </>
+ ) : (
+ <>
+ {/* String operator select */}
+ <Select
+ value={filter.operator}
+ onValueChange={(value) =>
+ handleFilterChange(index, {
+ operator: value as "=" | "contains" | "does not contain",
+ })
+ }
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {Object.entries(STRING_OPERATOR_LABELS).map(
+ ([op, label]) => (
+ <SelectItem key={op} value={op}>
+ {label}
+ </SelectItem>
+ ),
+ )}
+ </SelectContent>
+ </Select>
+
+ {/* String value input */}
+ <Input
+ type="text"
+ placeholder="Value"
+ value={filter.value as string}
+ onChange={(e) =>
+ handleFilterChange(index, {
+ value: e.target.value,
+ })
+ }
+ disabled={!filter.key}
+ />
+ </>
+ )}
+ </div>
+ );
+ })}
+
+ {/* Add filter button */}
+ <Button
+ onClick={handleAddFilter}
+ size="sm"
+ variant="outline"
+ className="w-full"
+ >
+ <Plus className="mr-2 h-4 w-4" />
+ Add filter
+ </Button>
+ </div>
+ );
+}
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index 13de678c01..ca6f5726d5 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -1,10 +1,16 @@
import { api } from "@/src/utils/api";
import { DataTable } from "@/src/components/table/data-table";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
+import {
+ DataTableControlsProvider,
+ DataTableControls,
+} from "@/src/components/table/data-table-controls";
import { useEffect, useMemo, useState } from "react";
import { TokenUsageBadge } from "@/src/components/token-usage-badge";
import { NumberParam, useQueryParams, withDefault } from "use-query-params";
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";
+import { observationFilterConfig } from "@/src/features/filters/config/observations-config";
import { formatIntervalSeconds } from "@/src/utils/dates";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
import { type LangfuseColumnDef } from "@/src/components/table/types";
@@ -27,7 +33,6 @@ import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-
import { MemoizedIOTableCell } from "../../ui/IOTableCell";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
-import { useDebounce } from "@/src/hooks/useDebounce";
import { type ScoreAggregate } from "@langfuse/shared";
import TagList from "@/src/features/tag/components/TagList";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
@@ -246,15 +251,75 @@ export default function ObservationsTable({
const environmentOptions =
environmentFilterOptions.data?.map((value) => value.environment) || [];
- const { selectedEnvironments, setSelectedEnvironments } =
- useEnvironmentFilter(environmentOptions, projectId);
+ const { selectedEnvironments } = useEnvironmentFilter(
+ environmentOptions,
+ projectId,
+ );
const environmentFilter = convertSelectedEnvironmentsToFilter(
["environment"],
selectedEnvironments,
);
- const filterState = inputFilterState.concat(
+ const oldFilterState = inputFilterState.concat(
+ dateRangeFilter,
+ promptNameFilter,
+ promptVersionFilter,
+ modelIdFilter,
+ environmentFilter,
+ );
+
+ const startTimeFilter = oldFilterState.find((f) => f.column === "Start Time");
+ const filterOptions = api.generations.filterOptions.useQuery(
+ {
+ projectId,
+ startTimeFilter:
+ startTimeFilter?.type === "datetime" ? startTimeFilter : undefined,
+ },
+ {
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ staleTime: Infinity,
+ },
+ );
+
+ const newFilterOptions = useMemo(
+ () => ({
+ environment:
+ environmentFilterOptions.data?.map((value) => value.environment) || [],
+ name: filterOptions.data?.name?.map((n) => n.value) || [],
+ type: filterOptions.data?.type?.map((t) => t.value) || [],
+ traceName: filterOptions.data?.traceName?.map((tn) => tn.value) || [],
+ level: ["DEFAULT", "DEBUG", "WARNING", "ERROR"],
+ model: filterOptions.data?.model?.map((m) => m.value) || [],
+ modelId: filterOptions.data?.modelId?.map((mid) => mid.value) || [],
+ promptName: filterOptions.data?.promptName?.map((pn) => pn.value) || [],
+ tags: filterOptions.data?.tags?.map((t) => t.value) || [],
+ latency: [],
+ timeToFirstToken: [],
+ tokensPerSecond: [],
+ inputTokens: [],
+ outputTokens: [],
+ totalTokens: [],
+ inputCost: [],
+ outputCost: [],
+ totalCost: [],
+ }),
+ [environmentFilterOptions.data, filterOptions.data],
+ );
+
+ const queryFilter = useSidebarFilterState(
+ observationFilterConfig,
+ newFilterOptions,
+ );
+
+ const filterState = queryFilter.filterState.concat(
dateRangeFilter,
promptNameFilter,
promptVersionFilter,
@@ -288,26 +353,6 @@ export default function ObservationsTable({
const totalCount = totalCountQuery.data?.totalCount ?? null;
- const startTimeFilter = filterState.find((f) => f.column === "Start Time");
- const filterOptions = api.generations.filterOptions.useQuery(
- {
- projectId,
- startTimeFilter:
- startTimeFilter?.type === "datetime" ? startTimeFilter : undefined,
- },
- {
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- staleTime: Infinity,
- },
- );
-
const addToQueueMutation = api.annotationQueueItems.createMany.useMutation({
onSuccess: (data) => {
showSuccessToast({
@@ -1062,141 +1107,145 @@ export default function ObservationsTable({
}, [generations]);
return (
- <>
- <DataTableToolbar
- columns={columns}
- filterColumnDefinition={transformFilterOptions(filterOptions.data)}
- filterState={inputFilterState}
- setFilterState={useDebounce(setInputFilterState)}
- searchConfig={{
- metadataSearchFields: ["ID", "Name", "Trace Name", "Model"],
- updateQuery: setSearchQuery,
- currentQuery: searchQuery ?? undefined,
- searchType,
- setSearchType,
- tableAllowsFullTextSearch: true,
- }}
- viewConfig={{
- tableName: TableViewPresetTableName.Observations,
- projectId,
- controllers: viewControllers,
- }}
- columnsWithCustomSelect={["model", "name", "traceName", "promptName"]}
- columnVisibility={columnVisibility}
- setColumnVisibility={setColumnVisibilityState}
- columnOrder={columnOrder}
- setColumnOrder={setColumnOrder}
- orderByState={orderByState}
- rowHeight={rowHeight}
- setRowHeight={setRowHeight}
- timeRange={timeRange}
- setTimeRange={setTimeRange}
- actionButtons={[
- <BatchExportTableButton
- {...{
- projectId,
- filterState,
- orderByState,
- searchQuery,
- searchType,
- }}
- tableName={BatchExportTableName.Observations}
- key="batchExport"
- />,
- Object.keys(selectedRows).filter((generationId) =>
- generations.data?.generations
- .map((g) => g.id)
- .includes(generationId),
- ).length > 0 ? (
- <TableActionMenu
- key="observations-multi-select-actions"
- projectId={projectId}
- actions={tableActions}
+ <DataTableControlsProvider>
+ <div className="flex h-full w-full flex-col">
+ {/* Toolbar spanning full width */}
+ <DataTableToolbar
+ columns={columns}
+ filterState={queryFilter.filterState}
+ searchConfig={{
+ metadataSearchFields: ["ID", "Name", "Trace Name", "Model"],
+ updateQuery: setSearchQuery,
+ currentQuery: searchQuery ?? undefined,
+ searchType,
+ setSearchType,
+ tableAllowsFullTextSearch: true,
+ }}
+ viewConfig={{
+ tableName: TableViewPresetTableName.Observations,
+ projectId,
+ controllers: viewControllers,
+ }}
+ columnsWithCustomSelect={["model", "name", "traceName", "promptName"]}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibilityState}
+ columnOrder={columnOrder}
+ setColumnOrder={setColumnOrder}
+ orderByState={orderByState}
+ rowHeight={rowHeight}
+ setRowHeight={setRowHeight}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
+ actionButtons={[
+ <BatchExportTableButton
+ {...{
+ projectId,
+ filterState,
+ orderByState,
+ searchQuery,
+ searchType,
+ }}
tableName={BatchExportTableName.Observations}
- />
- ) : null,
- ]}
- environmentFilter={{
- values: selectedEnvironments,
- onValueChange: setSelectedEnvironments,
- options: environmentOptions.map((env) => ({ value: env })),
- }}
- multiSelect={{
- selectAll,
- setSelectAll,
- selectedRowIds: Object.keys(selectedRows).filter((generationId) =>
- generations.data?.generations
- .map((g) => g.id)
- .includes(generationId),
- ),
- setRowSelection: setSelectedRows,
- totalCount,
- ...paginationState,
- }}
- />
- <DataTable
- tableName={"observations"}
- columns={columns}
- peekView={peekConfig}
- data={
- generations.isPending || isViewLoading
- ? { isLoading: true, isError: false }
- : generations.error
- ? {
- isLoading: false,
- isError: true,
- error: generations.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: rows,
- }
- }
- pagination={{
- totalCount,
- onChange: setPaginationState,
- state: paginationState,
- }}
- rowSelection={selectedRows}
- setRowSelection={setSelectedRows}
- setOrderBy={setOrderByState}
- orderBy={orderByState}
- columnOrder={columnOrder}
- onColumnOrderChange={setColumnOrder}
- columnVisibility={columnVisibility}
- onColumnVisibilityChange={setColumnVisibilityState}
- rowHeight={rowHeight}
- onRowClick={(row, event) => {
- // Handle Command/Ctrl+click to open observation in new tab
- if (event && (event.metaKey || event.ctrlKey)) {
- // Prevent the default peek behavior
- event.preventDefault();
-
- // Construct the observation URL directly to avoid race conditions
- const observationId = row.id;
- const traceId = row.traceId;
- const timestamp = row.timestamp;
+ key="batchExport"
+ />,
+ Object.keys(selectedRows).filter((generationId) =>
+ generations.data?.generations
+ .map((g) => g.id)
+ .includes(generationId),
+ ).length > 0 ? (
+ <TableActionMenu
+ key="observations-multi-select-actions"
+ projectId={projectId}
+ actions={tableActions}
+ tableName={BatchExportTableName.Observations}
+ />
+ ) : null,
+ ]}
+ multiSelect={{
+ selectAll,
+ setSelectAll,
+ selectedRowIds: Object.keys(selectedRows).filter((generationId) =>
+ generations.data?.generations
+ .map((g) => g.id)
+ .includes(generationId),
+ ),
+ setRowSelection: setSelectedRows,
+ totalCount,
+ ...paginationState,
+ }}
+ />
- if (traceId) {
- let observationUrl = `/project/${projectId}/traces/${encodeURIComponent(traceId)}`;
+ {/* Content area with sidebar and table */}
+ <div className="flex flex-1 overflow-hidden">
+ <DataTableControls queryFilter={queryFilter} />
- const params = new URLSearchParams();
- params.set("observation", observationId);
- if (timestamp) {
- params.set("timestamp", timestamp.toISOString());
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <DataTable
+ tableName={"observations"}
+ columns={columns}
+ peekView={peekConfig}
+ data={
+ generations.isPending || isViewLoading
+ ? { isLoading: true, isError: false }
+ : generations.error
+ ? {
+ isLoading: false,
+ isError: true,
+ error: generations.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: rows,
+ }
}
+ pagination={{
+ totalCount,
+ onChange: setPaginationState,
+ state: paginationState,
+ }}
+ rowSelection={selectedRows}
+ setRowSelection={setSelectedRows}
+ setOrderBy={setOrderByState}
+ orderBy={orderByState}
+ columnOrder={columnOrder}
+ onColumnOrderChange={setColumnOrder}
+ columnVisibility={columnVisibility}
+ onColumnVisibilityChange={setColumnVisibilityState}
+ rowHeight={rowHeight}
+ onRowClick={(row, event) => {
+ // Handle Command/Ctrl+click to open observation in new tab
+ if (event && (event.metaKey || event.ctrlKey)) {
+ // Prevent the default peek behavior
+ event.preventDefault();
+
+ // Construct the observation URL directly to avoid race conditions
+ const observationId = row.id;
+ const traceId = row.traceId;
+ const timestamp = row.timestamp;
+
+ if (traceId) {
+ let observationUrl = `/project/${projectId}/traces/${encodeURIComponent(traceId)}`;
- observationUrl += `?${params.toString()}`;
+ const params = new URLSearchParams();
+ params.set("observation", observationId);
+ if (timestamp) {
+ params.set("timestamp", timestamp.toISOString());
+ }
- const fullUrl = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${observationUrl}`;
- window.open(fullUrl, "_blank");
- }
- }
- // For normal clicks, let the data-table handle opening the peek view
- }}
- />
- </>
+ observationUrl += `?${params.toString()}`;
+
+ const fullUrl = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${observationUrl}`;
+ window.open(fullUrl, "_blank");
+ }
+ }
+ // For normal clicks, let the data-table handle opening the peek view
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ </DataTableControlsProvider>
);
}
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index 7935519d1c..645d86be80 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -1,15 +1,20 @@
import { DataTable } from "@/src/components/table/data-table";
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
+import {
+ DataTableControlsProvider,
+ DataTableControls,
+} from "@/src/components/table/data-table-controls";
import TableLink from "@/src/components/table/table-link";
import { type LangfuseColumnDef } from "@/src/components/table/types";
import { IOTableCell } from "../../ui/IOTableCell";
import { Avatar, AvatarImage } from "@/src/components/ui/avatar";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";
+import { scoreFilterConfig } from "@/src/features/filters/config/scores-config";
import { isNumericDataType } from "@/src/features/scores/lib/helpers";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
-import { useDebounce } from "@/src/hooks/useDebounce";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
import {
@@ -167,8 +172,10 @@ export default function ScoresTable({
const environmentOptions =
environmentFilterOptions.data?.map((value) => value.environment) || [];
- const { selectedEnvironments, setSelectedEnvironments } =
- useEnvironmentFilter(environmentOptions, projectId);
+ const { selectedEnvironments } = useEnvironmentFilter(
+ environmentOptions,
+ projectId,
+ );
const environmentFilter = convertSelectedEnvironmentsToFilter(
["environment"],
@@ -263,6 +270,21 @@ export default function ScoresTable({
},
);
+ const newFilterOptions = React.useMemo(
+ () => ({
+ name: filterOptions.data?.name?.map((n) => n.value) || [],
+ source: ["ANNOTATION", "API", "EVAL"],
+ dataType: ["NUMERIC", "CATEGORICAL", "BOOLEAN"],
+ value: [],
+ }),
+ [filterOptions.data],
+ );
+
+ const queryFilter = useSidebarFilterState(
+ scoreFilterConfig,
+ newFilterOptions,
+ );
+
const { selectActionColumn } = TableSelectionManager<ScoresTableRow>({
projectId,
tableName: "scores",
@@ -646,92 +668,96 @@ export default function ScoresTable({
});
return (
- <>
- <DataTableToolbar
- columns={columns}
- filterColumnDefinition={transformFilterOptions(filterOptions.data)}
- filterState={userFilterState}
- setFilterState={useDebounce(setUserFilterState)}
- columnVisibility={columnVisibility}
- setColumnVisibility={setColumnVisibility}
- columnOrder={columnOrder}
- setColumnOrder={setColumnOrder}
- viewConfig={{
- tableName: TableViewPresetTableName.Scores,
- projectId,
- controllers: viewControllers,
- }}
- actionButtons={[
- Object.keys(selectedRows).filter((scoreId) =>
- scores.data?.scores.map((s) => s.id).includes(scoreId),
- ).length > 0 ? (
- <TableActionMenu
- key="scores-multi-select-actions"
- projectId={projectId}
- actions={tableActions}
+ <DataTableControlsProvider>
+ <div className="flex h-full w-full flex-col">
+ {/* Toolbar spanning full width */}
+ <DataTableToolbar
+ columns={columns}
+ filterState={queryFilter.filterState}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibility}
+ columnOrder={columnOrder}
+ setColumnOrder={setColumnOrder}
+ viewConfig={{
+ tableName: TableViewPresetTableName.Scores,
+ projectId,
+ controllers: viewControllers,
+ }}
+ actionButtons={[
+ Object.keys(selectedRows).filter((scoreId) =>
+ scores.data?.scores.map((s) => s.id).includes(scoreId),
+ ).length > 0 ? (
+ <TableActionMenu
+ key="scores-multi-select-actions"
+ projectId={projectId}
+ actions={tableActions}
+ tableName={BatchExportTableName.Scores}
+ />
+ ) : null,
+ <BatchExportTableButton
+ {...{ projectId, filterState, orderByState }}
tableName={BatchExportTableName.Scores}
+ key="batchExport"
+ />,
+ ]}
+ rowHeight={rowHeight}
+ setRowHeight={setRowHeight}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
+ multiSelect={{
+ selectAll,
+ setSelectAll,
+ selectedRowIds: Object.keys(selectedRows).filter((scoreId) =>
+ scores.data?.scores.map((s) => s.id).includes(scoreId),
+ ),
+ setRowSelection: setSelectedRows,
+ totalCount,
+ ...paginationState,
+ }}
+ />
+
+ {/* Content area with sidebar and table */}
+ <div className="flex flex-1 overflow-hidden">
+ <DataTableControls queryFilter={queryFilter} />
+
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <DataTable
+ tableName={"scores"}
+ columns={columns}
+ data={
+ scores.isPending || isViewLoading
+ ? { isLoading: true, isError: false }
+ : scores.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: scores.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: scores.data?.scores.map(convertToTableRow) ?? [],
+ }
+ }
+ pagination={{
+ totalCount,
+ onChange: setPaginationState,
+ state: paginationState,
+ }}
+ setOrderBy={setOrderByState}
+ orderBy={orderByState}
+ rowSelection={selectedRows}
+ setRowSelection={setSelectedRows}
+ columnVisibility={columnVisibility}
+ onColumnVisibilityChange={setColumnVisibility}
+ columnOrder={columnOrder}
+ onColumnOrderChange={setColumnOrder}
+ rowHeight={rowHeight}
/>
- ) : null,
- <BatchExportTableButton
- {...{ projectId, filterState, orderByState }}
- tableName={BatchExportTableName.Scores}
- key="batchExport"
- />,
- ]}
- rowHeight={rowHeight}
- setRowHeight={setRowHeight}
- timeRange={timeRange}
- setTimeRange={setTimeRange}
- multiSelect={{
- selectAll,
- setSelectAll,
- selectedRowIds: Object.keys(selectedRows).filter((scoreId) =>
- scores.data?.scores.map((s) => s.id).includes(scoreId),
- ),
- setRowSelection: setSelectedRows,
- totalCount,
- ...paginationState,
- }}
- environmentFilter={{
- values: selectedEnvironments,
- onValueChange: setSelectedEnvironments,
- options: environmentOptions.map((env) => ({ value: env })),
- }}
- />
- <DataTable
- tableName={"scores"}
- columns={columns}
- data={
- scores.isPending || isViewLoading
- ? { isLoading: true, isError: false }
- : scores.isError
- ? {
- isLoading: false,
- isError: true,
- error: scores.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: scores.data?.scores.map(convertToTableRow) ?? [],
- }
- }
- pagination={{
- totalCount,
- onChange: setPaginationState,
- state: paginationState,
- }}
- setOrderBy={setOrderByState}
- orderBy={orderByState}
- rowSelection={selectedRows}
- setRowSelection={setSelectedRows}
- columnVisibility={columnVisibility}
- onColumnVisibilityChange={setColumnVisibility}
- columnOrder={columnOrder}
- onColumnOrderChange={setColumnOrder}
- rowHeight={rowHeight}
- />
- </>
+ </div>
+ </div>
+ </div>
+ </DataTableControlsProvider>
);
}
diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsx
index 30851ece00..17fb6a16f3 100644
--- a/web/src/components/table/use-cases/sessions.tsx
+++ b/web/src/components/table/use-cases/sessions.tsx
@@ -1,11 +1,17 @@
import { StarSessionToggle } from "@/src/components/star-toggle";
import { DataTable } from "@/src/components/table/data-table";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
+import {
+ DataTableControlsProvider,
+ DataTableControls,
+} from "@/src/components/table/data-table-controls";
import TableLink from "@/src/components/table/table-link";
import { type LangfuseColumnDef } from "@/src/components/table/types";
import { TokenUsageBadge } from "@/src/components/token-usage-badge";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";
+import { sessionFilterConfig } from "@/src/features/filters/config/sessions-config";
import {
type FilterState,
sessionsTableColsWithOptions,
@@ -25,7 +31,6 @@ import { useEffect, useState, useMemo } from "react";
import { NumberParam, useQueryParams, withDefault } from "use-query-params";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
-import { useDebounce } from "@/src/hooks/useDebounce";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
import { Skeleton } from "@/src/components/ui/skeleton";
import TagList from "@/src/features/tag/components/TagList";
@@ -143,8 +148,10 @@ export default function SessionsTable({
const environmentOptions =
environmentFilterOptions.data?.map((value) => value.environment) || [];
- const { selectedEnvironments, setSelectedEnvironments } =
- useEnvironmentFilter(environmentOptions, projectId);
+ const { selectedEnvironments } = useEnvironmentFilter(
+ environmentOptions,
+ projectId,
+ );
const environmentFilter = convertSelectedEnvironmentsToFilter(
["environment"],
@@ -254,6 +261,26 @@ export default function SessionsTable({
},
);
+ const newFilterOptions = useMemo(
+ () => ({
+ bookmarked: ["Bookmarked", "Not bookmarked"],
+ sessionDuration: [],
+ countTraces: [],
+ inputTokens: [],
+ outputTokens: [],
+ totalTokens: [],
+ inputCost: [],
+ outputCost: [],
+ totalCost: [],
+ }),
+ [],
+ );
+
+ const queryFilter = useSidebarFilterState(
+ sessionFilterConfig,
+ newFilterOptions,
+ );
+
const totalCount = sessionCountQuery.data?.totalCount ?? null;
useEffect(() => {
if (sessions.isSuccess) {
@@ -652,110 +679,116 @@ export default function SessionsTable({
});
return (
- <>
- <DataTableToolbar
- filterColumnDefinition={transformFilterOptions()}
- filterState={userFilterState}
- setFilterState={useDebounce(setUserFilterState)}
- actionButtons={[
- Object.keys(selectedRows).filter((sessionId) =>
- sessions.data?.sessions.map((s) => s.id).includes(sessionId),
- ).length > 0 ? (
- <TableActionMenu
- key="sessions-multi-select-actions"
- projectId={projectId}
- actions={tableActions}
- tableName={BatchExportTableName.Sessions}
+ <DataTableControlsProvider>
+ <div className="flex h-full w-full flex-col">
+ {/* Toolbar spanning full width */}
+ <DataTableToolbar
+ filterState={queryFilter.filterState}
+ actionButtons={[
+ Object.keys(selectedRows).filter((sessionId) =>
+ sessions.data?.sessions.map((s) => s.id).includes(sessionId),
+ ).length > 0 ? (
+ <TableActionMenu
+ key="sessions-multi-select-actions"
+ projectId={projectId}
+ actions={tableActions}
+ tableName={BatchExportTableName.Sessions}
+ />
+ ) : null,
+ ]}
+ columns={columns}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibility}
+ columnOrder={columnOrder}
+ setColumnOrder={setColumnOrder}
+ viewConfig={{
+ tableName: TableViewPresetTableName.Sessions,
+ projectId,
+ controllers: viewControllers,
+ }}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
+ columnsWithCustomSelect={["userIds"]}
+ rowHeight={rowHeight}
+ setRowHeight={setRowHeight}
+ multiSelect={{
+ selectAll,
+ setSelectAll,
+ selectedRowIds: Object.keys(selectedRows).filter((sessionId) =>
+ sessions.data?.sessions.map((s) => s.id).includes(sessionId),
+ ),
+ setRowSelection: setSelectedRows,
+ totalCount,
+ ...paginationState,
+ }}
+ />
+
+ {/* Content area with sidebar and table */}
+ <div className="flex flex-1 overflow-hidden">
+ <DataTableControls queryFilter={queryFilter} />
+
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <DataTable
+ tableName={"sessions"}
+ columns={columns}
+ data={
+ sessions.isPending || isViewLoading
+ ? { isLoading: true, isError: false }
+ : sessions.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: sessions.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: sessionRowData.rows?.map<SessionTableRow>(
+ (session) => {
+ return {
+ id: session.id,
+ createdAt: session.createdAt,
+ bookmarked: session.bookmarked,
+ userIds: session.userIds,
+ countTraces: session.countTraces,
+ sessionDuration: session.sessionDuration,
+ inputCost: session.inputCost,
+ outputCost: session.outputCost,
+ totalCost: session.totalCost,
+ inputTokens: session.promptTokens,
+ outputTokens: session.completionTokens,
+ totalTokens: session.totalTokens,
+ traceTags: session.traceTags,
+ environment: session.environment,
+ scores: session.scores,
+ };
+ },
+ ),
+ }
+ }
+ pagination={{
+ totalCount,
+ onChange: setPaginationState,
+ state: paginationState,
+ }}
+ setOrderBy={setOrderByState}
+ orderBy={orderByState}
+ columnVisibility={columnVisibility}
+ onColumnVisibilityChange={setColumnVisibility}
+ columnOrder={columnOrder}
+ onColumnOrderChange={setColumnOrder}
+ rowSelection={selectedRows}
+ setRowSelection={setSelectedRows}
+ help={{
+ description:
+ "A session is a collection of related traces, such as a conversation or thread. To begin, add a sessionId to the trace.",
+ href: "https://langfuse.com/docs/observability/features/sessions",
+ }}
+ rowHeight={rowHeight}
/>
- ) : null,
- ]}
- columns={columns}
- columnVisibility={columnVisibility}
- setColumnVisibility={setColumnVisibility}
- columnOrder={columnOrder}
- setColumnOrder={setColumnOrder}
- viewConfig={{
- tableName: TableViewPresetTableName.Sessions,
- projectId,
- controllers: viewControllers,
- }}
- timeRange={timeRange}
- setTimeRange={setTimeRange}
- columnsWithCustomSelect={["userIds"]}
- rowHeight={rowHeight}
- setRowHeight={setRowHeight}
- multiSelect={{
- selectAll,
- setSelectAll,
- selectedRowIds: Object.keys(selectedRows).filter((sessionId) =>
- sessions.data?.sessions.map((s) => s.id).includes(sessionId),
- ),
- setRowSelection: setSelectedRows,
- totalCount,
- ...paginationState,
- }}
- environmentFilter={{
- values: selectedEnvironments,
- onValueChange: setSelectedEnvironments,
- options: environmentOptions.map((env) => ({ value: env })),
- }}
- />
- <DataTable
- tableName={"sessions"}
- columns={columns}
- data={
- sessions.isPending || isViewLoading
- ? { isLoading: true, isError: false }
- : sessions.isError
- ? {
- isLoading: false,
- isError: true,
- error: sessions.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: sessionRowData.rows?.map<SessionTableRow>((session) => {
- return {
- id: session.id,
- createdAt: session.createdAt,
- bookmarked: session.bookmarked,
- userIds: session.userIds,
- countTraces: session.countTraces,
- sessionDuration: session.sessionDuration,
- inputCost: session.inputCost,
- outputCost: session.outputCost,
- totalCost: session.totalCost,
- inputTokens: session.promptTokens,
- outputTokens: session.completionTokens,
- totalTokens: session.totalTokens,
- traceTags: session.traceTags,
- environment: session.environment,
- scores: session.scores,
- };
- }),
- }
- }
- pagination={{
- totalCount,
- onChange: setPaginationState,
- state: paginationState,
- }}
- setOrderBy={setOrderByState}
- orderBy={orderByState}
- columnVisibility={columnVisibility}
- onColumnVisibilityChange={setColumnVisibility}
- columnOrder={columnOrder}
- onColumnOrderChange={setColumnOrder}
- rowSelection={selectedRows}
- setRowSelection={setSelectedRows}
- help={{
- description:
- "A session is a collection of related traces, such as a conversation or thread. To begin, add a sessionId to the trace.",
- href: "https://langfuse.com/docs/observability/features/sessions",
- }}
- rowHeight={rowHeight}
- />
- </>
+ </div>
+ </div>
+ </div>
+ </DataTableControlsProvider>
);
}
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index 9633df8bae..bf92c0faa9 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -1,12 +1,15 @@
import { StarTraceToggle } from "@/src/components/star-toggle";
import { DataTable } from "@/src/components/table/data-table";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
+import {
+ DataTableControlsProvider,
+ DataTableControls,
+} from "@/src/components/table/data-table-controls";
import { Badge } from "@/src/components/ui/badge";
import { type LangfuseColumnDef } from "@/src/components/table/types";
import { TagTracePopover } from "@/src/features/tag/components/TagTracePopver";
import { TokenUsageBadge } from "@/src/components/token-usage-badge";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
-import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
import { api } from "@/src/utils/api";
import { formatIntervalSeconds } from "@/src/utils/dates";
import { type RouterOutput } from "@/src/utils/types";
@@ -41,7 +44,6 @@ import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-
import { MemoizedIOTableCell } from "../../ui/IOTableCell";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
-import { useDebounce } from "@/src/hooks/useDebounce";
import { type ScoreAggregate } from "@langfuse/shared";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
import { Skeleton } from "@/src/components/ui/skeleton";
@@ -69,10 +71,8 @@ import {
} from "@/src/components/ui/dropdown-menu";
import { Button } from "@/src/components/ui/button";
import TableIdOrName from "@/src/components/table/table-id";
-import {
- useEnvironmentFilter,
- convertSelectedEnvironmentsToFilter,
-} from "@/src/hooks/use-environment-filter";
+import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";
+import { traceFilterConfig } from "@/src/features/filters/config/traces-config";
import { PeekViewTraceDetail } from "@/src/components/table/peek/peek-trace-detail";
import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";
@@ -80,7 +80,6 @@ import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextS
import { type TableDateRange } from "@/src/utils/date-range-utils";
import { useScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";
import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";
-import { useRouter } from "next/router";
export type TracesTableRow = {
// Shown by default
@@ -143,7 +142,6 @@ export default function TracesTable({
externalDateRange,
limitRows,
}: TracesTableProps) {
- const router = useRouter();
const utils = api.useUtils();
const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});
const { setDetailPageList } = useDetailPageLists();
@@ -157,12 +155,6 @@ export default function TracesTable({
const dateRange = externalDateRange ?? tableDateRange;
- const [userFilterState, setUserFilterState] = useQueryFilterState(
- [],
- "traces",
- projectId,
- );
-
const [orderByState, setOrderByState] = useOrderByState({
column: "timestamp",
order: "DESC",
@@ -214,21 +206,53 @@ export default function TracesTable({
},
);
- const environmentOptions =
- environmentFilterOptions.data?.map((value) => value.environment) || [];
+ const traceFilterOptionsResponse = api.traces.filterOptions.useQuery(
+ { projectId },
+ {
+ trpc: { context: { skipBatch: true } },
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ staleTime: Infinity,
+ },
+ );
+
+ const filterOptions = useMemo(() => {
+ const scoreCategories =
+ traceFilterOptionsResponse.data?.score_categories?.reduce(
+ (acc, score) => {
+ acc[score.label] = score.values;
+ return acc;
+ },
+ {} as Record<string, string[]>,
+ ) || {};
+
+ const scoresNumeric = traceFilterOptionsResponse.data?.scores_avg || [];
- const { selectedEnvironments, setSelectedEnvironments } =
- useEnvironmentFilter(environmentOptions, projectId);
+ return {
+ name: traceFilterOptionsResponse.data?.name?.map((n) => n.value) || [],
+ tags: traceFilterOptionsResponse.data?.tags?.map((t) => t.value) || [],
+ environment:
+ environmentFilterOptions.data?.map((value) => value.environment) || [],
+ level: ["DEFAULT", "DEBUG", "WARNING", "ERROR"],
+ bookmarked: ["Bookmarked", "Not bookmarked"],
+ latency: [],
+ inputTokens: [],
+ outputTokens: [],
+ totalTokens: [],
+ inputCost: [],
+ outputCost: [],
+ totalCost: [],
+ "Scores (categorical)": scoreCategories,
+ "Scores (numeric)": scoresNumeric,
+ };
+ }, [environmentFilterOptions.data, traceFilterOptionsResponse.data]);
- const environmentFilter = convertSelectedEnvironmentsToFilter(
- ["environment"],
- selectedEnvironments,
- );
+ const queryFilter = useSidebarFilterState(traceFilterConfig, filterOptions);
- const combinedFilterState = userFilterState.concat(
+ const combinedFilterState = queryFilter.filterState.concat(
userIdFilter,
dateRangeFilter,
- environmentFilter,
);
// Use external filter state if provided, otherwise use combined filter state
@@ -312,21 +336,23 @@ export default function TracesTable({
// traces.all should load first together with everything else.
// This here happens in the background.
- const traceFilterOptionsResponse = api.traces.filterOptions.useQuery(
- { projectId },
- {
- trpc: { context: { skipBatch: true } },
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- staleTime: Infinity,
- },
- );
-
const traceFilterOptions = traceFilterOptionsResponse.data;
const transformedFilterOptions = useMemo(() => {
- return tracesTableColsWithOptions(traceFilterOptions).filter(
+ // Normalize API response to match TraceOptions in shared package
+ const normalizedOptions = traceFilterOptions
+ ? {
+ name: traceFilterOptions.name?.map((n) => ({
+ value: n.value,
+ count: Number(n.count),
+ })),
+ scores_avg: traceFilterOptions.scores_avg,
+ score_categories: traceFilterOptions.score_categories,
+ tags: traceFilterOptions.tags?.map((t) => ({ value: t.value })),
+ }
+ : undefined;
+
+ return tracesTableColsWithOptions(normalizedOptions).filter(
(c) =>
c.id !== "environment" &&
c.id !== "timestamp" &&
@@ -1072,7 +1098,7 @@ export default function TracesTable({
projectId,
stateUpdaters: {
setOrderBy: setOrderByState,
- setFilters: setUserFilterState,
+ setFilters: queryFilter.setFilterState,
setColumnOrder: setColumnOrder,
setColumnVisibility: setColumnVisibility,
setSearchQuery: setSearchQuery,
@@ -1129,150 +1155,122 @@ export default function TracesTable({
: [];
}, [traces.isSuccess, traceRowData?.rows]);
- const setFilterState = useDebounce(setUserFilterState);
-
return (
- <>
- {!hideControls && (
- <DataTableToolbar
- columns={columns}
- filterWithAI
- viewConfig={{
- tableName: TableViewPresetTableName.Traces,
- projectId,
- controllers: viewControllers,
- }}
- filterColumnDefinition={transformedFilterOptions}
- searchConfig={{
- metadataSearchFields: ["ID", "Trace Name", "User ID"],
- updateQuery: setSearchQuery,
- currentQuery: searchQuery ?? undefined,
- tableAllowsFullTextSearch: true,
- setSearchType,
- searchType,
- }}
- filterState={userFilterState}
- setFilterState={setFilterState}
- columnsWithCustomSelect={["name", "tags"]}
- actionButtons={[
- Object.keys(selectedRows).filter((traceId) =>
- traces.data?.traces.map((t) => t.id).includes(traceId),
- ).length > 0 ? (
- <TableActionMenu
- key="traces-multi-select-actions"
- projectId={projectId}
- actions={tableActions}
+ <DataTableControlsProvider>
+ <div className="flex h-full w-full flex-col">
+ {/* Toolbar spanning full width */}
+ {!hideControls && (
+ <DataTableToolbar
+ columns={columns}
+ filterWithAI
+ filterState={queryFilter.filterState}
+ viewConfig={{
+ tableName: TableViewPresetTableName.Traces,
+ projectId,
+ controllers: viewControllers,
+ }}
+ searchConfig={{
+ metadataSearchFields: ["ID", "Trace Name", "User ID"],
+ updateQuery: setSearchQuery,
+ currentQuery: searchQuery ?? undefined,
+ tableAllowsFullTextSearch: true,
+ setSearchType,
+ searchType,
+ }}
+ columnsWithCustomSelect={["name", "tags"]}
+ actionButtons={[
+ Object.keys(selectedRows).filter((traceId) =>
+ traces.data?.traces.map((t) => t.id).includes(traceId),
+ ).length > 0 ? (
+ <TableActionMenu
+ key="traces-multi-select-actions"
+ projectId={projectId}
+ actions={tableActions}
+ tableName={BatchExportTableName.Traces}
+ />
+ ) : null,
+ <BatchExportTableButton
+ {...{
+ projectId,
+ filterState,
+ orderByState,
+ searchQuery,
+ searchType,
+ }}
tableName={BatchExportTableName.Traces}
- />
- ) : null,
- <BatchExportTableButton
- {...{
- projectId,
- filterState,
- orderByState,
- searchQuery,
- searchType,
- }}
- tableName={BatchExportTableName.Traces}
- key="batchExport"
- />,
- ]}
- orderByState={orderByState}
- columnVisibility={columnVisibility}
- setColumnVisibility={setColumnVisibility}
- columnOrder={columnOrder}
- setColumnOrder={setColumnOrder}
- rowHeight={rowHeight}
- setRowHeight={setRowHeight}
- timeRange={timeRange}
- setTimeRange={setTimeRange}
- multiSelect={{
- selectAll,
- setSelectAll,
- selectedRowIds: Object.keys(selectedRows).filter((traceId) =>
- traces.data?.traces.map((t) => t.id).includes(traceId),
- ),
- setRowSelection: setSelectedRows,
- totalCount,
- ...paginationState,
- }}
- environmentFilter={{
- values: selectedEnvironments,
- onValueChange: setSelectedEnvironments,
- options: environmentOptions.map((env) => ({ value: env })),
- }}
- />
- )}
- <DataTable
- columns={columns}
- hidePagination={hideControls}
- data={
- traces.isPending || isViewLoading
- ? { isLoading: true, isError: false }
- : traces.isError
- ? {
- isLoading: false,
- isError: true,
- error: traces.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: rows,
- }
- }
- pagination={
- limitRows
- ? undefined
- : {
- totalCount,
- onChange: setPaginationState,
- state: paginationState,
+ key="batchExport"
+ />,
+ ]}
+ orderByState={orderByState}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibility}
+ columnOrder={columnOrder}
+ setColumnOrder={setColumnOrder}
+ rowHeight={rowHeight}
+ setRowHeight={setRowHeight}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
+ multiSelect={{
+ selectAll,
+ setSelectAll,
+ selectedRowIds: Object.keys(selectedRows).filter((traceId) =>
+ traces.data?.traces.map((t) => t.id).includes(traceId),
+ ),
+ setRowSelection: setSelectedRows,
+ totalCount,
+ ...paginationState,
+ }}
+ />
+ )}
+
+ {/* Content area with sidebar and table */}
+ <div className="flex flex-1 overflow-hidden">
+ <DataTableControls queryFilter={queryFilter} filterWithAI />
+
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <DataTable
+ columns={columns}
+ hidePagination={hideControls}
+ data={
+ traces.isPending || isViewLoading
+ ? { isLoading: true, isError: false }
+ : traces.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: traces.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: rows,
+ }
}
- }
- setOrderBy={setOrderByState}
- orderBy={orderByState}
- rowSelection={selectedRows}
- setRowSelection={setSelectedRows}
- columnVisibility={columnVisibility}
- onColumnVisibilityChange={setColumnVisibility}
- columnOrder={columnOrder}
- onColumnOrderChange={setColumnOrder}
- rowHeight={rowHeight}
- peekView={peekConfig}
- onRowClick={(row, event) => {
- // Handle Command/Ctrl+click to open trace in new tab
- if (event && (event.metaKey || event.ctrlKey)) {
- // Prevent the default peek behavior
- event.preventDefault();
-
- // Construct the trace URL directly to avoid race conditions
- const traceId = row.id;
- const timestamp = row.timestamp;
- const display = router.query.display ?? "details";
-
- let traceUrl = `/project/${projectId}/traces/${encodeURIComponent(traceId)}`;
-
- const params = new URLSearchParams();
- if (timestamp) {
- params.set("timestamp", timestamp.toISOString());
- }
- if (display && typeof display === "string") {
- params.set("display", display);
- }
-
- if (params.toString()) {
- traceUrl += `?${params.toString()}`;
- }
-
- const fullUrl = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${traceUrl}`;
- window.open(fullUrl, "_blank");
- }
- // For normal clicks, let the data-table handle opening the peek view
- }}
- tableName={"traces"}
- />
- </>
+ pagination={
+ limitRows
+ ? undefined
+ : {
+ totalCount,
+ onChange: setPaginationState,
+ state: paginationState,
+ }
+ }
+ setOrderBy={setOrderByState}
+ orderBy={orderByState}
+ rowSelection={selectedRows}
+ setRowSelection={setSelectedRows}
+ columnVisibility={columnVisibility}
+ onColumnVisibilityChange={setColumnVisibility}
+ columnOrder={columnOrder}
+ onColumnOrderChange={setColumnOrder}
+ rowHeight={rowHeight}
+ peekView={peekConfig}
+ tableName={"traces"}
+ />
+ </div>
+ </div>
+ </div>
+ </DataTableControlsProvider>
);
}
diff --git a/web/src/components/ui/slider.tsx b/web/src/components/ui/slider.tsx
index 28f3de9a74..b0626b0c4d 100644
--- a/web/src/components/ui/slider.tsx
+++ b/web/src/components/ui/slider.tsx
@@ -82,6 +82,10 @@ const Slider = React.forwardRef<
}
};
+ const initialValue = Array.isArray(props.value)
+ ? props.value
+ : [props.min ?? 0, props.max ?? 100];
+
return (
<div className={cn("flex items-center gap-4", className)}>
<SliderPrimitive.Root
@@ -97,12 +101,15 @@ const Slider = React.forwardRef<
)}
/>
</SliderPrimitive.Track>
- <SliderPrimitive.Thumb
- className={cn(
- "block h-5 w-5 rounded-full border-2 bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
- props.disabled ? "border-secondary" : "border-primary",
- )}
- />
+ {initialValue.map((_, index) => (
+ <SliderPrimitive.Thumb
+ key={index}
+ className={cn(
+ "block h-4 w-4 rounded-full border-2 bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
+ props.disabled ? "border-secondary" : "border-primary",
+ )}
+ />
+ ))}
</SliderPrimitive.Root>
{showInput && (
diff --git a/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx b/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
index 8b3f2fb855..92fcd49442 100644
--- a/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
+++ b/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
@@ -40,7 +40,6 @@ function RunAggregateHeader({
onChange={(filters: FilterState) =>
debouncedUpdateRunFilters(runId, filters)
}
- variant="icon"
/>
</div>
);
diff --git a/web/src/features/evals/components/evaluator-table.tsx b/web/src/features/evals/components/evaluator-table.tsx
index d00688a1c4..e9cd7d14be 100644
--- a/web/src/features/evals/components/evaluator-table.tsx
+++ b/web/src/features/evals/components/evaluator-table.tsx
@@ -2,11 +2,17 @@ import { StatusBadge } from "@/src/components/layouts/status-badge";
import { LevelCountsDisplay } from "@/src/components/level-counts-display";
import { DataTable } from "@/src/components/table/data-table";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
+import {
+ DataTableControlsProvider,
+ DataTableControls,
+} from "@/src/components/table/data-table-controls";
import { type LangfuseColumnDef } from "@/src/components/table/types";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
import { InlineFilterState } from "@/src/features/filters/components/filter-builder";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";
+import { evaluatorFilterConfig } from "@/src/features/filters/config/evaluators-config";
import { type RouterOutputs, api } from "@/src/utils/api";
import { safeExtract } from "@/src/utils/map-utils";
import { type FilterState, singleFilter } from "@langfuse/shared";
@@ -44,7 +50,6 @@ import {
import { EvaluatorForm } from "@/src/features/evals/components/evaluator-form";
import { useRouter } from "next/router";
import { DeleteEvalConfigButton } from "@/src/components/deleteButton";
-import { evalConfigFilterColumns } from "@/src/server/api/definitions/evalConfigsTable";
import { RAGAS_TEMPLATE_PREFIX } from "@/src/features/evals/types";
import { MaintainerTooltip } from "@/src/features/evals/components/maintainer-tooltip";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
@@ -86,17 +91,23 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
const [editConfigId, setEditConfigId] = useState<string | null>(null);
const utils = api.useUtils();
- const [filterState, setFilterState] = useQueryFilterState(
- [],
- "eval_configs",
- projectId,
- );
+ const [filterState] = useQueryFilterState([], "eval_configs", projectId);
const [orderByState, setOrderByState] = useOrderByState({
column: "createdAt",
order: "DESC",
});
+ const newFilterOptions = {
+ status: ["ACTIVE", "INACTIVE"],
+ target: ["trace", "dataset"],
+ };
+
+ const queryFilter = useSidebarFilterState(
+ evaluatorFilterConfig,
+ newFilterOptions,
+ );
+
const evaluators = api.evals.allConfigs.useQuery({
page: paginationState.pageIndex,
limit: paginationState.pageSize,
@@ -353,109 +364,121 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
};
return (
- <>
- <DataTableToolbar
- columns={columns}
- filterColumnDefinition={evalConfigFilterColumns}
- filterState={filterState}
- setFilterState={setFilterState}
- columnVisibility={columnVisibility}
- setColumnVisibility={setColumnVisibility}
- searchConfig={{
- metadataSearchFields: ["Name"],
- updateQuery: setSearchQuery,
- currentQuery: searchQuery ?? undefined,
- tableAllowsFullTextSearch: false,
- setSearchType: undefined,
- searchType: undefined,
- }}
- />
- <DataTable
- tableName={"evalConfigs"}
- columns={columns}
- peekView={{
- itemType: "RUNNING_EVALUATOR",
- detailNavigationKey: "evals",
- peekEventOptions: {
- ignoredSelectors: [
- "[aria-label='edit'], [aria-label='actions'], [aria-label='view-logs'], [aria-label='delete']",
- ],
- },
- tableDataUpdatedAt: evaluators.dataUpdatedAt,
- children: <PeekViewEvaluatorConfigDetail projectId={projectId} />,
- ...peekNavigationProps,
- }}
- data={
- evaluators.isLoading
- ? { isLoading: true, isError: false }
- : evaluators.isError
- ? {
- isLoading: false,
- isError: true,
- error: evaluators.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: safeExtract(evaluators.data, "configs", []).map(
- (evaluator) => convertToTableRow(evaluator),
- ),
- }
- }
- pagination={{
- totalCount,
- onChange: setPaginationState,
- state: paginationState,
- }}
- orderBy={orderByState}
- setOrderBy={setOrderByState}
- columnVisibility={columnVisibility}
- onColumnVisibilityChange={setColumnVisibility}
- />
- <Dialog
- open={!!editConfigId && existingEvaluator.isSuccess}
- onOpenChange={(open) => {
- if (!open) setEditConfigId(null);
- }}
- >
- <DialogContent className="max-h-[90vh] max-w-screen-xl overflow-y-auto">
- <DialogHeader>
- <DialogTitle>Edit configuration</DialogTitle>
- </DialogHeader>
- {existingEvaluator.isLoading ? (
- <div className="flex items-center justify-center p-4">
- <Loader2 className="h-6 w-6 animate-spin" />
- </div>
- ) : (
- <EvaluatorForm
- projectId={projectId}
- evalTemplates={[]}
- existingEvaluator={
- existingEvaluator.data && existingEvaluator.data.evalTemplate
- ? {
- ...existingEvaluator.data,
- evalTemplate: {
- ...existingEvaluator.data.evalTemplate,
- },
- }
- : undefined
+ <DataTableControlsProvider>
+ <div className="flex h-full w-full flex-col">
+ {/* Toolbar spanning full width */}
+ <DataTableToolbar
+ columns={columns}
+ filterState={queryFilter.filterState}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibility}
+ searchConfig={{
+ metadataSearchFields: ["Name"],
+ updateQuery: setSearchQuery,
+ currentQuery: searchQuery ?? undefined,
+ tableAllowsFullTextSearch: false,
+ setSearchType: undefined,
+ searchType: undefined,
+ }}
+ />
+
+ {/* Content area with sidebar and table */}
+ <div className="flex flex-1 overflow-hidden">
+ <DataTableControls queryFilter={queryFilter} />
+
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <DataTable
+ tableName={"evalConfigs"}
+ columns={columns}
+ peekView={{
+ itemType: "RUNNING_EVALUATOR",
+ detailNavigationKey: "evals",
+ peekEventOptions: {
+ ignoredSelectors: [
+ "[aria-label='edit'], [aria-label='actions'], [aria-label='view-logs'], [aria-label='delete']",
+ ],
+ },
+ tableDataUpdatedAt: evaluators.dataUpdatedAt,
+ children: (
+ <PeekViewEvaluatorConfigDetail projectId={projectId} />
+ ),
+ ...peekNavigationProps,
+ }}
+ data={
+ evaluators.isLoading
+ ? { isLoading: true, isError: false }
+ : evaluators.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: evaluators.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: safeExtract(evaluators.data, "configs", []).map(
+ (evaluator) => convertToTableRow(evaluator),
+ ),
+ }
}
- shouldWrapVariables={true}
- useDialog={true}
- mode="edit"
- onFormSuccess={() => {
- setEditConfigId(null);
- void utils.evals.allConfigs.invalidate();
- showSuccessToast({
- title: "Evaluator updated successfully",
- description:
- "Changes will automatically be reflected future evaluator runs",
- });
+ pagination={{
+ totalCount,
+ onChange: setPaginationState,
+ state: paginationState,
}}
+ orderBy={orderByState}
+ setOrderBy={setOrderByState}
+ columnVisibility={columnVisibility}
+ onColumnVisibilityChange={setColumnVisibility}
/>
- )}
- </DialogContent>
- </Dialog>
- </>
+ <Dialog
+ open={!!editConfigId && existingEvaluator.isSuccess}
+ onOpenChange={(open) => {
+ if (!open) setEditConfigId(null);
+ }}
+ >
+ <DialogContent className="max-h-[90vh] max-w-screen-xl overflow-y-auto">
+ <DialogHeader>
+ <DialogTitle>Edit configuration</DialogTitle>
+ </DialogHeader>
+ {existingEvaluator.isLoading ? (
+ <div className="flex items-center justify-center p-4">
+ <Loader2 className="h-6 w-6 animate-spin" />
+ </div>
+ ) : (
+ <EvaluatorForm
+ projectId={projectId}
+ evalTemplates={[]}
+ existingEvaluator={
+ existingEvaluator.data &&
+ existingEvaluator.data.evalTemplate
+ ? {
+ ...existingEvaluator.data,
+ evalTemplate: {
+ ...existingEvaluator.data.evalTemplate,
+ },
+ }
+ : undefined
+ }
+ shouldWrapVariables={true}
+ useDialog={true}
+ mode="edit"
+ onFormSuccess={() => {
+ setEditConfigId(null);
+ void utils.evals.allConfigs.invalidate();
+ showSuccessToast({
+ title: "Evaluator updated successfully",
+ description:
+ "Changes will automatically be reflected future evaluator runs",
+ });
+ }}
+ />
+ )}
+ </DialogContent>
+ </Dialog>
+ </div>
+ </div>
+ </div>
+ </DataTableControlsProvider>
);
}
diff --git a/web/src/features/evals/components/inner-evaluator-form.tsx b/web/src/features/evals/components/inner-evaluator-form.tsx
index 4658bb191b..236a6ce209 100644
--- a/web/src/features/evals/components/inner-evaluator-form.tsx
+++ b/web/src/features/evals/components/inner-evaluator-form.tsx
@@ -215,8 +215,23 @@ export const InnerEvaluatorForm = (props: {
);
const traceFilterOptions = useMemo(() => {
+ // Normalize API response to match TraceOptions type (count should be number, not string)
+ const normalized = traceFilterOptionsResponse.data
+ ? {
+ name: traceFilterOptionsResponse.data.name?.map((n) => ({
+ value: n.value,
+ count: Number(n.count),
+ })),
+ scores_avg: traceFilterOptionsResponse.data.scores_avg,
+ score_categories: traceFilterOptionsResponse.data.score_categories,
+ tags: traceFilterOptionsResponse.data.tags?.map((t) => ({
+ value: t.value,
+ })),
+ }
+ : {};
+
return {
- ...(traceFilterOptionsResponse.data ?? {}),
+ ...normalized,
environment: environmentFilterOptionsResponse.data?.map((e) => ({
value: e.environment,
})),
diff --git a/web/src/features/filters/components/filter-builder.tsx b/web/src/features/filters/components/filter-builder.tsx
index e29402afab..8cc4e00bdc 100644
--- a/web/src/features/filters/components/filter-builder.tsx
+++ b/web/src/features/filters/components/filter-builder.tsx
@@ -16,7 +16,6 @@ import {
Check,
ChevronDown,
ExternalLink,
- Filter,
Info,
Plus,
WandSparkles,
@@ -63,7 +62,6 @@ export function PopoverFilterBuilder({
filterState,
onChange,
columnsWithCustomSelect = [],
- variant = "default",
filterWithAI = false,
}: {
columns: ColumnDefinition[];
@@ -72,7 +70,6 @@ export function PopoverFilterBuilder({
| Dispatch<SetStateAction<FilterState>>
| ((newState: FilterState) => void);
columnsWithCustomSelect?: string[];
- variant?: "default" | "icon";
filterWithAI?: boolean;
}) {
const capture = usePostHogClientCapture();
@@ -128,43 +125,27 @@ export function PopoverFilterBuilder({
}}
>
<PopoverTrigger asChild>
- {variant === "default" ? (
- <Button variant="outline" type="button">
- <span>Filters</span>
- {filterState.length > 0 && filterState.length < 3 ? (
- <InlineFilterState
- filterState={filterState}
- className="hidden @6xl:block"
- />
- ) : null}
- {filterState.length > 0 ? (
- <span
- className={cn(
- "ml-1.5 rounded-sm bg-input px-1 text-xs shadow-sm @6xl:hidden",
- filterState.length > 2 && "@6xl:inline",
- )}
- >
- {filterState.length}
- </span>
- ) : (
- <ChevronDown className="ml-1 h-4 w-4 opacity-50" />
- )}
- </Button>
- ) : (
- <Button
- variant="outline"
- type="button"
- size="icon"
- className="relative"
- >
- <Filter className="h-4 w-4" />
- {filterState.length > 0 && (
- <span className="absolute right-0.5 top-0.5 flex h-3 w-3 items-center justify-center rounded-sm bg-input text-xs shadow-sm">
- {filterState.length}
- </span>
- )}
- </Button>
- )}
+ <Button variant="outline" type="button">
+ <span>Filters</span>
+ {filterState.length > 0 && filterState.length < 3 ? (
+ <InlineFilterState
+ filterState={filterState}
+ className="hidden @6xl:block"
+ />
+ ) : null}
+ {filterState.length > 0 ? (
+ <span
+ className={cn(
+ "ml-1.5 rounded-sm bg-input px-1 text-xs shadow-sm @6xl:hidden",
+ filterState.length > 2 && "@6xl:inline",
+ )}
+ >
+ {filterState.length}
+ </span>
+ ) : (
+ <ChevronDown className="ml-1 h-4 w-4 opacity-50" />
+ )}
+ </Button>
</PopoverTrigger>
<PopoverContent
className="w-fit max-w-[90vw] overflow-x-auto"
diff --git a/web/src/features/filters/config/evaluators-config.ts b/web/src/features/filters/config/evaluators-config.ts
new file mode 100644
index 0000000000..b0810e57af
--- /dev/null
+++ b/web/src/features/filters/config/evaluators-config.ts
@@ -0,0 +1,31 @@
+import { evalConfigsTableCols } from "@/src/server/api/definitions/evalConfigsTable";
+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";
+import type { ColumnToQueryKeyMap } from "@/src/features/filters/lib/filter-query-encoding";
+
+const EVALUATOR_COLUMN_TO_QUERY_KEY: ColumnToQueryKeyMap = {
+ status: "status",
+ target: "target",
+};
+
+export const evaluatorFilterConfig: FilterConfig = {
+ tableName: "evaluators",
+
+ columnToQueryKey: EVALUATOR_COLUMN_TO_QUERY_KEY,
+
+ columnDefinitions: evalConfigsTableCols,
+
+ defaultExpanded: ["status"],
+
+ facets: [
+ {
+ type: "categorical" as const,
+ column: "status",
+ label: "Status",
+ },
+ {
+ type: "categorical" as const,
+ column: "target",
+ label: "Target",
+ },
+ ],
+};
diff --git a/web/src/features/filters/config/observations-config.ts b/web/src/features/filters/config/observations-config.ts
new file mode 100644
index 0000000000..3233016192
--- /dev/null
+++ b/web/src/features/filters/config/observations-config.ts
@@ -0,0 +1,143 @@
+import { observationsTableCols } from "@langfuse/shared";
+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";
+import type { ColumnToQueryKeyMap } from "@/src/features/filters/lib/filter-query-encoding";
+
+const OBSERVATION_COLUMN_TO_QUERY_KEY: ColumnToQueryKeyMap = {
+ environment: "env",
+ name: "name",
+ type: "type",
+ traceName: "traceName",
+ level: "level",
+ model: "model",
+ modelId: "modelId",
+ promptName: "promptName",
+ tags: "tags",
+ timeToFirstToken: "ttft",
+ latency: "latency",
+ tokensPerSecond: "tps",
+ inputCost: "inputCost",
+ outputCost: "outputCost",
+ totalCost: "totalCost",
+ inputTokens: "inputTokens",
+ outputTokens: "outputTokens",
+ totalTokens: "totalTokens",
+};
+
+export const observationFilterConfig: FilterConfig = {
+ tableName: "observations",
+
+ columnToQueryKey: OBSERVATION_COLUMN_TO_QUERY_KEY,
+
+ columnDefinitions: observationsTableCols,
+
+ defaultExpanded: ["environment", "name"],
+
+ facets: [
+ {
+ type: "categorical" as const,
+ column: "environment",
+ label: "Environment",
+ },
+ {
+ type: "categorical" as const,
+ column: "type",
+ label: "Type",
+ },
+ {
+ type: "categorical" as const,
+ column: "name",
+ label: "Name",
+ },
+ {
+ type: "categorical" as const,
+ column: "traceName",
+ label: "Trace Name",
+ },
+ {
+ type: "categorical" as const,
+ column: "level",
+ label: "Level",
+ },
+ {
+ type: "categorical" as const,
+ column: "model",
+ label: "Model",
+ },
+ {
+ type: "categorical" as const,
+ column: "modelId",
+ label: "Model ID",
+ },
+ {
+ type: "categorical" as const,
+ column: "promptName",
+ label: "Prompt Name",
+ },
+ {
+ type: "categorical" as const,
+ column: "tags",
+ label: "Trace Tags",
+ },
+ {
+ type: "numeric" as const,
+ column: "latency",
+ label: "Latency",
+ min: 0,
+ max: 60,
+ unit: "s",
+ },
+ {
+ type: "numeric" as const,
+ column: "timeToFirstToken",
+ label: "Time to First Token",
+ min: 0,
+ max: 60,
+ unit: "s",
+ },
+ {
+ type: "numeric" as const,
+ column: "inputTokens",
+ label: "Input Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "outputTokens",
+ label: "Output Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "totalTokens",
+ label: "Total Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "inputCost",
+ label: "Input Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ {
+ type: "numeric" as const,
+ column: "outputCost",
+ label: "Output Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ {
+ type: "numeric" as const,
+ column: "totalCost",
+ label: "Total Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ ],
+};
diff --git a/web/src/features/filters/config/prompts-config.ts b/web/src/features/filters/config/prompts-config.ts
new file mode 100644
index 0000000000..3e43796288
--- /dev/null
+++ b/web/src/features/filters/config/prompts-config.ts
@@ -0,0 +1,45 @@
+import { promptsTableCols } from "@langfuse/shared";
+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";
+import type { ColumnToQueryKeyMap } from "@/src/features/filters/lib/filter-query-encoding";
+
+const PROMPT_COLUMN_TO_QUERY_KEY: ColumnToQueryKeyMap = {
+ type: "type",
+ labels: "labels",
+ tags: "tags",
+ version: "version",
+};
+
+export const promptFilterConfig: FilterConfig = {
+ tableName: "prompts",
+
+ columnToQueryKey: PROMPT_COLUMN_TO_QUERY_KEY,
+
+ columnDefinitions: promptsTableCols,
+
+ defaultExpanded: ["type"],
+
+ facets: [
+ {
+ type: "categorical" as const,
+ column: "type",
+ label: "Type",
+ },
+ {
+ type: "categorical" as const,
+ column: "labels",
+ label: "Labels",
+ },
+ {
+ type: "categorical" as const,
+ column: "tags",
+ label: "Tags",
+ },
+ {
+ type: "numeric" as const,
+ column: "version",
+ label: "Version",
+ min: 1,
+ max: 100,
+ },
+ ],
+};
diff --git a/web/src/features/filters/config/scores-config.ts b/web/src/features/filters/config/scores-config.ts
new file mode 100644
index 0000000000..cb49891334
--- /dev/null
+++ b/web/src/features/filters/config/scores-config.ts
@@ -0,0 +1,45 @@
+import { scoresTableCols } from "@/src/server/api/definitions/scoresTable";
+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";
+import type { ColumnToQueryKeyMap } from "@/src/features/filters/lib/filter-query-encoding";
+
+const SCORE_COLUMN_TO_QUERY_KEY: ColumnToQueryKeyMap = {
+ source: "source",
+ dataType: "dataType",
+ name: "name",
+ value: "value",
+};
+
+export const scoreFilterConfig: FilterConfig = {
+ tableName: "scores",
+
+ columnToQueryKey: SCORE_COLUMN_TO_QUERY_KEY,
+
+ columnDefinitions: scoresTableCols,
+
+ defaultExpanded: ["name"],
+
+ facets: [
+ {
+ type: "categorical" as const,
+ column: "name",
+ label: "Name",
+ },
+ {
+ type: "categorical" as const,
+ column: "source",
+ label: "Source",
+ },
+ {
+ type: "categorical" as const,
+ column: "dataType",
+ label: "Data Type",
+ },
+ {
+ type: "numeric" as const,
+ column: "value",
+ label: "Value",
+ min: -100,
+ max: 100,
+ },
+ ],
+};
diff --git a/web/src/features/filters/config/sessions-config.ts b/web/src/features/filters/config/sessions-config.ts
new file mode 100644
index 0000000000..138137db79
--- /dev/null
+++ b/web/src/features/filters/config/sessions-config.ts
@@ -0,0 +1,95 @@
+import { sessionsViewCols } from "@langfuse/shared";
+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";
+import type { ColumnToQueryKeyMap } from "@/src/features/filters/lib/filter-query-encoding";
+
+const SESSION_COLUMN_TO_QUERY_KEY: ColumnToQueryKeyMap = {
+ bookmarked: "bookmarked",
+ sessionDuration: "duration",
+ countTraces: "traces",
+ inputCost: "inputCost",
+ outputCost: "outputCost",
+ totalCost: "totalCost",
+ inputTokens: "inputTokens",
+ outputTokens: "outputTokens",
+ totalTokens: "totalTokens",
+};
+
+export const sessionFilterConfig: FilterConfig = {
+ tableName: "sessions",
+
+ columnToQueryKey: SESSION_COLUMN_TO_QUERY_KEY,
+
+ columnDefinitions: sessionsViewCols,
+
+ defaultExpanded: ["bookmarked"],
+
+ facets: [
+ {
+ type: "boolean" as const,
+ column: "bookmarked",
+ label: "Bookmarked",
+ trueLabel: "Bookmarked",
+ falseLabel: "Not bookmarked",
+ },
+ {
+ type: "numeric" as const,
+ column: "sessionDuration",
+ label: "Session Duration",
+ min: 0,
+ max: 3600,
+ unit: "s",
+ },
+ {
+ type: "numeric" as const,
+ column: "countTraces",
+ label: "Traces Count",
+ min: 0,
+ max: 1000,
+ },
+ {
+ type: "numeric" as const,
+ column: "inputTokens",
+ label: "Input Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "outputTokens",
+ label: "Output Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "totalTokens",
+ label: "Total Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "inputCost",
+ label: "Input Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ {
+ type: "numeric" as const,
+ column: "outputCost",
+ label: "Output Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ {
+ type: "numeric" as const,
+ column: "totalCost",
+ label: "Total Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ ],
+};
diff --git a/web/src/features/filters/config/traces-config.ts b/web/src/features/filters/config/traces-config.ts
new file mode 100644
index 0000000000..3f1ad6d7ff
--- /dev/null
+++ b/web/src/features/filters/config/traces-config.ts
@@ -0,0 +1,159 @@
+import { tracesTableCols } from "@langfuse/shared";
+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";
+import type { ColumnToQueryKeyMap } from "@/src/features/filters/lib/filter-query-encoding";
+
+const TRACE_COLUMN_TO_QUERY_KEY: ColumnToQueryKeyMap = {
+ id: "id",
+ name: "name",
+ userId: "userId",
+ sessionId: "sessionId",
+ version: "version",
+ release: "release",
+ tags: "tags",
+ environment: "env",
+ level: "level",
+ bookmarked: "bookmarked",
+ latency: "latency",
+ inputTokens: "inputTokens",
+ outputTokens: "outputTokens",
+ totalTokens: "totalTokens",
+ inputCost: "inputCost",
+ outputCost: "outputCost",
+ totalCost: "totalCost",
+ "Scores (categorical)": "scoreCategories",
+ "Scores (numeric)": "scoresNumeric",
+ Metadata: "metadata",
+};
+
+export const traceFilterConfig: FilterConfig = {
+ tableName: "traces",
+
+ columnToQueryKey: TRACE_COLUMN_TO_QUERY_KEY,
+
+ columnDefinitions: tracesTableCols,
+
+ defaultExpanded: ["environment", "name"],
+
+ facets: [
+ {
+ type: "categorical" as const,
+ column: "environment",
+ label: "Environment",
+ },
+ {
+ type: "categorical" as const,
+ column: "name",
+ label: "Trace Name",
+ },
+ {
+ type: "string" as const,
+ column: "id",
+ label: "Trace ID",
+ },
+ {
+ type: "string" as const,
+ column: "sessionId",
+ label: "Session ID",
+ },
+ {
+ type: "string" as const,
+ column: "userId",
+ label: "User ID",
+ },
+ {
+ type: "stringKeyValue" as const,
+ column: "Metadata",
+ label: "Metadata",
+ },
+ {
+ type: "string" as const,
+ column: "version",
+ label: "Version",
+ },
+ {
+ type: "string" as const,
+ column: "release",
+ label: "Release",
+ },
+ {
+ type: "boolean" as const,
+ column: "bookmarked",
+ label: "Bookmarked",
+ trueLabel: "Bookmarked",
+ falseLabel: "Not bookmarked",
+ },
+ {
+ type: "categorical" as const,
+ column: "tags",
+ label: "Tags",
+ },
+ {
+ type: "categorical" as const,
+ column: "level",
+ label: "Level",
+ },
+ {
+ type: "numeric" as const,
+ column: "latency",
+ label: "Latency",
+ min: 0,
+ max: 60,
+ unit: "s",
+ },
+ {
+ type: "numeric" as const,
+ column: "inputTokens",
+ label: "Input Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "outputTokens",
+ label: "Output Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "totalTokens",
+ label: "Total Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "inputCost",
+ label: "Input Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ {
+ type: "numeric" as const,
+ column: "outputCost",
+ label: "Output Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ {
+ type: "numeric" as const,
+ column: "totalCost",
+ label: "Total Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ {
+ type: "keyValue" as const,
+ column: "Scores (categorical)",
+ label: "Categorical Scores",
+ },
+ {
+ type: "numericKeyValue" as const,
+ column: "Scores (numeric)",
+ label: "Numeric Scores",
+ },
+ ],
+};
diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsx
new file mode 100644
index 0000000000..f6a59371c7
--- /dev/null
+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx
@@ -0,0 +1,860 @@
+import { useCallback, useMemo } from "react";
+import { StringParam, useQueryParam, withDefault } from "use-query-params";
+import { type FilterState, singleFilter } from "@langfuse/shared";
+import {
+ computeSelectedValues,
+ encodeFiltersGeneric,
+ decodeFiltersGeneric,
+} from "../lib/filter-query-encoding";
+import useSessionStorage from "@/src/components/useSessionStorage";
+import type { FilterConfig } from "../lib/filter-config";
+
+function computeNumericRange(
+ column: string,
+ filterState: FilterState,
+ defaultMin: number,
+ defaultMax: number,
+): [number, number] {
+ const minFilter = filterState.find(
+ (f) => f.column === column && f.type === "number" && f.operator === ">=",
+ );
+ const maxFilter = filterState.find(
+ (f) => f.column === column && f.type === "number" && f.operator === "<=",
+ );
+
+ const minValue =
+ minFilter && typeof minFilter.value === "number"
+ ? minFilter.value
+ : defaultMin;
+ const maxValue =
+ maxFilter && typeof maxFilter.value === "number"
+ ? maxFilter.value
+ : defaultMax;
+
+ return [minValue, maxValue];
+}
+
+export interface BaseUIFilter {
+ column: string;
+ label: string;
+ shortKey: string | null;
+ loading: boolean;
+ expanded: boolean;
+ isActive: boolean;
+ onReset: () => void;
+}
+
+export interface CategoricalUIFilter extends BaseUIFilter {
+ type: "categorical";
+ value: string[];
+ options: string[];
+ counts: Map<string, number>;
+ onChange: (values: string[]) => void;
+ onOnlyChange?: (value: string) => void;
+}
+
+export interface NumericUIFilter extends BaseUIFilter {
+ type: "numeric";
+ value: [number, number];
+ min: number;
+ max: number;
+ onChange: (value: [number, number]) => void;
+ unit?: string;
+}
+
+export interface StringUIFilter extends BaseUIFilter {
+ type: "string";
+ value: string;
+ onChange: (value: string) => void;
+}
+
+// Represents one active filter row in the key-value facet UI
+// Example: key="accuracy", operator="any of", value=["good", "excellent"]
+export type KeyValueFilterEntry = {
+ key: string;
+ operator: "any of" | "none of";
+ value: string[];
+};
+
+// Represents one active numeric filter row in the numeric key-value facet UI
+// Example: key="accuracy", operator=">=", value=0.8
+export type NumericKeyValueFilterEntry = {
+ key: string;
+ operator: "=" | ">" | "<" | ">=" | "<=";
+ value: number | "";
+};
+
+// Represents one active string filter row in the string key-value facet UI
+// Example: key="environment", operator="=", value="production"
+export type StringKeyValueFilterEntry = {
+ key: string;
+ operator: "=" | "contains" | "does not contain";
+ value: string;
+};
+
+export interface KeyValueUIFilter extends BaseUIFilter {
+ type: "keyValue";
+ value: KeyValueFilterEntry[]; // Array of active filter rows
+ keyOptions?: string[];
+ availableValues: Record<string, string[]>;
+ onChange: (filters: KeyValueFilterEntry[]) => void;
+}
+
+export interface NumericKeyValueUIFilter extends BaseUIFilter {
+ type: "numericKeyValue";
+ value: NumericKeyValueFilterEntry[]; // Array of active filter rows
+ keyOptions?: string[];
+ onChange: (filters: NumericKeyValueFilterEntry[]) => void;
+}
+
+export interface StringKeyValueUIFilter extends BaseUIFilter {
+ type: "stringKeyValue";
+ value: StringKeyValueFilterEntry[]; // Array of active filter rows
+ keyOptions?: string[];
+ onChange: (filters: StringKeyValueFilterEntry[]) => void;
+}
+
+export type UIFilter =
+ | CategoricalUIFilter
+ | NumericUIFilter
+ | StringUIFilter
+ | KeyValueUIFilter
+ | NumericKeyValueUIFilter
+ | StringKeyValueUIFilter;
+
+const EMPTY_MAP: Map<string, number> = new Map();
+
+type UpdateFilter = (
+ column: string,
+ values: string[],
+ operator?: "any of" | "none of",
+) => void;
+
+export function useSidebarFilterState(
+ config: FilterConfig,
+ options: Record<string, string[] | Record<string, string[]>>,
+) {
+ const FILTER_EXPANDED_STORAGE_KEY = `${config.tableName}-filters-expanded`;
+ const DEFAULT_EXPANDED_FILTERS = config.defaultExpanded ?? [];
+
+ const [expandedString, setExpandedString] = useSessionStorage<string>(
+ FILTER_EXPANDED_STORAGE_KEY,
+ DEFAULT_EXPANDED_FILTERS.join(","),
+ );
+ const expandedState = useMemo(() => {
+ return expandedString.split(",").filter(Boolean);
+ }, [expandedString]);
+ const onExpandedChange = useCallback(
+ (value: string[]) => {
+ setExpandedString(value.join(","));
+ },
+ [setExpandedString],
+ );
+
+ const [filtersQuery, setFiltersQuery] = useQueryParam(
+ "filter",
+ withDefault(StringParam, ""),
+ );
+
+ const filterState: FilterState = useMemo(() => {
+ try {
+ const filters = decodeFiltersGeneric(
+ filtersQuery,
+ config.columnToQueryKey,
+ options,
+ (column) => {
+ const columnDef = config.columnDefinitions.find(
+ (col) => col.id === column,
+ );
+ return columnDef?.type || "stringOptions";
+ },
+ );
+
+ // Validate filters
+ const result: FilterState = [];
+ for (const filter of filters) {
+ const validationResult = singleFilter.safeParse(filter);
+ if (validationResult.success) {
+ result.push(validationResult.data);
+ } else {
+ console.warn(
+ `Invalid filter skipped:`,
+ filter,
+ validationResult.error,
+ );
+ }
+ }
+ return result;
+ } catch (error) {
+ console.error("Error decoding filters:", error);
+ return [];
+ }
+ }, [
+ filtersQuery,
+ config.columnToQueryKey,
+ config.columnDefinitions,
+ options,
+ ]);
+
+ const setFilterState = useCallback(
+ (newFilters: FilterState) => {
+ const encoded = encodeFiltersGeneric(
+ newFilters,
+ config.columnToQueryKey,
+ options,
+ );
+ setFiltersQuery(encoded || null);
+ },
+ [config.columnToQueryKey, options, setFiltersQuery],
+ );
+
+ const clearAll = () => {
+ setFilterState([]);
+ };
+
+ // Generic apply selection logic
+ const applySelection = useCallback(
+ (
+ current: FilterState,
+ column: string,
+ values: string[],
+ operator?: "any of" | "none of",
+ ): FilterState => {
+ const other = current.filter((f) => f.column !== column);
+
+ const facet = config.facets.find((f) => f.column === column);
+ if (!facet) return current;
+
+ const colDef = config.columnDefinitions.find(
+ (c) => c.id === column || c.name === column,
+ );
+ const colType = colDef?.type;
+
+ // Handle boolean facets
+ if (facet.type === "boolean") {
+ const trueLabel = facet.trueLabel ?? "True";
+ const falseLabel = facet.falseLabel ?? "False";
+
+ if (values.length === 0 || values.length === 2) return other;
+ if (values.includes(trueLabel)) {
+ return [
+ ...other,
+ {
+ column,
+ type: "boolean" as const,
+ operator: "=" as const,
+ value: true,
+ },
+ ];
+ }
+ if (values.includes(falseLabel)) {
+ return [
+ ...other,
+ {
+ column,
+ type: "boolean" as const,
+ operator: "=" as const,
+ value: false,
+ },
+ ];
+ }
+ return other;
+ }
+
+ // Handle numeric facets
+ if (facet.type === "numeric") {
+ return other;
+ }
+
+ // Handle categorical facets
+ if (!(column in options)) return current;
+ const availableValuesRaw = options[column];
+
+ // For nested structures (keyValue filters), skip this logic
+ if (!Array.isArray(availableValuesRaw)) {
+ return current;
+ }
+
+ const availableValues = availableValuesRaw;
+
+ // If all items selected or none selected, remove filter
+ if (
+ values.length === 0 ||
+ (values.length === availableValues.length &&
+ availableValues.every((v) => values.includes(v)))
+ ) {
+ return other;
+ }
+
+ // Determine operator and values based on context
+ let finalOperator: "any of" | "none of";
+ let finalValues: string[];
+
+ if (operator !== undefined) {
+ // Explicit operator provided (e.g., from "Only" button) - use as-is
+ finalOperator = operator;
+ finalValues = values;
+ } else {
+ // Checkbox interaction - smart operator selection
+ const existingFilter = current.find((f) => f.column === column);
+
+ if (!existingFilter) {
+ // No existing filter - user is deselecting from "all selected" state
+ // Use "none of" with deselected items
+ const deselected = availableValues.filter((v) => !values.includes(v));
+ finalOperator = "none of";
+ finalValues = deselected;
+ } else if (
+ existingFilter.operator === "none of" &&
+ (existingFilter.type === "stringOptions" ||
+ existingFilter.type === "arrayOptions")
+ ) {
+ // Existing "none of" filter - keep "none of", update to deselected items
+ const deselected = availableValues.filter((v) => !values.includes(v));
+ finalOperator = "none of";
+ finalValues = deselected;
+ } else {
+ // Existing "any of" filter or other - keep "any of" with selected items
+ finalOperator = "any of";
+ finalValues = values;
+ }
+ }
+
+ const filterType: "arrayOptions" | "stringOptions" =
+ colType === "arrayOptions" ? "arrayOptions" : "stringOptions";
+
+ if (filterType === "arrayOptions") {
+ return [
+ ...other,
+ {
+ column,
+ type: "arrayOptions" as const,
+ operator: finalOperator,
+ value: finalValues,
+ },
+ ];
+ }
+
+ return [
+ ...other,
+ {
+ column,
+ type: "stringOptions" as const,
+ operator: finalOperator,
+ value: finalValues,
+ },
+ ];
+ },
+ [config, options],
+ );
+
+ const updateFilter: UpdateFilter = useCallback(
+ (column, values, operator?: "any of" | "none of") => {
+ const next = applySelection(filterState, column, values, operator);
+ setFilterState(next);
+ },
+ [filterState, applySelection, setFilterState],
+ );
+
+ const updateFilterOnly = useCallback(
+ (column: string, value: string) => {
+ const facet = config.facets.find((f) => f.column === column);
+ if (!facet) return;
+
+ // Handle boolean specially
+ if (facet.type === "boolean") {
+ updateFilter(column, [value]);
+ return;
+ }
+
+ if (!(column in options)) return;
+ // Only apply for array-type options (not nested objects)
+ const optionValue = options[column];
+ if (!Array.isArray(optionValue)) return;
+ updateFilter(column, [value], "any of");
+ },
+ [config.facets, options, updateFilter],
+ );
+
+ const updateNumericFilter = useCallback(
+ (
+ column: string,
+ value: [number, number] | null,
+ _defaultMin: number,
+ _defaultMax: number,
+ ) => {
+ // Remove existing numeric filters for this column
+ const withoutNumeric = filterState.filter((f) => f.column !== column);
+
+ // If value is null, clear the filter (reset case)
+ if (value === null) {
+ setFilterState(withoutNumeric);
+ return;
+ }
+
+ // Always add both filters when user interacts (even at min/max bounds)
+ // This ensures the filter is marked as "active" and UI shows values
+ const filters: FilterState = [
+ {
+ column,
+ type: "number" as const,
+ operator: ">=" as const,
+ value: value[0],
+ },
+ {
+ column,
+ type: "number" as const,
+ operator: "<=" as const,
+ value: value[1],
+ },
+ ];
+
+ const next: FilterState = [...withoutNumeric, ...filters];
+ setFilterState(next);
+ },
+ [filterState, setFilterState],
+ );
+
+ const updateStringFilter = useCallback(
+ (column: string, value: string) => {
+ const withoutString = filterState.filter((f) => f.column !== column);
+
+ if (value.trim() === "") {
+ // Empty value means no filter
+ setFilterState(withoutString);
+ } else {
+ // Add string filter with contains operator
+ const next: FilterState = [
+ ...withoutString,
+ {
+ column,
+ type: "string" as const,
+ operator: "contains" as const,
+ value,
+ },
+ ];
+ setFilterState(next);
+ }
+ },
+ [filterState, setFilterState],
+ );
+
+ const filters: UIFilter[] = useMemo((): UIFilter[] => {
+ const filterByColumn = new Map(filterState.map((f) => [f.column, f]));
+ const expandedSet = new Set(expandedState);
+
+ const getShortKey = (column: string): string | null => {
+ return config.columnToQueryKey[column] ?? null;
+ };
+
+ return config.facets
+ .map((facet): UIFilter | null => {
+ if (facet.type === "numeric") {
+ const currentRange = computeNumericRange(
+ facet.column,
+ filterState,
+ facet.min,
+ facet.max,
+ );
+ // Check if there are any numeric filters for this column
+ const isActive = filterState.some(
+ (f) => f.column === facet.column && f.type === "number",
+ );
+ return {
+ type: "numeric",
+ column: facet.column,
+ label: facet.label,
+ shortKey: getShortKey(facet.column),
+ value: currentRange,
+ min: facet.min,
+ max: facet.max,
+ unit: facet.unit,
+ loading: false,
+ expanded: expandedSet.has(facet.column),
+ isActive,
+ onChange: (value: [number, number]) =>
+ updateNumericFilter(facet.column, value, facet.min, facet.max),
+ onReset: () =>
+ updateNumericFilter(facet.column, null, facet.min, facet.max),
+ };
+ }
+
+ // Handle string filters
+ if (facet.type === "string") {
+ const filterEntry = filterByColumn.get(facet.column);
+ const currentValue =
+ filterEntry?.type === "string" &&
+ typeof filterEntry.value === "string"
+ ? filterEntry.value
+ : "";
+ const isActive = currentValue.trim() !== "";
+
+ return {
+ type: "string",
+ column: facet.column,
+ label: facet.label,
+ shortKey: getShortKey(facet.column),
+ value: currentValue,
+ loading: false,
+ expanded: expandedSet.has(facet.column),
+ isActive,
+ onChange: (value: string) =>
+ updateStringFilter(facet.column, value),
+ onReset: () => updateStringFilter(facet.column, ""),
+ };
+ }
+
+ // Handle keyValue filters
+ if (facet.type === "keyValue") {
+ // Extract all categoryOptions filters for this column from filterState
+ const categoryFilters = filterState.filter(
+ (f) => f.column === facet.column && f.type === "categoryOptions",
+ ) as Array<{
+ column: string;
+ type: "categoryOptions";
+ operator: "any of" | "none of";
+ key: string;
+ value: string[];
+ }>;
+
+ // Convert to KeyValueFilterEntry array
+ const activeFilters: KeyValueFilterEntry[] = categoryFilters.map(
+ (f) => ({
+ key: f.key,
+ operator: f.operator,
+ value: f.value,
+ }),
+ );
+
+ const isActive = activeFilters.length > 0;
+
+ // Get available values from options
+ const availableValues = options[facet.column] ?? {};
+
+ // Extract key options from availableValues if not defined in facet
+ const keyOptions =
+ facet.keyOptions ??
+ (typeof availableValues === "object" &&
+ !Array.isArray(availableValues)
+ ? Object.keys(availableValues as Record<string, string[]>)
+ : undefined);
+
+ return {
+ type: "keyValue",
+ column: facet.column,
+ label: facet.label,
+ shortKey: getShortKey(facet.column),
+ value: activeFilters,
+ keyOptions,
+ availableValues:
+ typeof availableValues === "object" &&
+ !Array.isArray(availableValues)
+ ? (availableValues as Record<string, string[]>)
+ : ({} as Record<string, string[]>),
+ loading: false,
+ expanded: expandedSet.has(facet.column),
+ isActive,
+ onChange: (filters: KeyValueFilterEntry[]) => {
+ // Remove all existing categoryOptions filters for this column
+ const withoutCategory = filterState.filter(
+ (f) =>
+ !(f.column === facet.column && f.type === "categoryOptions"),
+ );
+
+ // Only add filters that have both key and values selected
+ // This filters at the filterState level, not the UI level
+ const validFilters = filters.filter(
+ (entry) => entry.key && entry.value.length > 0,
+ );
+
+ const newFilters: FilterState = [
+ ...withoutCategory,
+ ...validFilters.map((entry) => ({
+ column: facet.column,
+ type: "categoryOptions" as const,
+ operator: entry.operator,
+ key: entry.key,
+ value: entry.value,
+ })),
+ ];
+
+ setFilterState(newFilters);
+ },
+ onReset: () => {
+ // Remove all categoryOptions filters for this column
+ const newFilters = filterState.filter(
+ (f) =>
+ !(f.column === facet.column && f.type === "categoryOptions"),
+ );
+ setFilterState(newFilters);
+ },
+ };
+ }
+
+ // Handle numericKeyValue filters
+ if (facet.type === "numericKeyValue") {
+ // Extract all numberObject filters for this column from filterState
+ const numericFilters = filterState.filter(
+ (f) => f.column === facet.column && f.type === "numberObject",
+ ) as Array<{
+ column: string;
+ type: "numberObject";
+ operator: "=" | ">" | "<" | ">=" | "<=";
+ key: string;
+ value: number;
+ }>;
+
+ // Convert to NumericKeyValueFilterEntry array
+ const activeFilters: NumericKeyValueFilterEntry[] =
+ numericFilters.map((f) => ({
+ key: f.key,
+ operator: f.operator,
+ value: f.value,
+ }));
+
+ const isActive = activeFilters.length > 0;
+
+ // Get available keys from options (should be array of score names)
+ const availableKeys = options[facet.column];
+ const keyOptions =
+ facet.keyOptions ??
+ (Array.isArray(availableKeys) ? availableKeys : undefined);
+
+ return {
+ type: "numericKeyValue",
+ column: facet.column,
+ label: facet.label,
+ shortKey: getShortKey(facet.column),
+ value: activeFilters,
+ keyOptions,
+ loading: false,
+ expanded: expandedSet.has(facet.column),
+ isActive,
+ onChange: (filters: NumericKeyValueFilterEntry[]) => {
+ // Remove all existing numberObject filters for this column
+ const withoutNumeric = filterState.filter(
+ (f) =>
+ !(f.column === facet.column && f.type === "numberObject"),
+ );
+
+ // Only add filters that have key and valid numeric value
+ const validFilters = filters.filter(
+ (entry) => entry.key && entry.value !== "",
+ );
+
+ const newFilters: FilterState = [
+ ...withoutNumeric,
+ ...validFilters.map((entry) => ({
+ column: facet.column,
+ type: "numberObject" as const,
+ operator: entry.operator,
+ key: entry.key,
+ value: entry.value as number,
+ })),
+ ];
+
+ setFilterState(newFilters);
+ },
+ onReset: () => {
+ // Remove all numberObject filters for this column
+ const newFilters = filterState.filter(
+ (f) =>
+ !(f.column === facet.column && f.type === "numberObject"),
+ );
+ setFilterState(newFilters);
+ },
+ };
+ }
+
+ // Handle stringKeyValue filters
+ if (facet.type === "stringKeyValue") {
+ // Extract all stringObject filters for this column from filterState
+ const stringFilters = filterState.filter(
+ (f) => f.column === facet.column && f.type === "stringObject",
+ ) as Array<{
+ column: string;
+ type: "stringObject";
+ operator: "=" | "contains" | "does not contain";
+ key: string;
+ value: string;
+ }>;
+
+ // Convert to StringKeyValueFilterEntry array
+ const activeFilters: StringKeyValueFilterEntry[] = stringFilters.map(
+ (f) => ({
+ key: f.key,
+ operator: f.operator,
+ value: f.value,
+ }),
+ );
+
+ const isActive = activeFilters.length > 0;
+
+ // Get available keys from options
+ const availableKeys = options[facet.column];
+ const keyOptions =
+ facet.keyOptions ??
+ (Array.isArray(availableKeys) ? availableKeys : undefined);
+
+ return {
+ type: "stringKeyValue",
+ column: facet.column,
+ label: facet.label,
+ shortKey: getShortKey(facet.column),
+ value: activeFilters,
+ keyOptions,
+ loading: false,
+ expanded: expandedSet.has(facet.column),
+ isActive,
+ onChange: (filters: StringKeyValueFilterEntry[]) => {
+ // Remove all existing stringObject filters for this column
+ const withoutString = filterState.filter(
+ (f) =>
+ !(f.column === facet.column && f.type === "stringObject"),
+ );
+
+ // Only add filters that have key and non-empty value
+ const validFilters = filters.filter(
+ (entry) => entry.key && entry.value.trim() !== "",
+ );
+
+ const newFilters: FilterState = [
+ ...withoutString,
+ ...validFilters.map((entry) => ({
+ column: facet.column,
+ type: "stringObject" as const,
+ operator: entry.operator,
+ key: entry.key,
+ value: entry.value,
+ })),
+ ];
+
+ setFilterState(newFilters);
+ },
+ onReset: () => {
+ // Remove all stringObject filters for this column
+ const newFilters = filterState.filter(
+ (f) =>
+ !(f.column === facet.column && f.type === "stringObject"),
+ );
+ setFilterState(newFilters);
+ },
+ };
+ }
+
+ // Handle boolean as categorical UI
+ if (facet.type === "boolean") {
+ const trueLabel = facet.trueLabel ?? "True";
+ const falseLabel = facet.falseLabel ?? "False";
+ const availableOptions = [trueLabel, falseLabel];
+ const filterEntry = filterByColumn.get(facet.column);
+ let selectedOptions = availableOptions;
+ if (filterEntry) {
+ const boolValue = filterEntry.value as boolean;
+ selectedOptions = boolValue === true ? [trueLabel] : [falseLabel];
+ }
+ const isActive = selectedOptions.length === 1;
+
+ return {
+ type: "categorical",
+ column: facet.column,
+ label: facet.label,
+ shortKey: getShortKey(facet.column),
+ value: selectedOptions,
+ options: availableOptions,
+ counts: EMPTY_MAP,
+ loading: false,
+ expanded: expandedSet.has(facet.column),
+ isActive,
+ onChange: (values: string[]) => {
+ if (values.length === 0 || values.length === 2) {
+ updateFilter(facet.column, []);
+ return;
+ }
+ if (values.includes(trueLabel) && !values.includes(falseLabel)) {
+ updateFilter(facet.column, [trueLabel]);
+ } else if (
+ values.includes(falseLabel) &&
+ !values.includes(trueLabel)
+ ) {
+ updateFilter(facet.column, [falseLabel]);
+ }
+ },
+ onOnlyChange: (value: string) => {
+ if (
+ selectedOptions.length === 1 &&
+ selectedOptions.includes(value)
+ ) {
+ updateFilter(facet.column, []);
+ } else {
+ updateFilter(facet.column, [value]);
+ }
+ },
+ onReset: () => updateFilter(facet.column, []),
+ };
+ }
+
+ // Handle categorical
+ const availableValuesRaw = options[facet.column] ?? [];
+ // For nested structures, default to empty array (shouldn't happen for categorical)
+ const availableValues = Array.isArray(availableValuesRaw)
+ ? availableValuesRaw
+ : [];
+ const selectedValues = computeSelectedValues(
+ availableValues,
+ filterByColumn.get(facet.column),
+ );
+ const isActive =
+ selectedValues.length !== availableValues.length &&
+ selectedValues.length > 0;
+
+ return {
+ type: "categorical",
+ column: facet.column,
+ label: facet.label,
+ shortKey: getShortKey(facet.column),
+ value: selectedValues,
+ options: availableValues,
+ counts: EMPTY_MAP,
+ loading: false,
+ expanded: expandedSet.has(facet.column),
+ isActive,
+ onChange: (values: string[]) => updateFilter(facet.column, values),
+ onOnlyChange: (value: string) => {
+ if (selectedValues.length === 1 && selectedValues.includes(value)) {
+ updateFilter(
+ facet.column,
+ selectedValues.filter((v) => v !== value),
+ );
+ } else {
+ updateFilterOnly(facet.column, value);
+ }
+ },
+ onReset: () => updateFilter(facet.column, []),
+ };
+ })
+ .filter((f): f is UIFilter => f !== null);
+ }, [
+ config,
+ options,
+ filterState,
+ updateFilter,
+ updateFilterOnly,
+ updateNumericFilter,
+ updateStringFilter,
+ expandedState,
+ setFilterState,
+ ]);
+
+ return {
+ filterState,
+ setFilterState,
+ updateFilter,
+ updateFilterOnly,
+ clearAll,
+ isFiltered: filterState.length > 0,
+ filters,
+ expanded: expandedState,
+ onExpandedChange,
+ };
+}
diff --git a/web/src/features/filters/lib/filter-config.ts b/web/src/features/filters/lib/filter-config.ts
new file mode 100644
index 0000000000..42931542f1
--- /dev/null
+++ b/web/src/features/filters/lib/filter-config.ts
@@ -0,0 +1,69 @@
+import type { ColumnDefinition } from "@langfuse/shared";
+import type { ColumnToQueryKeyMap } from "./filter-query-encoding";
+
+interface CategoricalFacet {
+ type: "categorical";
+ column: string;
+ label: string;
+}
+
+interface BooleanFacet {
+ type: "boolean";
+ column: string;
+ label: string;
+ trueLabel?: string;
+ falseLabel?: string;
+}
+
+interface NumericFacet {
+ type: "numeric";
+ column: string;
+ label: string;
+ min: number;
+ max: number;
+ unit?: string;
+}
+
+interface StringFacet {
+ type: "string";
+ column: string;
+ label: string;
+}
+
+interface KeyValueFacet {
+ type: "keyValue";
+ column: string;
+ label: string;
+ keyOptions?: string[];
+}
+
+interface NumericKeyValueFacet {
+ type: "numericKeyValue";
+ column: string;
+ label: string;
+ keyOptions?: string[];
+}
+
+interface StringKeyValueFacet {
+ type: "stringKeyValue";
+ column: string;
+ label: string;
+ keyOptions?: string[];
+}
+
+export type Facet =
+ | CategoricalFacet
+ | BooleanFacet
+ | NumericFacet
+ | StringFacet
+ | KeyValueFacet
+ | NumericKeyValueFacet
+ | StringKeyValueFacet;
+
+export interface FilterConfig {
+ tableName: string;
+ columnToQueryKey: ColumnToQueryKeyMap;
+ columnDefinitions: ColumnDefinition[];
+ defaultExpanded?: string[];
+ facets: Facet[];
+}
diff --git a/web/src/features/filters/lib/filter-query-encoding.ts b/web/src/features/filters/lib/filter-query-encoding.ts
new file mode 100644
index 0000000000..220b4a03b2
--- /dev/null
+++ b/web/src/features/filters/lib/filter-query-encoding.ts
@@ -0,0 +1,527 @@
+import { type FilterState } from "@langfuse/shared";
+
+// Generic helpers for reusable encoding/decoding across feature areas
+export type ColumnToQueryKeyMap = Record<string, string>;
+export type GenericFilterOptions = Record<
+ string,
+ string[] | Record<string, string[]>
+>;
+
+export const createShortKeyGetter =
+ (columnToQueryKey: ColumnToQueryKeyMap) =>
+ (column: string): string | null => {
+ const key = columnToQueryKey[column];
+ return key ?? null;
+ };
+
+// Note: short key getters are feature-specific; use createShortKeyGetter in feature modules
+
+function splitQueryParts(query: string): string[] {
+ const parts: string[] = [];
+ let current = "";
+ let i = 0;
+
+ while (i < query.length) {
+ const char = query[i];
+
+ if (char === "\\") {
+ // Escaped character - include backslash and next character
+ current += char;
+ if (i + 1 < query.length) {
+ i++;
+ current += query[i];
+ }
+ } else if (char === " " && current.trim()) {
+ // Unescaped space - end current part
+ parts.push(current);
+ current = "";
+ } else if (char !== " ") {
+ // Regular character
+ current += char;
+ }
+
+ i++;
+ }
+
+ // Add the last part
+ if (current.trim()) {
+ parts.push(current);
+ }
+
+ return parts;
+}
+
+function parseQuotedValues(valueString: string): string[] {
+ const values: string[] = [];
+ let currentValue = "";
+ let inQuotes = false;
+ let i = 0;
+
+ while (i < valueString.length) {
+ const char = valueString[i];
+
+ if (char === '"' && !inQuotes) {
+ // Start of quoted value
+ inQuotes = true;
+ } else if (char === '"' && inQuotes) {
+ // End of quoted value
+ inQuotes = false;
+ } else if (char === "," && !inQuotes) {
+ // Comma outside quotes - end of value
+ if (currentValue) {
+ values.push(currentValue);
+ currentValue = "";
+ }
+ } else {
+ // Regular character
+ currentValue += char;
+ }
+
+ i++;
+ }
+
+ // Add the last value
+ if (currentValue) {
+ values.push(currentValue);
+ }
+
+ return values;
+}
+
+// Pure helper: compute UI-selected values from a filter entry and available values
+export function computeSelectedValues(
+ availableValues: string[],
+ filterEntry: { operator?: string; value?: unknown } | undefined,
+): string[] {
+ if (!filterEntry) return availableValues;
+ const values = (filterEntry.value as string[]) ?? [];
+ if (filterEntry.operator === "none of") {
+ const excluded = new Set(values);
+ return availableValues.filter((v) => !excluded.has(v));
+ }
+ return values;
+}
+
+export function encodeFiltersGeneric(
+ filters: FilterState,
+ columnToQueryKey: ColumnToQueryKeyMap,
+ options?: Partial<GenericFilterOptions>,
+): string {
+ const serializedParts: string[] = [];
+ const processedNumericColumns = new Set<string>();
+
+ for (const filter of filters) {
+ // boolean filters: key:true|false
+ if (filter.type === "boolean") {
+ const queryKey = columnToQueryKey[filter.column];
+ if (!queryKey) continue;
+ serializedParts.push(`${queryKey}:${Boolean(filter.value)}`);
+ continue;
+ }
+
+ // string filters: key:*value* (contains operator)
+ if (filter.type === "string") {
+ const queryKey = columnToQueryKey[filter.column];
+ if (!queryKey) continue;
+ const value = String(filter.value ?? "").trim();
+ if (value === "") continue;
+ // Escape spaces and asterisks with backslashes
+ const escapedValue = value
+ .replace(/\\/g, "\\\\")
+ .replace(/ /g, "\\ ")
+ .replace(/\*/g, "\\*");
+ serializedParts.push(`${queryKey}:*${escapedValue}*`);
+ continue;
+ }
+
+ // number filters: combine >= and <= into bracket notation [min,max]
+ if (filter.type === "number") {
+ const queryKey = columnToQueryKey[filter.column];
+ if (!queryKey || processedNumericColumns.has(filter.column)) continue;
+
+ // Look for both >= and <= filters for this column
+ const gteFilter = filters.find(
+ (f) =>
+ f.column === filter.column &&
+ f.type === "number" &&
+ f.operator === ">=",
+ );
+ const lteFilter = filters.find(
+ (f) =>
+ f.column === filter.column &&
+ f.type === "number" &&
+ f.operator === "<=",
+ );
+
+ if (
+ gteFilter &&
+ lteFilter &&
+ typeof gteFilter.value === "number" &&
+ typeof lteFilter.value === "number"
+ ) {
+ // Both operators present: use bracket notation
+ serializedParts.push(
+ `${queryKey}:[${gteFilter.value},${lteFilter.value}]`,
+ );
+ processedNumericColumns.add(filter.column);
+ } else if (filter.operator === ">=" && typeof filter.value === "number") {
+ // Only >= operator
+ serializedParts.push(`${queryKey}:>=${filter.value}`);
+ processedNumericColumns.add(filter.column);
+ } else if (filter.operator === "<=" && typeof filter.value === "number") {
+ // Only <= operator
+ serializedParts.push(`${queryKey}:<=${filter.value}`);
+ processedNumericColumns.add(filter.column);
+ }
+ continue;
+ }
+
+ // categoryOptions filters: queryKey.key:value1,value2
+ if (filter.type === "categoryOptions") {
+ const queryKey = columnToQueryKey[filter.column];
+ if (!queryKey) continue;
+
+ const key = (filter as any).key;
+ const selectedValues = (filter.value as string[]) || [];
+ if (!key || selectedValues.length === 0) continue;
+
+ // Quote key if it contains special characters
+ const needsQuotingKey =
+ key.includes(" ") || key.includes(".") || key.includes(":");
+ const serializedKey = needsQuotingKey ? `"${key}"` : key;
+
+ const serializedValues = selectedValues.map((val) => {
+ const lowerVal = val.toLowerCase();
+ return lowerVal.includes(":") ||
+ lowerVal.includes(",") ||
+ lowerVal.includes(" ")
+ ? `"${lowerVal}"`
+ : lowerVal;
+ });
+ const valueString = serializedValues.join(",");
+ const prefix = filter.operator === "none of" ? "-" : "";
+ serializedParts.push(
+ `${prefix}${queryKey}.${serializedKey}:${valueString}`,
+ );
+ continue;
+ }
+
+ // numberObject filters: queryKey.key:operator:value (e.g., scoresNumeric.accuracy:>=:0.8)
+ if (filter.type === "numberObject") {
+ const queryKey = columnToQueryKey[filter.column];
+ if (!queryKey) continue;
+
+ const key = (filter as any).key;
+ const operator = (filter as any).operator;
+ const value = (filter as any).value;
+ if (!key || typeof value !== "number") continue;
+
+ // Quote key if it contains special characters
+ const needsQuotingKey =
+ key.includes(" ") || key.includes(".") || key.includes(":");
+ const serializedKey = needsQuotingKey ? `"${key}"` : key;
+
+ serializedParts.push(`${queryKey}.${serializedKey}:${operator}:${value}`);
+ continue;
+ }
+
+ // stringObject filters: queryKey.key=value or queryKey.key*=value or queryKey.key!=value
+ if (filter.type === "stringObject") {
+ const queryKey = columnToQueryKey[filter.column];
+ if (!queryKey) continue;
+
+ const key = (filter as any).key;
+ const operator = (filter as any).operator;
+ const value = (filter as any).value;
+ if (!key || !value) continue;
+
+ // Quote key if it contains special characters
+ const needsQuotingKey =
+ key.includes(" ") ||
+ key.includes(".") ||
+ key.includes(":") ||
+ key.includes("=");
+ const serializedKey = needsQuotingKey ? `"${key}"` : key;
+
+ // Quote value if it contains special characters
+ const needsQuotingValue =
+ value.includes(" ") || value.includes(":") || value.includes("=");
+ const serializedValue = needsQuotingValue ? `"${value}"` : value;
+
+ // Map operator to symbol
+ const operatorSymbol =
+ operator === "="
+ ? "="
+ : operator === "contains"
+ ? "*="
+ : operator === "does not contain"
+ ? "!="
+ : "="; // fallback
+
+ serializedParts.push(
+ `${queryKey}.${serializedKey}${operatorSymbol}${serializedValue}`,
+ );
+ continue;
+ }
+
+ // Only serialize string-like filters with supported operators
+ if (
+ (filter.type !== "stringOptions" && filter.type !== "arrayOptions") ||
+ (filter.operator !== "any of" && filter.operator !== "none of")
+ ) {
+ continue;
+ }
+
+ const queryKey = columnToQueryKey[filter.column];
+ if (!queryKey) continue;
+
+ const availableValuesRaw = options?.[filter.column] ?? [];
+ // Handle both flat arrays and nested objects (for keyValue filters)
+ const availableValues = Array.isArray(availableValuesRaw)
+ ? availableValuesRaw
+ : [];
+ const availableSet = new Set(availableValues);
+
+ const selectedValues = (filter.value as string[]) || [];
+ const validValues = selectedValues.filter(
+ (val) => availableSet.size === 0 || availableSet.has(val),
+ );
+ if (validValues.length === 0) continue;
+
+ const serializedValues = validValues.map((val) => {
+ const lowerVal = val.toLowerCase();
+ return lowerVal.includes(":") ? `"${lowerVal}"` : lowerVal;
+ });
+ const valueString = serializedValues.join(",");
+ const prefix = filter.operator === "none of" ? "-" : "";
+ serializedParts.push(`${prefix}${queryKey}:${valueString}`);
+ }
+
+ return serializedParts.join(" ");
+}
+
+export function decodeFiltersGeneric(
+ query: string,
+ columnToQueryKey: ColumnToQueryKeyMap,
+ options: Partial<GenericFilterOptions>,
+ getType?: (column: string) => any,
+): FilterState {
+ if (!query.trim()) return [];
+
+ const filters: FilterState = [];
+ const parts = splitQueryParts(query.trim());
+
+ for (const part of parts) {
+ if (!part) continue;
+ const isExclusive = part.startsWith("-");
+ const cleanPart = isExclusive ? part.substring(1) : part;
+
+ // Check for stringObject filters first (format: queryKey.key=value or queryKey.key*=value or queryKey.key!=value)
+ if (cleanPart.includes(".")) {
+ // Try to match symbol-based operators (=, *=, !=)
+ const dotIndex = cleanPart.indexOf(".");
+ const queryKey = cleanPart.substring(0, dotIndex);
+ const afterDot = cleanPart.substring(dotIndex + 1);
+
+ // Check for symbol operators
+ let operatorMatch: RegExpMatchArray | null = null;
+ let operator: "=" | "contains" | "does not contain" | null = null;
+
+ if (afterDot.includes("!=")) {
+ operatorMatch = afterDot.match(/^(.+?)!=(.+)$/);
+ operator = "does not contain";
+ } else if (afterDot.includes("*=")) {
+ operatorMatch = afterDot.match(/^(.+?)\*=(.+)$/);
+ operator = "contains";
+ } else if (afterDot.includes("=") && !afterDot.includes(":")) {
+ // Only match = if there's no colon (to avoid matching category/number filters)
+ operatorMatch = afterDot.match(/^(.+?)=(.+)$/);
+ operator = "=";
+ }
+
+ if (operatorMatch && operator) {
+ let key = operatorMatch[1];
+ let value = operatorMatch[2];
+
+ // Remove quotes if present
+ if (key.startsWith('"') && key.endsWith('"')) {
+ key = key.substring(1, key.length - 1);
+ }
+ if (value.startsWith('"') && value.endsWith('"')) {
+ value = value.substring(1, value.length - 1);
+ }
+
+ // Find column from query key
+ const column = Object.keys(columnToQueryKey).find(
+ (c) => columnToQueryKey[c] === queryKey,
+ );
+ if (column) {
+ filters.push({
+ column,
+ type: "stringObject",
+ operator,
+ key,
+ value,
+ } as any);
+ continue;
+ }
+ }
+ }
+
+ const colonIndex = cleanPart.indexOf(":");
+ if (colonIndex === -1) continue;
+
+ const key = cleanPart.substring(0, colonIndex);
+ const valueString = cleanPart.substring(colonIndex + 1);
+
+ // categoryOptions and numberObject filters: queryKey.key:value1,value2 OR queryKey.key:operator:value
+ // Check if key contains a dot (e.g., ratings.danger or scoresNumeric.accuracy) BEFORE looking up column
+ if (key.includes(".")) {
+ const dotIndex = key.indexOf(".");
+ const queryKey = key.substring(0, dotIndex);
+ let categoryKey = key.substring(dotIndex + 1);
+
+ // Handle quoted keys (e.g., "fossil quality")
+ if (categoryKey.startsWith('"') && categoryKey.endsWith('"')) {
+ categoryKey = categoryKey.substring(1, categoryKey.length - 1);
+ }
+
+ // Find column from query key
+ const column = Object.keys(columnToQueryKey).find(
+ (c) => columnToQueryKey[c] === queryKey,
+ );
+ if (!column) continue;
+
+ // Check if this is a numberObject filter (format: operator:value)
+ const operatorMatch = valueString.match(/^(=|>|<|>=|<=):(.+)$/);
+ if (operatorMatch) {
+ const operator = operatorMatch[1] as "=" | ">" | "<" | ">=" | "<=";
+ const numericValue = parseFloat(operatorMatch[2]);
+ if (!isNaN(numericValue)) {
+ filters.push({
+ column,
+ type: "numberObject",
+ operator,
+ key: categoryKey,
+ value: numericValue,
+ } as any);
+ continue;
+ }
+ }
+
+ // Parse as categoryOptions
+ const serializedValues = parseQuotedValues(valueString);
+ if (serializedValues.length === 0) continue;
+
+ filters.push({
+ column,
+ type: "categoryOptions",
+ operator: isExclusive ? "none of" : "any of",
+ key: categoryKey,
+ value: serializedValues,
+ } as any);
+ continue;
+ }
+
+ // boolean
+ const columnFromBoolean = Object.keys(columnToQueryKey).find(
+ (c) => columnToQueryKey[c] === key,
+ );
+ if (!columnFromBoolean) continue;
+
+ if (valueString === "true" || valueString === "false") {
+ filters.push({
+ column: columnFromBoolean,
+ type: "boolean",
+ operator: "=",
+ value: valueString === "true",
+ } as any);
+ continue;
+ }
+
+ // string filters: key:*value* (contains operator)
+ const stringMatch = valueString.match(/^\*(.+)\*$/);
+ if (stringMatch) {
+ const escapedValue = stringMatch[1];
+ // Unescape backslashes, spaces, and asterisks
+ const decodedValue = escapedValue
+ .replace(/\\\*/g, "*")
+ .replace(/\\ /g, " ")
+ .replace(/\\\\/g, "\\");
+ filters.push({
+ column: columnFromBoolean,
+ type: "string",
+ operator: "contains",
+ value: decodedValue,
+ } as any);
+ continue;
+ }
+
+ // number filters: key:[min,max] (range) or key:>=value or key:<=value (single bound)
+ // Check for bracket notation first [min,max]
+ const bracketMatch = valueString.match(/^\[(-?[0-9.]+),(-?[0-9.]+)\]$/);
+ if (bracketMatch) {
+ const minValue = parseFloat(bracketMatch[1]);
+ const maxValue = parseFloat(bracketMatch[2]);
+ if (!isNaN(minValue) && !isNaN(maxValue)) {
+ filters.push(
+ {
+ column: columnFromBoolean,
+ type: "number",
+ operator: ">=",
+ value: minValue,
+ } as any,
+ {
+ column: columnFromBoolean,
+ type: "number",
+ operator: "<=",
+ value: maxValue,
+ } as any,
+ );
+ continue;
+ }
+ }
+
+ // Check for single-sided operators (>= or <=)
+ const numericMatch = valueString.match(/^(>=|<=)(.+)$/);
+ if (numericMatch) {
+ const operator = numericMatch[1] as ">=" | "<=";
+ const numValue = parseFloat(numericMatch[2]);
+ if (!isNaN(numValue)) {
+ filters.push({
+ column: columnFromBoolean,
+ type: "number",
+ operator,
+ value: numValue,
+ } as any);
+ continue;
+ }
+ }
+
+ const availableValuesRaw = options[columnFromBoolean] ?? [];
+ // Handle both flat arrays and nested objects (for keyValue filters)
+ const availableValues = Array.isArray(availableValuesRaw)
+ ? availableValuesRaw
+ : [];
+ if (valueString === "") continue;
+
+ const serializedValues = parseQuotedValues(valueString);
+ const availableLowerCaseMap = new Map(
+ availableValues.map((val) => [val.toLowerCase(), val]),
+ );
+ const filterValues = serializedValues
+ .map((val) => availableLowerCaseMap.get(val))
+ .filter((val): val is string => val !== undefined);
+ if (filterValues.length === 0) continue;
+
+ const filterType = getType?.(columnFromBoolean) ?? "stringOptions";
+ filters.push({
+ column: columnFromBoolean,
+ type: filterType as any,
+ operator: (isExclusive ? "none of" : "any of") as any,
+ value: filterValues,
+ } as any);
+ }
+
+ return filters;
+}
diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsx
index 178b2c6dc8..e405992fdd 100644
--- a/web/src/features/prompts/components/prompts-table.tsx
+++ b/web/src/features/prompts/components/prompts-table.tsx
@@ -1,5 +1,9 @@
import { useEffect, useMemo } from "react";
import { DataTable } from "@/src/components/table/data-table";
+import {
+ DataTableControlsProvider,
+ DataTableControls,
+} from "@/src/components/table/data-table-controls";
import TableLink from "@/src/components/table/table-link";
import { type LangfuseColumnDef } from "@/src/components/table/types";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
@@ -10,6 +14,8 @@ import { type RouterOutput } from "@/src/utils/types";
import { TagPromptPopover } from "@/src/features/tag/components/TagPromptPopover";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";
+import { promptFilterConfig } from "@/src/features/filters/config/prompts-config";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import {
NumberParam,
@@ -31,7 +37,6 @@ import {
BreadcrumbSeparator,
} from "@/src/components/ui/breadcrumb";
import { Slash, Folder, Home } from "lucide-react";
-import { promptsTableColsWithOptions } from "@langfuse/shared";
import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";
type PromptTableRow = {
@@ -81,11 +86,7 @@ export function PromptTable() {
const projectId = useProjectIdFromURL();
const { setDetailPageList } = useDetailPageLists();
- const [filterState, setFilterState] = useQueryFilterState(
- [],
- "prompts",
- projectId,
- );
+ const [filterState] = useQueryFilterState([], "prompts", projectId);
const [orderByState, setOrderByState] = useOrderByState({
column: "createdAt",
@@ -229,6 +230,21 @@ export function PromptTable() {
const allTags = filterOptionTags.map((t) => t.value);
const totalCount = prompts.data?.totalCount ?? null;
+ const newFilterOptions = useMemo(
+ () => ({
+ type: ["text", "chat"],
+ labels: promptFilterOptions.data?.labels?.map((l) => l.value) || [],
+ tags: promptFilterOptions.data?.tags?.map((t) => t.value) || [],
+ version: [],
+ }),
+ [promptFilterOptions.data],
+ );
+
+ const queryFilter = useSidebarFilterState(
+ promptFilterConfig,
+ newFilterOptions,
+ );
+
useEffect(() => {
if (prompts.isSuccess) {
setDetailPageList(
@@ -378,114 +394,121 @@ export function PromptTable() {
] as LangfuseColumnDef<PromptTableRow>[];
return (
- <>
- {currentFolderPath && (
- <div className="ml-2 pt-2">
- <Breadcrumb>
- <BreadcrumbList>
- <BreadcrumbItem>
- <BreadcrumbLink
- className="cursor-pointer hover:underline"
- onClick={() => {
- setQueryParams({
- folder: undefined,
- pageIndex: 0,
- pageSize: queryParams.pageSize,
- });
- }}
- >
- <Home className="h-4 w-4" />
- </BreadcrumbLink>
- </BreadcrumbItem>
- {createBreadcrumbItems(currentFolderPath).flatMap(
- (item, index, array) => [
- index > 0 && (
- <BreadcrumbSeparator key={`sep-${item.folderPath}`}>
- <Slash />
- </BreadcrumbSeparator>
- ),
- <BreadcrumbItem key={item.folderPath}>
- {index === array.length - 1 ? (
- <BreadcrumbPage>{item.name}</BreadcrumbPage>
- ) : (
- <BreadcrumbLink
- className="cursor-pointer hover:underline"
- onClick={() => {
- setQueryParams({
- folder: item.folderPath,
- pageIndex: 0,
- pageSize: queryParams.pageSize,
- });
- }}
- >
- {item.name}
- </BreadcrumbLink>
- )}
- </BreadcrumbItem>,
- ],
- )}
- </BreadcrumbList>
- </Breadcrumb>
- </div>
- )}
- <DataTableToolbar
- columns={promptColumns}
- filterColumnDefinition={promptsTableColsWithOptions(
- promptFilterOptions.data,
+ <DataTableControlsProvider>
+ <div className="flex h-full w-full flex-col">
+ {/* Toolbar spanning full width */}
+ {currentFolderPath && (
+ <div className="ml-2 pt-2">
+ <Breadcrumb>
+ <BreadcrumbList>
+ <BreadcrumbItem>
+ <BreadcrumbLink
+ className="cursor-pointer hover:underline"
+ onClick={() => {
+ setQueryParams({
+ folder: undefined,
+ pageIndex: 0,
+ pageSize: queryParams.pageSize,
+ });
+ }}
+ >
+ <Home className="h-4 w-4" />
+ </BreadcrumbLink>
+ </BreadcrumbItem>
+ {createBreadcrumbItems(currentFolderPath).flatMap(
+ (item, index, array) => [
+ index > 0 && (
+ <BreadcrumbSeparator key={`sep-${item.folderPath}`}>
+ <Slash />
+ </BreadcrumbSeparator>
+ ),
+ <BreadcrumbItem key={item.folderPath}>
+ {index === array.length - 1 ? (
+ <BreadcrumbPage>{item.name}</BreadcrumbPage>
+ ) : (
+ <BreadcrumbLink
+ className="cursor-pointer hover:underline"
+ onClick={() => {
+ setQueryParams({
+ folder: item.folderPath,
+ pageIndex: 0,
+ pageSize: queryParams.pageSize,
+ });
+ }}
+ >
+ {item.name}
+ </BreadcrumbLink>
+ )}
+ </BreadcrumbItem>,
+ ],
+ )}
+ </BreadcrumbList>
+ </Breadcrumb>
+ </div>
)}
- filterState={filterState}
- setFilterState={useDebounce(setFilterState)}
- columnsWithCustomSelect={["labels", "tags"]}
- searchConfig={{
- metadataSearchFields: ["Name", "Tags", "Content"],
- updateQuery: useDebounce(setSearchQuery, 300),
- currentQuery: searchQuery ?? undefined,
- tableAllowsFullTextSearch: true,
- setSearchType,
- searchType,
- customDropdownLabels: {
- metadata: "Names, Tags",
- fullText: "Full Text",
- },
- hidePerformanceWarning: true,
- }}
- />
- <DataTable
- tableName={"prompts"}
- columns={promptColumns}
- data={
- prompts.isLoading
- ? { isLoading: true, isError: false }
- : prompts.isError
- ? {
- isLoading: false,
- isError: true,
- error: prompts.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: processedRowData.rows?.map((item) => ({
- id: item.id,
- name: item.name,
- fullPath: item.fullPath,
- version: item.version,
- createdAt: item.createdAt,
- type: item.type,
- labels: item.labels,
- numberOfObservations: item.numberOfObservations,
- tags: item.tags,
- })),
- }
- }
- orderBy={orderByState}
- setOrderBy={setOrderByState}
- pagination={{
- totalCount,
- onChange: setQueryParams,
- state: paginationState,
- }}
- />
- </>
+ <DataTableToolbar
+ columns={promptColumns}
+ filterState={queryFilter.filterState}
+ columnsWithCustomSelect={["labels", "tags"]}
+ searchConfig={{
+ metadataSearchFields: ["Name", "Tags", "Content"],
+ updateQuery: useDebounce(setSearchQuery, 300),
+ currentQuery: searchQuery ?? undefined,
+ tableAllowsFullTextSearch: true,
+ setSearchType,
+ searchType,
+ customDropdownLabels: {
+ metadata: "Names, Tags",
+ fullText: "Full Text",
+ },
+ hidePerformanceWarning: true,
+ }}
+ />
+
+ {/* Content area with sidebar and table */}
+ <div className="flex flex-1 overflow-hidden">
+ <DataTableControls queryFilter={queryFilter} />
+
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <DataTable
+ tableName={"prompts"}
+ columns={promptColumns}
+ data={
+ prompts.isLoading
+ ? { isLoading: true, isError: false }
+ : prompts.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: prompts.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: processedRowData.rows?.map((item) => ({
+ id: item.id,
+ name: item.name,
+ fullPath: item.fullPath,
+ version: item.version,
+ createdAt: item.createdAt,
+ type: item.type,
+ labels: item.labels,
+ numberOfObservations: item.numberOfObservations,
+ tags: item.tags,
+ })),
+ }
+ }
+ orderBy={orderByState}
+ setOrderBy={setOrderByState}
+ pagination={{
+ totalCount,
+ onChange: setQueryParams,
+ state: paginationState,
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ </DataTableControlsProvider>
);
}
diff --git a/web/src/hooks/use-environment-filter.tsx b/web/src/hooks/use-environment-filter.tsx
index 721e03dd4c..e8c0ddb4a9 100644
--- a/web/src/hooks/use-environment-filter.tsx
+++ b/web/src/hooks/use-environment-filter.tsx
@@ -12,14 +12,22 @@ export function convertSelectedEnvironmentsToFilter(
environmentColumns: string[],
selectedEnvironments: string[],
) {
- return selectedEnvironments.length > 0
- ? environmentColumns.map((column) => ({
- type: "stringOptions" as const,
- column,
- operator: "any of" as const,
- value: selectedEnvironments,
- }))
- : [];
+ if (selectedEnvironments.length === 0) {
+ // No environments selected = show nothing
+ return environmentColumns.map((column) => ({
+ type: "stringOptions" as const,
+ column,
+ operator: "any of" as const,
+ value: ["__NEVER_MATCH_ANYTHING__"], // Impossible value to match
+ }));
+ }
+
+ return environmentColumns.map((column) => ({
+ type: "stringOptions" as const,
+ column,
+ operator: "any of" as const,
+ value: selectedEnvironments,
+ }));
}
export function useEnvironmentFilter(
@@ -55,9 +63,9 @@ export function useEnvironmentFilter(
let hasChanges = false;
availableEnvironments.forEach((env) => {
- // If environment doesn't exist in map, set default visibility
+ // If environment doesn't exist in map, set default visibility to true (all selected)
if (updatedMap[env] === undefined) {
- updatedMap[env] = !env.startsWith("langfuse");
+ updatedMap[env] = true;
hasChanges = true;
}
});
diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsx
index c7157a00e7..90319c2005 100644
--- a/web/src/pages/project/[projectId]/index.tsx
+++ b/web/src/pages/project/[projectId]/index.tsx
@@ -98,7 +98,11 @@ export default function Dashboard() {
const { selectedEnvironments, setSelectedEnvironments } =
useEnvironmentFilter(environmentOptions, projectId);
- const nameOptions = traceFilterOptions.data?.name || [];
+ const nameOptions =
+ traceFilterOptions.data?.name?.map((n) => ({
+ value: n.value,
+ count: Number(n.count),
+ })) || [];
const tagsOptions = traceFilterOptions.data?.tags || [];
const filterColumns: ColumnDefinition[] = [
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index 429e8c22b4..72cd026d19 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -206,7 +206,7 @@ export const traceRouter = createTRPCRouter({
]);
return {
- name: traceNames.map((n) => ({ value: n.name })),
+ name: traceNames.map((n) => ({ value: n.name, count: n.count })),
scores_avg: numericScoreNames.map((s) => s.name),
score_categories: categoricalScoreNames,
tags: tags,