Skip to content

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

feat(filters): filter sidebar (#9782)

Nimara7131090d987
diff --git a/packages/shared/src/interfaces/filters.ts b/packages/shared/src/interfaces/filters.ts
index 4cf579511c..b88f0028f5 100644
--- a/packages/shared/src/interfaces/filters.ts
+++ b/packages/shared/src/interfaces/filters.ts
@@ -45,12 +45,17 @@ export const stringOptionsFilter = z.object({
value: z.array(z.string()).refine((v) => v.length > 0),
type: z.literal("stringOptions"),
});
-export const arrayOptionsFilter = z.object({
- column: z.string(),
- operator: z.enum(filterOperators.arrayOptions),
- value: z.array(z.string()).refine((v) => v.length > 0),
- type: z.literal("arrayOptions"),
-});
+export const arrayOptionsFilter = z
+ .object({
+ column: z.string(),
+ operator: z.enum(filterOperators.arrayOptions),
+ value: z.array(z.string()),
+ type: z.literal("arrayOptions"),
+ })
+ .refine((data) => data.operator === "all of" || data.value.length > 0, {
+ message:
+ "Value array must not be empty unless operator is 'all of' (which represents waiting for selection)",
+ });
export const stringObjectFilter = z.object({
type: z.literal("stringObject"),
column: z.string(),
diff --git a/web/jest.config.mjs b/web/jest.config.mjs
index 2b601ebe23..9fc492b49a 100644
--- a/web/jest.config.mjs
+++ b/web/jest.config.mjs
@@ -40,13 +40,21 @@ const endToEndServerTestConfig = {
};
// To avoid the "Cannot use import statement outside a module" errors while transforming ESM.
-const esModules = ["superjson"];
+// jsonpath-plus is needed because @langfuse/shared barrel exports evals/utilities which imports it
+const esModules = ["superjson", "jsonpath-plus"];
// Add any custom config to be passed to Jest
/** @type {import('jest').Config} */
const config = {
// Add more setup options before each test is run
projects: [
- await createJestConfig(clientTestConfig)(),
+ {
+ ...(await createJestConfig(clientTestConfig)()),
+ // Added transformIgnorePatterns to client tests to handle ESM dependencies from @langfuse/shared
+ // Without this, importing from @langfuse/shared fails with "Unexpected token 'export'" errors
+ transformIgnorePatterns: [
+ `/web/node_modules/(?!(${esModules.join("|")})/)`,
+ ],
+ },
{
...(await createJestConfig(serverTestConfig)()),
transformIgnorePatterns: [
diff --git a/web/src/components/table/data-table-ai-filters.tsx b/web/src/components/table/data-table-ai-filters.tsx
new file mode 100644
index 0000000000..a4a8d58b21
--- /dev/null
+++ b/web/src/components/table/data-table-ai-filters.tsx
@@ -0,0 +1,155 @@
+import { useState } from "react";
+import { Button } from "@/src/components/ui/button";
+import { Textarea } from "@/src/components/ui/textarea";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
+import { Info, ExternalLink } from "lucide-react";
+import { useQueryProject } from "@/src/features/projects/hooks";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
+import { api } from "@/src/utils/api";
+import { type FilterState } from "@langfuse/shared";
+
+interface DataTableAIFiltersProps {
+ onFiltersGenerated: (filters: FilterState) => void;
+}
+
+export function DataTableAIFilters({
+ onFiltersGenerated,
+}: DataTableAIFiltersProps) {
+ const [aiPrompt, setAiPrompt] = useState("");
+ const [aiError, setAiError] = useState<string | null>(null);
+ const projectId = useProjectIdFromURL();
+ const { organization } = useQueryProject();
+
+ const hasAdminAccess = useHasOrganizationAccess({
+ organizationId: organization?.id ?? undefined,
+ scope: "organization:update",
+ });
+
+ const createFilterMutation =
+ api.naturalLanguageFilters.createCompletion.useMutation();
+
+ const handleAiFilterSubmit = async () => {
+ if (aiPrompt.trim() && !createFilterMutation.isPending && projectId) {
+ setAiError(null);
+ try {
+ const result = await createFilterMutation.mutateAsync({
+ projectId,
+ prompt: aiPrompt.trim(),
+ });
+
+ if (result && Array.isArray(result.filters)) {
+ if (result.filters.length === 0) {
+ setAiError("Failed to generate filters, try again");
+ return;
+ }
+
+ // Set the filters from the API response
+ onFiltersGenerated(result.filters as FilterState);
+ setAiPrompt("");
+ } else {
+ console.error(result);
+ setAiError("Invalid response format from API");
+ }
+ } catch (error) {
+ console.error("Error calling tRPC API:", error);
+ setAiError(
+ error instanceof Error ? error.message : "Failed to generate filters",
+ );
+ }
+ }
+ };
+
+ // When AI features are not enabled
+ if (!organization?.aiFeaturesEnabled) {
+ return (
+ <div className="flex flex-col gap-3">
+ <p className="text-sm text-muted-foreground">
+ AI-powered filters use natural language to generate deterministic
+ filters.
+ {!hasAdminAccess &&
+ " Ask your organization administrator to enable AI features in organization settings."}
+ </p>
+ {hasAdminAccess && organization?.id && (
+ <Button
+ onClick={() => {
+ window.open(
+ `/organization/${organization.id}/settings`,
+ "_blank",
+ );
+ }}
+ variant="outline"
+ size="sm"
+ className="w-fit"
+ >
+ Enable in Organization Settings
+ <ExternalLink className="ml-2 h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ );
+ }
+
+ // When AI features are enabled
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">Filter with AI</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info className="h-4 w-4 text-muted-foreground" />
+ </TooltipTrigger>
+ <TooltipContent>
+ <p className="text-xs">
+ We convert natural language into deterministic filters which you
+ can adjust afterwards
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ <Textarea
+ autoFocus
+ value={aiPrompt}
+ onChange={(e) => {
+ setAiPrompt(e.target.value);
+ if (aiError) setAiError(null);
+ }}
+ placeholder="Describe the filters you want to apply..."
+ className="min-h-[80px] resize-none"
+ disabled={createFilterMutation.isPending}
+ onKeyDown={(e) => {
+ if (
+ e.key === "Enter" &&
+ !e.shiftKey &&
+ !createFilterMutation.isPending
+ ) {
+ e.preventDefault();
+ handleAiFilterSubmit();
+ }
+ }}
+ />
+ <Button
+ onClick={handleAiFilterSubmit}
+ type="button"
+ variant="default"
+ size="sm"
+ disabled={createFilterMutation.isPending || !aiPrompt.trim()}
+ className="w-fit"
+ >
+ {createFilterMutation.isPending ? "Loading..." : "Generate"}
+ </Button>
+ {aiError && (
+ <div className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
+ {aiError}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/components/table/data-table-controls.tsx b/web/src/components/table/data-table-controls.tsx
new file mode 100644
index 0000000000..30564d95b7
--- /dev/null
+++ b/web/src/components/table/data-table-controls.tsx
@@ -0,0 +1,1240 @@
+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,
+ TextFilterEntry,
+} 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,
+ tableName,
+ defaultSidebarCollapsed,
+}: {
+ children: React.ReactNode;
+ tableName?: string;
+ defaultSidebarCollapsed?: boolean;
+}) {
+ const storageKey = tableName
+ ? `data-table-controls-${tableName}`
+ : "data-table-controls";
+ const defaultOpen = !defaultSidebarCollapsed;
+ const [open, setOpen] = useLocalStorage(storageKey, defaultOpen);
+
+ 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}
+ operator={filter.operator}
+ onOperatorChange={filter.onOperatorChange}
+ textFilters={filter.textFilters}
+ onTextFilterAdd={filter.onTextFilterAdd}
+ onTextFilterRemove={filter.onTextFilterRemove}
+ />
+ );
+ }
+
+ 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}
+ keyPlaceholder="Name"
+ />
+ );
+ }
+
+ 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}
+ keyPlaceholder="Name"
+ />
+ );
+ }
+
+ 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;
+ operator?: "any of" | "all of";
+ onOperatorChange?: (operator: "any of" | "all of") => void;
+ textFilters?: TextFilterEntry[];
+ onTextFilterAdd?: (
+ operator: "contains" | "does not contain",
+ value: string,
+ ) => void;
+ onTextFilterRemove?: (
+ operator: "contains" | "does not contain",
+ 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;
+ keyPlaceholder?: string;
+}
+
+interface NumericKeyValueFacetProps extends BaseFacetProps {
+ keyOptions?: string[];
+ value: NumericKeyValueFilterEntry[];
+ onChange: (filters: NumericKeyValueFilterEntry[]) => void;
+ keyPlaceholder?: string;
+}
+
+interface StringKeyValueFacetProps extends BaseFacetProps {
+ keyOptions?: string[];
+ value: StringKeyValueFilterEntry[];
+ onChange: (filters: StringKeyValueFilterEntry[]) => void;
+ keyPlaceholder?: string;
+}
+
+// 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,
+ operator,
+ onOperatorChange,
+ textFilters,
+ onTextFilterAdd,
+ onTextFilterRemove,
+}: CategoricalFacetProps) {
+ const [showAll, setShowAll] = useState(false);
+ const [searchQuery, setSearchQuery] = useState("");
+ // Track which filter mode is active (select checkboxes vs text filters)
+ const [filterMode, setFilterMode] = useState<"select" | "text">("select");
+
+ // Reset showAll and searchQuery state when accordion is collapsed
+ useEffect(() => {
+ if (!expanded) {
+ setShowAll(false);
+ setSearchQuery("");
+ }
+ }, [expanded]);
+
+ // Handle mode change with auto-clear of filters from the other mode
+ const handleModeChange = useCallback(
+ (newMode: "select" | "text") => {
+ setFilterMode(newMode);
+
+ // Clear filters from the other mode
+ if (newMode === "select") {
+ textFilters?.forEach((f) => onTextFilterRemove?.(f.operator, f.value));
+ } else {
+ onChange([]);
+ }
+ },
+ [textFilters, onTextFilterRemove, onChange],
+ );
+
+ 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">
+ {/* Tab switcher - only show when text filtering is supported */}
+ {onTextFilterAdd && (
+ <FilterModeTabs mode={filterMode} onModeChange={handleModeChange} />
+ )}
+
+ {/* SELECT MODE: Checkboxes with optional counts */}
+ {filterMode === "select" && (
+ <div className="px-2">
+ {/* SOME/ALL Operator Toggle for arrayOptions filters
+
+ This toggle appears for multi-valued array columns (arrayOptions) like tags.
+ It allows switching between OR and AND logic:
+ - SOME: Match items with ANY selected value (OR logic)
+ - ALL: Match items with ALL selected values (AND logic)
+
+ The toggle is automatically enabled by useSidebarFilterState for any
+ arrayOptions column when selections exist. Other filter types (stringOptions,
+ boolean, numeric) don't get this toggle as "ALL" wouldn't be semantically meaningful.
+
+ Currently enabled for:
+ - Traces: tags
+ - Sessions: userIds, tags
+ - Prompts: labels, tags
+ */}
+ {onOperatorChange && value.length > 0 && (
+ <div className="mb-1.5 flex items-center gap-1.5 px-2">
+ <span className="text-[10px] text-muted-foreground/80">
+ Match:
+ </span>
+ <div className="inline-flex rounded border border-input/50 bg-background text-[10px]">
+ <button
+ onClick={() => onOperatorChange("any of")}
+ className={cn(
+ "rounded-l px-1.5 py-0.5 transition-colors",
+ operator === "any of" || !operator
+ ? "bg-accent font-medium text-accent-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ SOME
+ </button>
+ <div className="w-px bg-border/50" />
+ <button
+ onClick={() => onOperatorChange("all of")}
+ className={cn(
+ "rounded-r px-1.5 py-0.5 transition-colors",
+ operator === "all of"
+ ? "bg-accent font-medium text-accent-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ ALL
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Loading / Empty / Options */}
+ {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>
+ ) : (
+ <>
+ {/* Search box for many options */}
+ {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>
+ )}
+
+ {/* Checkbox list */}
+ {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>
+ )}
+
+ {/* TEXT MODE: Contains/Does Not Contain filters */}
+ {filterMode === "text" && onTextFilterAdd && (
+ <div className="px-2 py-1">
+ <TextFilterSection
+ allFilters={textFilters ?? []}
+ onAdd={onTextFilterAdd}
+ onRemove={onTextFilterRemove}
+ />
+ </div>
+ )}
+ </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,
+ keyPlaceholder,
+}: 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}
+ keyPlaceholder={keyPlaceholder}
+ />
+ )}
+ </FilterAccordionItem>
+ );
+}
+
+export function NumericKeyValueFacet({
+ label,
+ filterKey,
+ filterKeyShort,
+ expanded: _expanded,
+ loading,
+ keyOptions,
+ value,
+ onChange,
+ isActive,
+ onReset,
+ keyPlaceholder,
+}: 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}
+ keyPlaceholder={keyPlaceholder}
+ />
+ )}
+ </FilterAccordionItem>
+ );
+}
+
+export function StringKeyValueFacet({
+ label,
+ filterKey,
+ filterKeyShort,
+ expanded: _expanded,
+ loading,
+ keyOptions,
+ value,
+ onChange,
+ isActive,
+ onReset,
+ keyPlaceholder,
+}: 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}
+ keyPlaceholder={keyPlaceholder}
+ />
+ )}
+ </FilterAccordionItem>
+ );
+}
+
+// Filter mode tabs for switching between Select (checkboxes) and Text (contains) modes
+interface FilterModeTabsProps {
+ mode: "select" | "text";
+ onModeChange: (mode: "select" | "text") => void;
+}
+
+function FilterModeTabs({ mode, onModeChange }: FilterModeTabsProps) {
+ return (
+ <div className="mb-2 flex items-center gap-1.5 px-4">
+ <span className="text-[10px] text-muted-foreground/80">Mode:</span>
+ <div className="inline-flex flex-1 rounded border border-input/50 bg-background text-[10px]">
+ <button
+ onClick={() => onModeChange("select")}
+ className={cn(
+ "flex-1 rounded-l px-3 py-0.5 transition-colors",
+ mode === "select"
+ ? "bg-accent font-medium text-accent-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ SELECT
+ </button>
+ <div className="w-px bg-border/50" />
+ <button
+ onClick={() => onModeChange("text")}
+ className={cn(
+ "flex-1 rounded-r px-3 py-0.5 transition-colors",
+ mode === "text"
+ ? "bg-accent font-medium text-accent-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ TEXT
+ </button>
+ </div>
+ </div>
+ );
+}
+
+// Text filter section for categorical filters
+// Single input with DOES/DOES NOT toggle, allows adding multiple filters
+function TextFilterSection({
+ allFilters,
+ onAdd,
+ onRemove,
+}: {
+ allFilters: TextFilterEntry[];
+ onAdd?: (op: "contains" | "does not contain", val: string) => void;
+ onRemove?: (op: "contains" | "does not contain", val: string) => void;
+}) {
+ const [inputValue, setInputValue] = useState("");
+ const [selectedOperator, setSelectedOperator] = useState<
+ "contains" | "does not contain"
+ >("contains");
+
+ const handleAdd = () => {
+ // people have filtered for a single " ", e.g. does not contain " " on sessionID to get all traces with a session id
+ if (inputValue.length > 0 && onAdd) {
+ onAdd(selectedOperator, inputValue);
+ setInputValue("");
+ }
+ };
+
+ return (
+ <div className="space-y-2">
+ {/* Operator toggle */}
+ <div className="flex items-center gap-1 px-2">
+ <div className="inline-flex rounded border border-input/50 bg-background text-[10px]">
+ <button
+ onClick={() => setSelectedOperator("contains")}
+ className={cn(
+ "rounded-l px-2 py-0.5 transition-colors",
+ selectedOperator === "contains"
+ ? "bg-accent font-medium text-accent-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ contains
+ </button>
+ <div className="w-px bg-border/50" />
+ <button
+ onClick={() => setSelectedOperator("does not contain")}
+ className={cn(
+ "rounded-r px-2 py-0.5 transition-colors",
+ selectedOperator === "does not contain"
+ ? "bg-accent font-medium text-accent-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ does not contain
+ </button>
+ </div>
+ </div>
+
+ {/* Input + Add button */}
+ <div className="flex items-center gap-2 px-2">
+ <Input
+ value={inputValue}
+ onChange={(e) => setInputValue(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleAdd();
+ }
+ }}
+ placeholder="Enter value..."
+ className="h-7 flex-1 text-xs"
+ />
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={handleAdd}
+ disabled={inputValue.length === 0}
+ className="h-7 shrink-0 px-2 text-xs"
+ >
+ Add
+ </Button>
+ </div>
+
+ {/* Active filters list */}
+ {allFilters.length > 0 && (
+ <div className="space-y-1 px-2">
+ {allFilters.map((f, idx) => (
+ <div
+ key={idx}
+ className="group/textfilter flex items-center gap-2 rounded border border-border/40 bg-muted/30 px-2 py-1 text-xs"
+ >
+ <span className="shrink-0 text-[10px] font-medium text-muted-foreground">
+ {f.operator === "contains" ? "contains" : "does not contain"}
+ </span>
+ <span className="min-w-0 flex-1 truncate font-medium">
+ {f.value}
+ </span>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => onRemove?.(f.operator, f.value)}
+ className="h-4 w-4 shrink-0 p-0 text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover/textfilter:opacity-100"
+ >
+ ×
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+interface FilterValueCheckboxProps {
+ id: string;
+ label: string;
+ count: number;
+ checked?: boolean;
+ onCheckedChange?: (checked: boolean) => void;
+ onLabelClick?: () => void; // For "only this" behavior
+ totalSelected?: number;
+ disabled?: boolean;
+}
+
+export function FilterValueCheckbox({
+ id,
+ label,
+ count,
+ checked = false,
+ onCheckedChange,
+ onLabelClick,
+ totalSelected,
+ disabled = false,
+}: FilterValueCheckboxProps) {
+ // Show "All" when clicking would reverse selection (only one item selected)
+ const labelText = checked && totalSelected === 1 ? "All" : "Only";
+
+ return (
+ <div
+ className={cn(
+ "relative flex items-center px-2",
+ disabled && "cursor-not-allowed opacity-50",
+ )}
+ >
+ {/* 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}
+ disabled={disabled}
+ className="pointer-events-auto"
+ />
+ </div>
+
+ {/* Label hover area */}
+ <div
+ className={cn(
+ "group/label flex min-w-0 flex-1 cursor-pointer items-center rounded-sm px-1 py-1 transition-colors hover:bg-accent",
+ disabled && "pointer-events-none",
+ )}
+ onClick={onLabelClick}
+ >
+ <span className="min-w-0 flex-1 truncate text-xs">{label}</span>
+
+ {/* "Only" or "All" indicator when hovering label */}
+ {onLabelClick && !disabled && (
+ <span className="hidden pl-1 text-xs text-muted-foreground group-hover/label:block">
+ {labelText}
+ </span>
+ )}
+
+ {count > 0 ? (
+ <span className="ml-auto w-7 pl-1 text-right text-xs text-muted-foreground">
+ {compactNumberFormatter(count, 0)}
+ </span>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+export function DataTableControlsSection({
+ title,
+ children,
+}: {
+ title: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="space-y-3">
+ <h3 className="text-sm font-medium text-foreground">{title}</h3>
+ <div>{children}</div>
+ </div>
+ );
+}
diff --git a/web/src/components/table/data-table-toolbar.tsx b/web/src/components/table/data-table-toolbar.tsx
index 25719721b6..27da735666 100644
--- a/web/src/components/table/data-table-toolbar.tsx
+++ b/web/src/components/table/data-table-toolbar.tsx
@@ -21,7 +21,13 @@ import {
DataTableRowHeightSwitch,
type RowHeight,
} from "@/src/components/table/data-table-row-height-switch";
-import { Search, ChevronDown } from "lucide-react";
+import {
+ Search,
+ ChevronDown,
+ PanelLeftClose,
+ PanelLeftOpen,
+} from "lucide-react";
+import { Badge } from "@/src/components/ui/badge";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { TimeRangePicker } from "@/src/components/date-picker";
import {
@@ -29,7 +35,6 @@ import {
TABLE_AGGREGATION_OPTIONS,
} from "@/src/utils/date-range-utils";
import { DataTableSelectAllBanner } from "@/src/components/table/data-table-multi-select-actions/data-table-select-all-banner";
-import { MultiSelect } from "@/src/features/filters/components/multi-select";
import { cn } from "@/src/utils/tailwind";
import DocPopup from "@/src/components/layouts/doc-popup";
import { TableViewPresetsDrawer } from "@/src/components/table/table-view-presets/components/data-table-view-presets-drawer";
@@ -40,6 +45,8 @@ import {
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from "@/src/components/ui/dropdown-menu";
+import { useDataTableControls } from "@/src/components/table/data-table-controls";
+import { MultiSelect as MultiSelectFilter } from "@/src/features/filters/components/multi-select";
export interface MultiSelect {
selectAll: boolean;
@@ -135,12 +142,36 @@ export function DataTableToolbar<TData, TValue>({
);
const capture = usePostHogClientCapture();
+ const { open: controlsPanelOpen, setOpen: setControlsPanelOpen } =
+ useDataTableControls();
+ // Only show the toggle button when we're using the new sidebar
+ const hasNewSidebar = !filterColumnDefinition && filterState !== undefined;
return (
<div className={cn("grid h-fit w-full gap-0 px-2", className)}>
<div className="my-2 flex flex-wrap items-center gap-2 @container">
+ {hasNewSidebar && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setControlsPanelOpen(!controlsPanelOpen)}
+ className="flex h-8 items-center gap-2 text-sm"
+ >
+ {controlsPanelOpen ? (
+ <PanelLeftClose className="h-4 w-4" />
+ ) : (
+ <PanelLeftOpen className="h-4 w-4" />
+ )}
+ <span>{controlsPanelOpen ? "Hide" : "Show"} filters</span>
+ {filterState && filterState.length > 0 && (
+ <Badge variant="secondary" className="ml-1 h-5 px-1.5 text-xs">
+ {filterState.length}
+ </Badge>
+ )}
+ </Button>
+ )}
{searchConfig && (
- <div className="flex min-w-0 max-w-64 flex-shrink-0 items-stretch">
+ <div className="flex max-w-[30rem] flex-shrink-0 items-stretch md:min-w-[24rem]">
<div
className={cn(
"flex h-8 flex-1 items-center border border-input bg-background pl-2",
@@ -265,7 +296,7 @@ export function DataTableToolbar<TData, TValue>({
/>
)}
{environmentFilter && (
- <MultiSelect
+ <MultiSelectFilter
title="Environment"
label="Env"
values={environmentFilter.values}
diff --git a/web/src/components/table/key-value-filter-builder.tsx b/web/src/components/table/key-value-filter-builder.tsx
new file mode 100644
index 0000000000..1356ad39b2
--- /dev/null
+++ b/web/src/components/table/key-value-filter-builder.tsx
@@ -0,0 +1,421 @@
+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;
+ keyPlaceholder?: string;
+ }
+ | {
+ mode: "numeric";
+ keyOptions?: string[];
+ activeFilters: NumericKeyValueFilterEntry[];
+ onChange: (filters: NumericKeyValueFilterEntry[]) => void;
+ keyPlaceholder?: string;
+ }
+ | {
+ mode: "string";
+ keyOptions?: string[];
+ activeFilters: StringKeyValueFilterEntry[];
+ onChange: (filters: StringKeyValueFilterEntry[]) => void;
+ keyPlaceholder?: string;
+ };
+
+// 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,
+ keyPlaceholder = "Key",
+ } = props;
+ const availableValues = mode === "categorical" ? props.availableValues : {};
+
+ // Local UI state for filter rows (includes incomplete filters)
+ const [localFilters, setLocalFilters] = useState<
+ | KeyValueFilterEntry[]
+ | NumericKeyValueFilterEntry[]
+ | StringKeyValueFilterEntry[]
+ >([]);
+
+ // Track which popover is open (by index)
+ const [openPopoverIndex, setOpenPopoverIndex] = useState<number | null>(null);
+
+ // Initialize from activeFilters (which only has complete filters)
+ useEffect(() => {
+ setLocalFilters(activeFilters.length > 0 ? activeFilters : []);
+ }, [activeFilters]);
+
+ const handleFilterChange = (
+ index: number,
+ updates:
+ | Partial<KeyValueFilterEntry>
+ | Partial<NumericKeyValueFilterEntry>
+ | Partial<StringKeyValueFilterEntry>,
+ ) => {
+ // TypeScript can't narrow the union array type automatically, so we narrow explicitly based on mode
+ if (mode === "categorical") {
+ const filters = localFilters as KeyValueFilterEntry[];
+ const newFilters = [...filters];
+ newFilters[index] = {
+ ...newFilters[index],
+ ...updates,
+ } as KeyValueFilterEntry;
+ setLocalFilters(newFilters);
+ (onChange as (filters: KeyValueFilterEntry[]) => void)(newFilters);
+ } else if (mode === "numeric") {
+ const filters = localFilters as NumericKeyValueFilterEntry[];
+ const newFilters = [...filters];
+ newFilters[index] = {
+ ...newFilters[index],
+ ...updates,
+ } as NumericKeyValueFilterEntry;
+ setLocalFilters(newFilters);
+ (onChange as (filters: NumericKeyValueFilterEntry[]) => void)(newFilters);
+ } else {
+ const filters = localFilters as StringKeyValueFilterEntry[];
+ const newFilters = [...filters];
+ newFilters[index] = {
+ ...newFilters[index],
+ ...updates,
+ } as StringKeyValueFilterEntry;
+ setLocalFilters(newFilters);
+ (onChange as (filters: StringKeyValueFilterEntry[]) => void)(newFilters);
+ }
+ };
+
+ const handleAddFilter = () => {
+ if (mode === "categorical") {
+ const newFilter: KeyValueFilterEntry = {
+ key: "",
+ operator: "any of" as const,
+ value: [],
+ };
+ const filters = localFilters as KeyValueFilterEntry[];
+ const newFilters = [...filters, newFilter];
+ setLocalFilters(newFilters);
+ } else if (mode === "numeric") {
+ const newFilter: NumericKeyValueFilterEntry = {
+ key: "",
+ operator: "=" as const,
+ value: "",
+ };
+ const filters = localFilters as NumericKeyValueFilterEntry[];
+ const newFilters = [...filters, newFilter];
+ setLocalFilters(newFilters);
+ } else {
+ const newFilter: StringKeyValueFilterEntry = {
+ key: "",
+ operator: "=" as const,
+ value: "",
+ };
+ const filters = localFilters as StringKeyValueFilterEntry[];
+ const newFilters = [...filters, newFilter];
+ setLocalFilters(newFilters);
+ }
+ };
+
+ const handleRemoveFilter = (index: number) => {
+ if (mode === "categorical") {
+ const filters = localFilters as KeyValueFilterEntry[];
+ const newFilters = filters.filter((_, i) => i !== index);
+ setLocalFilters(newFilters);
+ (onChange as (filters: KeyValueFilterEntry[]) => void)(newFilters);
+ } else if (mode === "numeric") {
+ const filters = localFilters as NumericKeyValueFilterEntry[];
+ const newFilters = filters.filter((_, i) => i !== index);
+ setLocalFilters(newFilters);
+ (onChange as (filters: NumericKeyValueFilterEntry[]) => void)(newFilters);
+ } else {
+ const filters = localFilters as StringKeyValueFilterEntry[];
+ const newFilters = filters.filter((_, i) => i !== index);
+ setLocalFilters(newFilters);
+ (onChange as (filters: StringKeyValueFilterEntry[]) => void)(newFilters);
+ }
+ };
+
+ return (
+ <div className="flex flex-col gap-4 px-4 py-1">
+ {/* Filter rows */}
+ {localFilters.map((filter, index) => {
+ const availableValuesForKey = filter.key
+ ? (availableValues[filter.key] ?? [])
+ : [];
+
+ return (
+ <div
+ key={index}
+ className="flex flex-col gap-2 border-b pb-3 last:border-b-0 last:pb-0"
+ >
+ {/* Key input and delete button row */}
+ <div className="flex items-center gap-2">
+ {keyOptions ? (
+ // Combobox for known keys
+ <Popover
+ open={openPopoverIndex === index}
+ onOpenChange={(open) =>
+ setOpenPopoverIndex(open ? index : null)
+ }
+ >
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ className="flex-1 justify-between text-left font-normal"
+ >
+ <span
+ className={cn(!filter.key && "text-muted-foreground")}
+ >
+ {filter.key || keyPlaceholder}
+ </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={keyPlaceholder}
+ 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/table-view-presets/hooks/useTableViewManager.ts b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
index 54b39b2174..e8919c387e 100644
--- a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
+++ b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
@@ -7,7 +7,7 @@ import {
type ColumnDefinition,
} from "@langfuse/shared";
import { useRouter } from "next/router";
-import { useEffect, useCallback, useState } from "react";
+import { useEffect, useCallback, useState, useRef } from "react";
import { type VisibilityState } from "@tanstack/react-table";
import { StringParam, withDefault } from "use-query-params";
import useSessionStorage from "@/src/components/useSessionStorage";
@@ -34,10 +34,7 @@ interface UseTableStateProps {
columns?: LangfuseColumnDef<any, any>[];
filterColumnDefinition?: ColumnDefinition[];
};
-}
-
-function isFunction(fn: unknown): fn is (...args: unknown[]) => void {
- return typeof fn === "function";
+ currentFilterState?: FilterState;
}
/**
@@ -48,12 +45,14 @@ export function useTableViewManager({
tableName,
stateUpdaters,
validationContext = {},
+ currentFilterState,
}: UseTableStateProps) {
const router = useRouter();
const { viewId } = router.query;
const [isInitialized, setIsInitialized] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const capture = usePostHogClientCapture();
+ const pendingFiltersRef = useRef<FilterState | null>(null);
const [storedViewId, setStoredViewId] = useSessionStorage<string | null>(
`${tableName}-${projectId}-viewId`,
@@ -73,7 +72,7 @@ export function useTableViewManager({
[setStoredViewId, setSelectedViewId],
);
- // Extract updater functions
+ // Extract updater functions and store in refs to avoid stale closures
const {
setOrderBy,
setFilters,
@@ -82,6 +81,17 @@ export function useTableViewManager({
setSearchQuery,
} = stateUpdaters;
+ // Use refs to always get latest function references to avoid stale closures in applyViewState
+ // for restoring view state from the saved views
+ const setFiltersRef = useRef(setFilters);
+ const setOrderByRef = useRef(setOrderBy);
+ const setSearchQueryRef = useRef(setSearchQuery);
+
+ // Update refs immediately on every render
+ setFiltersRef.current = setFilters;
+ setOrderByRef.current = setOrderBy;
+ setSearchQueryRef.current = setSearchQuery;
+
useEffect(() => {
const urlParams = new URLSearchParams(window.location.search);
const viewIdInUrl = urlParams.get("viewId");
@@ -148,12 +158,17 @@ export function useTableViewManager({
);
}
- if (isFunction(setOrderBy)) setOrderBy(validOrderBy);
- if (isFunction(setFilters)) setFilters(validFilters);
+ if (setOrderByRef.current) setOrderByRef.current(validOrderBy);
+
+ if (setFiltersRef.current) {
+ setFiltersRef.current(validFilters);
+ // Track expected filters to observe when state actually updates (for useEffect below)
+ pendingFiltersRef.current = validFilters;
+ }
- // Handle search query
- if (viewData.searchQuery !== undefined && isFunction(setSearchQuery)) {
- setSearchQuery(viewData.searchQuery);
+ // Handle search query (only set if non-empty to avoid use-query-params batching conflicts)
+ if (viewData.searchQuery && setSearchQueryRef.current) {
+ setSearchQueryRef.current(viewData.searchQuery);
}
// Apply column order and visibility without validation since UI will handle gracefully
@@ -161,17 +176,11 @@ export function useTableViewManager({
if (viewData.columnVisibility)
setColumnVisibility(viewData.columnVisibility);
- // unlock table
- setIsLoading(false);
+ // NOTE: Table remains locked until useEffect observer detects filter state propagation
+ // This is relevant for the saved views. Because the URL lazy updates and we don't want to wait
+ // for a page reload
},
- [
- setOrderBy,
- setFilters,
- setColumnOrder,
- setColumnVisibility,
- setSearchQuery,
- validationContext,
- ],
+ [setColumnOrder, setColumnVisibility, validationContext],
);
// Handle successful view data fetch
@@ -184,10 +193,8 @@ export function useTableViewManager({
name: viewData.name,
});
- // Apply view state
applyViewState(viewData);
setIsInitialized(true);
- setIsLoading(false);
}
}, [
viewData,
@@ -219,6 +226,18 @@ export function useTableViewManager({
}
}, [isInitialized, isViewLoading, viewId]);
+ // Observe when filter state propagates from saved view
+ // After calling setFilters, URL updates async → filterState recalculates → this effect detects completion
+ useEffect(() => {
+ if (pendingFiltersRef.current && currentFilterState) {
+ if (isEqual(currentFilterState, pendingFiltersRef.current)) {
+ // Filter state has synchronized - safe to unlock table
+ pendingFiltersRef.current = null;
+ setIsLoading(false);
+ }
+ }
+ }, [currentFilterState]);
+
return {
isLoading,
applyViewState,
diff --git a/web/src/components/table/table-view-presets/validation.ts b/web/src/components/table/table-view-presets/validation.ts
index 53dcdbad4d..a1387aeb4c 100644
--- a/web/src/components/table/table-view-presets/validation.ts
+++ b/web/src/components/table/table-view-presets/validation.ts
@@ -22,7 +22,20 @@ export function validateOrderBy(
}
/**
- * Validates if filters reference valid columns
+ * Validates if filters reference valid columns and normalizes column names to IDs
+ * - Old system: filters used display names (e.g., "User ID", "Name", "⭐️")
+ * - New system: filters use column IDs (e.g., "userId", "name", "bookmarked")
+ *
+ * Switched to IDs because better:
+ * - Display names can change for UX or i18n (in future), IDs are stable
+ * - IDs match database field names and rest of codebase
+ * - Special characters in display names can cause issues
+ * - Better type safety and predictability
+ *
+ * Here, we:
+ * - validate that filter columns exist
+ * - normalize old display names to new IDs
+ * - filter out invalid/deleted columns
*/
export function validateFilters(
filters: FilterState,
@@ -31,10 +44,27 @@ export function validateFilters(
if (!filterColumnDefinition || filterColumnDefinition.length === 0)
return filters;
- // Filter out invalid filters
- return filters.filter((filter) => {
- return filterColumnDefinition.some(
- (def) => def.id === filter.column || def.name === filter.column,
- );
- });
+ // Validate and normalize filters
+ return filters
+ .map((filter) => {
+ // Find matching column definition (by ID or name for backward compat)
+ const matchingDef = filterColumnDefinition.find(
+ (def) => def.id === filter.column || def.name === filter.column,
+ );
+
+ // Filter is invalid if no matching definition found
+ if (!matchingDef) return null;
+
+ // If filter uses old display name, normalize to ID
+ if (filter.column !== matchingDef.id) {
+ return {
+ ...filter,
+ column: matchingDef.id,
+ };
+ }
+
+ // Filter already uses correct ID
+ return filter;
+ })
+ .filter((f): f is NonNullable<typeof f> => f !== null);
}
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index 13de678c01..98dcb76d29 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -1,17 +1,22 @@
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";
import {
type ObservationLevelType,
type FilterState,
- type ObservationOptions,
BatchExportTableName,
type ObservationType,
TableViewPresetTableName,
@@ -21,13 +26,11 @@ import {
import { cn } from "@/src/utils/tailwind";
import { LevelColors } from "@/src/components/level-colors";
import { numberFormatter, usdFormatter } from "@/src/utils/numbers";
-import { observationsTableColsWithOptions } from "@langfuse/shared";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
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";
@@ -115,7 +118,6 @@ export default function ObservationsTable({
promptName,
promptVersion,
modelId,
- omittedFilter = [],
}: ObservationsTableProps) {
const router = useRouter();
const { viewId } = router.query;
@@ -246,15 +248,103 @@ export default function ObservationsTable({
const environmentOptions =
environmentFilterOptions.data?.map((value) => value.environment) || [];
- const { selectedEnvironments, setSelectedEnvironments } =
- useEnvironmentFilter(environmentOptions, projectId);
+ const { selectedEnvironments } = useEnvironmentFilter(
+ environmentOptions,
+ projectId,
+ );
const environmentFilter = convertSelectedEnvironmentsToFilter(
["environment"],
selectedEnvironments,
);
- const filterState = inputFilterState.concat(
+ const oldFilterState = inputFilterState.concat(
+ dateRangeFilter,
+ promptNameFilter,
+ promptVersionFilter,
+ modelIdFilter,
+ environmentFilter,
+ );
+
+ const startTimeFilter = oldFilterState.find((f) => f.column === "Start Time");
+ const filterOptions = api.generations.filterOptions.useQuery(
+ {
+ projectId,
+ startTimeFilter:
+ startTimeFilter?.type === "datetime" ? startTimeFilter : undefined,
+ },
+ {
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ staleTime: Infinity,
+ },
+ );
+
+ const newFilterOptions = useMemo(
+ () => ({
+ environment:
+ environmentFilterOptions.data?.map((value) => value.environment) || [],
+ name:
+ filterOptions.data?.name?.map((n) => ({
+ value: n.value,
+ count: n.count !== undefined ? Number(n.count) : undefined,
+ })) || [],
+ type:
+ filterOptions.data?.type?.map((t) => ({
+ value: t.value,
+ count: t.count !== undefined ? Number(t.count) : undefined,
+ })) || [],
+ traceName:
+ filterOptions.data?.traceName?.map((tn) => ({
+ value: tn.value,
+ count: tn.count !== undefined ? Number(tn.count) : undefined,
+ })) || [],
+ level: ["DEFAULT", "DEBUG", "WARNING", "ERROR"],
+ model:
+ filterOptions.data?.model?.map((m) => ({
+ value: m.value,
+ count: m.count !== undefined ? Number(m.count) : undefined,
+ })) || [],
+ modelId:
+ filterOptions.data?.modelId?.map((mid) => ({
+ value: mid.value,
+ count: mid.count !== undefined ? Number(mid.count) : undefined,
+ })) || [],
+ promptName:
+ filterOptions.data?.promptName?.map((pn) => ({
+ value: pn.value,
+ count: pn.count !== undefined ? Number(pn.count) : undefined,
+ })) || [],
+ tags:
+ filterOptions.data?.tags?.map((t) => ({
+ value: t.value,
+ count: t.count !== undefined ? Number(t.count) : undefined,
+ })) || [],
+ latency: [],
+ timeToFirstToken: [],
+ tokensPerSecond: [],
+ inputTokens: [],
+ outputTokens: [],
+ totalTokens: [],
+ inputCost: [],
+ outputCost: [],
+ totalCost: [],
+ }),
+ [environmentFilterOptions.data, filterOptions.data],
+ );
+
+ const queryFilter = useSidebarFilterState(
+ observationFilterConfig,
+ newFilterOptions,
+ );
+
+ const filterState = queryFilter.filterState.concat(
dateRangeFilter,
promptNameFilter,
promptVersionFilter,
@@ -288,26 +378,6 @@ export default function ObservationsTable({
const totalCount = totalCountQuery.data?.totalCount ?? null;
- const startTimeFilter = filterState.find((f) => f.column === "Start Time");
- const filterOptions = api.generations.filterOptions.useQuery(
- {
- projectId,
- startTimeFilter:
- startTimeFilter?.type === "datetime" ? startTimeFilter : undefined,
- },
- {
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- staleTime: Infinity,
- },
- );
-
const addToQueueMutation = api.annotationQueueItems.createMany.useMutation({
onSuccess: (data) => {
showSuccessToast({
@@ -347,17 +417,6 @@ export default function ObservationsTable({
fromTimestamp: dateRange?.from,
});
- const transformFilterOptions = (
- filterOptions: ObservationOptions | undefined,
- ) => {
- return observationsTableColsWithOptions(filterOptions).filter(
- (col) =>
- col.id !== "startTime" &&
- col.id !== "endTime" &&
- !omittedFilter?.includes(col.name),
- );
- };
-
const { selectActionColumn } = TableSelectionManager<ObservationsTableRow>({
projectId,
tableName: "observations",
@@ -1003,8 +1062,9 @@ export default function ObservationsTable({
},
validationContext: {
columns,
- filterColumnDefinition: transformFilterOptions(filterOptions.data),
+ filterColumnDefinition: observationFilterConfig.columnDefinitions,
},
+ currentFilterState: inputFilterState,
});
const peekConfig: DataTablePeekViewProps = useMemo(
@@ -1062,141 +1122,145 @@ export default function ObservationsTable({
}, [generations]);
return (
- <>
- <DataTableToolbar
- columns={columns}
- filterColumnDefinition={transformFilterOptions(filterOptions.data)}
- filterState={inputFilterState}
- setFilterState={useDebounce(setInputFilterState)}
- searchConfig={{
- metadataSearchFields: ["ID", "Name", "Trace Name", "Model"],
- updateQuery: setSearchQuery,
- currentQuery: searchQuery ?? undefined,
- searchType,
- setSearchType,
- tableAllowsFullTextSearch: true,
- }}
- viewConfig={{
- tableName: TableViewPresetTableName.Observations,
- projectId,
- controllers: viewControllers,
- }}
- columnsWithCustomSelect={["model", "name", "traceName", "promptName"]}
- columnVisibility={columnVisibility}
- setColumnVisibility={setColumnVisibilityState}
- columnOrder={columnOrder}
- setColumnOrder={setColumnOrder}
- orderByState={orderByState}
- rowHeight={rowHeight}
- setRowHeight={setRowHeight}
- timeRange={timeRange}
- setTimeRange={setTimeRange}
- actionButtons={[
- <BatchExportTableButton
- {...{
- projectId,
- filterState,
- orderByState,
- searchQuery,
- searchType,
- }}
- tableName={BatchExportTableName.Observations}
- key="batchExport"
- />,
- Object.keys(selectedRows).filter((generationId) =>
- generations.data?.generations
- .map((g) => g.id)
- .includes(generationId),
- ).length > 0 ? (
- <TableActionMenu
- key="observations-multi-select-actions"
- projectId={projectId}
- actions={tableActions}
+ <DataTableControlsProvider>
+ <div className="flex h-full w-full flex-col">
+ {/* Toolbar spanning full width */}
+ <DataTableToolbar
+ columns={columns}
+ filterState={queryFilter.filterState}
+ searchConfig={{
+ metadataSearchFields: ["ID", "Name", "Trace Name", "Model"],
+ updateQuery: setSearchQuery,
+ currentQuery: searchQuery ?? undefined,
+ searchType,
+ setSearchType,
+ tableAllowsFullTextSearch: true,
+ }}
+ viewConfig={{
+ tableName: TableViewPresetTableName.Observations,
+ projectId,
+ controllers: viewControllers,
+ }}
+ columnsWithCustomSelect={["model", "name", "traceName", "promptName"]}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibilityState}
+ columnOrder={columnOrder}
+ setColumnOrder={setColumnOrder}
+ orderByState={orderByState}
+ rowHeight={rowHeight}
+ setRowHeight={setRowHeight}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
+ actionButtons={[
+ <BatchExportTableButton
+ {...{
+ projectId,
+ filterState,
+ orderByState,
+ searchQuery,
+ searchType,
+ }}
tableName={BatchExportTableName.Observations}
- />
- ) : null,
- ]}
- environmentFilter={{
- values: selectedEnvironments,
- onValueChange: setSelectedEnvironments,
- options: environmentOptions.map((env) => ({ value: env })),
- }}
- multiSelect={{
- selectAll,
- setSelectAll,
- selectedRowIds: Object.keys(selectedRows).filter((generationId) =>
- generations.data?.generations
- .map((g) => g.id)
- .includes(generationId),
- ),
- setRowSelection: setSelectedRows,
- totalCount,
- ...paginationState,
- }}
- />
- <DataTable
- tableName={"observations"}
- columns={columns}
- peekView={peekConfig}
- data={
- generations.isPending || isViewLoading
- ? { isLoading: true, isError: false }
- : generations.error
- ? {
- isLoading: false,
- isError: true,
- error: generations.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: rows,
- }
- }
- pagination={{
- totalCount,
- onChange: setPaginationState,
- state: paginationState,
- }}
- rowSelection={selectedRows}
- setRowSelection={setSelectedRows}
- setOrderBy={setOrderByState}
- orderBy={orderByState}
- columnOrder={columnOrder}
- onColumnOrderChange={setColumnOrder}
- columnVisibility={columnVisibility}
- onColumnVisibilityChange={setColumnVisibilityState}
- rowHeight={rowHeight}
- onRowClick={(row, event) => {
- // Handle Command/Ctrl+click to open observation in new tab
- if (event && (event.metaKey || event.ctrlKey)) {
- // Prevent the default peek behavior
- event.preventDefault();
-
- // Construct the observation URL directly to avoid race conditions
- const observationId = row.id;
- const traceId = row.traceId;
- const timestamp = row.timestamp;
+ key="batchExport"
+ />,
+ Object.keys(selectedRows).filter((generationId) =>
+ generations.data?.generations
+ .map((g) => g.id)
+ .includes(generationId),
+ ).length > 0 ? (
+ <TableActionMenu
+ key="observations-multi-select-actions"
+ projectId={projectId}
+ actions={tableActions}
+ tableName={BatchExportTableName.Observations}
+ />
+ ) : null,
+ ]}
+ multiSelect={{
+ selectAll,
+ setSelectAll,
+ selectedRowIds: Object.keys(selectedRows).filter((generationId) =>
+ generations.data?.generations
+ .map((g) => g.id)
+ .includes(generationId),
+ ),
+ setRowSelection: setSelectedRows,
+ totalCount,
+ ...paginationState,
+ }}
+ />
- if (traceId) {
- let observationUrl = `/project/${projectId}/traces/${encodeURIComponent(traceId)}`;
+ {/* Content area with sidebar and table */}
+ <div className="flex flex-1 overflow-hidden">
+ <DataTableControls queryFilter={queryFilter} />
- const params = new URLSearchParams();
- params.set("observation", observationId);
- if (timestamp) {
- params.set("timestamp", timestamp.toISOString());
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <DataTable
+ tableName={"observations"}
+ columns={columns}
+ peekView={peekConfig}
+ data={
+ generations.isPending || isViewLoading
+ ? { isLoading: true, isError: false }
+ : generations.error
+ ? {
+ isLoading: false,
+ isError: true,
+ error: generations.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: rows,
+ }
}
+ pagination={{
+ totalCount,
+ onChange: setPaginationState,
+ state: paginationState,
+ }}
+ rowSelection={selectedRows}
+ setRowSelection={setSelectedRows}
+ setOrderBy={setOrderByState}
+ orderBy={orderByState}
+ columnOrder={columnOrder}
+ onColumnOrderChange={setColumnOrder}
+ columnVisibility={columnVisibility}
+ onColumnVisibilityChange={setColumnVisibilityState}
+ rowHeight={rowHeight}
+ onRowClick={(row, event) => {
+ // Handle Command/Ctrl+click to open observation in new tab
+ if (event && (event.metaKey || event.ctrlKey)) {
+ // Prevent the default peek behavior
+ event.preventDefault();
+
+ // Construct the observation URL directly to avoid race conditions
+ const observationId = row.id;
+ const traceId = row.traceId;
+ const timestamp = row.timestamp;
+
+ if (traceId) {
+ let observationUrl = `/project/${projectId}/traces/${encodeURIComponent(traceId)}`;
- observationUrl += `?${params.toString()}`;
+ const params = new URLSearchParams();
+ params.set("observation", observationId);
+ if (timestamp) {
+ params.set("timestamp", timestamp.toISOString());
+ }
- const fullUrl = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${observationUrl}`;
- window.open(fullUrl, "_blank");
- }
- }
- // For normal clicks, let the data-table handle opening the peek view
- }}
- />
- </>
+ observationUrl += `?${params.toString()}`;
+
+ const fullUrl = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${observationUrl}`;
+ window.open(fullUrl, "_blank");
+ }
+ }
+ // For normal clicks, let the data-table handle opening the peek view
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ </DataTableControlsProvider>
);
}
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index 9886f1546c..86ce036571 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -1,21 +1,22 @@
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 {
- type ScoreOptions,
- scoresTableColsWithOptions,
-} from "@/src/server/api/definitions/scoresTable";
import { api } from "@/src/utils/api";
import type { RouterOutput } from "@/src/utils/types";
@@ -95,7 +96,6 @@ export default function ScoresTable({
userId,
traceId,
observationId,
- omittedFilter = [],
hiddenColumns = [],
localStorageSuffix = "",
}: {
@@ -168,8 +168,10 @@ export default function ScoresTable({
const environmentOptions =
environmentFilterOptions.data?.map((value) => value.environment) || [];
- const { selectedEnvironments, setSelectedEnvironments } =
- useEnvironmentFilter(environmentOptions, projectId);
+ const { selectedEnvironments } = useEnvironmentFilter(
+ environmentOptions,
+ projectId,
+ );
const environmentFilter = convertSelectedEnvironmentsToFilter(
["environment"],
@@ -268,6 +270,25 @@ export default function ScoresTable({
},
);
+ const newFilterOptions = React.useMemo(
+ () => ({
+ name:
+ filterOptions.data?.name?.map((n) => ({
+ value: n.value,
+ count: n.count !== undefined ? Number(n.count) : undefined,
+ })) || [],
+ source: ["ANNOTATION", "API", "EVAL"],
+ dataType: ["NUMERIC", "CATEGORICAL", "BOOLEAN"],
+ value: [],
+ }),
+ [filterOptions.data],
+ );
+
+ const queryFilter = useSidebarFilterState(
+ scoreFilterConfig,
+ newFilterOptions,
+ );
+
const { selectActionColumn } = TableSelectionManager<ScoresTableRow>({
projectId,
tableName: "scores",
@@ -643,17 +664,6 @@ export default function ScoresTable({
};
};
- const transformFilterOptions = (
- traceFilterOptions: ScoreOptions | undefined,
- ) => {
- return scoresTableColsWithOptions(traceFilterOptions).filter(
- (c) =>
- c.id !== "timestamp" &&
- !omittedFilter?.includes(c.name) &&
- !hiddenColumns.includes(c.id),
- );
- };
-
const { isLoading: isViewLoading, ...viewControllers } = useTableViewManager({
tableName: TableViewPresetTableName.Scores,
projectId,
@@ -665,97 +675,105 @@ export default function ScoresTable({
},
validationContext: {
columns,
- filterColumnDefinition: transformFilterOptions(filterOptions.data),
+ filterColumnDefinition: scoreFilterConfig.columnDefinitions,
},
+ currentFilterState: userFilterState,
});
return (
- <>
- <DataTableToolbar
- columns={columns}
- filterColumnDefinition={transformFilterOptions(filterOptions.data)}
- filterState={userFilterState}
- setFilterState={useDebounce(setUserFilterState)}
- columnVisibility={columnVisibility}
- setColumnVisibility={setColumnVisibility}
- columnOrder={columnOrder}
- setColumnOrder={setColumnOrder}
- viewConfig={{
- tableName: TableViewPresetTableName.Scores,
- projectId,
- controllers: viewControllers,
- }}
- actionButtons={[
- Object.keys(selectedRows).filter((scoreId) =>
- scores.data?.scores.map((s) => s.id).includes(scoreId),
- ).length > 0 ? (
- <TableActionMenu
- key="scores-multi-select-actions"
- projectId={projectId}
- actions={tableActions}
+ <DataTableControlsProvider
+ tableName={scoreFilterConfig.tableName}
+ defaultSidebarCollapsed={scoreFilterConfig.defaultSidebarCollapsed}
+ >
+ <div className="flex h-full w-full flex-col">
+ {/* Toolbar spanning full width */}
+ <DataTableToolbar
+ columns={columns}
+ filterState={queryFilter.filterState}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibility}
+ columnOrder={columnOrder}
+ setColumnOrder={setColumnOrder}
+ viewConfig={{
+ tableName: TableViewPresetTableName.Scores,
+ projectId,
+ controllers: viewControllers,
+ }}
+ actionButtons={[
+ Object.keys(selectedRows).filter((scoreId) =>
+ scores.data?.scores.map((s) => s.id).includes(scoreId),
+ ).length > 0 ? (
+ <TableActionMenu
+ key="scores-multi-select-actions"
+ projectId={projectId}
+ actions={tableActions}
+ tableName={BatchExportTableName.Scores}
+ />
+ ) : null,
+ <BatchExportTableButton
+ {...{ projectId, filterState, orderByState }}
tableName={BatchExportTableName.Scores}
+ key="batchExport"
+ />,
+ ]}
+ rowHeight={rowHeight}
+ setRowHeight={setRowHeight}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
+ multiSelect={{
+ selectAll,
+ setSelectAll,
+ selectedRowIds: Object.keys(selectedRows).filter((scoreId) =>
+ scores.data?.scores.map((s) => s.id).includes(scoreId),
+ ),
+ setRowSelection: setSelectedRows,
+ totalCount,
+ ...paginationState,
+ }}
+ />
+
+ {/* Content area with sidebar and table */}
+ <div className="flex flex-1 overflow-hidden">
+ <DataTableControls queryFilter={queryFilter} />
+
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <DataTable
+ tableName={"scores"}
+ columns={columns}
+ data={
+ scores.isPending || isViewLoading
+ ? { isLoading: true, isError: false }
+ : scores.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: scores.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: scores.data?.scores.map(convertToTableRow) ?? [],
+ }
+ }
+ pagination={{
+ totalCount,
+ onChange: setPaginationState,
+ state: paginationState,
+ }}
+ setOrderBy={setOrderByState}
+ orderBy={orderByState}
+ rowSelection={selectedRows}
+ setRowSelection={setSelectedRows}
+ columnVisibility={columnVisibility}
+ onColumnVisibilityChange={setColumnVisibility}
+ columnOrder={columnOrder}
+ onColumnOrderChange={setColumnOrder}
+ rowHeight={rowHeight}
/>
- ) : null,
- <BatchExportTableButton
- {...{ projectId, filterState, orderByState }}
- tableName={BatchExportTableName.Scores}
- key="batchExport"
- />,
- ]}
- rowHeight={rowHeight}
- setRowHeight={setRowHeight}
- timeRange={timeRange}
- setTimeRange={setTimeRange}
- multiSelect={{
- selectAll,
- setSelectAll,
- selectedRowIds: Object.keys(selectedRows).filter((scoreId) =>
- scores.data?.scores.map((s) => s.id).includes(scoreId),
- ),
- setRowSelection: setSelectedRows,
- totalCount,
- ...paginationState,
- }}
- environmentFilter={{
- values: selectedEnvironments,
- onValueChange: setSelectedEnvironments,
- options: environmentOptions.map((env) => ({ value: env })),
- }}
- />
- <DataTable
- tableName={"scores"}
- columns={columns}
- data={
- scores.isPending || isViewLoading
- ? { isLoading: true, isError: false }
- : scores.isError
- ? {
- isLoading: false,
- isError: true,
- error: scores.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: scores.data?.scores.map(convertToTableRow) ?? [],
- }
- }
- pagination={{
- totalCount,
- onChange: setPaginationState,
- state: paginationState,
- }}
- setOrderBy={setOrderByState}
- orderBy={orderByState}
- rowSelection={selectedRows}
- setRowSelection={setSelectedRows}
- columnVisibility={columnVisibility}
- onColumnVisibilityChange={setColumnVisibility}
- columnOrder={columnOrder}
- onColumnOrderChange={setColumnOrder}
- rowHeight={rowHeight}
- />
- </>
+ </div>
+ </div>
+ </div>
+ </DataTableControlsProvider>
);
}
diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsx
index 30851ece00..55db649572 100644
--- a/web/src/components/table/use-cases/sessions.tsx
+++ b/web/src/components/table/use-cases/sessions.tsx
@@ -1,14 +1,19 @@
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,
BatchExportTableName,
TableViewPresetTableName,
AnnotationQueueObjectType,
@@ -25,7 +30,6 @@ import { useEffect, useState, useMemo } from "react";
import { NumberParam, useQueryParams, withDefault } from "use-query-params";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
-import { useDebounce } from "@/src/hooks/useDebounce";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
import { Skeleton } from "@/src/components/ui/skeleton";
import TagList from "@/src/features/tag/components/TagList";
@@ -143,8 +147,10 @@ export default function SessionsTable({
const environmentOptions =
environmentFilterOptions.data?.map((value) => value.environment) || [];
- const { selectedEnvironments, setSelectedEnvironments } =
- useEnvironmentFilter(environmentOptions, projectId);
+ const { selectedEnvironments } = useEnvironmentFilter(
+ environmentOptions,
+ projectId,
+ );
const environmentFilter = convertSelectedEnvironmentsToFilter(
["environment"],
@@ -233,25 +239,24 @@ export default function SessionsTable({
SessionMetricOutput
>(sessions.data?.sessions, sessionMetrics.data);
- const filterOptions = api.sessions.filterOptions.useQuery(
- {
- projectId,
- timestampFilter:
- dateRangeFilter[0]?.type === "datetime"
- ? dateRangeFilter[0]
- : undefined,
- },
- {
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- staleTime: Infinity,
- },
+ const newFilterOptions = useMemo(
+ () => ({
+ bookmarked: ["Bookmarked", "Not bookmarked"],
+ sessionDuration: [],
+ countTraces: [],
+ inputTokens: [],
+ outputTokens: [],
+ totalTokens: [],
+ inputCost: [],
+ outputCost: [],
+ totalCost: [],
+ }),
+ [],
+ );
+
+ const queryFilter = useSidebarFilterState(
+ sessionFilterConfig,
+ newFilterOptions,
);
const totalCount = sessionCountQuery.data?.totalCount ?? null;
@@ -622,12 +627,6 @@ export default function SessionsTable({
},
];
- const transformFilterOptions = () => {
- return sessionsTableColsWithOptions(filterOptions.data).filter(
- (c) => c.id !== "createdAt" && !omittedFilter?.includes(c.name),
- );
- };
-
const [columnVisibility, setColumnVisibility] =
useColumnVisibility<SessionTableRow>("sessionsColumnVisibility", columns);
@@ -647,115 +646,122 @@ export default function SessionsTable({
},
validationContext: {
columns,
- filterColumnDefinition: transformFilterOptions(),
+ filterColumnDefinition: sessionFilterConfig.columnDefinitions,
},
+ currentFilterState: userFilterState,
});
return (
- <>
- <DataTableToolbar
- filterColumnDefinition={transformFilterOptions()}
- filterState={userFilterState}
- setFilterState={useDebounce(setUserFilterState)}
- actionButtons={[
- Object.keys(selectedRows).filter((sessionId) =>
- sessions.data?.sessions.map((s) => s.id).includes(sessionId),
- ).length > 0 ? (
- <TableActionMenu
- key="sessions-multi-select-actions"
- projectId={projectId}
- actions={tableActions}
- tableName={BatchExportTableName.Sessions}
+ <DataTableControlsProvider>
+ <div className="flex h-full w-full flex-col">
+ {/* Toolbar spanning full width */}
+ <DataTableToolbar
+ filterState={queryFilter.filterState}
+ actionButtons={[
+ Object.keys(selectedRows).filter((sessionId) =>
+ sessions.data?.sessions.map((s) => s.id).includes(sessionId),
+ ).length > 0 ? (
+ <TableActionMenu
+ key="sessions-multi-select-actions"
+ projectId={projectId}
+ actions={tableActions}
+ tableName={BatchExportTableName.Sessions}
+ />
+ ) : null,
+ ]}
+ columns={columns}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibility}
+ columnOrder={columnOrder}
+ setColumnOrder={setColumnOrder}
+ viewConfig={{
+ tableName: TableViewPresetTableName.Sessions,
+ projectId,
+ controllers: viewControllers,
+ }}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
+ columnsWithCustomSelect={["userIds"]}
+ rowHeight={rowHeight}
+ setRowHeight={setRowHeight}
+ multiSelect={{
+ selectAll,
+ setSelectAll,
+ selectedRowIds: Object.keys(selectedRows).filter((sessionId) =>
+ sessions.data?.sessions.map((s) => s.id).includes(sessionId),
+ ),
+ setRowSelection: setSelectedRows,
+ totalCount,
+ ...paginationState,
+ }}
+ />
+
+ {/* Content area with sidebar and table */}
+ <div className="flex flex-1 overflow-hidden">
+ <DataTableControls queryFilter={queryFilter} />
+
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <DataTable
+ tableName={"sessions"}
+ columns={columns}
+ data={
+ sessions.isPending || isViewLoading
+ ? { isLoading: true, isError: false }
+ : sessions.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: sessions.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: sessionRowData.rows?.map<SessionTableRow>(
+ (session) => {
+ return {
+ id: session.id,
+ createdAt: session.createdAt,
+ bookmarked: session.bookmarked,
+ userIds: session.userIds,
+ countTraces: session.countTraces,
+ sessionDuration: session.sessionDuration,
+ inputCost: session.inputCost,
+ outputCost: session.outputCost,
+ totalCost: session.totalCost,
+ inputTokens: session.promptTokens,
+ outputTokens: session.completionTokens,
+ totalTokens: session.totalTokens,
+ traceTags: session.traceTags,
+ environment: session.environment,
+ scores: session.scores,
+ };
+ },
+ ),
+ }
+ }
+ pagination={{
+ totalCount,
+ onChange: setPaginationState,
+ state: paginationState,
+ }}
+ setOrderBy={setOrderByState}
+ orderBy={orderByState}
+ columnVisibility={columnVisibility}
+ onColumnVisibilityChange={setColumnVisibility}
+ columnOrder={columnOrder}
+ onColumnOrderChange={setColumnOrder}
+ rowSelection={selectedRows}
+ setRowSelection={setSelectedRows}
+ help={{
+ description:
+ "A session is a collection of related traces, such as a conversation or thread. To begin, add a sessionId to the trace.",
+ href: "https://langfuse.com/docs/observability/features/sessions",
+ }}
+ rowHeight={rowHeight}
/>
- ) : null,
- ]}
- columns={columns}
- columnVisibility={columnVisibility}
- setColumnVisibility={setColumnVisibility}
- columnOrder={columnOrder}
- setColumnOrder={setColumnOrder}
- viewConfig={{
- tableName: TableViewPresetTableName.Sessions,
- projectId,
- controllers: viewControllers,
- }}
- timeRange={timeRange}
- setTimeRange={setTimeRange}
- columnsWithCustomSelect={["userIds"]}
- rowHeight={rowHeight}
- setRowHeight={setRowHeight}
- multiSelect={{
- selectAll,
- setSelectAll,
- selectedRowIds: Object.keys(selectedRows).filter((sessionId) =>
- sessions.data?.sessions.map((s) => s.id).includes(sessionId),
- ),
- setRowSelection: setSelectedRows,
- totalCount,
- ...paginationState,
- }}
- environmentFilter={{
- values: selectedEnvironments,
- onValueChange: setSelectedEnvironments,
- options: environmentOptions.map((env) => ({ value: env })),
- }}
- />
- <DataTable
- tableName={"sessions"}
- columns={columns}
- data={
- sessions.isPending || isViewLoading
- ? { isLoading: true, isError: false }
- : sessions.isError
- ? {
- isLoading: false,
- isError: true,
- error: sessions.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: sessionRowData.rows?.map<SessionTableRow>((session) => {
- return {
- id: session.id,
- createdAt: session.createdAt,
- bookmarked: session.bookmarked,
- userIds: session.userIds,
- countTraces: session.countTraces,
- sessionDuration: session.sessionDuration,
- inputCost: session.inputCost,
- outputCost: session.outputCost,
- totalCost: session.totalCost,
- inputTokens: session.promptTokens,
- outputTokens: session.completionTokens,
- totalTokens: session.totalTokens,
- traceTags: session.traceTags,
- environment: session.environment,
- scores: session.scores,
- };
- }),
- }
- }
- pagination={{
- totalCount,
- onChange: setPaginationState,
- state: paginationState,
- }}
- setOrderBy={setOrderByState}
- orderBy={orderByState}
- columnVisibility={columnVisibility}
- onColumnVisibilityChange={setColumnVisibility}
- columnOrder={columnOrder}
- onColumnOrderChange={setColumnOrder}
- rowSelection={selectedRows}
- setRowSelection={setSelectedRows}
- help={{
- description:
- "A session is a collection of related traces, such as a conversation or thread. To begin, add a sessionId to the trace.",
- href: "https://langfuse.com/docs/observability/features/sessions",
- }}
- rowHeight={rowHeight}
- />
- </>
+ </div>
+ </div>
+ </div>
+ </DataTableControlsProvider>
);
}
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index 9633df8bae..b885ae9bd9 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -1,17 +1,20 @@
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";
import { type Row, type RowSelectionState } from "@tanstack/react-table";
-import { useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { NumberParam, useQueryParams, withDefault } from "use-query-params";
import type Decimal from "decimal.js";
import {
@@ -30,7 +33,6 @@ import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import {
type FilterState,
- tracesTableColsWithOptions,
type ObservationLevelType,
BatchExportTableName,
AnnotationQueueObjectType,
@@ -41,7 +43,6 @@ import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-
import { MemoizedIOTableCell } from "../../ui/IOTableCell";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
-import { useDebounce } from "@/src/hooks/useDebounce";
import { type ScoreAggregate } from "@langfuse/shared";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
import { Skeleton } from "@/src/components/ui/skeleton";
@@ -69,10 +70,8 @@ import {
} from "@/src/components/ui/dropdown-menu";
import { Button } from "@/src/components/ui/button";
import TableIdOrName from "@/src/components/table/table-id";
-import {
- useEnvironmentFilter,
- convertSelectedEnvironmentsToFilter,
-} from "@/src/hooks/use-environment-filter";
+import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";
+import { traceFilterConfig } from "@/src/features/filters/config/traces-config";
import { PeekViewTraceDetail } from "@/src/components/table/peek/peek-trace-detail";
import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";
@@ -80,7 +79,6 @@ import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextS
import { type TableDateRange } from "@/src/utils/date-range-utils";
import { useScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";
import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";
-import { useRouter } from "next/router";
export type TracesTableRow = {
// Shown by default
@@ -143,7 +141,6 @@ export default function TracesTable({
externalDateRange,
limitRows,
}: TracesTableProps) {
- const router = useRouter();
const utils = api.useUtils();
const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});
const { setDetailPageList } = useDetailPageLists();
@@ -157,12 +154,6 @@ export default function TracesTable({
const dateRange = externalDateRange ?? tableDateRange;
- const [userFilterState, setUserFilterState] = useQueryFilterState(
- [],
- "traces",
- projectId,
- );
-
const [orderByState, setOrderByState] = useOrderByState({
column: "timestamp",
order: "DESC",
@@ -214,21 +205,68 @@ export default function TracesTable({
},
);
- const environmentOptions =
- environmentFilterOptions.data?.map((value) => value.environment) || [];
+ const traceFilterOptionsResponse = api.traces.filterOptions.useQuery(
+ { projectId },
+ {
+ trpc: { context: { skipBatch: true } },
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ staleTime: Infinity,
+ },
+ );
- const { selectedEnvironments, setSelectedEnvironments } =
- useEnvironmentFilter(environmentOptions, projectId);
+ const filterOptions = useMemo(() => {
+ const scoreCategories =
+ traceFilterOptionsResponse.data?.score_categories?.reduce(
+ (acc, score) => {
+ acc[score.label] = score.values;
+ return acc;
+ },
+ {} as Record<string, string[]>,
+ ) || {};
- const environmentFilter = convertSelectedEnvironmentsToFilter(
- ["environment"],
- selectedEnvironments,
- );
+ const scoresNumeric = traceFilterOptionsResponse.data?.scores_avg || [];
- const combinedFilterState = userFilterState.concat(
+ return {
+ name:
+ traceFilterOptionsResponse.data?.name?.map((n) => ({
+ value: n.value,
+ count: Number(n.count),
+ })) || [],
+ // tags don't have counts
+ tags: traceFilterOptionsResponse.data?.tags?.map((t) => t.value) || [],
+ environment:
+ environmentFilterOptions.data?.map((value) => value.environment) || [],
+ level: ["DEFAULT", "DEBUG", "WARNING", "ERROR"],
+ bookmarked: ["Bookmarked", "Not bookmarked"],
+ userId:
+ traceFilterOptionsResponse.data?.users?.map((u) => ({
+ value: u.value,
+ count: Number(u.count),
+ })) || [],
+ sessionId:
+ traceFilterOptionsResponse.data?.sessions?.map((s) => ({
+ value: s.value,
+ count: Number(s.count),
+ })) || [],
+ latency: [],
+ inputTokens: [],
+ outputTokens: [],
+ totalTokens: [],
+ inputCost: [],
+ outputCost: [],
+ totalCost: [],
+ "Scores (categorical)": scoreCategories,
+ "Scores (numeric)": scoresNumeric,
+ };
+ }, [environmentFilterOptions.data, traceFilterOptionsResponse.data]);
+
+ const queryFilter = useSidebarFilterState(traceFilterConfig, filterOptions);
+
+ const combinedFilterState = queryFilter.filterState.concat(
userIdFilter,
dateRangeFilter,
- environmentFilter,
);
// Use external filter state if provided, otherwise use combined filter state
@@ -312,29 +350,8 @@ export default function TracesTable({
// traces.all should load first together with everything else.
// This here happens in the background.
- const traceFilterOptionsResponse = api.traces.filterOptions.useQuery(
- { projectId },
- {
- trpc: { context: { skipBatch: true } },
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- staleTime: Infinity,
- },
- );
-
const traceFilterOptions = traceFilterOptionsResponse.data;
- const transformedFilterOptions = useMemo(() => {
- return tracesTableColsWithOptions(traceFilterOptions).filter(
- (c) =>
- c.id !== "environment" &&
- c.id !== "timestamp" &&
- !omittedFilter?.includes(c.name) &&
- !omittedFilter?.includes(c.id),
- );
- }, [traceFilterOptions, omittedFilter]);
-
const [storedRowHeight, setRowHeight] = useRowHeightLocalStorage(
"traces",
"s",
@@ -1067,20 +1084,30 @@ export default function TracesTable({
traceMetrics.dataUpdatedAt,
]);
+ // Create ref-based wrapper to avoid stale closure when queryFilter updates
+ const queryFilterRef = useRef(queryFilter);
+ queryFilterRef.current = queryFilter;
+
+ const setFiltersWrapper = useCallback(
+ (filters: FilterState) => queryFilterRef.current?.setFilterState(filters),
+ [],
+ );
+
const { isLoading: isViewLoading, ...viewControllers } = useTableViewManager({
tableName: TableViewPresetTableName.Traces,
projectId,
stateUpdaters: {
setOrderBy: setOrderByState,
- setFilters: setUserFilterState,
+ setFilters: setFiltersWrapper,
setColumnOrder: setColumnOrder,
setColumnVisibility: setColumnVisibility,
setSearchQuery: setSearchQuery,
},
validationContext: {
columns,
- filterColumnDefinition: transformedFilterOptions,
+ filterColumnDefinition: traceFilterConfig.columnDefinitions,
},
+ currentFilterState: queryFilter.filterState,
});
const rows = useMemo(() => {
@@ -1129,150 +1156,122 @@ export default function TracesTable({
: [];
}, [traces.isSuccess, traceRowData?.rows]);
- const setFilterState = useDebounce(setUserFilterState);
-
return (
- <>
- {!hideControls && (
- <DataTableToolbar
- columns={columns}
- filterWithAI
- viewConfig={{
- tableName: TableViewPresetTableName.Traces,
- projectId,
- controllers: viewControllers,
- }}
- filterColumnDefinition={transformedFilterOptions}
- searchConfig={{
- metadataSearchFields: ["ID", "Trace Name", "User ID"],
- updateQuery: setSearchQuery,
- currentQuery: searchQuery ?? undefined,
- tableAllowsFullTextSearch: true,
- setSearchType,
- searchType,
- }}
- filterState={userFilterState}
- setFilterState={setFilterState}
- columnsWithCustomSelect={["name", "tags"]}
- actionButtons={[
- Object.keys(selectedRows).filter((traceId) =>
- traces.data?.traces.map((t) => t.id).includes(traceId),
- ).length > 0 ? (
- <TableActionMenu
- key="traces-multi-select-actions"
- projectId={projectId}
- actions={tableActions}
+ <DataTableControlsProvider>
+ <div className="flex h-full w-full flex-col">
+ {/* Toolbar spanning full width */}
+ {!hideControls && (
+ <DataTableToolbar
+ columns={columns}
+ filterWithAI
+ filterState={queryFilter.filterState}
+ viewConfig={{
+ tableName: TableViewPresetTableName.Traces,
+ projectId,
+ controllers: viewControllers,
+ }}
+ searchConfig={{
+ metadataSearchFields: ["ID", "Trace Name", "User ID"],
+ updateQuery: setSearchQuery,
+ currentQuery: searchQuery ?? undefined,
+ tableAllowsFullTextSearch: true,
+ setSearchType,
+ searchType,
+ }}
+ columnsWithCustomSelect={["name", "tags"]}
+ actionButtons={[
+ Object.keys(selectedRows).filter((traceId) =>
+ traces.data?.traces.map((t) => t.id).includes(traceId),
+ ).length > 0 ? (
+ <TableActionMenu
+ key="traces-multi-select-actions"
+ projectId={projectId}
+ actions={tableActions}
+ tableName={BatchExportTableName.Traces}
+ />
+ ) : null,
+ <BatchExportTableButton
+ {...{
+ projectId,
+ filterState,
+ orderByState,
+ searchQuery,
+ searchType,
+ }}
tableName={BatchExportTableName.Traces}
- />
- ) : null,
- <BatchExportTableButton
- {...{
- projectId,
- filterState,
- orderByState,
- searchQuery,
- searchType,
- }}
- tableName={BatchExportTableName.Traces}
- key="batchExport"
- />,
- ]}
- orderByState={orderByState}
- columnVisibility={columnVisibility}
- setColumnVisibility={setColumnVisibility}
- columnOrder={columnOrder}
- setColumnOrder={setColumnOrder}
- rowHeight={rowHeight}
- setRowHeight={setRowHeight}
- timeRange={timeRange}
- setTimeRange={setTimeRange}
- multiSelect={{
- selectAll,
- setSelectAll,
- selectedRowIds: Object.keys(selectedRows).filter((traceId) =>
- traces.data?.traces.map((t) => t.id).includes(traceId),
- ),
- setRowSelection: setSelectedRows,
- totalCount,
- ...paginationState,
- }}
- environmentFilter={{
- values: selectedEnvironments,
- onValueChange: setSelectedEnvironments,
- options: environmentOptions.map((env) => ({ value: env })),
- }}
- />
- )}
- <DataTable
- columns={columns}
- hidePagination={hideControls}
- data={
- traces.isPending || isViewLoading
- ? { isLoading: true, isError: false }
- : traces.isError
- ? {
- isLoading: false,
- isError: true,
- error: traces.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: rows,
- }
- }
- pagination={
- limitRows
- ? undefined
- : {
- totalCount,
- onChange: setPaginationState,
- state: paginationState,
+ key="batchExport"
+ />,
+ ]}
+ orderByState={orderByState}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibility}
+ columnOrder={columnOrder}
+ setColumnOrder={setColumnOrder}
+ rowHeight={rowHeight}
+ setRowHeight={setRowHeight}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
+ multiSelect={{
+ selectAll,
+ setSelectAll,
+ selectedRowIds: Object.keys(selectedRows).filter((traceId) =>
+ traces.data?.traces.map((t) => t.id).includes(traceId),
+ ),
+ setRowSelection: setSelectedRows,
+ totalCount,
+ ...paginationState,
+ }}
+ />
+ )}
+
+ {/* Content area with sidebar and table */}
+ <div className="flex flex-1 overflow-hidden">
+ <DataTableControls queryFilter={queryFilter} filterWithAI />
+
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <DataTable
+ columns={columns}
+ hidePagination={hideControls}
+ data={
+ traces.isPending || isViewLoading
+ ? { isLoading: true, isError: false }
+ : traces.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: traces.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: rows,
+ }
}
- }
- setOrderBy={setOrderByState}
- orderBy={orderByState}
- rowSelection={selectedRows}
- setRowSelection={setSelectedRows}
- columnVisibility={columnVisibility}
- onColumnVisibilityChange={setColumnVisibility}
- columnOrder={columnOrder}
- onColumnOrderChange={setColumnOrder}
- rowHeight={rowHeight}
- peekView={peekConfig}
- onRowClick={(row, event) => {
- // Handle Command/Ctrl+click to open trace in new tab
- if (event && (event.metaKey || event.ctrlKey)) {
- // Prevent the default peek behavior
- event.preventDefault();
-
- // Construct the trace URL directly to avoid race conditions
- const traceId = row.id;
- const timestamp = row.timestamp;
- const display = router.query.display ?? "details";
-
- let traceUrl = `/project/${projectId}/traces/${encodeURIComponent(traceId)}`;
-
- const params = new URLSearchParams();
- if (timestamp) {
- params.set("timestamp", timestamp.toISOString());
- }
- if (display && typeof display === "string") {
- params.set("display", display);
- }
-
- if (params.toString()) {
- traceUrl += `?${params.toString()}`;
- }
-
- const fullUrl = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${traceUrl}`;
- window.open(fullUrl, "_blank");
- }
- // For normal clicks, let the data-table handle opening the peek view
- }}
- tableName={"traces"}
- />
- </>
+ pagination={
+ limitRows
+ ? undefined
+ : {
+ totalCount,
+ onChange: setPaginationState,
+ state: paginationState,
+ }
+ }
+ setOrderBy={setOrderByState}
+ orderBy={orderByState}
+ rowSelection={selectedRows}
+ setRowSelection={setSelectedRows}
+ columnVisibility={columnVisibility}
+ onColumnVisibilityChange={setColumnVisibility}
+ columnOrder={columnOrder}
+ onColumnOrderChange={setColumnOrder}
+ rowHeight={rowHeight}
+ peekView={peekConfig}
+ tableName={"traces"}
+ />
+ </div>
+ </div>
+ </div>
+ </DataTableControlsProvider>
);
}
diff --git a/web/src/components/ui/slider.tsx b/web/src/components/ui/slider.tsx
index 28f3de9a74..b0626b0c4d 100644
--- a/web/src/components/ui/slider.tsx
+++ b/web/src/components/ui/slider.tsx
@@ -82,6 +82,10 @@ const Slider = React.forwardRef<
}
};
+ const initialValue = Array.isArray(props.value)
+ ? props.value
+ : [props.min ?? 0, props.max ?? 100];
+
return (
<div className={cn("flex items-center gap-4", className)}>
<SliderPrimitive.Root
@@ -97,12 +101,15 @@ const Slider = React.forwardRef<
)}
/>
</SliderPrimitive.Track>
- <SliderPrimitive.Thumb
- className={cn(
- "block h-5 w-5 rounded-full border-2 bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
- props.disabled ? "border-secondary" : "border-primary",
- )}
- />
+ {initialValue.map((_, index) => (
+ <SliderPrimitive.Thumb
+ key={index}
+ className={cn(
+ "block h-4 w-4 rounded-full border-2 bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
+ props.disabled ? "border-secondary" : "border-primary",
+ )}
+ />
+ ))}
</SliderPrimitive.Root>
{showInput && (
diff --git a/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx b/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
index 46d997f387..33cf287d0f 100644
--- a/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
+++ b/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
@@ -40,7 +40,6 @@ function RunAggregateHeader({
onChange={(filters: FilterState) =>
debouncedUpdateRunFilters(runId, filters)
}
- variant="icon"
/>
</div>
);
diff --git a/web/src/features/evals/components/evaluator-table.tsx b/web/src/features/evals/components/evaluator-table.tsx
index 25c0fd2e48..e42063dc5b 100644
--- a/web/src/features/evals/components/evaluator-table.tsx
+++ b/web/src/features/evals/components/evaluator-table.tsx
@@ -2,11 +2,16 @@ import { StatusBadge } from "@/src/components/layouts/status-badge";
import { LevelCountsDisplay } from "@/src/components/level-counts-display";
import { DataTable } from "@/src/components/table/data-table";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
+import {
+ DataTableControlsProvider,
+ DataTableControls,
+} from "@/src/components/table/data-table-controls";
import { type LangfuseColumnDef } from "@/src/components/table/types";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
import { InlineFilterState } from "@/src/features/filters/components/filter-builder";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
-import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";
+import { evaluatorFilterConfig } from "@/src/features/filters/config/evaluators-config";
import { type RouterOutputs, api } from "@/src/utils/api";
import { safeExtract } from "@/src/utils/map-utils";
import { type FilterState, singleFilter } from "@langfuse/shared";
@@ -44,7 +49,6 @@ import {
import { EvaluatorForm } from "@/src/features/evals/components/evaluator-form";
import { useRouter } from "next/router";
import { DeleteEvalConfigButton } from "@/src/components/deleteButton";
-import { evalConfigFilterColumns } from "@/src/server/api/definitions/evalConfigsTable";
import { RAGAS_TEMPLATE_PREFIX } from "@/src/features/evals/types";
import { MaintainerTooltip } from "@/src/features/evals/components/maintainer-tooltip";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
@@ -89,22 +93,26 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
const [editConfigId, setEditConfigId] = useState<string | null>(null);
const utils = api.useUtils();
- const [filterState, setFilterState] = useQueryFilterState(
- [],
- "eval_configs",
- projectId,
- );
-
const [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,
projectId,
- filter: filterState,
+ filter: queryFilter.filterState,
orderBy: orderByState,
searchQuery: searchQuery,
});
@@ -385,68 +393,82 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
};
return (
- <>
- <DataTableToolbar
- columns={columns}
- filterColumnDefinition={evalConfigFilterColumns}
- filterState={filterState}
- setFilterState={setFilterState}
- columnVisibility={columnVisibility}
- setColumnVisibility={setColumnVisibility}
- searchConfig={{
- metadataSearchFields: ["Name"],
- updateQuery: setSearchQuery,
- currentQuery: searchQuery ?? undefined,
- tableAllowsFullTextSearch: false,
- setSearchType: undefined,
- searchType: undefined,
- }}
- />
- <DataTable
- tableName={"evalConfigs"}
- columns={columns}
- peekView={{
- itemType: "RUNNING_EVALUATOR",
- detailNavigationKey: "evals",
- peekEventOptions: {
- ignoredSelectors: [
- "[aria-label='edit'], [aria-label='actions'], [aria-label='view-logs'], [aria-label='delete']",
- ],
- },
- tableDataUpdatedAt: Math.max(
- evaluators.dataUpdatedAt,
- costs.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}
- />
+ <DataTableControlsProvider
+ tableName={evaluatorFilterConfig.tableName}
+ defaultSidebarCollapsed={evaluatorFilterConfig.defaultSidebarCollapsed}
+ >
+ <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: Math.max(
+ evaluators.dataUpdatedAt,
+ costs.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}
+ />
+ </div>
+ </div>
+ </div>
<Dialog
open={!!editConfigId && existingEvaluator.isSuccess}
onOpenChange={(open) => {
@@ -491,6 +513,6 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
)}
</DialogContent>
</Dialog>
- </>
+ </DataTableControlsProvider>
);
}
diff --git a/web/src/features/evals/components/inner-evaluator-form.tsx b/web/src/features/evals/components/inner-evaluator-form.tsx
index 4658bb191b..236a6ce209 100644
--- a/web/src/features/evals/components/inner-evaluator-form.tsx
+++ b/web/src/features/evals/components/inner-evaluator-form.tsx
@@ -215,8 +215,23 @@ export const InnerEvaluatorForm = (props: {
);
const traceFilterOptions = useMemo(() => {
+ // Normalize API response to match TraceOptions type (count should be number, not string)
+ const normalized = traceFilterOptionsResponse.data
+ ? {
+ name: traceFilterOptionsResponse.data.name?.map((n) => ({
+ value: n.value,
+ count: Number(n.count),
+ })),
+ scores_avg: traceFilterOptionsResponse.data.scores_avg,
+ score_categories: traceFilterOptionsResponse.data.score_categories,
+ tags: traceFilterOptionsResponse.data.tags?.map((t) => ({
+ value: t.value,
+ })),
+ }
+ : {};
+
return {
- ...(traceFilterOptionsResponse.data ?? {}),
+ ...normalized,
environment: environmentFilterOptionsResponse.data?.map((e) => ({
value: e.environment,
})),
diff --git a/web/src/features/filters/components/filter-builder.tsx b/web/src/features/filters/components/filter-builder.tsx
index e29402afab..8cc4e00bdc 100644
--- a/web/src/features/filters/components/filter-builder.tsx
+++ b/web/src/features/filters/components/filter-builder.tsx
@@ -16,7 +16,6 @@ import {
Check,
ChevronDown,
ExternalLink,
- Filter,
Info,
Plus,
WandSparkles,
@@ -63,7 +62,6 @@ export function PopoverFilterBuilder({
filterState,
onChange,
columnsWithCustomSelect = [],
- variant = "default",
filterWithAI = false,
}: {
columns: ColumnDefinition[];
@@ -72,7 +70,6 @@ export function PopoverFilterBuilder({
| Dispatch<SetStateAction<FilterState>>
| ((newState: FilterState) => void);
columnsWithCustomSelect?: string[];
- variant?: "default" | "icon";
filterWithAI?: boolean;
}) {
const capture = usePostHogClientCapture();
@@ -128,43 +125,27 @@ export function PopoverFilterBuilder({
}}
>
<PopoverTrigger asChild>
- {variant === "default" ? (
- <Button variant="outline" type="button">
- <span>Filters</span>
- {filterState.length > 0 && filterState.length < 3 ? (
- <InlineFilterState
- filterState={filterState}
- className="hidden @6xl:block"
- />
- ) : null}
- {filterState.length > 0 ? (
- <span
- className={cn(
- "ml-1.5 rounded-sm bg-input px-1 text-xs shadow-sm @6xl:hidden",
- filterState.length > 2 && "@6xl:inline",
- )}
- >
- {filterState.length}
- </span>
- ) : (
- <ChevronDown className="ml-1 h-4 w-4 opacity-50" />
- )}
- </Button>
- ) : (
- <Button
- variant="outline"
- type="button"
- size="icon"
- className="relative"
- >
- <Filter className="h-4 w-4" />
- {filterState.length > 0 && (
- <span className="absolute right-0.5 top-0.5 flex h-3 w-3 items-center justify-center rounded-sm bg-input text-xs shadow-sm">
- {filterState.length}
- </span>
- )}
- </Button>
- )}
+ <Button variant="outline" type="button">
+ <span>Filters</span>
+ {filterState.length > 0 && filterState.length < 3 ? (
+ <InlineFilterState
+ filterState={filterState}
+ className="hidden @6xl:block"
+ />
+ ) : null}
+ {filterState.length > 0 ? (
+ <span
+ className={cn(
+ "ml-1.5 rounded-sm bg-input px-1 text-xs shadow-sm @6xl:hidden",
+ filterState.length > 2 && "@6xl:inline",
+ )}
+ >
+ {filterState.length}
+ </span>
+ ) : (
+ <ChevronDown className="ml-1 h-4 w-4 opacity-50" />
+ )}
+ </Button>
</PopoverTrigger>
<PopoverContent
className="w-fit max-w-[90vw] overflow-x-auto"
diff --git a/web/src/features/filters/config/evaluators-config.ts b/web/src/features/filters/config/evaluators-config.ts
new file mode 100644
index 0000000000..bb0cafc926
--- /dev/null
+++ b/web/src/features/filters/config/evaluators-config.ts
@@ -0,0 +1,33 @@
+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"],
+
+ defaultSidebarCollapsed: true,
+
+ facets: [
+ {
+ type: "categorical" as const,
+ column: "status",
+ label: "Status",
+ },
+ {
+ type: "categorical" as const,
+ column: "target",
+ label: "Target",
+ },
+ ],
+};
diff --git a/web/src/features/filters/config/observations-config.ts b/web/src/features/filters/config/observations-config.ts
new file mode 100644
index 0000000000..1efa22e43a
--- /dev/null
+++ b/web/src/features/filters/config/observations-config.ts
@@ -0,0 +1,143 @@
+import { observationsTableCols } from "@langfuse/shared";
+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";
+import type { ColumnToQueryKeyMap } from "@/src/features/filters/lib/filter-query-encoding";
+
+const OBSERVATION_COLUMN_TO_QUERY_KEY: ColumnToQueryKeyMap = {
+ environment: "environment",
+ name: "name",
+ type: "type",
+ traceName: "traceName",
+ level: "level",
+ model: "model",
+ modelId: "modelId",
+ promptName: "promptName",
+ tags: "tags",
+ timeToFirstToken: "timeToFirstToken",
+ latency: "latency",
+ tokensPerSecond: "tokensPerSecond",
+ inputCost: "inputCost",
+ outputCost: "outputCost",
+ totalCost: "totalCost",
+ inputTokens: "inputTokens",
+ outputTokens: "outputTokens",
+ totalTokens: "totalTokens",
+};
+
+export const observationFilterConfig: FilterConfig = {
+ tableName: "observations",
+
+ columnToQueryKey: OBSERVATION_COLUMN_TO_QUERY_KEY,
+
+ columnDefinitions: observationsTableCols,
+
+ defaultExpanded: ["environment", "name"],
+
+ facets: [
+ {
+ type: "categorical" as const,
+ column: "environment",
+ label: "Environment",
+ },
+ {
+ type: "categorical" as const,
+ column: "type",
+ label: "Type",
+ },
+ {
+ type: "categorical" as const,
+ column: "name",
+ label: "Name",
+ },
+ {
+ type: "categorical" as const,
+ column: "traceName",
+ label: "Trace Name",
+ },
+ {
+ type: "categorical" as const,
+ column: "level",
+ label: "Level",
+ },
+ {
+ type: "categorical" as const,
+ column: "model",
+ label: "Model",
+ },
+ {
+ type: "categorical" as const,
+ column: "modelId",
+ label: "Model ID",
+ },
+ {
+ type: "categorical" as const,
+ column: "promptName",
+ label: "Prompt Name",
+ },
+ {
+ type: "categorical" as const,
+ column: "tags",
+ label: "Trace Tags",
+ },
+ {
+ type: "numeric" as const,
+ column: "latency",
+ label: "Latency",
+ min: 0,
+ max: 60,
+ unit: "s",
+ },
+ {
+ type: "numeric" as const,
+ column: "timeToFirstToken",
+ label: "Time to First Token",
+ min: 0,
+ max: 60,
+ unit: "s",
+ },
+ {
+ type: "numeric" as const,
+ column: "inputTokens",
+ label: "Input Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "outputTokens",
+ label: "Output Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "totalTokens",
+ label: "Total Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "inputCost",
+ label: "Input Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ {
+ type: "numeric" as const,
+ column: "outputCost",
+ label: "Output Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ {
+ type: "numeric" as const,
+ column: "totalCost",
+ label: "Total Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ ],
+};
diff --git a/web/src/features/filters/config/prompts-config.ts b/web/src/features/filters/config/prompts-config.ts
new file mode 100644
index 0000000000..40d03dcfe6
--- /dev/null
+++ b/web/src/features/filters/config/prompts-config.ts
@@ -0,0 +1,47 @@
+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"],
+
+ defaultSidebarCollapsed: true,
+
+ facets: [
+ {
+ type: "categorical" as const,
+ column: "type",
+ label: "Type",
+ },
+ {
+ type: "categorical" as const,
+ column: "labels",
+ label: "Labels",
+ },
+ {
+ type: "categorical" as const,
+ column: "tags",
+ label: "Tags",
+ },
+ {
+ type: "numeric" as const,
+ column: "version",
+ label: "Version",
+ min: 1,
+ max: 100,
+ },
+ ],
+};
diff --git a/web/src/features/filters/config/scores-config.ts b/web/src/features/filters/config/scores-config.ts
new file mode 100644
index 0000000000..0d50f2182e
--- /dev/null
+++ b/web/src/features/filters/config/scores-config.ts
@@ -0,0 +1,47 @@
+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"],
+
+ defaultSidebarCollapsed: true,
+
+ facets: [
+ {
+ type: "categorical" as const,
+ column: "name",
+ label: "Name",
+ },
+ {
+ type: "categorical" as const,
+ column: "source",
+ label: "Source",
+ },
+ {
+ type: "categorical" as const,
+ column: "dataType",
+ label: "Data Type",
+ },
+ {
+ type: "numeric" as const,
+ column: "value",
+ label: "Value",
+ min: -100,
+ max: 100,
+ },
+ ],
+};
diff --git a/web/src/features/filters/config/sessions-config.ts b/web/src/features/filters/config/sessions-config.ts
new file mode 100644
index 0000000000..197b2eb720
--- /dev/null
+++ b/web/src/features/filters/config/sessions-config.ts
@@ -0,0 +1,95 @@
+import { sessionsViewCols } from "@langfuse/shared";
+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";
+import type { ColumnToQueryKeyMap } from "@/src/features/filters/lib/filter-query-encoding";
+
+const SESSION_COLUMN_TO_QUERY_KEY: ColumnToQueryKeyMap = {
+ bookmarked: "bookmarked",
+ sessionDuration: "sessionDuration",
+ countTraces: "countTraces",
+ inputCost: "inputCost",
+ outputCost: "outputCost",
+ totalCost: "totalCost",
+ inputTokens: "inputTokens",
+ outputTokens: "outputTokens",
+ totalTokens: "totalTokens",
+};
+
+export const sessionFilterConfig: FilterConfig = {
+ tableName: "sessions",
+
+ columnToQueryKey: SESSION_COLUMN_TO_QUERY_KEY,
+
+ columnDefinitions: sessionsViewCols,
+
+ defaultExpanded: ["bookmarked"],
+
+ facets: [
+ {
+ type: "boolean" as const,
+ column: "bookmarked",
+ label: "Bookmarked",
+ trueLabel: "Bookmarked",
+ falseLabel: "Not bookmarked",
+ },
+ {
+ type: "numeric" as const,
+ column: "sessionDuration",
+ label: "Session Duration",
+ min: 0,
+ max: 3600,
+ unit: "s",
+ },
+ {
+ type: "numeric" as const,
+ column: "countTraces",
+ label: "Traces Count",
+ min: 0,
+ max: 1000,
+ },
+ {
+ type: "numeric" as const,
+ column: "inputTokens",
+ label: "Input Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "outputTokens",
+ label: "Output Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "totalTokens",
+ label: "Total Tokens",
+ min: 0,
+ max: 1000000,
+ },
+ {
+ type: "numeric" as const,
+ column: "inputCost",
+ label: "Input Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ {
+ type: "numeric" as const,
+ column: "outputCost",
+ label: "Output Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ {
+ type: "numeric" as const,
+ column: "totalCost",
+ label: "Total Cost",
+ min: 0,
+ max: 100,
+ unit: "$",
+ },
+ ],
+};
diff --git a/web/src/features/filters/config/traces-config.ts b/web/src/features/filters/config/traces-config.ts
new file mode 100644
index 0000000000..084d5a833a
--- /dev/null
+++ b/web/src/features/filters/config/traces-config.ts
@@ -0,0 +1,159 @@
+import { tracesTableCols } from "@langfuse/shared";
+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";
+import type { ColumnToQueryKeyMap } from "@/src/features/filters/lib/filter-query-encoding";
+
+const TRACE_COLUMN_TO_QUERY_KEY: ColumnToQueryKeyMap = {
+ id: "id",
+ name: "name",
+ userId: "userId",
+ sessionId: "sessionId",
+ version: "version",
+ release: "release",
+ tags: "tags",
+ environment: "environment",
+ level: "level",
+ bookmarked: "bookmarked",
+ latency: "latency",
+ inputTokens: "inputTokens",
+ outputTokens: "outputTokens",
+ totalTokens: "totalTokens",
+ inputCost: "inputCost",
+ outputCost: "outputCost",
+ totalCost: "totalCost",
+ "Scores (categorical)": "score_categories",
+ "Scores (numeric)": "scores_avg",
+ 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: "categorical" as const,
+ column: "userId",
+ label: "User ID",
+ },
+ {
+ type: "categorical" as const,
+ column: "sessionId",
+ label: "Session 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/filter-integration.clienttest.ts b/web/src/features/filters/filter-integration.clienttest.ts
new file mode 100644
index 0000000000..ccae80ad95
--- /dev/null
+++ b/web/src/features/filters/filter-integration.clienttest.ts
@@ -0,0 +1,419 @@
+/**
+ * Integration tests for filter query encoding/decoding through full URL lifecycle.
+ * These tests verify the complete flow: FilterState → URL → FilterState
+ * using browser URLSearchParams APIs to simulate real-world usage.
+ */
+
+import { type FilterState, tracesTableCols } from "@langfuse/shared";
+import {
+ encodeFiltersGeneric,
+ decodeFiltersGeneric,
+ type ColumnToQueryKeyMap,
+ type GenericFilterOptions,
+} from "./lib/filter-query-encoding";
+import { validateFilters } from "@/src/components/table/table-view-presets/validation";
+
+const mockColumnMap: ColumnToQueryKeyMap = {
+ name: "name",
+ period: "period",
+ diet: "diet",
+ length: "length",
+ extinct: "extinct",
+ ratings: "ratings",
+ scoresNumeric: "scoresNumeric",
+ metadata: "metadata",
+};
+
+const mockOptions: GenericFilterOptions = {
+ period: ["triassic", "jurassic", "cretaceous"],
+ diet: ["carnivore", "herbivore", "omnivore"],
+};
+
+// Helper to simulate complete URL flow
+function simulateUrlFlow(filters: FilterState): FilterState {
+ // encode filters to query string
+ const encoded = encodeFiltersGeneric(filters, mockColumnMap, mockOptions);
+
+ // mock browser URL API
+ const params = new URLSearchParams();
+ params.set("filter", encoded);
+ const urlString = params.toString();
+
+ // mock reading from URL like on page load
+ const readParams = new URLSearchParams(urlString);
+ const queryValue = readParams.get("filter") || "";
+
+ // decode to filter state
+ return decodeFiltersGeneric(queryValue, mockColumnMap, mockOptions);
+}
+
+describe("Filter Query Encoding Integration (Full URL Lifecycle)", () => {
+ it("should handle all filter types through complete URL flow", () => {
+ const filters: FilterState = [
+ // string
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "tyrannosaurus rex",
+ },
+ // number with >= and <=
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 5,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 10,
+ },
+ // boolean with =
+ {
+ column: "extinct",
+ type: "boolean",
+ operator: "=",
+ value: true,
+ },
+ // stringOptions (any of)
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic", "jurassic"],
+ },
+ // stringOptions (none of)
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["carnivore"],
+ },
+ // numberObject
+ {
+ column: "scoresNumeric",
+ type: "numberObject",
+ operator: ">=",
+ key: "accuracy",
+ value: 0.8,
+ },
+ // stringObject
+ {
+ column: "metadata",
+ type: "stringObject",
+ operator: "contains",
+ key: "environment",
+ value: "production",
+ },
+ // categoryOptions
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "danger",
+ value: ["high", "medium"],
+ },
+ ];
+
+ const result = simulateUrlFlow(filters);
+ expect(result).toEqual(filters);
+ });
+
+ it("should handle backwards compatibility with legacy URL-encoded operators", () => {
+ // Verify legacy bookmarked URLs with %3E%3D (>=), %3C%3D (<=), %3D (=) still work
+ const legacyUrl =
+ "filter=length;number;;%3E%3D;5,length;number;;%3C%3D;10,extinct;boolean;;%3D;true";
+ const params = new URLSearchParams(legacyUrl);
+ const decoded = decodeFiltersGeneric(
+ params.get("filter") || "",
+ mockColumnMap,
+ mockOptions,
+ );
+
+ expect(decoded).toEqual([
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 5,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 10,
+ },
+ {
+ column: "extinct",
+ type: "boolean",
+ operator: "=",
+ value: true,
+ },
+ ]);
+ });
+
+ it("should handle URL-unsafe characters and edge cases", () => {
+ const edgeCases: Array<{ filters: FilterState; description: string }> = [
+ {
+ description: "special characters in values",
+ filters: [
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "T-Rex (Tyrannosaurus) & Friends!",
+ },
+ ],
+ },
+ {
+ description: "unicode characters",
+ filters: [
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "🦖 T-Rex 恐竜 恐龙",
+ },
+ ],
+ },
+ {
+ description: "percent characters",
+ filters: [
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "50%",
+ },
+ ],
+ },
+ {
+ description: "empty string value",
+ filters: [
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "",
+ },
+ ],
+ },
+ {
+ description: "pipe characters in array values",
+ filters: [
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic", "jurassic"],
+ },
+ ],
+ },
+ {
+ description: "operators with URL-unsafe chars (>=, <=)",
+ filters: [
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 5,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 10,
+ },
+ ],
+ },
+ ];
+
+ edgeCases.forEach(({ filters }) => {
+ const result = simulateUrlFlow(filters);
+ expect(result).toEqual(filters);
+ });
+
+ // Empty filters
+ expect(simulateUrlFlow([])).toEqual([]);
+ });
+});
+
+describe("Saved View Validation (Backward & Forward Compatibility)", () => {
+ /**
+ * Integration tests simulating the full save/restore flow.
+ * These test what happens when:
+ * 1. Old saved views (no env/timestamp) are loaded → should work
+ * 2. New saved views (with env/timestamp) are saved → should be preserved
+ * 3. New saved views (with env/timestamp) are loaded → should work
+ */
+
+ it("should restore old saved view without environment or timestamp filters", () => {
+ // Simulate loading an old saved view from database
+ const oldSavedView: FilterState = [
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["test"],
+ },
+ { column: "latency", type: "number", operator: ">=", value: 1.5 },
+ ];
+
+ // This is what useTableViewManager does: validates then applies
+ const validated = validateFilters(oldSavedView, tracesTableCols);
+
+ // Should pass through unchanged - no env/timestamp to validate
+ expect(validated).toEqual(oldSavedView);
+ expect(validated).toHaveLength(2);
+ });
+
+ it("should save new view with environment filter and restore it correctly", () => {
+ // User creates filter state with environment (now possible in new UI)
+ const newFilterState: FilterState = [
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["prod"],
+ },
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["test"],
+ },
+ ];
+
+ // 1. SAVE: Component saves this to database (no transformation)
+ const savedToDB = newFilterState; // Stored as-is in JSON column
+
+ // 2. RESTORE: Later, load from database and validate
+ const validated = validateFilters(savedToDB, tracesTableCols);
+
+ // Should restore with environment filter intact
+ expect(validated).toEqual(newFilterState);
+ expect(validated).toHaveLength(2);
+ expect(validated[0]?.column).toBe("environment"); // ✅ Environment preserved
+ });
+
+ it("should save new view with timestamp filter and restore it correctly", () => {
+ // User sets date range, which creates timestamp filters
+ const newFilterState: FilterState = [
+ {
+ column: "timestamp",
+ type: "datetime",
+ operator: ">=",
+ value: new Date("2024-01-01"),
+ },
+ {
+ column: "timestamp",
+ type: "datetime",
+ operator: "<=",
+ value: new Date("2024-12-31"),
+ },
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["test"],
+ },
+ ];
+
+ // SAVE → RESTORE cycle
+ const validated = validateFilters(newFilterState, tracesTableCols);
+
+ // Should restore with timestamp filters intact
+ expect(validated).toEqual(newFilterState);
+ expect(validated).toHaveLength(3);
+ expect(validated[0]?.column).toBe("timestamp"); // ✅ Timestamp preserved
+ });
+
+ it("should demonstrate BUG: restore fails with filtered column definitions", () => {
+ // This simulates the CURRENT BUG in traces.tsx:1131
+ // where transformedFilterOptions filters out environment/timestamp
+ const filteredCols = tracesTableCols.filter(
+ (c) => c.id !== "environment" && c.id !== "timestamp",
+ );
+
+ // Load a view with environment filter (valid in new system)
+ const savedView: FilterState = [
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["prod"],
+ },
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["test"],
+ },
+ ];
+
+ // Validate with FILTERED columns (what traces.tsx currently does)
+ const validated = validateFilters(savedView, filteredCols);
+
+ // BUG: environment filter incorrectly removed during restore!
+ expect(validated).toHaveLength(1); // ❌ Lost environment filter
+ expect(validated[0]?.column).toBe("name");
+ // This would show error toast: "Outdated view - Some filters were ignored"
+ });
+
+ it("should remove truly invalid columns but keep valid ones", () => {
+ // View has both valid and invalid columns
+ const mixedView: FilterState = [
+ {
+ column: "deletedColumn",
+ type: "string",
+ operator: "contains",
+ value: "x",
+ },
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["prod"],
+ },
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["test"],
+ },
+ ];
+
+ const validated = validateFilters(mixedView, tracesTableCols);
+
+ // Should remove deletedColumn, keep environment and name
+ expect(validated).toHaveLength(2);
+ expect(validated.map((f) => f.column)).toEqual(["environment", "name"]);
+ });
+
+ it("should normalize old display names to column IDs", () => {
+ // Old saved views used display names like "User ID" instead of "userId"
+ const oldViewWithDisplayNames: FilterState = [
+ {
+ column: "User ID",
+ type: "string",
+ operator: "contains",
+ value: "test-user",
+ },
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["test-trace"],
+ },
+ ];
+
+ const validated = validateFilters(oldViewWithDisplayNames, tracesTableCols);
+
+ // Should normalize "User ID" to "userId", keep "name" as-is
+ expect(validated).toHaveLength(2);
+ expect(validated[0]?.column).toBe("userId"); // Normalized!
+ expect(validated[1]?.column).toBe("name"); // Already correct
+ });
+});
diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsx
new file mode 100644
index 0000000000..edcaf8a418
--- /dev/null
+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx
@@ -0,0 +1,1166 @@
+import { useCallback, useMemo } from "react";
+import { StringParam, useQueryParam, withDefault } from "use-query-params";
+import {
+ type FilterState,
+ singleFilter,
+ type SingleValueOption,
+} 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;
+}
+
+/**
+ * Represents one text filter entry (contains/does not contain)
+ * Used for free-text filtering that's mutually exclusive with checkbox selection
+ */
+export type TextFilterEntry = {
+ operator: "contains" | "does not contain";
+ value: string;
+};
+
+export interface CategoricalUIFilter extends BaseUIFilter {
+ type: "categorical";
+ value: string[];
+ options: string[];
+ counts: Map<string, number>;
+ onChange: (values: string[]) => void;
+ onOnlyChange?: (value: string) => void;
+ /**
+ * Current operator for arrayOptions columns (tags, labels, etc.)
+ * - "any of": OR logic - match if item has ANY selected value
+ * - "all of": AND logic - match if item has ALL selected values
+ * undefined for non-arrayOptions columns
+ */
+ operator?: "any of" | "all of";
+ /**
+ * Callback to change the operator. Only provided for arrayOptions columns.
+ * When called, updates the filter to use the specified operator.
+ */
+ onOperatorChange?: (operator: "any of" | "all of") => void;
+ /**
+ * Active text filters (contains/does not contain) for this column
+ * Mutually exclusive with checkbox selections
+ */
+ textFilters?: TextFilterEntry[];
+ // Add a new text filter. Automatically clears checkbox selections.
+ onTextFilterAdd?: (
+ operator: "contains" | "does not contain",
+ value: string,
+ ) => void;
+ // Remove a text filter by operator and value
+ onTextFilterRemove?: (
+ operator: "contains" | "does not contain",
+ value: string,
+ ) => void;
+ // True if any text filters are active for this column
+ hasTextFilters?: boolean;
+ // True if any checkboxes are selected (excluding "all selected" state)
+ hasCheckboxSelections?: boolean;
+}
+
+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();
+
+// extract values and counts from options array
+// for both string[] and SingleValueOption[]
+function processOptions(options: (string | SingleValueOption)[]): {
+ values: string[];
+ counts: Map<string, number>;
+} {
+ const values: string[] = [];
+ const counts = new Map<string, number>();
+
+ for (const opt of options) {
+ if (typeof opt === "string") {
+ values.push(opt);
+ } else if (typeof opt === "object" && "value" in opt) {
+ values.push(opt.value);
+ if (opt.count !== undefined) {
+ counts.set(opt.value, opt.count);
+ }
+ }
+ }
+
+ return { values, counts: counts.size > 0 ? counts : EMPTY_MAP };
+}
+
+type UpdateFilter = (
+ column: string,
+ values: string[],
+ operator?: "any of" | "none of" | "all of",
+) => void;
+
+export function useSidebarFilterState(
+ config: FilterConfig,
+ options: Record<
+ string,
+ (string | SingleValueOption)[] | 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" | "all 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.map((opt) =>
+ typeof opt === "string" ? opt : opt.value,
+ );
+
+ // Determine operator and values based on context
+ let finalOperator: "any of" | "none of" | "all of";
+ let finalValues: string[];
+
+ if (operator !== undefined) {
+ // Explicit operator provided (e.g., from "Only" button or operator toggle) - use as-is
+ finalOperator = operator;
+ finalValues = values;
+ } else {
+ // If all items selected or none selected, remove filter
+ // (only for implicit/checkbox-based selection, not when operator is explicitly set)
+ if (
+ values.length === 0 ||
+ (values.length === availableValues.length &&
+ availableValues.every((v) => values.includes(v)))
+ ) {
+ return other;
+ }
+ // 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 if (
+ existingFilter.operator === "all of" &&
+ existingFilter.type === "arrayOptions"
+ ) {
+ // Existing "all of" filter - keep "all of" with selected items
+ finalOperator = "all of";
+ finalValues = values;
+ } 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,
+ },
+ ];
+ }
+
+ // stringOptions only supports "any of" | "none of", not "all of"
+ // finalOperator can be "all of" because UpdateFilter type signature allows it,
+ // but this shouldn't happen. UI only shows operator toggle for arrayOptions,
+ // which cannot be set to "all of". We just prevent a TS build error here.
+ const stringOperator: "any of" | "none of" =
+ finalOperator === "all of" ? "any of" : finalOperator;
+
+ return [
+ ...other,
+ {
+ column,
+ type: "stringOptions" as const,
+ operator: stringOperator,
+ value: finalValues,
+ },
+ ];
+ },
+ [config, options],
+ );
+
+ const updateFilter: UpdateFilter = useCallback(
+ (column, values, operator?: "any of" | "none of" | "all of") => {
+ // Remove text filters for this column (they're mutually exclusive with checkboxes)
+ const withoutTextFilters = filterState.filter(
+ (f) =>
+ !(
+ f.column === column &&
+ f.type === "string" &&
+ (f.operator === "contains" || f.operator === "does not contain")
+ ),
+ );
+
+ const next = applySelection(withoutTextFilters, 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 updateOperator = useCallback(
+ (column: string, newOperator: "any of" | "all of") => {
+ // Find the existing filter for this column
+ const existingFilter = filterState.find((f) => f.column === column);
+ if (!existingFilter) {
+ // Create a filter with the operator and empty values
+ // important so users set the operator preference before selecting values,
+ // in case for ALL on TAGS filter
+ updateFilter(column, [], newOperator);
+ return;
+ }
+
+ // Only works for arrayOptions and stringOptions filters
+ if (
+ existingFilter.type !== "arrayOptions" &&
+ existingFilter.type !== "stringOptions"
+ ) {
+ return;
+ }
+
+ // Get the current selected values
+ // For "none of", we need to compute the actual selected values
+ const availableValuesRaw = options[column];
+ const availableValues = Array.isArray(availableValuesRaw)
+ ? availableValuesRaw.map((opt) =>
+ typeof opt === "string" ? opt : opt.value,
+ )
+ : [];
+
+ let currentValues: string[];
+ if (existingFilter.operator === "none of") {
+ // Convert "none of [excluded]" to selected values
+ const excluded = new Set(existingFilter.value);
+ currentValues = availableValues.filter((v) => !excluded.has(v));
+ } else {
+ currentValues = existingFilter.value;
+ }
+
+ // Update the filter with the new operator
+ updateFilter(column, currentValues, newOperator);
+ },
+ [filterState, updateFilter, options],
+ );
+
+ 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],
+ );
+
+ // Text filter management for categorical filters
+ // Mutually exclusive with checkbox selections
+ const addTextFilter = useCallback(
+ (
+ column: string,
+ operator: "contains" | "does not contain",
+ value: string,
+ ) => {
+ if (!value.trim()) {
+ return;
+ }
+
+ // Remove all checkbox filters (stringOptions/arrayOptions) for this column
+ const withoutCheckboxFilters = filterState.filter(
+ (f) =>
+ !(
+ f.column === column &&
+ (f.type === "stringOptions" || f.type === "arrayOptions")
+ ),
+ );
+
+ // Add the new text filter
+ const newFilter: FilterState[number] = {
+ column,
+ type: "string",
+ operator,
+ value: value.trim(),
+ };
+
+ const next: FilterState = [...withoutCheckboxFilters, newFilter];
+ setFilterState(next);
+ },
+ [filterState, setFilterState],
+ );
+
+ const removeTextFilter = useCallback(
+ (
+ column: string,
+ operator: "contains" | "does not contain",
+ value: string,
+ ) => {
+ const newFilters = filterState.filter(
+ (f) =>
+ !(
+ f.column === column &&
+ f.type === "string" &&
+ f.operator === operator &&
+ f.value === value
+ ),
+ );
+
+ setFilterState(newFilters);
+ },
+ [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.map((opt) =>
+ typeof opt === "string" ? opt : opt.value,
+ )
+ : 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.map((opt) =>
+ typeof opt === "string" ? opt : opt.value,
+ )
+ : 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 availableValuesWithOptions = Array.isArray(availableValuesRaw)
+ ? availableValuesRaw
+ : [];
+
+ // Extract counts and values to display along multi-select values
+ const { values: availableValues, counts } = Array.isArray(
+ availableValuesWithOptions,
+ )
+ ? processOptions(availableValuesWithOptions)
+ : { values: [], counts: EMPTY_MAP };
+
+ // Check if this column supports operator toggle
+ // Only arrayOptions columns get the ANY/ALL toggle
+ // - arrayOptions: multi-valued arrays (e.g., tags on a trace)
+ // - stringOptions: single-valued strings (e.g., environment)
+ const colDef = config.columnDefinitions.find(
+ (c) => c.id === facet.column,
+ );
+ const isArrayOptions = colDef?.type === "arrayOptions";
+
+ // Get the checkbox filter (stringOptions/arrayOptions) for this column
+ const checkboxFilter = filterState.find(
+ (f) =>
+ f.column === facet.column &&
+ (f.type === "stringOptions" || f.type === "arrayOptions"),
+ );
+
+ const selectedValues = computeSelectedValues(
+ availableValues,
+ checkboxFilter,
+ );
+
+ // Determine current operator for ANY/ALL toggle
+ // When a user selects items in an arrayOptions filter, we expose a toggle
+ // to switch between:
+ // - "any of" (OR logic): match if item has ANY selected value
+ // - "all of" (AND logic): match if item has ALL selected values
+ // This operator is persisted in the filter state and URL
+ let currentOperator: "any of" | "all of" | undefined;
+ if (
+ checkboxFilter &&
+ (checkboxFilter.type === "arrayOptions" ||
+ checkboxFilter.type === "stringOptions") &&
+ (checkboxFilter.operator === "any of" ||
+ checkboxFilter.operator === "all of")
+ ) {
+ currentOperator = checkboxFilter.operator;
+ } else if (isArrayOptions && selectedValues.length > 0) {
+ // Default to "any of" for arrayOptions when selections exist but no explicit operator
+ currentOperator = "any of";
+ } else {
+ currentOperator = undefined;
+ }
+
+ // Extract text filters for this column (contains/does not contain)
+ const textFilters: TextFilterEntry[] = filterState
+ .filter(
+ (f): f is Extract<typeof f, { type: "string" }> =>
+ f.column === facet.column &&
+ f.type === "string" &&
+ (f.operator === "contains" || f.operator === "does not contain"),
+ )
+ .map((f) => ({
+ operator: f.operator as "contains" | "does not contain",
+ value: f.value,
+ }));
+
+ const hasTextFilters = textFilters.length > 0;
+ const hasCheckboxSelections =
+ selectedValues.length > 0 &&
+ selectedValues.length !== availableValues.length;
+
+ // isActive check: filter is active if we have text filters OR checkbox selections
+ // Special case: "all of" with all values selected is still an active filter
+ const isActive =
+ hasTextFilters ||
+ (currentOperator === "all of" &&
+ selectedValues.length === availableValues.length) ||
+ hasCheckboxSelections;
+
+ return {
+ type: "categorical",
+ column: facet.column,
+ label: facet.label,
+ shortKey: getShortKey(facet.column),
+ value: selectedValues,
+ options: availableValues,
+ counts,
+ 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: () => {
+ // Reset both checkboxes AND text filters
+ const withoutAll = filterState.filter(
+ (f) =>
+ !(
+ f.column === facet.column &&
+ (f.type === "stringOptions" ||
+ f.type === "arrayOptions" ||
+ (f.type === "string" &&
+ (f.operator === "contains" ||
+ f.operator === "does not contain")))
+ ),
+ );
+ setFilterState(withoutAll);
+ },
+ // Only add operator toggle for arrayOptions columns
+ operator: isArrayOptions ? currentOperator : undefined,
+ onOperatorChange: isArrayOptions
+ ? (op: "any of" | "all of") => updateOperator(facet.column, op)
+ : undefined,
+ // Text filter support - ONLY for stringOptions, NOT arrayOptions or boolean
+ textFilters: !isArrayOptions ? textFilters : undefined,
+ onTextFilterAdd: !isArrayOptions
+ ? (op, val) => addTextFilter(facet.column, op, val)
+ : undefined,
+ onTextFilterRemove: !isArrayOptions
+ ? (op, val) => removeTextFilter(facet.column, op, val)
+ : undefined,
+ hasTextFilters: !isArrayOptions ? hasTextFilters : undefined,
+ hasCheckboxSelections,
+ };
+ })
+ .filter((f): f is UIFilter => f !== null);
+ }, [
+ config,
+ options,
+ filterState,
+ updateFilter,
+ updateFilterOnly,
+ updateOperator,
+ updateNumericFilter,
+ updateStringFilter,
+ addTextFilter,
+ removeTextFilter,
+ expandedState,
+ setFilterState,
+ ]);
+
+ return {
+ filterState,
+ setFilterState,
+ updateFilter,
+ updateFilterOnly,
+ updateOperator,
+ clearAll,
+ isFiltered: filterState.length > 0,
+ filters,
+ expanded: expandedState,
+ onExpandedChange,
+ };
+}
diff --git a/web/src/features/filters/lib/filter-config.ts b/web/src/features/filters/lib/filter-config.ts
new file mode 100644
index 0000000000..d33971d351
--- /dev/null
+++ b/web/src/features/filters/lib/filter-config.ts
@@ -0,0 +1,70 @@
+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[];
+ defaultSidebarCollapsed?: boolean;
+ facets: Facet[];
+}
diff --git a/web/src/features/filters/lib/filter-query-encoding-decoding.clienttest.ts b/web/src/features/filters/lib/filter-query-encoding-decoding.clienttest.ts
new file mode 100644
index 0000000000..6e00508676
--- /dev/null
+++ b/web/src/features/filters/lib/filter-query-encoding-decoding.clienttest.ts
@@ -0,0 +1,554 @@
+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",
+ scoresNumeric: "scoresNumeric",
+ metadata: "metadata",
+};
+
+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: "scoresNumeric",
+ name: "scoresNumeric",
+ type: "numberObject" as const,
+ },
+ { id: "metadata", name: "metadata", type: "stringObject" 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 (Legacy Format)", () => {
+ const mockOptions: FilterQueryOptions = {
+ species: [
+ "t-rex",
+ "triceratops",
+ "velociraptor",
+ "brachiosaurus",
+ "stegosaurus",
+ ],
+ diet: ["carnivore", "herbivore", "omnivore"],
+ period: ["triassic", "jurassic", "cretaceous"],
+ habitat: ["forest", "plains", "swamp", "desert"],
+ extinct: ["Extinct", "Not extinct"],
+ length: [],
+ name: [],
+ ratings: [],
+ scoresNumeric: [],
+ metadata: [],
+ };
+
+ 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;stringOptions;;any of;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;stringOptions;;any of;jurassic%7Ccretaceous",
+ );
+ });
+
+ 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;stringOptions;;any of;jurassic,diet;stringOptions;;any of;carnivore%7Comnivore",
+ );
+ });
+
+ it("should encode exclusive filters", () => {
+ const filters: FilterState = [
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["triassic"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "period;stringOptions;;none of;triassic",
+ );
+ });
+
+ it("should encode numeric >= filter", () => {
+ const filters: FilterState = [
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 5,
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("length;number;;>=;5");
+ });
+
+ it("should encode numeric <= filter", () => {
+ const filters: FilterState = [
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 10,
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe("length;number;;<=;10");
+ });
+
+ it("should encode numeric range with both >= and <=", () => {
+ const filters: FilterState = [
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 5,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 10,
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "length;number;;>=;5,length;number;;<=;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;string;;contains;rex",
+ );
+ });
+
+ it("should encode categoryOptions filter", () => {
+ const filters: FilterState = [
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "danger",
+ value: ["high", "medium"],
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "ratings;categoryOptions;danger;any of;high%7Cmedium",
+ );
+ });
+
+ it("should encode numberObject filter", () => {
+ const filters: FilterState = [
+ {
+ column: "scoresNumeric",
+ type: "numberObject",
+ operator: ">=",
+ key: "accuracy",
+ value: 0.8,
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "scoresNumeric;numberObject;accuracy;>=;0.8",
+ );
+ });
+
+ it("should encode stringObject filter", () => {
+ const filters: FilterState = [
+ {
+ column: "metadata",
+ type: "stringObject",
+ operator: "contains",
+ key: "environment",
+ value: "production",
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "metadata;stringObject;environment;contains;production",
+ );
+ });
+
+ it("should encode boolean filter", () => {
+ const filters: FilterState = [
+ {
+ column: "extinct",
+ type: "boolean",
+ operator: "=",
+ value: true,
+ },
+ ];
+ expect(encodeFilters(filters, mockOptions)).toBe(
+ "extinct;boolean;;=;true",
+ );
+ });
+ });
+
+ describe("Decoding", () => {
+ it("should decode empty string to empty filter state", () => {
+ expect(decodeFilters("", mockOptions)).toEqual([]);
+ });
+
+ it("should decode single categorical filter", () => {
+ const result = decodeFilters(
+ "period;stringOptions;;any of;triassic",
+ mockOptions,
+ );
+ expect(result).toEqual([
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic"],
+ },
+ ]);
+ });
+
+ it("should decode multiple values in categorical filter", () => {
+ const result = decodeFilters(
+ "period;stringOptions;;any of;triassic%7Cjurassic",
+ mockOptions,
+ );
+ expect(result).toEqual([
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic", "jurassic"],
+ },
+ ]);
+ });
+
+ it("should decode multiple filters", () => {
+ const result = decodeFilters(
+ "period;stringOptions;;any of;triassic,diet;stringOptions;;any of;carnivore%7Cherbivore",
+ 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 decode exclusive filters", () => {
+ const result = decodeFilters(
+ "period;stringOptions;;none of;triassic",
+ mockOptions,
+ );
+ expect(result).toEqual([
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["triassic"],
+ },
+ ]);
+ });
+
+ it("should decode numeric >= filter", () => {
+ const query = "length;number;;%3E%3D;5";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 5,
+ },
+ ]);
+ });
+
+ it("should decode numeric <= filter", () => {
+ const query = "length;number;;%3C%3D;10";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 10,
+ },
+ ]);
+ });
+
+ it("should decode numeric range with both >= and <=", () => {
+ const query = "length;number;;%3E%3D;5,length;number;;%3C%3D;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", () => {
+ const query = "name;string;;contains;rex";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "rex",
+ },
+ ]);
+ });
+
+ it("should decode categoryOptions filter", () => {
+ const query = "ratings;categoryOptions;danger;any of;high%7Cmedium";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "danger",
+ value: ["high", "medium"],
+ },
+ ]);
+ });
+
+ it("should decode numberObject filter", () => {
+ const query = "scoresNumeric;numberObject;accuracy;%3E%3D;0.8";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "scoresNumeric",
+ type: "numberObject",
+ operator: ">=",
+ key: "accuracy",
+ value: 0.8,
+ },
+ ]);
+ });
+
+ it("should decode stringObject filter", () => {
+ const query = "metadata;stringObject;environment;contains;production";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "metadata",
+ type: "stringObject",
+ operator: "contains",
+ key: "environment",
+ value: "production",
+ },
+ ]);
+ });
+
+ it("should decode boolean filter", () => {
+ const query = "extinct;boolean;;%3D;true";
+ const decoded = decodeFilters(query, mockOptions);
+ expect(decoded).toEqual([
+ {
+ column: "extinct",
+ type: "boolean",
+ operator: "=",
+ value: true,
+ },
+ ]);
+ });
+ });
+
+ 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"],
+ },
+ ];
+
+ const serialized = encodeFilters(originalFilters, mockOptions);
+ const deserialized = decodeFilters(serialized, mockOptions);
+
+ expect(deserialized).toEqual(originalFilters);
+ });
+
+ 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 filter types", () => {
+ const mixedFilters: FilterState = [
+ {
+ column: "period",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["triassic", "jurassic"],
+ },
+ {
+ column: "diet",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["omnivore"],
+ },
+ {
+ column: "extinct",
+ type: "boolean",
+ operator: "=",
+ value: true,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: ">=",
+ value: 0.5,
+ },
+ {
+ column: "length",
+ type: "number",
+ operator: "<=",
+ value: 15.2,
+ },
+ {
+ column: "ratings",
+ type: "categoryOptions",
+ operator: "any of",
+ key: "danger",
+ value: ["high"],
+ },
+ ];
+
+ const serialized = encodeFilters(mixedFilters, mockOptions);
+ const deserialized = decodeFilters(serialized, mockOptions);
+
+ expect(deserialized).toEqual(mixedFilters);
+ });
+ });
+});
diff --git a/web/src/features/filters/lib/filter-query-encoding.ts b/web/src/features/filters/lib/filter-query-encoding.ts
new file mode 100644
index 0000000000..b58762b2ae
--- /dev/null
+++ b/web/src/features/filters/lib/filter-query-encoding.ts
@@ -0,0 +1,177 @@
+import {
+ type FilterState,
+ singleFilter,
+ type SingleValueOption,
+} from "@langfuse/shared";
+import { encodeDelimitedArray, decodeDelimitedArray } from "use-query-params";
+
+// Generic helpers for reusable encoding/decoding across feature areas
+export type ColumnToQueryKeyMap = Record<string, string>;
+export type GenericFilterOptions = Record<
+ string,
+ string[] | (string | SingleValueOption)[] | 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
+
+// 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;
+}
+
+/**
+ * Encodes FilterState to the legacy semicolon-delimited format
+ * Format: columnId;type;key;operator;value
+ * Multiple filters separated by commas
+ * Array values joined with |
+ */
+export function encodeFiltersGeneric(
+ filters: FilterState,
+ columnToQueryKey: ColumnToQueryKeyMap,
+ _options?: Partial<GenericFilterOptions>,
+): string {
+ return (
+ encodeDelimitedArray(
+ filters
+ .map((f) => {
+ const columnId = columnToQueryKey[f.column];
+
+ if (!columnId) {
+ return null;
+ }
+
+ // Determine the key field (for categoryOptions, numberObject, stringObject)
+ const key =
+ f.type === "numberObject" ||
+ f.type === "stringObject" ||
+ f.type === "categoryOptions"
+ ? (f as any).key || ""
+ : "";
+
+ // Encode the value
+ let encodedValue: string;
+ if (f.type === "datetime") {
+ encodedValue = encodeURIComponent(new Date(f.value).toISOString());
+ } else if (
+ f.type === "stringOptions" ||
+ f.type === "arrayOptions" ||
+ f.type === "categoryOptions"
+ ) {
+ encodedValue = encodeURIComponent((f.value as string[]).join("|"));
+ } else {
+ encodedValue = encodeURIComponent(String(f.value));
+ }
+
+ return `${columnId};${f.type};${key};${f.operator};${encodedValue}`;
+ })
+ .filter((s): s is string => s !== null),
+ ",",
+ ) || ""
+ );
+}
+
+/**
+ * Decodes the legacy semicolon-delimited format to FilterState
+ * Format: columnId;type;key;operator;value
+ */
+export function decodeFiltersGeneric(
+ query: string,
+ columnToQueryKey: ColumnToQueryKeyMap,
+ _options: Partial<GenericFilterOptions>,
+ _getType?: (column: string) => any,
+): FilterState {
+ if (!query.trim()) return [];
+
+ const decoded = decodeDelimitedArray(query, ",");
+ if (!decoded) return [];
+
+ const filters: FilterState = [];
+
+ // Create reverse mapping from columnId to column name
+ const idToColumn: Record<string, string> = {};
+ for (const [columnName, columnId] of Object.entries(columnToQueryKey)) {
+ idToColumn[columnId] = columnName;
+ }
+
+ for (const filterString of decoded) {
+ if (!filterString) continue;
+
+ const [columnId, type, key, operator, encodedValue] =
+ filterString.split(";");
+
+ if (!columnId || !type || !operator || encodedValue === undefined) {
+ continue;
+ }
+
+ const column = idToColumn[columnId];
+ if (!column) {
+ continue;
+ }
+
+ const decodedOperator = decodeURIComponent(operator);
+ const decodedKey = key ? decodeURIComponent(key) : "";
+ const decodedValue = decodeURIComponent(encodedValue);
+
+ // Parse value based on type
+ let parsedValue: any;
+ if (type === "datetime") {
+ parsedValue = new Date(decodedValue);
+ } else if (type === "number" || type === "numberObject") {
+ parsedValue = Number(decodedValue);
+ } else if (
+ type === "stringOptions" ||
+ type === "arrayOptions" ||
+ type === "categoryOptions"
+ ) {
+ parsedValue = decodedValue ? decodedValue.split("|") : [];
+ } else if (type === "boolean") {
+ parsedValue = decodedValue === "true";
+ } else {
+ parsedValue = decodedValue;
+ }
+
+ // Build filter object
+ const filter: any = {
+ column,
+ type,
+ operator: decodedOperator,
+ value: parsedValue,
+ };
+
+ // Add key field for types that need it
+ if (
+ decodedKey &&
+ (type === "categoryOptions" ||
+ type === "numberObject" ||
+ type === "stringObject")
+ ) {
+ filter.key = decodedKey;
+ }
+
+ // Validate with zod
+ const parsed = singleFilter.safeParse(filter);
+ if (parsed.success) {
+ filters.push(parsed.data);
+ } else {
+ console.warn("Invalid filter skipped:", filter, parsed.error);
+ }
+ }
+
+ return filters;
+}
diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsx
index e1357cb039..2381dd3e19 100644
--- a/web/src/features/prompts/components/prompts-table.tsx
+++ b/web/src/features/prompts/components/prompts-table.tsx
@@ -1,5 +1,9 @@
import { useEffect, useMemo } from "react";
import { DataTable } from "@/src/components/table/data-table";
+import {
+ DataTableControlsProvider,
+ DataTableControls,
+} from "@/src/components/table/data-table-controls";
import TableLink from "@/src/components/table/table-link";
import { type LangfuseColumnDef } from "@/src/components/table/types";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
@@ -10,6 +14,8 @@ import { type RouterOutput } from "@/src/utils/types";
import { TagPromptPopover } from "@/src/features/tag/components/TagPromptPopover";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";
+import { promptFilterConfig } from "@/src/features/filters/config/prompts-config";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import {
NumberParam,
@@ -31,7 +37,6 @@ import {
BreadcrumbSeparator,
} from "@/src/components/ui/breadcrumb";
import { Slash, Folder, Home } from "lucide-react";
-import { promptsTableColsWithOptions } from "@langfuse/shared";
import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";
type PromptTableRow = {
@@ -81,11 +86,7 @@ export function PromptTable() {
const projectId = useProjectIdFromURL();
const { setDetailPageList } = useDetailPageLists();
- const [filterState, setFilterState] = useQueryFilterState(
- [],
- "prompts",
- projectId,
- );
+ const [filterState] = useQueryFilterState([], "prompts", projectId);
const [orderByState, setOrderByState] = useOrderByState({
column: "createdAt",
@@ -232,6 +233,37 @@ 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) => {
+ // API type says { value: string }[], but for some items, there is an optional count
+ const item = l as { value: string; count?: number };
+ return {
+ value: item.value,
+ count: item.count !== undefined ? Number(item.count) : undefined,
+ };
+ }) || [],
+ tags:
+ promptFilterOptions.data?.tags?.map((t) => {
+ // API type says { value: string }[], but for some items, there is an optional count
+ const item = t as { value: string; count?: number };
+ return {
+ value: item.value,
+ count: item.count !== undefined ? Number(item.count) : undefined,
+ };
+ }) || [],
+ version: [],
+ }),
+ [promptFilterOptions.data],
+ );
+
+ const queryFilter = useSidebarFilterState(
+ promptFilterConfig,
+ newFilterOptions,
+ );
+
useEffect(() => {
if (prompts.isSuccess) {
setDetailPageList(
@@ -381,114 +413,124 @@ export function PromptTable() {
] as LangfuseColumnDef<PromptTableRow>[];
return (
- <>
- {currentFolderPath && (
- <div className="ml-2 pt-2">
- <Breadcrumb>
- <BreadcrumbList>
- <BreadcrumbItem>
- <BreadcrumbLink
- className="cursor-pointer hover:underline"
- onClick={() => {
- setQueryParams({
- folder: undefined,
- pageIndex: 0,
- pageSize: queryParams.pageSize,
- });
- }}
- >
- <Home className="h-4 w-4" />
- </BreadcrumbLink>
- </BreadcrumbItem>
- {createBreadcrumbItems(currentFolderPath).flatMap(
- (item, index, array) => [
- index > 0 && (
- <BreadcrumbSeparator key={`sep-${item.folderPath}`}>
- <Slash />
- </BreadcrumbSeparator>
- ),
- <BreadcrumbItem key={item.folderPath}>
- {index === array.length - 1 ? (
- <BreadcrumbPage>{item.name}</BreadcrumbPage>
- ) : (
- <BreadcrumbLink
- className="cursor-pointer hover:underline"
- onClick={() => {
- setQueryParams({
- folder: item.folderPath,
- pageIndex: 0,
- pageSize: queryParams.pageSize,
- });
- }}
- >
- {item.name}
- </BreadcrumbLink>
- )}
- </BreadcrumbItem>,
- ],
- )}
- </BreadcrumbList>
- </Breadcrumb>
- </div>
- )}
- <DataTableToolbar
- columns={promptColumns}
- filterColumnDefinition={promptsTableColsWithOptions(
- promptFilterOptions.data,
+ <DataTableControlsProvider
+ tableName={promptFilterConfig.tableName}
+ defaultSidebarCollapsed={promptFilterConfig.defaultSidebarCollapsed}
+ >
+ <div className="flex h-full w-full flex-col">
+ {/* Toolbar spanning full width */}
+ {currentFolderPath && (
+ <div className="ml-2 pt-2">
+ <Breadcrumb>
+ <BreadcrumbList>
+ <BreadcrumbItem>
+ <BreadcrumbLink
+ className="cursor-pointer hover:underline"
+ onClick={() => {
+ setQueryParams({
+ folder: undefined,
+ pageIndex: 0,
+ pageSize: queryParams.pageSize,
+ });
+ }}
+ >
+ <Home className="h-4 w-4" />
+ </BreadcrumbLink>
+ </BreadcrumbItem>
+ {createBreadcrumbItems(currentFolderPath).flatMap(
+ (item, index, array) => [
+ index > 0 && (
+ <BreadcrumbSeparator key={`sep-${item.folderPath}`}>
+ <Slash />
+ </BreadcrumbSeparator>
+ ),
+ <BreadcrumbItem key={item.folderPath}>
+ {index === array.length - 1 ? (
+ <BreadcrumbPage>{item.name}</BreadcrumbPage>
+ ) : (
+ <BreadcrumbLink
+ className="cursor-pointer hover:underline"
+ onClick={() => {
+ setQueryParams({
+ folder: item.folderPath,
+ pageIndex: 0,
+ pageSize: queryParams.pageSize,
+ });
+ }}
+ >
+ {item.name}
+ </BreadcrumbLink>
+ )}
+ </BreadcrumbItem>,
+ ],
+ )}
+ </BreadcrumbList>
+ </Breadcrumb>
+ </div>
)}
- filterState={filterState}
- setFilterState={useDebounce(setFilterState)}
- columnsWithCustomSelect={["labels", "tags"]}
- searchConfig={{
- metadataSearchFields: ["Name", "Tags", "Content"],
- updateQuery: useDebounce(setSearchQuery, 300),
- currentQuery: searchQuery ?? undefined,
- tableAllowsFullTextSearch: true,
- setSearchType,
- searchType,
- customDropdownLabels: {
- metadata: "Names, Tags",
- fullText: "Full Text",
- },
- hidePerformanceWarning: true,
- }}
- />
- <DataTable
- tableName={"prompts"}
- columns={promptColumns}
- data={
- prompts.isLoading
- ? { isLoading: true, isError: false }
- : prompts.isError
- ? {
- isLoading: false,
- isError: true,
- error: prompts.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: processedRowData.rows?.map((item) => ({
- id: item.id,
- name: item.name,
- fullPath: item.fullPath,
- version: item.version,
- createdAt: item.createdAt,
- type: item.type,
- labels: item.labels,
- numberOfObservations: item.numberOfObservations,
- tags: item.tags,
- })),
- }
- }
- orderBy={orderByState}
- setOrderBy={setOrderByState}
- pagination={{
- totalCount,
- onChange: setQueryParams,
- state: paginationState,
- }}
- />
- </>
+ <DataTableToolbar
+ columns={promptColumns}
+ filterState={queryFilter.filterState}
+ columnsWithCustomSelect={["labels", "tags"]}
+ searchConfig={{
+ metadataSearchFields: ["Name", "Tags", "Content"],
+ updateQuery: useDebounce(setSearchQuery, 300),
+ currentQuery: searchQuery ?? undefined,
+ tableAllowsFullTextSearch: true,
+ setSearchType,
+ searchType,
+ customDropdownLabels: {
+ metadata: "Names, Tags",
+ fullText: "Full Text",
+ },
+ hidePerformanceWarning: true,
+ }}
+ />
+
+ {/* Content area with sidebar and table */}
+ <div className="flex flex-1 overflow-hidden">
+ <DataTableControls queryFilter={queryFilter} />
+
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <DataTable
+ tableName={"prompts"}
+ columns={promptColumns}
+ data={
+ prompts.isLoading
+ ? { isLoading: true, isError: false }
+ : prompts.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: prompts.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: processedRowData.rows?.map((item) => ({
+ id: item.id,
+ name: item.name,
+ fullPath: item.fullPath,
+ version: item.version,
+ createdAt: item.createdAt,
+ type: item.type,
+ labels: item.labels,
+ numberOfObservations: item.numberOfObservations,
+ tags: item.tags,
+ })),
+ }
+ }
+ orderBy={orderByState}
+ setOrderBy={setOrderByState}
+ pagination={{
+ totalCount,
+ onChange: setQueryParams,
+ state: paginationState,
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ </DataTableControlsProvider>
);
}
diff --git a/web/src/hooks/use-environment-filter.tsx b/web/src/hooks/use-environment-filter.tsx
index 721e03dd4c..e8c0ddb4a9 100644
--- a/web/src/hooks/use-environment-filter.tsx
+++ b/web/src/hooks/use-environment-filter.tsx
@@ -12,14 +12,22 @@ export function convertSelectedEnvironmentsToFilter(
environmentColumns: string[],
selectedEnvironments: string[],
) {
- return selectedEnvironments.length > 0
- ? environmentColumns.map((column) => ({
- type: "stringOptions" as const,
- column,
- operator: "any of" as const,
- value: selectedEnvironments,
- }))
- : [];
+ if (selectedEnvironments.length === 0) {
+ // No environments selected = show nothing
+ return environmentColumns.map((column) => ({
+ type: "stringOptions" as const,
+ column,
+ operator: "any of" as const,
+ value: ["__NEVER_MATCH_ANYTHING__"], // Impossible value to match
+ }));
+ }
+
+ return environmentColumns.map((column) => ({
+ type: "stringOptions" as const,
+ column,
+ operator: "any of" as const,
+ value: selectedEnvironments,
+ }));
}
export function useEnvironmentFilter(
@@ -55,9 +63,9 @@ export function useEnvironmentFilter(
let hasChanges = false;
availableEnvironments.forEach((env) => {
- // If environment doesn't exist in map, set default visibility
+ // If environment doesn't exist in map, set default visibility to true (all selected)
if (updatedMap[env] === undefined) {
- updatedMap[env] = !env.startsWith("langfuse");
+ updatedMap[env] = true;
hasChanges = true;
}
});
diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsx
index c7157a00e7..90319c2005 100644
--- a/web/src/pages/project/[projectId]/index.tsx
+++ b/web/src/pages/project/[projectId]/index.tsx
@@ -98,7 +98,11 @@ export default function Dashboard() {
const { selectedEnvironments, setSelectedEnvironments } =
useEnvironmentFilter(environmentOptions, projectId);
- const nameOptions = traceFilterOptions.data?.name || [];
+ const nameOptions =
+ traceFilterOptions.data?.name?.map((n) => ({
+ value: n.value,
+ count: Number(n.count),
+ })) || [];
const tagsOptions = traceFilterOptions.data?.tags || [];
const filterColumns: ColumnDefinition[] = [
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index f6435a78da..d8b939c586 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -228,7 +228,7 @@ export const traceRouter = createTRPCRouter({
]);
return {
- name: traceNames.map((n) => ({ value: n.name })),
+ name: traceNames.map((n) => ({ value: n.name, count: n.count })),
scores_avg: numericScoreNames.map((s) => s.name),
score_categories: categoricalScoreNames,
tags: tags,