Skip to content

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

revert: filter sidebar (#9592)

Leo Weigand72d7a99ff247
diff --git a/packages/shared/src/server/repositories/trace-sessions.ts b/packages/shared/src/server/repositories/trace-sessions.ts
index 77fbb85862..742c6ffcc9 100644
--- a/packages/shared/src/server/repositories/trace-sessions.ts
+++ b/packages/shared/src/server/repositories/trace-sessions.ts
@@ -9,9 +9,7 @@ export const getPublicSessionsFilter = async (
// Theoretically we should also filter the sessions by environment here. As this would return a huge list that's probably not feasible.
// I.e. we only perform the environment check on the ClickHouse queries.
- const sessionsBookmarkedFilter = filter?.find(
- (f) => f.column === "⭐️" || f.column === "bookmarked",
- );
+ const sessionsBookmarkedFilter = filter?.find((f) => f.column === "⭐️");
let additionalBookmarkFilter: z.infer<typeof singleFilter>[] = [];
if (sessionsBookmarkedFilter) {
@@ -67,12 +65,7 @@ export const getPublicSessionsFilter = async (
}
return filter
- ? [
- ...filter.filter(
- (f) => f.column !== "⭐️" && f.column !== "bookmarked",
- ),
- ...additionalBookmarkFilter,
- ]
+ ? [...filter.filter((f) => f.column !== "⭐️"), ...additionalBookmarkFilter]
: [...additionalBookmarkFilter];
};
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index ee30dd5ac8..1912440c8e 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -830,7 +830,6 @@ export const getTracesGroupedByName = async (
from traces t
WHERE t.project_id = {projectId: String}
AND t.name IS NOT NULL
- AND t.name != ''
${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}
GROUP BY name
ORDER BY count(*) desc
@@ -861,7 +860,6 @@ export const getTracesGroupedByName = async (
from ${traceAmt} t
WHERE t.project_id = {projectId: String}
AND t.name IS NOT NULL
- AND t.name != ''
GROUP BY name
ORDER BY count(*) desc
LIMIT 1000;
diff --git a/packages/shared/src/tableDefinitions/sessionsView.ts b/packages/shared/src/tableDefinitions/sessionsView.ts
index 20b7d42acd..6834593a12 100644
--- a/packages/shared/src/tableDefinitions/sessionsView.ts
+++ b/packages/shared/src/tableDefinitions/sessionsView.ts
@@ -83,7 +83,7 @@ export const sessionsViewCols: ColumnDefinition[] = [
},
{
name: "Trace Tags",
- id: "traceTags",
+ id: "tags",
type: "arrayOptions",
internal: 't."tags"',
options: [], // to be filled in at runtime
@@ -106,7 +106,7 @@ export const sessionsViewCols: ColumnDefinition[] = [
export type SessionOptions = {
userIds: Array<SingleValueOption>;
- traceTags: Array<SingleValueOption>;
+ tags: Array<SingleValueOption>;
scores_avg?: Array<string>;
score_categories?: Array<MultiValueOption>;
};
@@ -118,8 +118,8 @@ export function sessionsTableColsWithOptions(
if (col.id === "userIds") {
return formatColumnOptions(col, options?.userIds ?? []);
}
- if (col.id === "traceTags") {
- return formatColumnOptions(col, options?.traceTags ?? []);
+ if (col.id === "tags") {
+ return formatColumnOptions(col, options?.tags ?? []);
}
if (col.id === "scores_avg") {
return formatColumnOptions(col, options?.scores_avg ?? []);
diff --git a/web/src/__tests__/filter-query-encoding-decoding.clienttest.ts b/web/src/__tests__/filter-query-encoding-decoding.clienttest.ts
deleted file mode 100644
index 77babf211c..0000000000
--- a/web/src/__tests__/filter-query-encoding-decoding.clienttest.ts
+++ /dev/null
@@ -1,1138 +0,0 @@
-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",
- scores: "scores",
-};
-
-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 },
- { id: "scores", name: "scores", type: "numberObject" 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: [],
- scores: [],
- };
-
- 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",
- );
- });
-
- it("should encode numberObject and categoryOptions filters with spaces in keys by quoting", () => {
- const filters: FilterState = [
- {
- column: "scores",
- type: "numberObject",
- operator: "<",
- key: "Neural Validation",
- value: 1,
- },
- {
- column: "ratings",
- type: "categoryOptions",
- operator: "any of",
- key: "Danger Level",
- value: ["high"],
- },
- ];
- expect(encodeFilters(filters, mockOptions)).toBe(
- 'scores."Neural Validation":<:1 ratings."Danger Level":high',
- );
- });
- });
-
- 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"],
- },
- ]);
- });
-
- it("should decode quoted keys with spaces in numberObject and categoryOptions filters", () => {
- const query =
- 'scores."Neural Validation":<:1 ratings."Danger Level":high';
- const decoded = decodeFilters(query, mockOptions);
- expect(decoded).toEqual([
- {
- column: "scores",
- type: "numberObject",
- operator: "<",
- key: "Neural Validation",
- value: 1,
- },
- {
- column: "ratings",
- type: "categoryOptions",
- operator: "any of",
- key: "Danger Level",
- value: ["high"],
- },
- ]);
- });
- });
-
- 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);
- });
-
- it("should maintain consistency for filters with quoted keys containing spaces", () => {
- const filters: FilterState = [
- {
- column: "scores",
- type: "numberObject",
- operator: "<",
- key: "Neural Validation",
- value: 1,
- },
- {
- column: "ratings",
- type: "categoryOptions",
- operator: "any of",
- key: "Danger Level",
- value: ["high"],
- },
- ];
-
- const serialized = encodeFilters(filters, mockOptions);
- const deserialized = decodeFilters(serialized, mockOptions);
-
- expect(deserialized).toEqual(filters);
- });
- });
-});
diff --git a/web/src/components/table/data-table-ai-filters.tsx b/web/src/components/table/data-table-ai-filters.tsx
deleted file mode 100644
index a4a8d58b21..0000000000
--- a/web/src/components/table/data-table-ai-filters.tsx
+++ /dev/null
@@ -1,155 +0,0 @@
-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
deleted file mode 100644
index 8916f62818..0000000000
--- a/web/src/components/table/data-table-controls.tsx
+++ /dev/null
@@ -1,946 +0,0 @@
-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 27da735666..25719721b6 100644
--- a/web/src/components/table/data-table-toolbar.tsx
+++ b/web/src/components/table/data-table-toolbar.tsx
@@ -21,13 +21,7 @@ import {
DataTableRowHeightSwitch,
type RowHeight,
} from "@/src/components/table/data-table-row-height-switch";
-import {
- Search,
- ChevronDown,
- PanelLeftClose,
- PanelLeftOpen,
-} from "lucide-react";
-import { Badge } from "@/src/components/ui/badge";
+import { Search, ChevronDown } from "lucide-react";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { TimeRangePicker } from "@/src/components/date-picker";
import {
@@ -35,6 +29,7 @@ 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";
@@ -45,8 +40,6 @@ 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;
@@ -142,36 +135,12 @@ 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 max-w-[30rem] flex-shrink-0 items-stretch md:min-w-[24rem]">
+ <div className="flex min-w-0 max-w-64 flex-shrink-0 items-stretch">
<div
className={cn(
"flex h-8 flex-1 items-center border border-input bg-background pl-2",
@@ -296,7 +265,7 @@ export function DataTableToolbar<TData, TValue>({
/>
)}
{environmentFilter && (
- <MultiSelectFilter
+ <MultiSelect
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
deleted file mode 100644
index 04e2de212d..0000000000
--- a/web/src/components/table/key-value-filter-builder.tsx
+++ /dev/null
@@ -1,417 +0,0 @@
-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);
-
- // Sync with activeFilters, but preserve draft filters when user is editing
- useEffect(() => {
- // Always sync when activeFilters has content (handles external updates like URL changes)
- if (activeFilters.length > 0) {
- setLocalFilters(activeFilters);
- }
- // When activeFilters is empty, keep existing localFilters to preserve drafts
- // This allows users to temporarily clear values while editing without losing the filter row
- }, [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 ca6f5726d5..13de678c01 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -1,16 +1,10 @@
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";
@@ -33,6 +27,7 @@ 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";
@@ -251,75 +246,15 @@ export default function ObservationsTable({
const environmentOptions =
environmentFilterOptions.data?.map((value) => value.environment) || [];
- const { selectedEnvironments } = useEnvironmentFilter(
- environmentOptions,
- projectId,
- );
+ const { selectedEnvironments, setSelectedEnvironments } =
+ useEnvironmentFilter(environmentOptions, projectId);
const environmentFilter = convertSelectedEnvironmentsToFilter(
["environment"],
selectedEnvironments,
);
- 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(
+ const filterState = inputFilterState.concat(
dateRangeFilter,
promptNameFilter,
promptVersionFilter,
@@ -353,6 +288,26 @@ 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({
@@ -1107,145 +1062,141 @@ export default function ObservationsTable({
}, [generations]);
return (
- <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,
- }}
+ <>
+ <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}
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}
- 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,
- }}
- />
-
- {/* 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={"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();
+ />
+ ) : 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;
+ // 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)}`;
+ if (traceId) {
+ let observationUrl = `/project/${projectId}/traces/${encodeURIComponent(traceId)}`;
- const params = new URLSearchParams();
- params.set("observation", observationId);
- if (timestamp) {
- params.set("timestamp", timestamp.toISOString());
- }
+ const params = new URLSearchParams();
+ params.set("observation", observationId);
+ if (timestamp) {
+ params.set("timestamp", timestamp.toISOString());
+ }
- observationUrl += `?${params.toString()}`;
+ 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>
+ 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
+ }}
+ />
+ </>
);
}
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index 645d86be80..7935519d1c 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -1,20 +1,15 @@
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 {
@@ -172,10 +167,8 @@ export default function ScoresTable({
const environmentOptions =
environmentFilterOptions.data?.map((value) => value.environment) || [];
- const { selectedEnvironments } = useEnvironmentFilter(
- environmentOptions,
- projectId,
- );
+ const { selectedEnvironments, setSelectedEnvironments } =
+ useEnvironmentFilter(environmentOptions, projectId);
const environmentFilter = convertSelectedEnvironmentsToFilter(
["environment"],
@@ -270,21 +263,6 @@ 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",
@@ -668,96 +646,92 @@ export default function ScoresTable({
});
return (
- <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 }}
+ <>
+ <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}
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}
/>
- </div>
- </div>
- </div>
- </DataTableControlsProvider>
+ ) : 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}
+ />
+ </>
);
}
diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsx
index 6945de5e54..30851ece00 100644
--- a/web/src/components/table/use-cases/sessions.tsx
+++ b/web/src/components/table/use-cases/sessions.tsx
@@ -1,17 +1,11 @@
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,
@@ -31,6 +25,7 @@ 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";
@@ -38,6 +33,10 @@ import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-
import { cn } from "@/src/utils/tailwind";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
import { LocalIsoDate } from "@/src/components/LocalIsoDate";
+import {
+ useEnvironmentFilter,
+ convertSelectedEnvironmentsToFilter,
+} from "@/src/hooks/use-environment-filter";
import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";
import { Badge } from "@/src/components/ui/badge";
import { type ScoreAggregate } from "@langfuse/shared";
@@ -141,6 +140,23 @@ export default function SessionsTable({
},
);
+ const environmentOptions =
+ environmentFilterOptions.data?.map((value) => value.environment) || [];
+
+ const { selectedEnvironments, setSelectedEnvironments } =
+ useEnvironmentFilter(environmentOptions, projectId);
+
+ const environmentFilter = convertSelectedEnvironmentsToFilter(
+ ["environment"],
+ selectedEnvironments,
+ );
+
+ const filterState = userFilterState.concat(
+ userIdFilter,
+ dateRangeFilter,
+ environmentFilter,
+ );
+
const { selectAll, setSelectAll } = useSelectAll(projectId, "sessions");
const [paginationState, setPaginationState] = useQueryParams({
@@ -155,6 +171,28 @@ export default function SessionsTable({
order: "DESC",
});
+ const payloadCount = {
+ projectId,
+ filter: filterState,
+ orderBy: null,
+ page: 0,
+ limit: 1,
+ };
+
+ const payloadGetAll = {
+ ...payloadCount,
+ orderBy: orderByState,
+ page: paginationState.pageIndex,
+ limit: paginationState.pageSize,
+ };
+
+ const sessions = api.sessions.all.useQuery(payloadGetAll, {
+ refetchOnWindowFocus: true,
+ });
+ const sessionCountQuery = api.sessions.countAll.useQuery(payloadCount, {
+ refetchOnWindowFocus: true,
+ });
+
const addToQueueMutation = api.annotationQueueItems.createMany.useMutation({
onSuccess: (data) => {
showSuccessToast({
@@ -176,6 +214,25 @@ export default function SessionsTable({
filter: scoreFilters.forSessions(),
});
+ const sessionMetrics = api.sessions.metrics.useQuery(
+ {
+ projectId,
+ sessionIds: sessions.data?.sessions.map((s) => s.id) ?? [],
+ },
+ {
+ enabled: sessions.data !== undefined,
+ refetchOnWindowFocus: true,
+ },
+ );
+
+ type SessionCoreOutput = RouterOutput["sessions"]["all"]["sessions"][number];
+ type SessionMetricOutput = RouterOutput["sessions"]["metrics"][number];
+
+ const sessionRowData = joinTableCoreAndMetrics<
+ SessionCoreOutput,
+ SessionMetricOutput
+ >(sessions.data?.sessions, sessionMetrics.data);
+
const filterOptions = api.sessions.filterOptions.useQuery(
{
projectId,
@@ -197,91 +254,6 @@ export default function SessionsTable({
},
);
- const newFilterOptions = useMemo(() => {
- const scoreCategories =
- filterOptions.data?.score_categories?.reduce(
- (acc, score) => {
- acc[score.label] = score.values;
- return acc;
- },
- {} as Record<string, string[]>,
- ) || {};
-
- const scoresNumeric = filterOptions.data?.scores_avg || [];
-
- return {
- bookmarked: ["Bookmarked", "Not bookmarked"],
- id: [],
- userIds: filterOptions.data?.userIds?.map((u) => u.value) || [],
- traceTags: filterOptions.data?.traceTags?.map((t) => t.value) || [],
- environment:
- environmentFilterOptions.data?.map((value) => value.environment) || [],
- sessionDuration: [],
- countTraces: [],
- inputTokens: [],
- outputTokens: [],
- totalTokens: [],
- usage: [],
- inputCost: [],
- outputCost: [],
- totalCost: [],
- "Scores (categorical)": scoreCategories,
- "Scores (numeric)": scoresNumeric,
- };
- }, [environmentFilterOptions.data, filterOptions.data]);
-
- const queryFilter = useSidebarFilterState(
- sessionFilterConfig,
- newFilterOptions,
- );
-
- const filterState = queryFilter.filterState.concat(
- userFilterState,
- userIdFilter,
- dateRangeFilter,
- );
-
- const payloadCount = {
- projectId,
- filter: filterState,
- orderBy: null,
- page: 0,
- limit: 1,
- };
-
- const payloadGetAll = {
- ...payloadCount,
- orderBy: orderByState,
- page: paginationState.pageIndex,
- limit: paginationState.pageSize,
- };
-
- const sessions = api.sessions.all.useQuery(payloadGetAll, {
- refetchOnWindowFocus: true,
- });
- const sessionCountQuery = api.sessions.countAll.useQuery(payloadCount, {
- refetchOnWindowFocus: true,
- });
-
- const sessionMetrics = api.sessions.metrics.useQuery(
- {
- projectId,
- sessionIds: sessions.data?.sessions.map((s) => s.id) ?? [],
- },
- {
- enabled: sessions.data !== undefined,
- refetchOnWindowFocus: true,
- },
- );
-
- type SessionCoreOutput = RouterOutput["sessions"]["all"]["sessions"][number];
- type SessionMetricOutput = RouterOutput["sessions"]["metrics"][number];
-
- const sessionRowData = joinTableCoreAndMetrics<
- SessionCoreOutput,
- SessionMetricOutput
- >(sessions.data?.sessions, sessionMetrics.data);
-
const totalCount = sessionCountQuery.data?.totalCount ?? null;
useEffect(() => {
if (sessions.isSuccess) {
@@ -680,116 +652,110 @@ export default function SessionsTable({
});
return (
- <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}
+ <>
+ <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}
/>
- </div>
- </div>
- </div>
- </DataTableControlsProvider>
+ ) : 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}
+ />
+ </>
);
}
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index bf92c0faa9..9633df8bae 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -1,15 +1,12 @@
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";
@@ -44,6 +41,7 @@ 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";
@@ -71,8 +69,10 @@ import {
} from "@/src/components/ui/dropdown-menu";
import { Button } from "@/src/components/ui/button";
import TableIdOrName from "@/src/components/table/table-id";
-import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";
-import { traceFilterConfig } from "@/src/features/filters/config/traces-config";
+import {
+ useEnvironmentFilter,
+ convertSelectedEnvironmentsToFilter,
+} from "@/src/hooks/use-environment-filter";
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,6 +80,7 @@ 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
@@ -142,6 +143,7 @@ export default function TracesTable({
externalDateRange,
limitRows,
}: TracesTableProps) {
+ const router = useRouter();
const utils = api.useUtils();
const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});
const { setDetailPageList } = useDetailPageLists();
@@ -155,6 +157,12 @@ export default function TracesTable({
const dateRange = externalDateRange ?? tableDateRange;
+ const [userFilterState, setUserFilterState] = useQueryFilterState(
+ [],
+ "traces",
+ projectId,
+ );
+
const [orderByState, setOrderByState] = useOrderByState({
column: "timestamp",
order: "DESC",
@@ -206,53 +214,21 @@ export default function TracesTable({
},
);
- 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 environmentOptions =
+ environmentFilterOptions.data?.map((value) => value.environment) || [];
- 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 { selectedEnvironments, setSelectedEnvironments } =
+ useEnvironmentFilter(environmentOptions, projectId);
- const queryFilter = useSidebarFilterState(traceFilterConfig, filterOptions);
+ const environmentFilter = convertSelectedEnvironmentsToFilter(
+ ["environment"],
+ selectedEnvironments,
+ );
- const combinedFilterState = queryFilter.filterState.concat(
+ const combinedFilterState = userFilterState.concat(
userIdFilter,
dateRangeFilter,
+ environmentFilter,
);
// Use external filter state if provided, otherwise use combined filter state
@@ -336,23 +312,21 @@ 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(() => {
- // 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(
+ return tracesTableColsWithOptions(traceFilterOptions).filter(
(c) =>
c.id !== "environment" &&
c.id !== "timestamp" &&
@@ -1098,7 +1072,7 @@ export default function TracesTable({
projectId,
stateUpdaters: {
setOrderBy: setOrderByState,
- setFilters: queryFilter.setFilterState,
+ setFilters: setUserFilterState,
setColumnOrder: setColumnOrder,
setColumnVisibility: setColumnVisibility,
setSearchQuery: setSearchQuery,
@@ -1155,122 +1129,150 @@ export default function TracesTable({
: [];
}, [traces.isSuccess, traceRowData?.rows]);
+ const setFilterState = useDebounce(setUserFilterState);
+
return (
- <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,
- }}
+ <>
+ {!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}
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,
- }}
- />
- )}
-
- {/* 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,
- }
- }
- pagination={
- limitRows
- ? undefined
- : {
- totalCount,
- onChange: setPaginationState,
- state: paginationState,
- }
+ />
+ ) : 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,
}
- 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>
+ }
+ 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"}
+ />
+ </>
);
}
diff --git a/web/src/components/ui/slider.tsx b/web/src/components/ui/slider.tsx
index b0626b0c4d..28f3de9a74 100644
--- a/web/src/components/ui/slider.tsx
+++ b/web/src/components/ui/slider.tsx
@@ -82,10 +82,6 @@ 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
@@ -101,15 +97,12 @@ const Slider = React.forwardRef<
)}
/>
</SliderPrimitive.Track>
- {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.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",
+ )}
+ />
</SliderPrimitive.Root>
{showInput && (
diff --git a/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx b/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
index 92fcd49442..8b3f2fb855 100644
--- a/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
+++ b/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
@@ -40,6 +40,7 @@ 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 e9cd7d14be..d00688a1c4 100644
--- a/web/src/features/evals/components/evaluator-table.tsx
+++ b/web/src/features/evals/components/evaluator-table.tsx
@@ -2,17 +2,11 @@ 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";
@@ -50,6 +44,7 @@ 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";
@@ -91,23 +86,17 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
const [editConfigId, setEditConfigId] = useState<string | null>(null);
const utils = api.useUtils();
- const [filterState] = useQueryFilterState([], "eval_configs", projectId);
+ const [filterState, setFilterState] = 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,
@@ -364,121 +353,109 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
};
return (
- <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),
- ),
- }
+ <>
+ <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
}
- pagination={{
- totalCount,
- onChange: setPaginationState,
- state: paginationState,
+ 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",
+ });
}}
- 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
- }
- 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>
+ )}
+ </DialogContent>
+ </Dialog>
+ </>
);
}
diff --git a/web/src/features/evals/components/inner-evaluator-form.tsx b/web/src/features/evals/components/inner-evaluator-form.tsx
index 236a6ce209..4658bb191b 100644
--- a/web/src/features/evals/components/inner-evaluator-form.tsx
+++ b/web/src/features/evals/components/inner-evaluator-form.tsx
@@ -215,23 +215,8 @@ 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 {
- ...normalized,
+ ...(traceFilterOptionsResponse.data ?? {}),
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 8cc4e00bdc..e29402afab 100644
--- a/web/src/features/filters/components/filter-builder.tsx
+++ b/web/src/features/filters/components/filter-builder.tsx
@@ -16,6 +16,7 @@ import {
Check,
ChevronDown,
ExternalLink,
+ Filter,
Info,
Plus,
WandSparkles,
@@ -62,6 +63,7 @@ export function PopoverFilterBuilder({
filterState,
onChange,
columnsWithCustomSelect = [],
+ variant = "default",
filterWithAI = false,
}: {
columns: ColumnDefinition[];
@@ -70,6 +72,7 @@ export function PopoverFilterBuilder({
| Dispatch<SetStateAction<FilterState>>
| ((newState: FilterState) => void);
columnsWithCustomSelect?: string[];
+ variant?: "default" | "icon";
filterWithAI?: boolean;
}) {
const capture = usePostHogClientCapture();
@@ -125,27 +128,43 @@ export function PopoverFilterBuilder({
}}
>
<PopoverTrigger asChild>
- <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>
+ {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>
+ )}
</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
deleted file mode 100644
index b0810e57af..0000000000
--- a/web/src/features/filters/config/evaluators-config.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-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
deleted file mode 100644
index 3233016192..0000000000
--- a/web/src/features/filters/config/observations-config.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-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
deleted file mode 100644
index 3e43796288..0000000000
--- a/web/src/features/filters/config/prompts-config.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-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
deleted file mode 100644
index cb49891334..0000000000
--- a/web/src/features/filters/config/scores-config.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-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
deleted file mode 100644
index f8c0ba8cb5..0000000000
--- a/web/src/features/filters/config/sessions-config.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-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",
- id: "id",
- userIds: "userIds",
- sessionDuration: "duration",
- countTraces: "traces",
- inputCost: "inputCost",
- outputCost: "outputCost",
- totalCost: "totalCost",
- inputTokens: "inputTokens",
- outputTokens: "outputTokens",
- totalTokens: "totalTokens",
- usage: "usage",
- traceTags: "tags",
- environment: "env",
- "Scores (categorical)": "scoreCategories",
- "Scores (numeric)": "scoresNumeric",
-};
-
-export const sessionFilterConfig: FilterConfig = {
- tableName: "sessions",
-
- columnToQueryKey: SESSION_COLUMN_TO_QUERY_KEY,
-
- columnDefinitions: sessionsViewCols,
-
- defaultExpanded: ["bookmarked"],
-
- facets: [
- {
- type: "categorical" as const,
- column: "environment",
- label: "Environment",
- },
- {
- type: "string" as const,
- column: "id",
- label: "ID",
- },
- {
- type: "categorical" as const,
- column: "userIds",
- label: "User IDs",
- },
- {
- type: "categorical" as const,
- column: "traceTags",
- label: "Trace Tags",
- },
- {
- 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: "$",
- },
- {
- type: "numeric" as const,
- column: "usage",
- label: "Usage",
- min: 0,
- max: 1000000,
- },
- {
- 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/config/traces-config.ts b/web/src/features/filters/config/traces-config.ts
deleted file mode 100644
index 3f1ad6d7ff..0000000000
--- a/web/src/features/filters/config/traces-config.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-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
deleted file mode 100644
index f6a59371c7..0000000000
--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx
+++ /dev/null
@@ -1,860 +0,0 @@
-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
deleted file mode 100644
index 42931542f1..0000000000
--- a/web/src/features/filters/lib/filter-config.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-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
deleted file mode 100644
index ee5ceea607..0000000000
--- a/web/src/features/filters/lib/filter-query-encoding.ts
+++ /dev/null
@@ -1,532 +0,0 @@
-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 inQuotes = false;
- 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 === '"') {
- // Toggle quote state and include the quote
- inQuotes = !inQuotes;
- current += char;
- } else if (char === " " && !inQuotes && current.trim()) {
- // Unescaped space outside quotes - end current part
- parts.push(current);
- current = "";
- } else if (char !== " " || inQuotes) {
- // Regular character, or space inside quotes
- 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 e405992fdd..178b2c6dc8 100644
--- a/web/src/features/prompts/components/prompts-table.tsx
+++ b/web/src/features/prompts/components/prompts-table.tsx
@@ -1,9 +1,5 @@
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";
@@ -14,8 +10,6 @@ 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,
@@ -37,6 +31,7 @@ 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 = {
@@ -86,7 +81,11 @@ export function PromptTable() {
const projectId = useProjectIdFromURL();
const { setDetailPageList } = useDetailPageLists();
- const [filterState] = useQueryFilterState([], "prompts", projectId);
+ const [filterState, setFilterState] = useQueryFilterState(
+ [],
+ "prompts",
+ projectId,
+ );
const [orderByState, setOrderByState] = useOrderByState({
column: "createdAt",
@@ -230,21 +229,6 @@ 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(
@@ -394,121 +378,114 @@ export function PromptTable() {
] as LangfuseColumnDef<PromptTableRow>[];
return (
- <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>
- )}
- <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>
+ <>
+ {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>
- </div>
- </DataTableControlsProvider>
+ )}
+ <DataTableToolbar
+ columns={promptColumns}
+ filterColumnDefinition={promptsTableColsWithOptions(
+ promptFilterOptions.data,
+ )}
+ 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,
+ }}
+ />
+ </>
);
}
diff --git a/web/src/hooks/use-environment-filter.tsx b/web/src/hooks/use-environment-filter.tsx
index e8c0ddb4a9..721e03dd4c 100644
--- a/web/src/hooks/use-environment-filter.tsx
+++ b/web/src/hooks/use-environment-filter.tsx
@@ -12,22 +12,14 @@ export function convertSelectedEnvironmentsToFilter(
environmentColumns: string[],
selectedEnvironments: string[],
) {
- 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,
- }));
+ return selectedEnvironments.length > 0
+ ? environmentColumns.map((column) => ({
+ type: "stringOptions" as const,
+ column,
+ operator: "any of" as const,
+ value: selectedEnvironments,
+ }))
+ : [];
}
export function useEnvironmentFilter(
@@ -63,9 +55,9 @@ export function useEnvironmentFilter(
let hasChanges = false;
availableEnvironments.forEach((env) => {
- // If environment doesn't exist in map, set default visibility to true (all selected)
+ // If environment doesn't exist in map, set default visibility
if (updatedMap[env] === undefined) {
- updatedMap[env] = true;
+ updatedMap[env] = !env.startsWith("langfuse");
hasChanges = true;
}
});
diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsx
index 90319c2005..c7157a00e7 100644
--- a/web/src/pages/project/[projectId]/index.tsx
+++ b/web/src/pages/project/[projectId]/index.tsx
@@ -98,11 +98,7 @@ export default function Dashboard() {
const { selectedEnvironments, setSelectedEnvironments } =
useEnvironmentFilter(environmentOptions, projectId);
- const nameOptions =
- traceFilterOptions.data?.name?.map((n) => ({
- value: n.value,
- count: Number(n.count),
- })) || [];
+ const nameOptions = traceFilterOptions.data?.name || [];
const tagsOptions = traceFilterOptions.data?.tags || [];
const filterColumns: ColumnDefinition[] = [
diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.ts
index ebe28a3bf1..404f73fb48 100644
--- a/web/src/server/api/routers/sessions.ts
+++ b/web/src/server/api/routers/sessions.ts
@@ -367,7 +367,7 @@ export const sessionRouter = createTRPCRouter({
userIds: userIds.map((row) => ({
value: row.user,
})),
- traceTags: tags.map((row) => ({
+ tags: tags.map((row) => ({
value: row.value,
})),
scores_avg: numericScoreNames.map((s) => s.name),
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index 21d6c9be1d..69590cd7ce 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -222,7 +222,7 @@ export const traceRouter = createTRPCRouter({
]);
return {
- name: traceNames.map((n) => ({ value: n.name, count: n.count })),
+ name: traceNames.map((n) => ({ value: n.name })),
scores_avg: numericScoreNames.map((s) => s.name),
score_categories: categoricalScoreNames,
tags: tags,