🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(ui): add separate date range filter to tables (#2398)
Richard Krümmelf9a5c23e9b0b
diff --git a/.env.prod.example b/.env.prod.exampleindex 1eb76bebac..4a815b8bee 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -104,9 +104,6 @@ LANGFUSE_CSP_ENFORCE_HTTPS="true"# Disable the expensive analytics queries and related features# LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES="true"-# Customize the default datetime offset filter used in for the UI tables-# LANGFUSE_DEFAULT_TABLE_DATETIME_OFFSET="7" # int (days)-### END Envs to be deprecated in Langfuse v3.0diff --git a/packages/shared/src/features/annotation/types.ts b/packages/shared/src/features/annotation/types.tsindex fec3c006ce..f5ab0dab74 100644--- a/packages/shared/src/features/annotation/types.ts+++ b/packages/shared/src/features/annotation/types.ts@@ -14,7 +14,7 @@ const NumericData = z.object({});const CategoricalData = z.object({- value: z.number().optional().nullish(),+ value: z.number().nullish(),stringValue: z.string(),dataType: z.literal("CATEGORICAL"),});@@ -31,7 +31,7 @@ const CreateAnnotationScoreBase = z.object({traceId: z.string(),configId: z.string().optional(),observationId: z.string().optional(),- comment: z.string().optional().nullish(),+ comment: z.string().nullish(),});const UpdateAnnotationScoreBase = CreateAnnotationScoreBase.extend({diff --git a/web/src/components/date-picker.tsx b/web/src/components/date-picker.tsxindex da378ee1e1..107a19e8af 100644--- a/web/src/components/date-picker.tsx+++ b/web/src/components/date-picker.tsx@@ -11,30 +11,18 @@ import {} from "@/src/components/ui/popover";import { cn } from "@/src/utils/tailwind";import { type DateRange } from "react-day-picker";-import { addMinutes, format } from "date-fns";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/src/components/ui/select";+import { format } from "date-fns";import { useEffect, useState } from "react";-import {- type DateTimeAggregationOption,- dateTimeAggregationSettings,- dateTimeAggregationOptions,-} from "@/src/features/dashboard/lib/timeseries-aggregation";import { useMediaQuery } from "react-responsive";-import { type DashboardDateRange } from "@/src/pages/project/[projectId]";-import { isValidOption } from "@/src/utils/types";import { setBeginningOfDay, setEndOfDay } from "@/src/utils/dates";import { TimePicker } from "@/src/components/ui/time-picker";--export const DEFAULT_DATE_RANGE_SELECTION = "Date range" as const;-export type AvailableDateRangeSelections =- | typeof DEFAULT_DATE_RANGE_SELECTION- | DateTimeAggregationOption;+import { DashboardDateRangeDropdown } from "@/src/components/date-range-dropdowns";+import {+ DASHBOARD_AGGREGATION_PLACEHOLDER,+ type DashboardDateRangeOptions,+ type DashboardDateRange,+} from "@/src/utils/date-range-utils";+import { combineDateAndTime } from "@/src/components/ui/time-picker-utils";export function DatePicker({date,@@ -101,9 +89,9 @@ export function DatePicker({export type DatePickerWithRangeProps = {dateRange?: DashboardDateRange;className?: string;- selectedOption: AvailableDateRangeSelections;+ selectedOption: DashboardDateRangeOptions;setDateRangeAndOption: (- option: AvailableDateRangeSelections,+ option: DashboardDateRangeOptions,date?: DashboardDateRange,) => void;};@@ -122,18 +110,35 @@ export function DatePickerWithRange({setInternalDateRange(dateRange);}, [dateRange]);- const onDropDownSelection = (value: string) => {- if (isValidOption(value)) {- const setting = dateTimeAggregationSettings[value];- const fromDate = addMinutes(new Date(), -1 * setting.minutes);+ const setNewDateRange = (+ internalDateRange: DateRange | undefined,+ newFromDate: Date | undefined,+ newToDate: Date | undefined,+ ): DateRange | undefined => {+ return internalDateRange+ ? {+ from: newFromDate ?? internalDateRange.from,+ to: newToDate ?? internalDateRange.to,+ }+ : undefined;+ };- setDateRangeAndOption(value, {- from: fromDate,- to: new Date(),- });- setInternalDateRange({ from: fromDate, to: new Date() });- } else {- setDateRangeAndOption(DEFAULT_DATE_RANGE_SELECTION, undefined);+ const updateDashboardDateRange = (+ newRange: DateRange | undefined,+ setDateRangeAndOption: (+ option: DashboardDateRangeOptions,+ date?: DashboardDateRange,+ ) => void,+ ) => {+ if (newRange && newRange.from && newRange.to) {+ const dashboardDateRange: DashboardDateRange = {+ from: newRange.from,+ to: newRange.to,+ };+ setDateRangeAndOption(+ DASHBOARD_AGGREGATION_PLACEHOLDER,+ dashboardDateRange,+ );}};@@ -146,13 +151,29 @@ export function DatePickerWithRange({: undefined;setInternalDateRange(newRange);- if (newRange && newRange.from && newRange.to) {- const dashboardDateRange: DashboardDateRange = {- from: newRange.from,- to: newRange.to,- };- setDateRangeAndOption(DEFAULT_DATE_RANGE_SELECTION, dashboardDateRange);- }+ updateDashboardDateRange(newRange, setDateRangeAndOption);+ };++ const onStartTimeSelection = (date: Date | undefined) => {+ const newDateTime = combineDateAndTime(internalDateRange?.from, date);+ const newRange = setNewDateRange(+ internalDateRange,+ newDateTime,+ internalDateRange?.to,+ );+ setInternalDateRange(newRange);+ updateDashboardDateRange(newRange, setDateRangeAndOption);+ };++ const onEndTimeSelection = (date: Date | undefined) => {+ const newDateTime = combineDateAndTime(internalDateRange?.to, date);+ const newRange = setNewDateRange(+ internalDateRange,+ internalDateRange?.from,+ newDateTime,+ );+ setInternalDateRange(newRange);+ updateDashboardDateRange(newRange, setDateRangeAndOption);};const isSmallScreen = useMediaQuery({ query: "(max-width: 640px)" });@@ -193,28 +214,54 @@ export function DatePickerWithRange({defaultMonth={internalDateRange?.from}selected={internalDateRange}onSelect={onCalendarSelection}- numberOfMonths={isSmallScreen ? 1 : 2} // TODO: make this configurable to screen size+ numberOfMonths={isSmallScreen ? 1 : 2}/>+ {!isSmallScreen && (+ <div className="flex flex-row border-t-2 py-1.5">+ <div className="px-3">+ <p className="px-1 text-sm font-medium">Start time</p>+ <TimePicker+ date={internalDateRange?.from}+ setDate={onStartTimeSelection}+ className="border-0 px-0 pt-1"+ />+ </div>+ <div className="px-3">+ <p className="px-1 text-sm font-medium">End time</p>+ <TimePicker+ date={internalDateRange?.to}+ setDate={onEndTimeSelection}+ className="border-0 px-0 pt-1"+ />+ </div>+ </div>+ )}+ {isSmallScreen && (+ <div className="flex flex-col gap-2 border-t-2 py-1.5">+ <div className="px-3">+ <p className="px-1 text-sm font-medium">Start</p>+ <TimePicker+ date={internalDateRange?.from}+ setDate={onStartTimeSelection}+ className="border-0 px-0 pt-1"+ />+ </div>+ <div className="px-3">+ <p className="px-1 text-sm font-medium">End</p>+ <TimePicker+ date={internalDateRange?.to}+ setDate={onEndTimeSelection}+ className="border-0 px-0 pt-1"+ />+ </div>+ </div>+ )}</PopoverContent></Popover>- <Select value={selectedOption} onValueChange={onDropDownSelection}>- <SelectTrigger className="w-[120px] hover:bg-accent hover:text-accent-foreground focus:ring-0 focus:ring-offset-0">- <SelectValue placeholder="Select" />- </SelectTrigger>- <SelectContent position="popper" defaultValue={60}>- <SelectItem- key={DEFAULT_DATE_RANGE_SELECTION}- value={DEFAULT_DATE_RANGE_SELECTION}- >- {DEFAULT_DATE_RANGE_SELECTION}- </SelectItem>- {dateTimeAggregationOptions.toReversed().map((item) => (- <SelectItem key={item} value={item}>- {item}- </SelectItem>- ))}- </SelectContent>- </Select>+ <DashboardDateRangeDropdown+ selectedOption={selectedOption}+ setDateRangeAndOption={setDateRangeAndOption}+ /></div>);}diff --git a/web/src/components/date-range-dropdowns.tsx b/web/src/components/date-range-dropdowns.tsxnew file mode 100644index 0000000000..ac374cb6f9--- /dev/null+++ b/web/src/components/date-range-dropdowns.tsx@@ -0,0 +1,124 @@+import * as React from "react";+import { addMinutes } from "date-fns";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";++import {+ DEFAULT_AGGREGATION_SELECTION,+ tableDateRangeAggregationSettings,+ dashboardDateRangeAggregationSettings,+ DASHBOARD_AGGREGATION_PLACEHOLDER,+ type DashboardDateRangeOptions,+ type TableDateRangeOptions,+ DASHBOARD_AGGREGATION_OPTIONS,+ TABLE_AGGREGATION_OPTIONS,+ type DashboardDateRange,+} from "@/src/utils/date-range-utils";+import { Clock } from "lucide-react";++type BaseDateRangeDropdownProps<T> = {+ selectedOption: T;+ options: T[];+ onSelectionChange: (value: T) => void;+};++const BaseDateRangeDropdown = <T extends string>({+ selectedOption,+ options,+ onSelectionChange,+}: BaseDateRangeDropdownProps<T>) => {+ return (+ <Select value={selectedOption} onValueChange={onSelectionChange}>+ <SelectTrigger className="w-[130px] hover:bg-accent hover:text-accent-foreground focus:ring-0 focus:ring-offset-0">+ <Clock className="h-4 w-4" />+ <SelectValue placeholder="Select" />+ </SelectTrigger>+ <SelectContent position="popper" defaultValue={60}>+ {options.map((item) => (+ <SelectItem key={item} value={item}>+ {item}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+};++type DashboardDateRangeDropdownProps = {+ selectedOption: DashboardDateRangeOptions;+ setDateRangeAndOption: (+ option: DashboardDateRangeOptions,+ date?: DashboardDateRange,+ ) => void;+};++export const DashboardDateRangeDropdown: React.FC<+ DashboardDateRangeDropdownProps+> = ({ selectedOption, setDateRangeAndOption }) => {+ const onDropDownSelection = (value: DashboardDateRangeOptions) => {+ if (value === DASHBOARD_AGGREGATION_PLACEHOLDER) {+ setDateRangeAndOption(DASHBOARD_AGGREGATION_PLACEHOLDER, undefined);+ return;+ }+ const setting =+ dashboardDateRangeAggregationSettings[+ value as keyof typeof dashboardDateRangeAggregationSettings+ ];+ setDateRangeAndOption(value, {+ from: addMinutes(new Date(), -setting.minutes),+ to: new Date(),+ });+ };++ return (+ <BaseDateRangeDropdown+ selectedOption={selectedOption}+ options={[+ ...DASHBOARD_AGGREGATION_OPTIONS,+ DASHBOARD_AGGREGATION_PLACEHOLDER,+ ]}+ onSelectionChange={onDropDownSelection}+ />+ );+};++type TableDateRangeDropdownProps = {+ selectedOption: TableDateRangeOptions;+ setDateRangeAndOption: (+ option: TableDateRangeOptions,+ date?: DashboardDateRange,+ ) => void;+};++export const TableDateRangeDropdown: React.FC<TableDateRangeDropdownProps> = ({+ selectedOption,+ setDateRangeAndOption,+}) => {+ const onDropDownSelection = (value: TableDateRangeOptions) => {+ if (value === DEFAULT_AGGREGATION_SELECTION) {+ setDateRangeAndOption(DEFAULT_AGGREGATION_SELECTION, undefined);+ return;+ }+ const setting =+ tableDateRangeAggregationSettings[+ value as keyof typeof tableDateRangeAggregationSettings+ ];+ setDateRangeAndOption(value, {+ from: addMinutes(new Date(), -setting),+ to: new Date(),+ });+ };++ return (+ <BaseDateRangeDropdown+ selectedOption={selectedOption}+ options={[...TABLE_AGGREGATION_OPTIONS, DEFAULT_AGGREGATION_SELECTION]}+ onSelectionChange={onDropDownSelection}+ />+ );+};diff --git a/web/src/components/table/data-table-toolbar.tsx b/web/src/components/table/data-table-toolbar.tsxindex 958e958216..08d2b242e2 100644--- a/web/src/components/table/data-table-toolbar.tsx+++ b/web/src/components/table/data-table-toolbar.tsx@@ -13,6 +13,11 @@ import {} from "@/src/components/table/data-table-row-height-switch";import { Search } from "lucide-react";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { TableDateRangeDropdown } from "@/src/components/date-range-dropdowns";+import {+ type TableDateRange,+ type TableDateRangeOptions,+} from "@/src/utils/date-range-utils";interface SearchConfig {placeholder: string;@@ -32,6 +37,11 @@ interface DataTableToolbarProps<TData, TValue> {rowHeight?: RowHeight;setRowHeight?: Dispatch<SetStateAction<RowHeight>>;columnsWithCustomSelect?: string[];+ selectedOption?: TableDateRangeOptions;+ setDateRangeAndOption?: (+ option: TableDateRangeOptions,+ date?: TableDateRange,+ ) => void;}export function DataTableToolbar<TData, TValue>({@@ -46,6 +56,8 @@ export function DataTableToolbar<TData, TValue>({rowHeight,setRowHeight,columnsWithCustomSelect,+ selectedOption,+ setDateRangeAndOption,}: DataTableToolbarProps<TData, TValue>) {const [searchString, setSearchString] = useState(searchConfig?.currentQuery ?? "",@@ -89,6 +101,12 @@ export function DataTableToolbar<TData, TValue>({columnsWithCustomSelect={columnsWithCustomSelect}/>)}+ {selectedOption && setDateRangeAndOption && (+ <TableDateRangeDropdown+ selectedOption={selectedOption}+ setDateRangeAndOption={setDateRangeAndOption}+ />+ )}<div className="flex flex-row flex-wrap gap-2 pr-0.5 @6xl:ml-auto">{!!columnVisibility && !!setColumnVisibility && (<DataTableColumnVisibilityFilterdiff --git a/web/src/components/table/use-cases/generations.tsx b/web/src/components/table/use-cases/generations.tsxindex bda7fa8d72..b51c71491c 100644--- a/web/src/components/table/use-cases/generations.tsx+++ b/web/src/components/table/use-cases/generations.tsx@@ -21,10 +21,7 @@ import {withDefault,} from "use-query-params";import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";-import {- formatIntervalSeconds,- localtimeDateOffsetByDays,-} from "@/src/utils/dates";+import { formatIntervalSeconds } from "@/src/utils/dates";import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";import { type LangfuseColumnDef } from "@/src/components/table/types";import {@@ -46,7 +43,7 @@ import { type ScoreSimplified } from "@/src/server/api/routers/generations/getAlimport { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { useTableLookBackDays } from "@/src/hooks/useTableLookBackDays";+import { useTableDateRange } from "@/src/hooks/useTableDateRange";export type GenerationsTableRow = {id: string;@@ -109,15 +106,11 @@ export default function GenerationsTable({"s",);+ const { selectedOption, dateRange, setDateRangeAndOption } =+ useTableDateRange();+const [inputFilterState, setInputFilterState] = useQueryFilterState(- [- {- column: "Start Time",- type: "datetime",- operator: ">",- value: localtimeDateOffsetByDays(-useTableLookBackDays(projectId)),- },- ],+ [],"generations",);@@ -148,7 +141,19 @@ export default function GenerationsTable({]: [];+ const dateRangeFilter: FilterState = dateRange+ ? [+ {+ column: "Start Time",+ type: "datetime",+ operator: ">=",+ value: dateRange.from,+ },+ ]+ : [];+const filterState = inputFilterState.concat([+ ...dateRangeFilter,...promptNameFilter,...promptVersionFilter,]);@@ -679,6 +684,8 @@ export default function GenerationsTable({setColumnVisibility={setColumnVisibilityState}rowHeight={rowHeight}setRowHeight={setRowHeight}+ selectedOption={selectedOption}+ setDateRangeAndOption={setDateRangeAndOption}actionButtons={<DropdownMenu><DropdownMenuTrigger asChild>diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsxindex a8205eb6f1..8db45d3ce0 100644--- a/web/src/components/table/use-cases/scores.tsx+++ b/web/src/components/table/use-cases/scores.tsx@@ -9,13 +9,12 @@ import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumimport { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";import { isNumericDataType } from "@/src/features/manual-scoring/lib/helpers";import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";-import { useTableLookBackDays } from "@/src/hooks/useTableLookBackDays";+import { useTableDateRange } from "@/src/hooks/useTableDateRange";import {type ScoreOptions,scoresTableColsWithOptions,} from "@/src/server/api/definitions/scoresTable";import { api } from "@/src/utils/api";-import { localtimeDateOffsetByDays } from "@/src/utils/dates";import { isPresent } from "@/src/utils/typeChecks";import type { RouterOutput, RouterInput } from "@/src/utils/types";import type { FilterState, ScoreDataType } from "@langfuse/shared";@@ -84,20 +83,27 @@ export default function ScoresTable({});const [rowHeight, setRowHeight] = useRowHeightLocalStorage("scores", "s");+ const { selectedOption, dateRange, setDateRangeAndOption } =+ useTableDateRange();const [userFilterState, setUserFilterState] = useQueryFilterState(- [- {- column: "Timestamp",- type: "datetime",- operator: ">",- value: localtimeDateOffsetByDays(-useTableLookBackDays(projectId)),- },- ],+ [],"scores",);- const filterState = createFilterState(userFilterState, [+ const dateRangeFilter: FilterState = dateRange+ ? [+ {+ column: "Timestamp",+ type: "datetime",+ operator: ">=",+ value: dateRange.from,+ },+ ]+ : [];++ const combinedFilter = userFilterState.concat(dateRangeFilter);+ const filterState = createFilterState(combinedFilter, [...(userId ? [{ key: "User ID", value: userId }] : []),...(traceId ? [{ key: "Trace ID", value: traceId }] : []),...(observationId ? [{ key: "Observation ID", value: observationId }] : []),@@ -358,6 +364,8 @@ export default function ScoresTable({setColumnVisibility={setColumnVisibility}rowHeight={rowHeight}setRowHeight={setRowHeight}+ selectedOption={selectedOption}+ setDateRangeAndOption={setDateRangeAndOption}/><DataTablecolumns={columns}diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsxindex e704cdc660..5e61a8fce1 100644--- a/web/src/components/table/use-cases/sessions.tsx+++ b/web/src/components/table/use-cases/sessions.tsx@@ -16,15 +16,14 @@ import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";import { api } from "@/src/utils/api";import {formatIntervalSeconds,- localtimeDateOffsetByDays,} from "@/src/utils/dates";import { numberFormatter, usdFormatter } from "@/src/utils/numbers";import { type RouterOutput } from "@/src/utils/types";import type Decimal from "decimal.js";import { useEffect } from "react";import { NumberParam, useQueryParams, withDefault } from "use-query-params";-import { useTableLookBackDays } from "@/src/hooks/useTableLookBackDays";import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";+import { useTableDateRange } from "@/src/hooks/useTableDateRange";export type SessionTableRow = {id: string;@@ -53,16 +52,11 @@ export default function SessionsTable({omittedFilter = [],}: SessionTableProps) {const { setDetailPageList } = useDetailPageLists();+ const { selectedOption, dateRange, setDateRangeAndOption } =+ useTableDateRange();const [userFilterState, setUserFilterState] = useQueryFilterState(- [- {- column: "Created At",- type: "datetime",- operator: ">",- value: localtimeDateOffsetByDays(-useTableLookBackDays(projectId)),- },- ],+ [],"sessions",);@@ -77,7 +71,18 @@ export default function SessionsTable({]: [];- const filterState = userFilterState.concat(userIdFilter);+ const dateRangeFilter: FilterState = dateRange+ ? [+ {+ column: "createdAt",+ type: "datetime",+ operator: ">=",+ value: dateRange.from,+ },+ ]+ : [];++ const filterState = userFilterState.concat(userIdFilter, dateRangeFilter);const [paginationState, setPaginationState] = useQueryParams({pageIndex: withDefault(NumberParam, 0),@@ -360,6 +365,8 @@ export default function SessionsTable({key="batchExport"/>,]}+ selectedOption={selectedOption}+ setDateRangeAndOption={setDateRangeAndOption}columnsWithCustomSelect={["userIds"]}/><DataTablediff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsxindex c804cc702e..c454eafab0 100644--- a/web/src/components/table/use-cases/traces.tsx+++ b/web/src/components/table/use-cases/traces.tsx@@ -11,10 +11,7 @@ import { Checkbox } from "@/src/components/ui/checkbox";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,- localtimeDateOffsetByDays,-} from "@/src/utils/dates";+import { formatIntervalSeconds } from "@/src/utils/dates";import { type RouterInput, type RouterOutput } from "@/src/utils/types";import { type RowSelectionState } from "@tanstack/react-table";import { useEffect, useState } from "react";@@ -40,8 +37,8 @@ import {} from "@langfuse/shared";import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";-import { useTableLookBackDays } from "@/src/hooks/useTableLookBackDays";import { type APIScore } from "@/src/features/public-api/types/scores";+import { useTableDateRange } from "@/src/hooks/useTableDateRange";export type TracesTableRow = {bookmarked: boolean;@@ -92,15 +89,10 @@ export default function TracesTable({withDefault(StringParam, null),);+ const { selectedOption, dateRange, setDateRangeAndOption } =+ useTableDateRange();const [userFilterState, setUserFilterState] = useQueryFilterState(- [- {- column: "Timestamp",- type: "datetime",- operator: ">",- value: localtimeDateOffsetByDays(-useTableLookBackDays(projectId)),- },- ],+ [],"traces",);const [orderByState, setOrderByState] = useOrderByState({@@ -108,6 +100,16 @@ export default function TracesTable({order: "DESC",});+ const dateRangeFilter: FilterState = dateRange+ ? [+ {+ column: "Timestamp",+ type: "datetime",+ operator: ">=",+ value: dateRange.from,+ },+ ]+ : [];const userIdFilter: FilterState = userId? [{@@ -119,11 +121,12 @@ export default function TracesTable({]: [];- const filterState = userFilterState.concat(userIdFilter);+ const filterState = userFilterState.concat(userIdFilter, dateRangeFilter);const [paginationState, setPaginationState] = useQueryParams({pageIndex: withDefault(NumberParam, 0),pageSize: withDefault(NumberParam, 50),});+const tracesAllQueryFilter = {page: paginationState.pageIndex,limit: paginationState.pageSize,@@ -148,12 +151,13 @@ export default function TracesTable({// loading filter options individually from the remaining calls// traces.all should load first together with everything else.// This here happens in the background.- const timestampFilter = filterState.find((f) => f.column === "Timestamp");const traceFilterOptions = api.traces.filterOptions.useQuery({projectId,timestampFilter:- timestampFilter?.type === "datetime" ? timestampFilter : undefined,+ dateRangeFilter[0]?.type === "datetime"+ ? dateRangeFilter[0]+ : undefined,},{trpc: {@@ -655,6 +659,8 @@ export default function TracesTable({setColumnVisibility={setColumnVisibility}rowHeight={rowHeight}setRowHeight={setRowHeight}+ selectedOption={selectedOption}+ setDateRangeAndOption={setDateRangeAndOption}/><DataTablecolumns={columns}diff --git a/web/src/components/ui/time-picker-utils.tsx b/web/src/components/ui/time-picker-utils.tsxindex 7b8cbc7c52..bbb0e2ad38 100644--- a/web/src/components/ui/time-picker-utils.tsx+++ b/web/src/components/ui/time-picker-utils.tsx@@ -201,3 +201,18 @@ export function display12HourValue(hours: number) {if (hours % 12 > 9) return `${hours}`;return `0${hours % 12}`;}++export function combineDateAndTime(+ date: Date | undefined,+ time: Date | undefined,+) {+ if (!date || !time) return undefined;+ return new Date(+ date.getFullYear(),+ date.getMonth(),+ date.getDate(),+ time.getHours(),+ time.getMinutes(),+ time.getSeconds(),+ );+}diff --git a/web/src/components/ui/time-picker.tsx b/web/src/components/ui/time-picker.tsxindex d0d673cf3a..7f690bdd6a 100644--- a/web/src/components/ui/time-picker.tsx+++ b/web/src/components/ui/time-picker.tsx@@ -6,15 +6,20 @@ import { TimePeriodSelect } from "./time-period-select";import { type Period } from "./time-picker-utils";import { getTimezoneDetails, getShortLocalTimezone } from "@/src/utils/dates";import { TimeIcon } from "@/src/components/ui/time-icon";+import { cn } from "@/src/utils/tailwind";interface TimePickerProps {date: Date | undefined;setDate: (date: Date | undefined) => void;+ className?: string;}-export function TimePicker({ date, setDate }: TimePickerProps) {- const [period, setPeriod] = React.useState<Period>("AM");-+export function TimePicker({ date, setDate, className }: TimePickerProps) {+ const getInitialPeriod = (date: Date | undefined): Period => {+ if (!date) return "AM";+ return date.getHours() >= 12 ? "PM" : "AM";+ };+ const [period, setPeriod] = React.useState<Period>(getInitialPeriod(date));const minuteRef = React.useRef<HTMLInputElement>(null);const hourRef = React.useRef<HTMLInputElement>(null);const secondRef = React.useRef<HTMLInputElement>(null);@@ -24,7 +29,12 @@ export function TimePicker({ date, setDate }: TimePickerProps) {const timezoneDetails = React.useMemo(() => getTimezoneDetails(), []);return (- <div className="flex w-full flex-1 items-center gap-1 rounded-b-md border-t-2 bg-transparent px-3 py-2 text-sm ring-offset-background">+ <div+ className={cn(+ "flex w-full flex-1 items-center gap-1 rounded-b-md border-t-2 bg-transparent px-3 py-2 text-sm ring-offset-background",+ className,+ )}+ ><div className="mx-1 grid gap-1 text-center"><TimeIcon time={date ?? period} /></div>diff --git a/web/src/env.mjs b/web/src/env.mjsindex 28badefe33..b1c1794e48 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -29,16 +29,6 @@ export const env = createEnv({LANGFUSE_NEW_USER_SIGNUP_WEBHOOK: z.string().url().optional(),// Add `.min(1) on ID and SECRET if you want to make sure they're not emptyLANGFUSE_ENABLE_EXPERIMENTAL_FEATURES: z.enum(["true", "false"]).optional(),- LANGFUSE_DEFAULT_TABLE_DATETIME_OFFSET: z- .string()- .optional()- .refine((v) => v === undefined || !isNaN(Number.parseInt(v)), {- message:- "LANGFUSE_DEFAULT_TABLE_DATETIME_OFFSET must be a number when set",- })- .transform(- (v) => (v === undefined ? undefined : -Number.parseInt(v)), // negative offset- ),LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES: z.enum(["true", "false"]).optional()@@ -174,8 +164,6 @@ export const env = createEnv({NEXT_PUBLIC_SIGN_UP_DISABLED: process.env.NEXT_PUBLIC_SIGN_UP_DISABLED,LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES:process.env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES,- LANGFUSE_DEFAULT_TABLE_DATETIME_OFFSET:- process.env.LANGFUSE_DEFAULT_TABLE_DATETIME_OFFSET,LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES:process.env.LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES,LANGFUSE_TEAM_SLACK_WEBHOOK: process.env.LANGFUSE_TEAM_SLACK_WEBHOOK,diff --git a/web/src/features/dashboard/components/BaseTimeSeriesChart.tsx b/web/src/features/dashboard/components/BaseTimeSeriesChart.tsxindex 32b11f004c..201a136b35 100644--- a/web/src/features/dashboard/components/BaseTimeSeriesChart.tsx+++ b/web/src/features/dashboard/components/BaseTimeSeriesChart.tsx@@ -1,9 +1,9 @@-import { type DateTimeAggregationOption } from "@/src/features/dashboard/lib/timeseries-aggregation";import { getColorsForCategories } from "@/src/features/dashboard/utils/getColorsForCategories";import { compactNumberFormatter } from "@/src/utils/numbers";import { cn } from "@/src/utils/tailwind";import { AreaChart, type CustomTooltipProps, LineChart } from "@tremor/react";import { Tooltip } from "@/src/features/dashboard/components/Tooltip";+import { type DashboardDateRangeAggregationOption } from "@/src/utils/date-range-utils";export type TimeSeriesChartDataPoint = {ts: number;@@ -12,7 +12,7 @@ export type TimeSeriesChartDataPoint = {export function BaseTimeSeriesChart(props: {className?: string;- agg: DateTimeAggregationOption;+ agg: DashboardDateRangeAggregationOption;data: TimeSeriesChartDataPoint[];showLegend?: boolean;connectNulls?: boolean;@@ -41,10 +41,13 @@ export function BaseTimeSeriesChart(props: {});}- const convertDate = (date: number, agg: DateTimeAggregationOption) => {- const showMinutes: DateTimeAggregationOption[] = [- "5 minutes",- "30 minutes",+ const convertDate = (+ date: number,+ agg: DashboardDateRangeAggregationOption,+ ) => {+ const showMinutes: DashboardDateRangeAggregationOption[] = [+ "5 min",+ "30 min","1 hour","3 hours",];diff --git a/web/src/features/dashboard/components/ChartScores.tsx b/web/src/features/dashboard/components/ChartScores.tsxindex 8b25651d17..0c0d139e8d 100644--- a/web/src/features/dashboard/components/ChartScores.tsx+++ b/web/src/features/dashboard/components/ChartScores.tsx@@ -1,8 +1,5 @@import { api } from "@/src/utils/api";-import {- dateTimeAggregationSettings,- type DateTimeAggregationOption,-} from "@/src/features/dashboard/lib/timeseries-aggregation";+import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";import { type FilterState } from "@langfuse/shared";@@ -14,10 +11,14 @@ import {import { NoData } from "@/src/features/dashboard/components/NoData";import DocPopup from "@/src/components/layouts/doc-popup";import { createTracesTimeFilter } from "@/src/features/dashboard/lib/dashboard-utils";+import {+ dashboardDateRangeAggregationSettings,+ type DashboardDateRangeAggregationOption,+} from "@/src/utils/date-range-utils";export function ChartScores(props: {className?: string;- agg: DateTimeAggregationOption;+ agg: DashboardDateRangeAggregationOption;globalFilterState: FilterState;projectId: string;}) {@@ -31,7 +32,8 @@ export function ChartScores(props: {{type: "datetime",column: "timestamp",- temporalUnit: dateTimeAggregationSettings[props.agg].date_trunc,+ temporalUnit:+ dashboardDateRangeAggregationSettings[props.agg].date_trunc,},{type: "string",diff --git a/web/src/features/dashboard/components/LatencyChart.tsx b/web/src/features/dashboard/components/LatencyChart.tsxindex 7b2c9a8127..f45a51c2a9 100644--- a/web/src/features/dashboard/components/LatencyChart.tsx+++ b/web/src/features/dashboard/components/LatencyChart.tsx@@ -1,8 +1,4 @@import { api } from "@/src/utils/api";-import {- dateTimeAggregationSettings,- type DateTimeAggregationOption,-} from "@/src/features/dashboard/lib/timeseries-aggregation";import { type FilterState } from "@langfuse/shared";import {getAllModels,@@ -15,6 +11,10 @@ import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimimport { TabComponent } from "@/src/features/dashboard/components/TabsComponent";import { latencyFormatter } from "@/src/utils/numbers";import { NoData } from "@/src/features/dashboard/components/NoData";+import {+ dashboardDateRangeAggregationSettings,+ type DashboardDateRangeAggregationOption,+} from "@/src/utils/date-range-utils";export const GenerationLatencyChart = ({className,@@ -25,7 +25,7 @@ export const GenerationLatencyChart = ({className?: string;projectId: string;globalFilterState: FilterState;- agg: DateTimeAggregationOption;+ agg: DashboardDateRangeAggregationOption;}) => {const latencies = api.dashboard.chart.useQuery({@@ -52,7 +52,7 @@ export const GenerationLatencyChart = ({{type: "datetime",column: "startTime",- temporalUnit: dateTimeAggregationSettings[agg].date_trunc,+ temporalUnit: dashboardDateRangeAggregationSettings[agg].date_trunc,},{ type: "string", column: "model" },],diff --git a/web/src/features/dashboard/components/ModelUsageChart.tsx b/web/src/features/dashboard/components/ModelUsageChart.tsxindex 805b5fa8f8..81604a3071 100644--- a/web/src/features/dashboard/components/ModelUsageChart.tsx+++ b/web/src/features/dashboard/components/ModelUsageChart.tsx@@ -1,9 +1,5 @@import { api } from "@/src/utils/api";-import {- dateTimeAggregationSettings,- type DateTimeAggregationOption,-} from "@/src/features/dashboard/lib/timeseries-aggregation";import { type FilterState } from "@langfuse/shared";import {@@ -19,6 +15,10 @@ import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimimport { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";import { NoData } from "@/src/features/dashboard/components/NoData";import { totalCostDashboardFormatted } from "@/src/features/dashboard/lib/dashboard-utils";+import {+ dashboardDateRangeAggregationSettings,+ type DashboardDateRangeAggregationOption,+} from "@/src/utils/date-range-utils";import { env } from "@/src/env.mjs";@@ -31,7 +31,7 @@ export const ModelUsageChart = ({className?: string;projectId: string;globalFilterState: FilterState;- agg: DateTimeAggregationOption;+ agg: DashboardDateRangeAggregationOption;}) => {const tokens = api.dashboard.chart.useQuery({@@ -52,7 +52,7 @@ export const ModelUsageChart = ({{type: "datetime",column: "startTime",- temporalUnit: dateTimeAggregationSettings[agg].date_trunc,+ temporalUnit: dashboardDateRangeAggregationSettings[agg].date_trunc,},{type: "string",diff --git a/web/src/features/dashboard/components/TabTimeSeriesChart.tsx b/web/src/features/dashboard/components/TabTimeSeriesChart.tsxindex 18ff1fd806..4f7da28991 100644--- a/web/src/features/dashboard/components/TabTimeSeriesChart.tsx+++ b/web/src/features/dashboard/components/TabTimeSeriesChart.tsx@@ -3,13 +3,12 @@ import {type TimeSeriesChartDataPoint,} from "@/src/features/dashboard/components/BaseTimeSeriesChart";import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";-import { type DateTimeAggregationOption } from "@/src/features/dashboard/lib/timeseries-aggregation";+import { type DashboardDateRangeAggregationOption } from "@/src/utils/date-range-utils";import { Tab, TabList, TabGroup, TabPanel, TabPanels } from "@tremor/react";-import { type ReactNode, useState } from "react";export type BaseTabTimeseriesChartProps = {- agg: DateTimeAggregationOption;+ agg: DashboardDateRangeAggregationOption;showLegend?: boolean;connectNulls?: boolean;data: {diff --git a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsxindex d4efab6a15..d190c84988 100644--- a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx+++ b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx@@ -1,8 +1,4 @@import { api } from "@/src/utils/api";-import {- dateTimeAggregationSettings,- type DateTimeAggregationOption,-} from "@/src/features/dashboard/lib/timeseries-aggregation";import { type FilterState } from "@langfuse/shared";import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";@@ -11,6 +7,10 @@ import { compactNumberFormatter } from "@/src/utils/numbers";import DocPopup from "@/src/components/layouts/doc-popup";import { isEmptyTimeSeries } from "@/src/features/dashboard/components/hooks";import { NoData } from "@/src/features/dashboard/components/NoData";+import {+ dashboardDateRangeAggregationSettings,+ type DashboardDateRangeAggregationOption,+} from "@/src/utils/date-range-utils";export const TracesTimeSeriesChart = ({className,@@ -21,7 +21,7 @@ export const TracesTimeSeriesChart = ({className?: string;projectId: string;globalFilterState: FilterState;- agg: DateTimeAggregationOption;+ agg: DashboardDateRangeAggregationOption;}) => {const traces = api.dashboard.chart.useQuery({@@ -35,7 +35,7 @@ export const TracesTimeSeriesChart = ({{type: "datetime",column: "timestamp",- temporalUnit: dateTimeAggregationSettings[agg].date_trunc,+ temporalUnit: dashboardDateRangeAggregationSettings[agg].date_trunc,},],},diff --git a/web/src/features/dashboard/components/UserChart.tsx b/web/src/features/dashboard/components/UserChart.tsxindex e2174d8c9f..6c87ccedd0 100644--- a/web/src/features/dashboard/components/UserChart.tsx+++ b/web/src/features/dashboard/components/UserChart.tsx@@ -1,5 +1,4 @@import { api } from "@/src/utils/api";-import { type DateTimeAggregationOption } from "@/src/features/dashboard/lib/timeseries-aggregation";import { type FilterState } from "@langfuse/shared";import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";import { compactNumberFormatter } from "@/src/utils/numbers";@@ -14,8 +13,8 @@ import {createTracesTimeFilter,totalCostDashboardFormatted,} from "@/src/features/dashboard/lib/dashboard-utils";-import { env } from "@/src/env.mjs";+import { type DashboardDateRangeAggregationOption } from "@/src/utils/date-range-utils";type BarChartDataPoint = {name: string;@@ -30,7 +29,7 @@ export const UserChart = ({className?: string;projectId: string;globalFilterState: FilterState;- agg: DateTimeAggregationOption;+ agg: DashboardDateRangeAggregationOption;}) => {const [isExpanded, setIsExpanded] = useState(false);const user = api.dashboard.chart.useQuery(diff --git a/web/src/features/dashboard/lib/timeseries-aggregation.ts b/web/src/features/dashboard/lib/timeseries-aggregation.tsdeleted file mode 100644index 322815e256..0000000000--- a/web/src/features/dashboard/lib/timeseries-aggregation.ts+++ /dev/null@@ -1,103 +0,0 @@-import { type DateRange } from "react-day-picker";--export const dateTimeAggregationOptions = [- "1 year",- "3 months",- "1 month",- "7 days",- "24 hours",- "3 hours",- "1 hour",- "30 minutes",- "5 minutes",-] as const;--export type DateTimeAggregationOption =- (typeof dateTimeAggregationOptions)[number];--export const dateTimeAggregationSettings: Record<- DateTimeAggregationOption,- {- date_trunc: "year" | "month" | "week" | "day" | "hour" | "minute";- date_formatter: (date: Date) => string;- minutes: number;- }-> = {- "1 year": {- date_trunc: "month",- date_formatter: (date) =>- date.toLocaleDateString("en-US", { year: "2-digit", month: "short" }),- minutes: 365 * 24 * 60,- },- "3 months": {- date_trunc: "day",- date_formatter: (date) =>- date.toLocaleDateString("en-US", { month: "short", day: "numeric" }),- minutes: 3 * 30 * 24 * 60,- },- "1 month": {- date_trunc: "day",- date_formatter: (date) =>- date.toLocaleDateString("en-US", { month: "short", day: "numeric" }),- minutes: 30 * 24 * 60,- },- "7 days": {- date_trunc: "day",- date_formatter: (date) =>- date.toLocaleDateString("en-US", { month: "short", day: "numeric" }),- minutes: 7 * 24 * 60,- },- "24 hours": {- date_trunc: "hour",- date_formatter: (date) =>- date.toLocaleTimeString("en-US", { hour: "numeric" }),- minutes: 24 * 60,- },- "3 hours": {- date_trunc: "minute",- date_formatter: (date) =>- date.toLocaleTimeString("en-US", { hour: "numeric", minute: "numeric" }),- minutes: 3 * 60,- },- "1 hour": {- date_trunc: "minute",- date_formatter: (date) =>- date.toLocaleTimeString("en-US", { hour: "numeric", minute: "numeric" }),- minutes: 60,- },- "30 minutes": {- date_trunc: "minute",- date_formatter: (date) =>- date.toLocaleTimeString("en-US", { hour: "numeric", minute: "numeric" }),- minutes: 30,- },- "5 minutes": {- date_trunc: "minute",- date_formatter: (date) =>- date.toLocaleTimeString("en-US", { hour: "numeric", minute: "numeric" }),- minutes: 5,- },-};--export const findClosestInterval = (- dateRange: DateRange,-): DateTimeAggregationOption | undefined => {- // Check for valid date range- if (!dateRange.from || !dateRange.to) return undefined;-- const duration = dateRange.to.getTime() - dateRange.from.getTime();-- // Map intervals to their difference from the given duration- const diffs = dateTimeAggregationOptions.map((interval) => {- const { minutes } = dateTimeAggregationSettings[interval];- return {- interval: interval,- diff: Math.abs(duration - minutes * 60 * 1000),- };- });-- // Sort by difference and pick the first one- diffs.sort((a, b) => a.diff - b.diff);-- return diffs[0]?.interval;-};diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsxindex 8641591c59..889fb39222 100644--- a/web/src/features/prompts/components/prompts-table.tsx+++ b/web/src/features/prompts/components/prompts-table.tsx@@ -22,6 +22,8 @@ import { createColumnHelper } from "@tanstack/react-table";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";import { Skeleton } from "@/src/components/ui/skeleton";+import { useTableDateRange } from "@/src/hooks/useTableDateRange";+import { type FilterState } from "@langfuse/shared";type PromptTableRow = {name: string;@@ -44,6 +46,9 @@ export function PromptTable() {const [filterState, setFilterState] = useQueryFilterState([], "prompts");+ const { selectedOption, dateRange, setDateRangeAndOption } =+ useTableDateRange("All time");+const [orderByState, setOrderByState] = useOrderByState({column: "createdAt",order: "DESC",@@ -53,12 +58,24 @@ export function PromptTable() {pageSize: withDefault(NumberParam, 50),});+ const dateRangeFilter: FilterState = dateRange+ ? [+ {+ column: "createdAt",+ type: "datetime",+ operator: ">=",+ value: dateRange.from,+ },+ ]+ : [];++ const combinedFilterState = filterState.concat(dateRangeFilter);const prompts = api.prompts.all.useQuery({page: paginationState.pageIndex,limit: paginationState.pageSize,projectId: projectId as string, // Typecast as query is enabled only when projectId is present- filter: filterState,+ filter: combinedFilterState,orderBy: orderByState,},{@@ -206,7 +223,7 @@ export function PromptTable() {promptsFilter={{...filterOptionTags,projectId: projectId as string,- filter: filterState,+ filter: combinedFilterState,orderBy: orderByState,}}/>@@ -233,6 +250,8 @@ export function PromptTable() {)}filterState={filterState}setFilterState={setFilterState}+ selectedOption={selectedOption}+ setDateRangeAndOption={setDateRangeAndOption}actionButtons={<Link href={`/project/${projectId}/prompts/new`}><Buttondiff --git a/web/src/features/public-api/types/score-configs.ts b/web/src/features/public-api/types/score-configs.tsindex e2daece4c2..07bd269673 100644--- a/web/src/features/public-api/types/score-configs.ts+++ b/web/src/features/public-api/types/score-configs.ts@@ -53,8 +53,8 @@ export const Category = z.object({const Categories = z.array(Category);const NumericScoreConfig = z.object({- maxValue: z.number().optional().nullish(),- minValue: z.number().optional().nullish(),+ maxValue: z.number().nullish(),+ minValue: z.number().nullish(),dataType: z.literal("NUMERIC"),categories: z.undefined().nullish(),});@@ -102,7 +102,7 @@ const ScoreConfigBase = z.object({id: z.string(),name: z.string().min(1).max(35),isArchived: z.boolean(),- description: z.string().optional().nullish(),+ description: z.string().nullish(),createdAt: z.coerce.date(),updatedAt: z.coerce.date(),projectId: z.string(),diff --git a/web/src/features/public-api/types/scores.ts b/web/src/features/public-api/types/scores.tsindex 068db1b04b..80c020cc1a 100644--- a/web/src/features/public-api/types/scores.ts+++ b/web/src/features/public-api/types/scores.ts@@ -31,7 +31,7 @@ const NumericData = z.object({});const CategoricalData = z.object({- value: z.number().optional().nullish(),+ value: z.number().nullish(),stringValue: z.string(),dataType: z.literal("CATEGORICAL"),});diff --git a/web/src/hooks/useDashboardDateRange.tsx b/web/src/hooks/useDashboardDateRange.tsxnew file mode 100644index 0000000000..c251addf1b--- /dev/null+++ b/web/src/hooks/useDashboardDateRange.tsx@@ -0,0 +1,79 @@+import { useState } from "react";+import { useQueryParams, StringParam, withDefault } from "use-query-params";+import {+ dashboardDateRangeAggregationSettings,+ type DashboardDateRangeAggregationOption,+ isValidDashboardDateRangeAggregationOption,+ type DashboardDateRangeOptions,+ DASHBOARD_AGGREGATION_PLACEHOLDER,+ type DashboardDateRange,+} from "@/src/utils/date-range-utils";+import { addMinutes } from "date-fns";++export interface UseDashboardDateRangeOutput {+ selectedOption: DashboardDateRangeOptions;+ dateRange: DashboardDateRange | undefined;+ setDateRangeAndOption: (+ option: DashboardDateRangeOptions,+ range?: DashboardDateRange,+ ) => void;+}++export function useDashboardDateRange(): UseDashboardDateRangeOutput {+ const [queryParams, setQueryParams] = useQueryParams({+ dateRange: withDefault(StringParam, "Select a date range"),+ from: StringParam,+ to: StringParam,+ });++ const initialRangeOption = "24 hours";++ const initialRange: DashboardDateRange | undefined =+ queryParams.dateRange !== "Select a date range" &&+ queryParams.from &&+ queryParams.to+ ? {+ from: new Date(queryParams.from),+ to: new Date(queryParams.to),+ }+ : {+ from: addMinutes(+ new Date(),+ -dashboardDateRangeAggregationSettings[initialRangeOption].minutes,+ ),+ to: new Date(),+ };++ const validatedInitialRangeOption =+ isValidDashboardDateRangeAggregationOption(queryParams.dateRange) ||+ queryParams.dateRange === DASHBOARD_AGGREGATION_PLACEHOLDER+ ? (queryParams.dateRange as DashboardDateRangeAggregationOption)+ : initialRangeOption;++ const [selectedOption, setSelectedOption] =+ useState<DashboardDateRangeOptions>(validatedInitialRangeOption);+ const [dateRange, setDateRange] = useState<DashboardDateRange | undefined>(+ initialRange,+ );++ const setDateRangeAndOption = (+ option: DashboardDateRangeOptions,+ range?: DashboardDateRange,+ ) => {+ setSelectedOption(option);+ setDateRange(range);++ const newParams: typeof queryParams = {+ dateRange: option,+ from: undefined,+ to: undefined,+ };+ if (option === DASHBOARD_AGGREGATION_PLACEHOLDER && range) {+ newParams.from = range.from.toISOString();+ newParams.to = range.to.toISOString();+ }+ setQueryParams(newParams);+ };++ return { selectedOption, dateRange, setDateRangeAndOption };+}diff --git a/web/src/hooks/useTableDateRange.tsx b/web/src/hooks/useTableDateRange.tsxnew file mode 100644index 0000000000..1824ab10d6--- /dev/null+++ b/web/src/hooks/useTableDateRange.tsx@@ -0,0 +1,59 @@+import { useState } from "react";+import { addMinutes } from "date-fns";+import { useQueryParams, StringParam, withDefault } from "use-query-params";+import {+ type TableDateRangeOptions,+ tableDateRangeAggregationSettings,+ isValidTableDateRangeAggregationOption,+ type TableDateRangeAggregationOption,+ type TableDateRange,+} from "@/src/utils/date-range-utils";++export interface UseTableDateRangeOutput {+ selectedOption: TableDateRangeOptions;+ dateRange: TableDateRange | undefined;+ setDateRangeAndOption: (+ option: TableDateRangeOptions,+ range?: TableDateRange,+ ) => void;+}++export function useTableDateRange(+ defaultDateRange: TableDateRangeOptions = "24 hours",+): UseTableDateRangeOutput {+ const [queryParams, setQueryParams] = useQueryParams({+ dateRange: withDefault(StringParam, "Select a date range"),+ });++ const validatedInitialRangeOption = isValidTableDateRangeAggregationOption(+ queryParams.dateRange,+ )+ ? (queryParams.dateRange as TableDateRangeAggregationOption)+ : defaultDateRange;++ const [selectedOption, setSelectedOption] = useState<TableDateRangeOptions>(+ validatedInitialRangeOption,+ );+ const initialDateRange = {+ from: addMinutes(+ new Date(),+ -tableDateRangeAggregationSettings[+ validatedInitialRangeOption as keyof typeof tableDateRangeAggregationSettings+ ],+ ),+ };++ const [dateRange, setDateRange] = useState<TableDateRange | undefined>(+ initialDateRange,+ );+ const setDateRangeAndOption = (+ option: TableDateRangeOptions,+ range?: TableDateRange,+ ) => {+ setSelectedOption(option);+ setDateRange(range);+ setQueryParams({ dateRange: option });+ };++ return { selectedOption, dateRange, setDateRangeAndOption };+}diff --git a/web/src/hooks/useTableLookBackDays.ts b/web/src/hooks/useTableLookBackDays.tsdeleted file mode 100644index 8d061fa1fa..0000000000--- a/web/src/hooks/useTableLookBackDays.ts+++ /dev/null@@ -1,11 +0,0 @@-import { useSession } from "next-auth/react";--export function useTableLookBackDays(projectId: string) {- const session = useSession();- const lookBackDays =- session.data?.environment.defaultTableDateTimeOffset ??- session.data?.user?.projects.find((project) => project.id === projectId)- ?.cloudConfig?.defaultLookBackDays ??- 7;- return lookBackDays;-}diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsxindex de06041653..4d4745566d 100644--- a/web/src/pages/project/[projectId]/index.tsx+++ b/web/src/pages/project/[projectId]/index.tsx@@ -1,5 +1,4 @@import Header from "@/src/components/layouts/header";-import { findClosestInterval } from "@/src/features/dashboard/lib/timeseries-aggregation";import { useRouter } from "next/router";import { GenerationLatencyChart } from "@/src/features/dashboard/components/LatencyChart";import { ChartScores } from "@/src/features/dashboard/components/ChartScores";@@ -9,19 +8,7 @@ import { ScoresTable } from "@/src/features/dashboard/components/ScoresTable";import { ModelUsageChart } from "@/src/features/dashboard/components/ModelUsageChart";import { TracesTimeSeriesChart } from "@/src/features/dashboard/components/TracesTimeSeriesChart";import { UserChart } from "@/src/features/dashboard/components/UserChart";-import {- type AvailableDateRangeSelections,- DEFAULT_DATE_RANGE_SELECTION,- DatePickerWithRange,-} from "@/src/components/date-picker";-import { addDays } from "date-fns";-import {- NumberParam,- StringParam,- useQueryParams,- withDefault,-} from "use-query-params";-import { isValidOption } from "@/src/utils/types";+import { DatePickerWithRange } from "@/src/components/date-picker";import { api } from "@/src/utils/api";import { FeedbackButtonWrapper } from "@/src/features/feedback/component/FeedbackButton";import { BarChart2 } from "lucide-react";@@ -33,17 +20,14 @@ import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterStateimport { LatencyTables } from "@/src/features/dashboard/components/LatencyTables";import { useMemo } from "react";import { useSession } from "next-auth/react";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";--export type DashboardDateRange = {- from: Date;- to: Date;-};+import { findClosestDashboardInterval } from "@/src/utils/date-range-utils";+import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";export default function Start() {const router = useRouter();const projectId = router.query.projectId as string;- const capture = usePostHogClientCapture();+ const { selectedOption, dateRange, setDateRangeAndOption } =+ useDashboardDateRange();const session = useSession();const disableExpensiveDashboardComponents =@@ -53,38 +37,6 @@ export default function Start() {(project) => project.id === projectId,);- const memoizedDate = useMemo(() => new Date(), []);-- const [urlParams, setUrlParams] = useQueryParams({- from: withDefault(NumberParam, addDays(memoizedDate, -1).getTime()),- to: withDefault(NumberParam, memoizedDate.getTime()),- select: withDefault(StringParam, "Select a date range"),- });-- const dateRange = useMemo(- () =>- urlParams.from && urlParams.to- ? { from: new Date(urlParams.from), to: new Date(urlParams.to) }- : undefined,- [urlParams.from, urlParams.to],- );-- const selectedOption = isValidOption(urlParams.select)- ? urlParams.select- : DEFAULT_DATE_RANGE_SELECTION;-- const setDateRangeAndOption = (- option?: AvailableDateRangeSelections,- dateRange?: DashboardDateRange,- ) => {- capture("dashboard:date_range_changed");- setUrlParams({- select: option ? option.toString() : urlParams.select,- from: dateRange ? dateRange.from.getTime() : urlParams.from,- to: dateRange ? dateRange.to.getTime() : urlParams.to,- });- };-const traceFilterOptions = api.traces.filterOptions.useQuery({projectId,@@ -123,7 +75,10 @@ export default function Start() {);const agg = useMemo(- () => (dateRange ? findClosestInterval(dateRange) ?? "7 days" : "7 days"),+ () =>+ dateRange+ ? findClosestDashboardInterval(dateRange) ?? "7 days"+ : "7 days",[dateRange],);@@ -142,7 +97,20 @@ export default function Start() {value: dateRange.to,},]- : [];+ : [+ {+ type: "datetime" as const,+ column: "startTime",+ operator: ">" as const,+ value: new Date(new Date().getTime() - 1000),+ },+ {+ type: "datetime" as const,+ column: "startTime",+ operator: "<" as const,+ value: new Date(),+ },+ ];const mergedFilterState: FilterState = [...userFilterState, ...timeFilter];diff --git a/web/src/pages/project/[projectId]/users.tsx b/web/src/pages/project/[projectId]/users.tsxindex 5207ccfd5a..75dfd81405 100644--- a/web/src/pages/project/[projectId]/users.tsx+++ b/web/src/pages/project/[projectId]/users.tsx@@ -15,11 +15,10 @@ import { useDetailPageLists } from "@/src/features/navigate-detail-pages/contextimport { api } from "@/src/utils/api";import { compactNumberFormatter, usdFormatter } from "@/src/utils/numbers";import { type RouterInput, type RouterOutput } from "@/src/utils/types";-import { type Score } from "@langfuse/shared";-import { localtimeDateOffsetByDays } from "@/src/utils/dates";+import { type FilterState, type Score } from "@langfuse/shared";import { usersTableCols } from "@/src/server/api/definitions/usersTable";import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";-import { useTableLookBackDays } from "@/src/hooks/useTableLookBackDays";+import { useTableDateRange } from "@/src/hooks/useTableDateRange";export type ScoreFilterInput = Omit<RouterInput["users"]["all"], "projectId">;@@ -38,14 +37,7 @@ export default function UsersPage() {const projectId = router.query.projectId as string;const [userFilterState, setUserFilterState] = useQueryFilterState(- [- {- column: "timestamp",- type: "datetime",- operator: ">",- value: localtimeDateOffsetByDays(-useTableLookBackDays(projectId)),- },- ],+ [],"users",);@@ -56,8 +48,23 @@ export default function UsersPage() {pageSize: withDefault(NumberParam, 50),});+ const { selectedOption, dateRange, setDateRangeAndOption } =+ useTableDateRange();++ const dateRangeFilter: FilterState = dateRange+ ? [+ {+ column: "Timestamp",+ type: "datetime",+ operator: ">=",+ value: dateRange.from,+ },+ ]+ : [];++ const filterState = userFilterState.concat(dateRangeFilter);const users = api.users.all.useQuery({- filter: userFilterState,+ filter: filterState,page: paginationState.pageIndex,limit: paginationState.pageSize,projectId,@@ -237,6 +244,8 @@ export default function UsersPage() {filterState={userFilterState}setFilterState={setUserFilterState}columns={columns}+ selectedOption={selectedOption}+ setDateRangeAndOption={setDateRangeAndOption}/><DataTablecolumns={columns}diff --git a/web/src/pages/project/[projectId]/users/[userId].tsx b/web/src/pages/project/[projectId]/users/[userId].tsxindex 6e0952d494..40818536f0 100644--- a/web/src/pages/project/[projectId]/users/[userId].tsx+++ b/web/src/pages/project/[projectId]/users/[userId].tsx@@ -41,6 +41,15 @@ export default function UserPage() {}};+ const handleTabChange = async (tab: string) => {+ if (router.query.filter) {+ const newQuery = { ...router.query };+ delete newQuery.filter;+ await router.replace({ query: newQuery });+ }+ setCurrentTab(tab);+ };+return (<div><Header@@ -70,7 +79,7 @@ export default function UserPage() {name="tabs"className="block w-full rounded-md border-border py-2 pl-3 pr-10 text-base focus:outline-none sm:text-sm"defaultValue={currentTab}- onChange={(e) => setCurrentTab(e.currentTarget.value)}+ onChange={(e) => handleTabChange(e.currentTarget.value)}>{tabs.map((tab) => (<option key={tab}>{tab}</option>@@ -90,7 +99,7 @@ export default function UserPage() {"whitespace-nowrap border-b-2 px-1 py-4 text-sm font-medium",)}aria-current={tab === currentTab ? "page" : undefined}- onClick={() => setCurrentTab(tab)}+ onClick={() => handleTabChange(tab)}>{tab}</button>diff --git a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.tsindex ce5a2359f0..4b2dff196a 100644--- a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts+++ b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts@@ -52,7 +52,7 @@ export async function getAllGenerations({// to improve query performance, add timeseries filter to observation queries as wellconst startTimeFilter = input.filter.find(- (f) => f.column === "start_time" && f.type === "datetime",+ (f) => f.column === "Start Time" && f.type === "datetime",);const datetimeFilter =startTimeFilter && startTimeFilter.type === "datetime"diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex 22056a40c7..e9dd5852ae 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -58,8 +58,9 @@ export const traceRouter = createTRPCRouter({// to improve query performance, add timeseries filter to observation queries as wellconst timeseriesFilter = input.filter?.find(- (f) => f.column === "timestamp" && f.type === "datetime",+ (f) => f.column === "Timestamp" && f.type === "datetime",);+const observationTimeseriesFilter =timeseriesFilter && timeseriesFilter.type === "datetime"? datetimeFilterToPrismaSql(diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 430ea95fb5..7dbe7fed03 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -38,8 +38,6 @@ import {export const cloudConfigSchema = z.object({plan: z.enum(["Hobby", "Pro", "Team", "Enterprise"]).optional(),monthlyObservationLimit: z.number().int().positive().optional(),- // used for table and dashboard queries- defaultLookBackDays: z.number().int().positive().optional(),});const staticProviders: Provider[] = [@@ -317,8 +315,6 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES === "true",disableExpensivePostgresQueries:env.LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES === "true",- defaultTableDateTimeOffset:- env.LANGFUSE_DEFAULT_TABLE_DATETIME_OFFSET,// Enables features that are only available under an enterprise license when self-hosting Langfuse// If you edit this line, you risk executing code that is not MIT licensed (self-contained in /ee folders otherwise)eeEnabled: env.LANGFUSE_EE_LICENSE_KEY !== undefined,@@ -333,18 +329,19 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {image: dbUser.image,admin: dbUser.admin,emailVerified: dbUser.emailVerified?.toISOString(),- projects: dbUser.projectMemberships.map((membership) => ({- id: membership.project.id,- name: membership.project.name,- role: membership.role,- cloudConfig: {- defaultLookBackDays:- cloudConfigSchema- .nullish()- .parse(membership.project.cloudConfig)- ?.defaultLookBackDays ?? null,- },- })),+ projects: dbUser.projectMemberships.map((membership) => {+ const cloudConfig = cloudConfigSchema.safeParse(+ membership.project.cloudConfig,+ );+ return {+ id: membership.project.id,+ name: membership.project.name,+ role: membership.role,+ cloudConfig: cloudConfig.success+ ? cloudConfig.data+ : null,+ };+ }),featureFlags: parseFlags(dbUser.featureFlags),}: null,diff --git a/web/src/utils/date-range-utils.ts b/web/src/utils/date-range-utils.tsnew file mode 100644index 0000000000..2c4c1b4638--- /dev/null+++ b/web/src/utils/date-range-utils.ts@@ -0,0 +1,204 @@+import { type DateRange } from "react-day-picker";++export const DEFAULT_DASHBOARD_AGGREGATION_SELECTION = "24 hours" as const;+export const DASHBOARD_AGGREGATION_PLACEHOLDER = "Custom" as const;+export const DEFAULT_AGGREGATION_SELECTION = "All time" as const;++export const DASHBOARD_AGGREGATION_OPTIONS = [+ "5 min",+ "30 min",+ "1 hour",+ "3 hours",+ "24 hours",+ "7 days",+ "1 month",+ "3 months",+ "1 year",+] as const;++export const TABLE_AGGREGATION_OPTIONS = [+ "30 min",+ "1 hour",+ "6 hours",+ "24 hours",+ "3 days",+ "7 days",+ "14 days",+ "1 month",+ "3 months",+] as const;++export type DashboardDateRangeAggregationOption =+ (typeof DASHBOARD_AGGREGATION_OPTIONS)[number];++export type TableDateRange = {+ from: Date;+};++export type TableDateRangeAggregationOption =+ (typeof TABLE_AGGREGATION_OPTIONS)[number];++export type DashboardDateRange = {+ from: Date;+ to: Date;+};++export type DateRangeAggregationOption =+ | DashboardDateRangeAggregationOption+ | TableDateRangeAggregationOption;++export type DashboardDateRangeOptions =+ | DashboardDateRangeAggregationOption+ | typeof DASHBOARD_AGGREGATION_PLACEHOLDER;++export type TableDateRangeOptions =+ | TableDateRangeAggregationOption+ | typeof DEFAULT_AGGREGATION_SELECTION;+export type DashboardDateRangeAggregationSettings = Record<+ DashboardDateRangeAggregationOption,+ {+ date_trunc: "year" | "month" | "week" | "day" | "hour" | "minute";+ minutes: number;+ }+>;++export type TableDateRangeAggregationSettings = Record<+ TableDateRangeAggregationOption,+ number+>;++export const dateTimeAggregationOptions = [+ ...TABLE_AGGREGATION_OPTIONS,+ ...DASHBOARD_AGGREGATION_OPTIONS,+ DEFAULT_AGGREGATION_SELECTION,+] as const;++export const dashboardDateRangeAggregationSettings: DashboardDateRangeAggregationSettings =+ {+ "1 year": {+ date_trunc: "month",+ minutes: 365 * 24 * 60,+ },+ "3 months": {+ date_trunc: "month",+ minutes: 3 * 28 * 24 * 60,+ },+ "1 month": {+ date_trunc: "month",+ minutes: 28 * 24 * 60,+ },+ "7 days": {+ date_trunc: "day",+ minutes: 7 * 24 * 60,+ },+ "24 hours": {+ date_trunc: "hour",+ minutes: 24 * 60,+ },+ "3 hours": {+ date_trunc: "hour",+ minutes: 3 * 60,+ },+ "1 hour": {+ date_trunc: "hour",+ minutes: 60,+ },+ "30 min": {+ date_trunc: "minute",+ minutes: 30,+ },+ "5 min": {+ date_trunc: "minute",+ minutes: 5,+ },+ };++export const tableDateRangeAggregationSettings: TableDateRangeAggregationSettings =+ {+ "3 months": 3 * 28 * 24 * 60,+ "1 month": 28 * 24 * 60,+ "14 days": 14 * 24 * 60,+ "7 days": 7 * 24 * 60,+ "3 days": 3 * 24 * 60,+ "24 hours": 24 * 60,+ "6 hours": 6 * 60,+ "1 hour": 60,+ "30 min": 30,+ };++export function isValidDashboardDateRangeAggregationOption(+ value: unknown,+): value is DashboardDateRangeAggregationOption {+ return (+ typeof value === "string" &&+ DASHBOARD_AGGREGATION_OPTIONS.includes(+ value as DashboardDateRangeAggregationOption,+ )+ );+}++export function isValidTableDateRangeAggregationOption(+ value: unknown,+): value is TableDateRangeAggregationOption {+ return (+ typeof value === "string" &&+ TABLE_AGGREGATION_OPTIONS.includes(value as TableDateRangeAggregationOption)+ );+}++export const findClosestTableIntervalToDate = (+ targetDate: Date,+): TableDateRangeAggregationOption | undefined => {+ const currentDate = new Date();+ const duration = Math.abs(currentDate.getTime() - targetDate.getTime());++ const diffs = TABLE_AGGREGATION_OPTIONS.map((interval) => {+ const minutes = tableDateRangeAggregationSettings[interval];+ return {+ interval,+ diff: Math.abs(duration - minutes * 60 * 1000),+ };+ });++ diffs.sort((a, b) => a.diff - b.diff);++ return diffs[0]?.interval;+};++export const findClosestDashboardIntervalToDate = (+ targetDate: Date,+): DashboardDateRangeAggregationOption | undefined => {+ const currentDate = new Date();+ const duration = Math.abs(currentDate.getTime() - targetDate.getTime());++ const diffs = DASHBOARD_AGGREGATION_OPTIONS.map((interval) => {+ const { minutes } = dashboardDateRangeAggregationSettings[interval];+ return {+ interval,+ diff: Math.abs(duration - minutes * 60 * 1000),+ };+ });++ diffs.sort((a, b) => a.diff - b.diff);++ return diffs[0]?.interval;+};++export const findClosestDashboardInterval = (+ dateRange: DateRange,+): DashboardDateRangeAggregationOption | undefined => {+ if (!dateRange.from || !dateRange.to) return undefined;+ const duration = dateRange.to.getTime() - dateRange.from.getTime();++ const diffs = DASHBOARD_AGGREGATION_OPTIONS.map((interval) => {+ const { minutes } = dashboardDateRangeAggregationSettings[interval];+ return {+ interval,+ diff: Math.abs(duration - minutes * 60 * 1000),+ };+ });++ diffs.sort((a, b) => a.diff - b.diff);++ return diffs[0]?.interval;+};diff --git a/web/src/utils/types.ts b/web/src/utils/types.tsindex 5ce20ef3ed..f0cd1950a2 100644--- a/web/src/utils/types.ts+++ b/web/src/utils/types.ts@@ -1,10 +1,6 @@import { type Observation } from "@langfuse/shared/src/db";import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server";import { type AppRouter } from "@/src/server/api/root";-import {- type DateTimeAggregationOption,- dateTimeAggregationOptions,-} from "@/src/features/dashboard/lib/timeseries-aggregation";import { type ObservationReturnType } from "@/src/server/api/routers/traces";import { type TiktokenModel } from "js-tiktoken";@@ -45,15 +41,6 @@ export const isNotNullOrUndefined = <T>(val?: T | null,): val is Exclude<T, null | undefined> => !isUndefinedOrNull(val);-export function isValidOption(- value: unknown,-): value is DateTimeAggregationOption {- return (- typeof value === "string" &&- dateTimeAggregationOptions.includes(value as DateTimeAggregationOption)- );-}-const chatModels = ["gpt-4","gpt-4-0314",diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.tsindex 2901c47986..551ce1206f 100644--- a/web/types/next-auth.d.ts+++ b/web/types/next-auth.d.ts@@ -5,6 +5,7 @@ import {type Project as PrismaProject,} from "@langfuse/shared/src/db";import { type Flags } from "@/src/features/feature-flags/types";+import { type cloudConfigSchema } from "@/src/server/auth";/*** Module augmentation for `next-auth` types. Allows us to add custom properties to the `session`@@ -19,7 +20,6 @@ declare module "next-auth" {// Run-time environment variables that need to be available client-sideenableExperimentalFeatures: boolean;disableExpensivePostgresQueries: boolean;- defaultTableDateTimeOffset?: number;// Enables features that are only available under an enterprise license when self-hosting LangfuseeeEnabled: boolean;};@@ -36,9 +36,7 @@ declare module "next-auth" {id: PrismaProject["id"];name: PrismaProject["name"];role: PrismaMembership["role"];- cloudConfig: {- defaultLookBackDays: number | null;- };+ cloudConfig: z.infer<typeof cloudConfigSchema> | null;}[];featureFlags: Flags;}