Skip to content

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

chore: refactor events table (#10522)

Max Deichmanncc7e69566350
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index 62677276bb..b1a673e6b6 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -1,4 +1,3 @@
-import { api } from "@/src/utils/api";
import { DataTable } from "@/src/components/table/data-table";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
import {
@@ -22,9 +21,7 @@ import {
BatchExportTableName,
type ObservationType,
TableViewPresetTableName,
- AnnotationQueueObjectType,
BatchActionType,
- type TimeFilter,
} from "@langfuse/shared";
import { cn } from "@/src/utils/tailwind";
import { LevelColors } from "@/src/components/level-colors";
@@ -54,7 +51,6 @@ import { useRouter } from "next/router";
import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";
import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";
import { useSelectAll } from "@/src/features/table/hooks/useSelectAll";
-import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
import { TableActionMenu } from "@/src/features/table/components/TableActionMenu";
import { type TableAction } from "@/src/features/table/types";
import { type DataTablePeekViewProps } from "@/src/components/table/peek";
@@ -62,6 +58,8 @@ import { useScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";
import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
import { MemoizedIOTableCell } from "@/src/components/ui/IOTableCell";
+import { useEventsTableData } from "@/src/features/events/hooks/useEventsTableData";
+import { useEventsFilterOptions } from "@/src/features/events/hooks/useEventsFilterOptions";
export type EventsTableRow = {
// Identity fields
@@ -214,74 +212,17 @@ export default function ObservationsEventsTable({
const oldFilterState = inputFilterState.concat(dateRangeFilter);
- const startTimeFilters = oldFilterState.filter(
- (f) =>
- (f.column === "Start Time" || f.column === "startTime") &&
- f.type === "datetime",
- ) as TimeFilter[];
-
- const filterOptions = api.events.filterOptions.useQuery(
- {
- projectId,
- startTimeFilter:
- startTimeFilters.length > 0 ? startTimeFilters : undefined,
- },
- {
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- staleTime: Infinity,
- },
- );
-
- const newFilterOptions = useMemo(() => {
- const scoreCategories =
- filterOptions.data?.score_categories?.reduce(
- (acc, score) => {
- acc[score.label] = score.values;
- return acc;
- },
- {} as Record<string, string[]>,
- ) ?? undefined;
-
- const scoresNumeric = filterOptions.data?.scores_avg ?? undefined;
-
- return {
- environment: filterOptions.data?.environment ?? undefined,
- name: filterOptions.data?.name ?? undefined,
- type: filterOptions.data?.type ?? undefined,
- level: filterOptions.data?.level ?? undefined,
- providedModelName: filterOptions.data?.providedModelName ?? undefined,
- modelId: filterOptions.data?.modelId ?? undefined,
- promptName: filterOptions.data?.promptName ?? undefined,
- traceTags: filterOptions.data?.traceTags ?? undefined,
- userId: filterOptions.data?.userId ?? undefined,
- sessionId: filterOptions.data?.sessionId ?? undefined,
- version: filterOptions.data?.version ?? undefined,
- latency: [],
- timeToFirstToken: [],
- tokensPerSecond: [],
- inputTokens: [],
- outputTokens: [],
- totalTokens: [],
- inputCost: [],
- outputCost: [],
- totalCost: [],
- score_categories: scoreCategories,
- scores_avg: scoresNumeric,
- };
- }, [filterOptions.data]);
+ // Fetch filter options
+ const { filterOptions, isFilterOptionsPending } = useEventsFilterOptions({
+ projectId,
+ oldFilterState,
+ });
const queryFilter = useSidebarFilterState(
observationEventsFilterConfig,
- newFilterOptions,
+ filterOptions,
projectId,
- filterOptions.isPending,
+ isFilterOptionsPending,
);
// Create ref-based wrapper to avoid stale closure when queryFilter updates
@@ -295,45 +236,19 @@ export default function ObservationsEventsTable({
const filterState = queryFilter.filterState.concat(dateRangeFilter);
- const getCountPayload = {
- projectId,
- filter: filterState,
- searchQuery,
- searchType,
- page: 1,
- limit: 1,
- orderBy: null,
- };
-
- const getAllPayload = {
- ...getCountPayload,
- page: paginationState.page,
- limit: paginationState.limit,
- orderBy: orderByState,
- };
-
- const observations = api.events.all.useQuery(getAllPayload, {
- refetchOnWindowFocus: true,
- });
-
- const totalCountQuery = api.events.countAll.useQuery(getCountPayload, {
- refetchOnWindowFocus: true,
- });
-
- const totalCount = totalCountQuery.data?.totalCount ?? null;
-
- const addToQueueMutation = api.annotationQueueItems.createMany.useMutation({
- onSuccess: (data) => {
- showSuccessToast({
- title: "Observations added to queue",
- description: `Selected observations will be added to queue "${data.queueName}". This may take a minute.`,
- link: {
- href: `/project/${projectId}/annotation-queues/${data.queueId}`,
- text: `View queue "${data.queueName}"`,
- },
- });
- },
- });
+ // Use the custom hook for observations data fetching
+ const { observations, totalCount, handleAddToAnnotationQueue } =
+ useEventsTableData({
+ projectId,
+ filterState,
+ paginationState,
+ orderByState,
+ searchQuery,
+ searchType,
+ selectedRows,
+ selectAll,
+ setSelectedRows,
+ });
useEffect(() => {
if (observations.isSuccess) {
@@ -367,34 +282,6 @@ export default function ObservationsEventsTable({
setSelectedRows,
});
- const handleAddToAnnotationQueue = async ({
- projectId,
- targetId,
- }: {
- projectId: string;
- targetId: string;
- }) => {
- const selectedObservationIds = Object.keys(selectedRows).filter(
- (observationId) =>
- observations.data?.observations
- .map((o) => o.id)
- .includes(observationId),
- );
-
- await addToQueueMutation.mutateAsync({
- projectId,
- objectIds: selectedObservationIds,
- objectType: AnnotationQueueObjectType.OBSERVATION,
- queueId: targetId,
- isBatchAction: selectAll,
- query: {
- filter: filterState,
- orderBy: orderByState,
- },
- });
- setSelectedRows({});
- };
-
const tableActions: TableAction[] = [
{
id: "observation-add-to-annotation-queue",
diff --git a/web/src/features/events/hooks/useEventsFilterOptions.ts b/web/src/features/events/hooks/useEventsFilterOptions.ts
new file mode 100644
index 0000000000..75a42a595f
--- /dev/null
+++ b/web/src/features/events/hooks/useEventsFilterOptions.ts
@@ -0,0 +1,86 @@
+import { api } from "@/src/utils/api";
+import { useMemo } from "react";
+import { type FilterState, type TimeFilter } from "@langfuse/shared";
+
+type UseEventsFilterOptionsParams = {
+ projectId: string;
+ oldFilterState: FilterState;
+};
+
+export function useEventsFilterOptions({
+ projectId,
+ oldFilterState,
+}: UseEventsFilterOptionsParams) {
+ // Extract start time filters for filter options query
+ const startTimeFilters = useMemo(() => {
+ return oldFilterState.filter(
+ (f) =>
+ (f.column === "Start Time" || f.column === "startTime") &&
+ f.type === "datetime",
+ ) as TimeFilter[];
+ }, [oldFilterState]);
+
+ // Fetch filter options
+ const filterOptions = api.events.filterOptions.useQuery(
+ {
+ projectId,
+ startTimeFilter:
+ startTimeFilters.length > 0 ? startTimeFilters : undefined,
+ },
+ {
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ staleTime: Infinity,
+ },
+ );
+
+ // Transform filter options for sidebar
+ const newFilterOptions = useMemo(() => {
+ const scoreCategories =
+ filterOptions.data?.score_categories?.reduce(
+ (acc, score) => {
+ acc[score.label] = score.values;
+ return acc;
+ },
+ {} as Record<string, string[]>,
+ ) ?? undefined;
+
+ const scoresNumeric = filterOptions.data?.scores_avg ?? undefined;
+
+ return {
+ environment: filterOptions.data?.environment ?? undefined,
+ name: filterOptions.data?.name ?? undefined,
+ type: filterOptions.data?.type ?? undefined,
+ level: filterOptions.data?.level ?? undefined,
+ providedModelName: filterOptions.data?.providedModelName ?? undefined,
+ modelId: filterOptions.data?.modelId ?? undefined,
+ promptName: filterOptions.data?.promptName ?? undefined,
+ traceTags: filterOptions.data?.traceTags ?? undefined,
+ userId: filterOptions.data?.userId ?? undefined,
+ sessionId: filterOptions.data?.sessionId ?? undefined,
+ version: filterOptions.data?.version ?? undefined,
+ latency: [],
+ timeToFirstToken: [],
+ tokensPerSecond: [],
+ inputTokens: [],
+ outputTokens: [],
+ totalTokens: [],
+ inputCost: [],
+ outputCost: [],
+ totalCost: [],
+ score_categories: scoreCategories,
+ scores_avg: scoresNumeric,
+ };
+ }, [filterOptions.data]);
+
+ return {
+ filterOptions: newFilterOptions,
+ isFilterOptionsPending: filterOptions.isPending,
+ };
+}
diff --git a/web/src/features/events/hooks/useEventsTableData.ts b/web/src/features/events/hooks/useEventsTableData.ts
new file mode 100644
index 0000000000..4bf12f475d
--- /dev/null
+++ b/web/src/features/events/hooks/useEventsTableData.ts
@@ -0,0 +1,126 @@
+import { api } from "@/src/utils/api";
+import { useMemo } from "react";
+import { type FilterState, AnnotationQueueObjectType } from "@langfuse/shared";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+
+type UseEventsTableDataParams = {
+ projectId: string;
+ filterState: FilterState;
+ paginationState: {
+ page: number;
+ limit: number;
+ };
+ orderByState: {
+ column: string;
+ order: "ASC" | "DESC";
+ } | null;
+ searchQuery?: string | null;
+ searchType?: ("id" | "content")[];
+ selectedRows: Record<string, boolean>;
+ selectAll: boolean;
+ setSelectedRows: (rows: Record<string, boolean>) => void;
+};
+
+export function useEventsTableData({
+ projectId,
+ filterState,
+ paginationState,
+ orderByState,
+ searchQuery,
+ searchType,
+ selectedRows,
+ selectAll,
+ setSelectedRows,
+}: UseEventsTableDataParams) {
+ // Prepare query payloads
+ const getCountPayload = useMemo(
+ () => ({
+ projectId,
+ filter: filterState,
+ searchQuery: searchQuery ?? null,
+ searchType: searchType ?? ["id", "content"],
+ page: 1,
+ limit: 1,
+ orderBy: null,
+ }),
+ [projectId, filterState, searchQuery, searchType],
+ );
+
+ const getAllPayload = useMemo(
+ () => ({
+ ...getCountPayload,
+ page: paginationState.page,
+ limit: paginationState.limit,
+ orderBy: orderByState,
+ }),
+ [
+ getCountPayload,
+ paginationState.page,
+ paginationState.limit,
+ orderByState,
+ ],
+ );
+
+ // Fetch observations
+ const observations = api.events.all.useQuery(getAllPayload, {
+ refetchOnWindowFocus: true,
+ });
+
+ // Fetch total count
+ const totalCountQuery = api.events.countAll.useQuery(getCountPayload, {
+ refetchOnWindowFocus: true,
+ });
+
+ const totalCount = totalCountQuery.data?.totalCount ?? null;
+
+ // Add to queue mutation
+ const addToQueueMutation = api.annotationQueueItems.createMany.useMutation({
+ onSuccess: (data) => {
+ showSuccessToast({
+ title: "Observations added to queue",
+ description: `Selected observations will be added to queue "${data.queueName}". This may take a minute.`,
+ link: {
+ href: `/project/${projectId}/annotation-queues/${data.queueId}`,
+ text: `View queue "${data.queueName}"`,
+ },
+ });
+ },
+ });
+
+ // Handler for adding to annotation queue
+ const handleAddToAnnotationQueue = async ({
+ projectId,
+ targetId,
+ }: {
+ projectId: string;
+ targetId: string;
+ }) => {
+ const selectedObservationIds = Object.keys(selectedRows).filter(
+ (observationId) =>
+ (observations.data?.observations ?? [])
+ .map((o) => o.id)
+ .includes(observationId),
+ );
+
+ await addToQueueMutation.mutateAsync({
+ projectId,
+ objectIds: selectedObservationIds,
+ objectType: AnnotationQueueObjectType.OBSERVATION,
+ queueId: targetId,
+ isBatchAction: selectAll,
+ query: {
+ filter: filterState,
+ orderBy: orderByState,
+ },
+ });
+ setSelectedRows({});
+ };
+
+ return {
+ observations,
+ totalCountQuery,
+ totalCount,
+ addToQueueMutation,
+ handleAddToAnnotationQueue,
+ };
+}