Skip to content

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

55.7 KB
Raw Blame
/* eslint-disable no-nested-ternary, react/no-unstable-nested-components, @typescript-eslint/no-use-before-define */
import { api } from "@/src/utils/api";
import { DataTable } from "@/src/components/table/data-table";
import { TRACING_PAGE_SIZE_OPTIONS } from "@/src/components/table/DataTablePagination";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
import {
  DataTableControlsProvider,
  DataTableControls,
} from "@/src/components/table/data-table-controls";
import { SearchableTableFilterLayout } from "@/src/components/table/resizable-filter-layout";
import {
  useEffect,
  useLayoutEffect,
  useMemo,
  useState,
  useRef,
  useCallback,
} from "react";
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
import {
  type UseSidebarFilterStateOptions,
  useSidebarFilterState,
} from "@/src/features/filters/hooks/useSidebarFilterState";

import {
  getObservationsFilterConfig,
  OBSERVATION_COLUMN_TO_BACKEND_KEY,
  type ObservationsOmittableFilterColumn,
} from "@/src/features/filters/config/observations-config";

import { buildSidebarFilterSessionContextId } from "@/src/features/filters/lib/persistedSidebarFilterQuery";
import { transformFiltersForBackend } from "@/src/features/filters/lib/filter-transform";
import { sortOptionValues } from "@/src/features/filters/lib/option-sort";
import { observationsFieldRegistry } from "@/src/features/filters/config/tracingSearchRegistry";

import { usePaginationState } from "@/src/hooks/usePaginationState";
import { useFacetOptionsWithObservedMetadata } from "@/src/hooks/useObservedMetadata";

import {
  normalizeOrderByForTable,
  DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,
  type ObservationLevelType,
  type FilterState,
  BatchExportTableName,
  type ObservationType,
  TableViewPresetTableName,
  AnnotationQueueObjectType,
  BatchActionType,
  ActionId,
  type TimeFilter,
  type OrderByState,
  type TracingSearchType,
  type ScoreAggregate,
  buildTracePath,
} from "@langfuse/shared";

import { formatIntervalSeconds } from "@/src/utils/dates";
import { default as useColumnVisibility } from "@/src/features/column-visibility/hooks/useColumnVisibility";
import { default as useColumnOrder } from "@/src/features/column-visibility/hooks/useColumnOrder";
import { Skeleton } from "@/src/components/ui/skeleton";
import { type LangfuseColumnDef } from "@/src/components/table/types";
import { ObservationLevelTag } from "@/src/components/ObservationLevelTag";
import { numberFormatter, usdFormatter } from "@/src/utils/numbers";
import {
  formatObservationCost,
  isObservationCostDisplayable,
} from "@/src/utils/observationCost";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import {
  customRowHeightMenu,
  isCompactRowHeight,
  useRowHeightLocalStorage,
} from "@/src/components/table/data-table-row-height-switch";
import { EmptyValue } from "@/src/components/design-system/table/components/EmptyValue/EmptyValue";
import { ConnectedIOTableCell } from "@/src/components/table/ConnectedIOTableCell";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
import { tablePlaceholderOptions } from "@/src/components/table/utils/tablePlaceholder";
import { usePeekTableState } from "@/src/components/table/peek/contexts/PeekTableStateProvider";
import {
  toAbsoluteTimeRange,
  type TableDateRange,
} from "@/src/utils/date-range-utils";
import { TableHeaderControls } from "@/src/components/table/TableHeaderControls";
import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { BreakdownTooltip } from "@/src/features/traces/components/BreakdownTooltip";
import { calculateAggregatedUsage } from "@/src/features/traces/fns/calculateAggregatedUsage";
import { InfoIcon } from "@langfuse/icons";
import { ProvidedModelNameCell } from "@/src/features/models/components/ProvidedModelNameCell";
import { createTagTableColumn } from "@/src/components/design-system/table/columns/createTagTableColumn";
import { createDateTableColumn } from "@/src/components/design-system/table/columns/createDateTableColumn";
import { createNumberTableColumn } from "@/src/components/design-system/table/columns/createNumberTableColumn";
import { createIdTableColumn } from "@/src/components/design-system/table/columns/createIdTableColumn";
import { createDurationTableColumn } from "@/src/components/design-system/table/columns/createDurationTableColumn";
import { createItemBadgeTableColumn } from "@/src/components/design-system/table/columns/createItemBadgeTableColumn";
import { createTableColumn } from "@/src/components/design-system/table/columns/utils/createTableColumn";
import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";
import { createTagsTableColumn } from "@/src/components/design-system/table/columns/createTagsTableColumn";
import { createTokenUsageTableColumn } from "@/src/components/design-system/table/columns/createTokenUsageTableColumn";
import { TablePeekViewObservationDetail } from "@/src/components/table/peek/TablePeekViewObservationDetail";
import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
import {
  detailPageListKeys,
  useDetailPageLists,
} from "@/src/features/navigate-detail-pages/DetailPageListsProvider";
import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";
import { useTableViewFilterChange } from "@/src/components/table/table-view-presets/hooks/useTableViewFilterChange";
import { TableSearchBar } from "@/src/features/search-bar/components/TableSearchBar";
import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";
import { useFullTextSearch } from "@/src/features/search-bar/hooks/useFullTextSearch";

import { useRouter } from "next/router";
import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";
import { TableActionMenu } from "@/src/features/table/components/TableActionMenu";
import type { TableAction } from "@/src/features/table/types";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { type DataTablePeekViewProps } from "@/src/components/table/peek";
import { useScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";
import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";
import { AddObservationsToDatasetDialog } from "@/src/features/batch-actions/components/AddObservationsToDatasetDialog/AddObservationsToDatasetDialog";
import useSessionStorage from "@/src/components/useSessionStorage";
import { getSafeRedirectPath } from "@/src/utils/redirect";
import {
  REFRESH_INTERVALS,
  type RefreshInterval,
} from "@/src/components/table/utils/refresh-intervals";
import {
  ObservationsTableStoreProvider,
  useObservationsTableStore,
} from "@/src/features/tracing-tables/observations/ObservationsTableStoreProvider";
import { useObservationsTableView } from "@/src/features/tracing-tables/observations/useObservationsTableView";
import { useStore } from "zustand";

export type ObservationsTableRow = {
  // Shown by default
  startTime: Date;
  type: ObservationType;
  name?: string;
  // i/o and metadata not set explicitly, but fetched from the server from the cell
  input?: unknown;
  output?: unknown;
  level?: ObservationLevelType;
  statusMessage?: string;
  latency?: number;
  timeToFirstToken?: number;
  usage: {
    inputUsage: number;
    outputUsage: number;
    totalUsage: number;
  };
  usageDetails: Record<string, number>;
  totalCost?: number;
  costDetails: Record<string, number>;
  usagePricingTierName?: string | null;
  model?: string;
  promptName?: string;
  environment?: string;
  traceTags?: string[];
  metadata?: unknown;
  // scores holds grouped column with individual scores
  scores: ScoreAggregate;
  // Hidden by default
  endTime?: Date;
  id: string;
  traceName?: string;
  traceId?: string;
  modelId?: string;
  version: string;
  timestamp?: Date;
  promptId?: string;
  promptVersion?: string;
  completionStartTime?: Date;
  cost: {
    inputCost?: number;
    outputCost?: number;
  };
  toolDefinitions?: number;
  toolCalls?: number;
};

export type ObservationsTableProps = {
  projectId: string;
  promptName?: string;
  promptVersion?: number;
  modelId?: string;
  omittedFilter?: ObservationsOmittableFilterColumn[];
  // External control props for embedded preview tables
  hideControls?: boolean;
  externalFilterState?: FilterState;
  externalDateRange?: TableDateRange;
  limitRows?: number;
  /**
   * When true, render the time-range picker and auto-refresh button in the
   * page header (next to the title) via the header controls slot, instead of
   * inside the table toolbar. Only used when the table is the primary content
   * of a `Page`.
   */
  showControlsInPageHeader?: boolean;
};

export default function ObservationsTable({
  projectId,
  promptName,
  promptVersion,
  modelId,
  omittedFilter = [],
  hideControls = false,
  externalFilterState,
  externalDateRange,
  limitRows,
  showControlsInPageHeader = false,
}: ObservationsTableProps) {
  const capture = usePostHogClientCapture();
  const peekContext = usePeekTableState();

  const observationsFilterConfig = useMemo(
    () => getObservationsFilterConfig(omittedFilter),
    [omittedFilter],
  );

  const router = useRouter();
  const { viewId } = router.query;
  const utils = api.useUtils();

  const { setDetailPageList } = useDetailPageLists();
  const { store: observationsTableStore } = useObservationsTableView({
    projectId,
  });
  const showAddToDatasetDialog = useStore(
    observationsTableStore,
    (state) => state.showAddToDatasetDialog,
  );
  const [rawRefreshInterval, setRawRefreshInterval] =
    useSessionStorage<RefreshInterval>(
      `tableRefreshInterval-${projectId}`,
      null,
    );

  // Validate session storage value against allowed intervals to prevent too small intervals
  const allowedValues = REFRESH_INTERVALS.map((i) => i.value);
  const refreshInterval = allowedValues.includes(rawRefreshInterval)
    ? rawRefreshInterval
    : null;
  const setRefreshInterval = useCallback(
    (value: RefreshInterval) => {
      if (allowedValues.includes(value)) {
        setRawRefreshInterval(value);
      }
    },
    [allowedValues, setRawRefreshInterval],
  );

  const [refreshTick, setRefreshTick] = useState(0);
  const [manualRefreshTrigger, setManualRefreshTrigger] = useState(0); // resets the interval when manual refresh is called

  // Auto-increment refresh tick to force date range recalculation
  useEffect(() => {
    if (!refreshInterval) return;
    const id = setInterval(() => {
      setRefreshTick((t) => t + 1);
    }, refreshInterval);
    return () => clearInterval(id);
  }, [refreshInterval, manualRefreshTrigger]);

  const handleRefresh = useCallback(() => {
    setRefreshTick((t) => t + 1);
    setManualRefreshTrigger((t) => t + 1);
    Promise.all([
      utils.generations.all.invalidate(),
      utils.generations.countAll.invalidate(),
      utils.generations.filterOptions.invalidate(),
      utils.projects.environmentFilterOptions.invalidate(),
    ]);
  }, [utils]);
  const legacyTracingSearchConfig = api.public.tracingSearchConfig.useQuery(
    { projectId },
    {
      enabled: !hideControls,
      refetchOnMount: false,
      refetchOnWindowFocus: false,
      refetchOnReconnect: false,
    },
  );
  const legacyTracingIoSearchEnabled =
    legacyTracingSearchConfig.data?.legacyTracingIoSearchEnabled ?? true;
  const { searchQuery, searchType, setSearchQuery, setSearchType } =
    useFullTextSearch({
      tableAllowsFullTextSearch: legacyTracingIoSearchEnabled,
    });

  const [paginationState, setPaginationState] = usePaginationState(0, 50, {
    page: "pageIndex",
    limit: "pageSize",
  });

  const [storedRowHeight, setRowHeight, rowHeights] = useRowHeightLocalStorage(
    "generations",
    "s",
  );
  const rowHeight = hideControls ? "s" : storedRowHeight;
  const compactRows =
    hideControls ||
    isCompactRowHeight(
      storedRowHeight,
      rowHeights.mode,
      rowHeights.activeHeightPx,
    );

  const [inputFilterState] = useQueryFilterState(
    // If the user loads saved table view presets, we should not apply the default type filter
    !viewId
      ? [
          {
            column: "type",
            type: "stringOptions",
            operator: "any of",
            value: [
              "GENERATION",
              "AGENT",
              "TOOL",
              "CHAIN",
              "RETRIEVER",
              "EVALUATOR",
              "EMBEDDING",
              "GUARDRAIL",
            ],
          },
        ]
      : [],
    "generations",
    projectId,
  );

  const [orderByState, setOrderByState] = useOrderByState({
    column: "startTime",
    order: "DESC",
  });
  const orderBy = normalizeOrderByForTable({
    orderBy: orderByState,
    expectedTimeColumn: "startTime",
  });

  const { timeRange, setTimeRange } = useTableDateRange(projectId);

  // Convert timeRange to absolute date range for compatibility
  // refreshTick forces recalculation on each refresh cycle
  const tableDateRange = useMemo(() => {
    return toAbsoluteTimeRange(timeRange) ?? undefined;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [timeRange, refreshTick]);

  const dateRange = externalDateRange ?? tableDateRange;

  const promptNameFilter: FilterState = promptName
    ? [
        {
          column: "Prompt Name",
          type: "string",
          operator: "=",
          value: promptName,
        },
      ]
    : [];

  const promptVersionFilter: FilterState = promptVersion
    ? [
        {
          column: "Prompt Version",
          type: "number",
          operator: "=",
          value: promptVersion,
        },
      ]
    : [];

  const modelIdFilter: FilterState = modelId
    ? [
        {
          column: "Model ID",
          type: "string",
          operator: "=",
          value: modelId,
        },
      ]
    : [];

  const dateRangeFilter: FilterState = dateRange
    ? [
        {
          column: "startTime",
          type: "datetime",
          operator: ">=",
          value: dateRange.from,
        },
        ...(dateRange.to
          ? [
              {
                column: "startTime",
                type: "datetime",
                operator: "<=",
                value: dateRange.to,
              } as const,
            ]
          : []),
      ]
    : [];

  const environmentFilterOptions =
    api.projects.environmentFilterOptions.useQuery(
      {
        projectId,
        fromTimestamp: dateRange?.from,
      },
      {
        trpc: { context: { skipBatch: true } },
        refetchOnMount: false,
        refetchOnWindowFocus: false,
        refetchOnReconnect: false,
        staleTime: Infinity,
      },
    );

  const oldFilterState = inputFilterState.concat(
    dateRangeFilter,
    promptNameFilter,
    promptVersionFilter,
    modelIdFilter,
  );

  const startTimeFilters = oldFilterState.filter(
    (f) =>
      (f.column === "Start Time" || f.column === "startTime") &&
      f.type === "datetime",
  ) as TimeFilter[];
  const filterOptions = api.generations.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;
    const scoresBoolean = filterOptions.data?.score_booleans ?? undefined;

    return {
      environment:
        environmentFilterOptions.data?.map((value) => value.environment) ??
        undefined,
      name:
        filterOptions.data?.name?.map((n) => ({
          value: n.value,
          count: n.count !== undefined ? Number(n.count) : undefined,
        })) ?? undefined,
      type:
        filterOptions.data?.type?.map((t) => ({
          value: t.value,
          count: t.count !== undefined ? Number(t.count) : undefined,
        })) ?? undefined,
      traceName:
        filterOptions.data?.traceName?.map((tn) => ({
          value: tn.value,
          count: tn.count !== undefined ? Number(tn.count) : undefined,
        })) ?? undefined,
      level: ["DEFAULT", "DEBUG", "WARNING", "ERROR"],
      model:
        filterOptions.data?.model?.map((m) => ({
          value: m.value,
          count: m.count !== undefined ? Number(m.count) : undefined,
        })) ?? undefined,
      modelId:
        filterOptions.data?.modelId?.map((mid) => ({
          value: mid.value,
          count: mid.count !== undefined ? Number(mid.count) : undefined,
        })) ?? undefined,
      promptName:
        filterOptions.data?.promptName?.map((pn) => ({
          value: pn.value,
          count: pn.count !== undefined ? Number(pn.count) : undefined,
        })) ?? undefined,
      // tags read A→Z
      tags: sortOptionValues(
        filterOptions.data?.tags?.map((t) => ({
          value: t.value,
          count: t.count !== undefined ? Number(t.count) : undefined,
        })),
      ),
      toolNames:
        filterOptions.data?.toolNames?.map((tn) => ({
          value: tn.value,
          count: tn.count !== undefined ? Number(tn.count) : undefined,
        })) ?? undefined,
      calledToolNames:
        filterOptions.data?.calledToolNames?.map((ctn) => ({
          value: ctn.value,
          count: ctn.count !== undefined ? Number(ctn.count) : undefined,
        })) ?? undefined,
      latency: [],
      timeToFirstToken: [],
      tokensPerSecond: [],
      inputTokens: [],
      outputTokens: [],
      totalTokens: [],
      inputCost: [],
      outputCost: [],
      totalCost: [],
      score_categories: scoreCategories,
      scores_avg: scoresNumeric,
      score_booleans: scoresBoolean,
    };
  }, [environmentFilterOptions.data, filterOptions.data]);

  const isSidebarFilterLoading =
    filterOptions.isPending || environmentFilterOptions.isPending;

  const { viewControllersRef, onExplicitFilterStateChange } =
    useTableViewFilterChange();

  const queryFilterOptions: UseSidebarFilterStateOptions = useMemo(() => {
    const baseOptions = {
      loading: isSidebarFilterLoading,
      implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,
      onExplicitFilterStateChange,
      isV4: false,
    };

    if (peekContext) {
      return {
        ...baseOptions,
        stateLocation: "peekContext",
        context: peekContext,
      };
    }

    if (hideControls) {
      return {
        ...baseOptions,
        stateLocation: "memory",
      };
    }

    return {
      ...baseOptions,
      stateLocation: "urlAndSessionStorage",
      sessionFilterContextId: buildSidebarFilterSessionContextId(
        projectId,
        promptName ? "prompt" : modelId ? "model" : undefined,
      ),
    };
  }, [
    hideControls,
    isSidebarFilterLoading,
    onExplicitFilterStateChange,
    peekContext,
    projectId,
    promptName,
    modelId,
  ]);

  // Opt into the shared observed-metadata suggestions for the Metadata facet
  // (LFE-11030). This table's rows fetch metadata per cell, so it reads the
  // per-project map without contributing to it.
  const facetOptions = useFacetOptionsWithObservedMetadata(
    projectId,
    newFilterOptions,
  );

  const queryFilter = useSidebarFilterState(
    observationsFilterConfig,
    facetOptions,
    queryFilterOptions,
  );
  const searchRegistry = observationsFieldRegistry(
    observationsFilterConfig,
    legacyTracingIoSearchEnabled,
  );
  const observedOptions = toObservedOptions(
    facetOptions,
    isSidebarFilterLoading,
  );

  // Create ref-based wrapper to avoid stale closure when queryFilter updates
  const queryFilterRef = useRef(queryFilter);
  queryFilterRef.current = queryFilter;

  const setSavedViewFilters = useCallback(
    (filters: FilterState) =>
      queryFilterRef.current?.setFilterState(filters, { origin: "saved_view" }),
    [],
  );

  const combinedFilterState = queryFilter.effectiveFilterState.concat(
    dateRangeFilter,
    promptNameFilter,
    promptVersionFilter,
    modelIdFilter,
  );

  // Use external filter state if provided, otherwise use combined filter
  // state. Even with an external filter, still apply the date-range bound so
  // callers that pass an externalDateRange (e.g. the eval preview's "last 24
  // hours" window) have it honored for the row query, not just score columns.
  const filterState = externalFilterState
    ? externalFilterState.concat(dateRangeFilter)
    : combinedFilterState;

  const backendFilterState = transformFiltersForBackend(
    filterState,
    OBSERVATION_COLUMN_TO_BACKEND_KEY,
    observationsFilterConfig.columnDefinitions,
  );

  const getCountPayload = {
    projectId,
    filter: backendFilterState,
    searchQuery,
    searchType,
    orderBy: null,
  };

  const getAllPayload = {
    ...getCountPayload,
    page: limitRows ? 0 : paginationState.pageIndex,
    limit: limitRows ?? paginationState.pageSize,
    orderBy,
  };

  const placeholderOptions = tablePlaceholderOptions({
    projectId,
    filter:
      externalFilterState ??
      queryFilter.effectiveFilterState.concat(
        promptNameFilter,
        promptVersionFilter,
        modelIdFilter,
      ),
    searchQuery,
    searchType,
    timeRange: externalDateRange ?? timeRange,
  });

  const generations = api.generations.all.useQuery(getAllPayload, {
    ...placeholderOptions,
    refetchOnWindowFocus: true,
  });
  const totalCountQuery = api.generations.countAll.useQuery(getCountPayload, {
    ...placeholderOptions,
    refetchOnWindowFocus: true,
  });
  const totalCount = totalCountQuery.data?.totalCount ?? null;

  const addToQueueMutation = api.annotationQueueItems.createMany.useMutation({
    onSuccess: (data, variables) => {
      if (variables.isBatchAction || data.createdCount > 0) {
        capture("annotation_queues:item_added", {
          type: "trace",
          source: "ObservationTable",
          targetType: "observation",
          objectType: "OBSERVATION",
          queueCount: 1,
          isV4: false,
          ...(variables.isBatchAction ? {} : { itemCount: data.createdCount }),
        });
      }
      showSuccessToast({
        operation: "observation.add_to_annotation_queue",
        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}"`,
        },
      });
    },
  });

  useEffect(() => {
    if (generations.isSuccess) {
      setDetailPageList(
        detailPageListKeys.observations,
        generations.data.generations.map((g) => ({
          id: g.id,
          params: {
            traceId: g.traceId || "",
            ...(g.traceTimestamp
              ? { timestamp: g.traceTimestamp.toISOString() }
              : {}),
            startTime: g.startTime.toISOString(),
          },
        })),
      );
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [generations.isSuccess, generations.data]);

  const { scoreColumns, isLoading: isColumnLoading } =
    useScoreColumns<ObservationsTableRow>({
      scoreColumnKey: "scores",
      projectId,
      filter: scoreFilters.forObservations(),
      fromTimestamp: dateRange?.from,
    });

  const { selectActionColumn } = TableSelectionManager<ObservationsTableRow>({
    projectId,
    tableName: "observations",
    setSelectedRows: observationsTableStore.getState().actions.setRowSelection,
    setSelectAll: observationsTableStore.getState().actions.setSelectAll,
    selectionStore: observationsTableStore,
  });

  const handleAddToAnnotationQueue = async ({
    projectId,
    targetId,
  }: {
    projectId: string;
    targetId: string;
  }) => {
    const {
      actions,
      selectAll,
      selectedPageRowIds: selectedGenerationIds,
    } = observationsTableStore.getState();

    await addToQueueMutation.mutateAsync({
      projectId,
      objectIds: selectedGenerationIds,
      objectType: AnnotationQueueObjectType.OBSERVATION,
      queueId: targetId,
      isBatchAction: selectAll,
      query: {
        filter: backendFilterState,
        orderBy,
      },
    });
    actions.clearSelection();
  };

  const tableActions: TableAction[] = [
    {
      id: ActionId.ObservationAddToAnnotationQueue,
      type: BatchActionType.Create,
      label: "Add to Annotation Queue",
      description: "Add selected observations to an annotation queue.",
      targetLabel: "Annotation Queue",
      execute: handleAddToAnnotationQueue,
      accessCheck: {
        scope: "annotationQueues:CUD",
      },
    },
    {
      id: ActionId.ObservationAddToDataset,
      type: BatchActionType.Create,
      label: "Add to Dataset",
      description: "Add selected observations to a dataset",
      customDialog: true,
      accessCheck: {
        scope: "datasets:CUD",
      },
    },
  ];

  const enableSorting = !hideControls;

  const columns: LangfuseColumnDef<ObservationsTableRow>[] = [
    ...(hideControls ? [] : [selectActionColumn]),
    createDateTableColumn<ObservationsTableRow>({
      accessorKey: "startTime",
      header: "Start Time",
      size: 150,
      enableHiding: true,
      enableSorting,
    }),
    createItemBadgeTableColumn<ObservationsTableRow>({
      accessorKey: "type",
      header: "Type",
      size: 50,
      enableSorting,
    }),
    createTextTableColumn<ObservationsTableRow>({
      accessorKey: "name",
      header: "Name",
      size: 150,
      enableSorting,
    }),
    {
      accessorKey: "input",
      header: "Input",
      id: "input",
      size: 300,
      cellBackground: "gray",
      loadingCell: () => (
        <ConnectedIOTableCell isLoading singleLine={compactRows} />
      ),
      cell: ({ row }) => {
        const observationId: string = row.getValue("id");
        const traceId: string = row.getValue("traceId");
        return (
          <GenerationsDynamicCell
            observationId={observationId}
            traceId={traceId}
            projectId={projectId}
            startTime={row.getValue("startTime")}
            col="input"
            singleLine={compactRows}
          />
        );
      },
      enableHiding: true,
    },
    {
      accessorKey: "output",
      id: "output",
      header: "Output",
      size: 300,
      cellBackground: "green",
      loadingCell: () => (
        <ConnectedIOTableCell isLoading singleLine={compactRows} />
      ),
      cell: ({ row }) => {
        const observationId: string = row.getValue("id");
        const traceId: string = row.getValue("traceId");
        return (
          <GenerationsDynamicCell
            observationId={observationId}
            traceId={traceId}
            projectId={projectId}
            startTime={row.getValue("startTime")}
            col="output"
            singleLine={compactRows}
          />
        );
      },
      enableHiding: true,
    },
    createTableColumn<ObservationsTableRow, ObservationLevelType>({
      accessorKey: "level",
      header: "Status",
      size: 100,
      headerTooltip: {
        description:
          "You can differentiate the importance of observations with the level attribute to control the verbosity of your traces and highlight errors and warnings.",
        href: "https://langfuse.com/docs/observability/features/log-levels",
      },
      enableHiding: true,
      enableSorting,
      loadingCell: <Skeleton className="h-5 w-16 shrink-0 rounded-sm" />,
      renderCell: (level) =>
        level ? <ObservationLevelTag level={level} /> : <EmptyValue />,
    }),
    createTextTableColumn<ObservationsTableRow>({
      accessorKey: "statusMessage",
      header: "Status Message",
      size: 150,
      headerTooltip: {
        description:
          "Use a statusMessage to e.g. provide additional information on a status such as level=ERROR.",
        href: "https://langfuse.com/docs/observability/features/log-levels",
      },
      enableHiding: true,
      defaultHidden: true,
    }),
    createDurationTableColumn<ObservationsTableRow>({
      accessorKey: "latency",
      header: "Latency",
      size: 100,
      enableHiding: true,
      enableSorting,
    }),
    {
      accessorKey: "totalCost",
      header: "Total Cost",
      id: "totalCost",
      size: 120,
      cell: ({ row }) => {
        const value: number | undefined = row.getValue("totalCost");
        const type = row.original.type;

        if (!isObservationCostDisplayable(value, type)) {
          return <span>{formatObservationCost(value, type)}</span>;
        }

        return (
          <BreakdownTooltip
            details={row.original.costDetails}
            isCost
            pricingTierName={row.original.usagePricingTierName ?? undefined}
          >
            <div className="flex items-center gap-1">
              <span>{usdFormatter(value)}</span>
              <InfoIcon size="sm" />
            </div>
          </BreakdownTooltip>
        );
      },
      enableHiding: true,
      enableSorting,
    },
    createNumberTableColumn<ObservationsTableRow>({
      accessorKey: "toolDefinitions",
      header: "Available Tools",
      size: 120,
      enableHiding: true,
      enableSorting,
      defaultHidden: true,
      formatter: (value) => numberFormatter(value, 0, 0),
    }),
    createNumberTableColumn<ObservationsTableRow>({
      accessorKey: "toolCalls",
      header: "Tool Calls",
      size: 100,
      enableHiding: true,
      enableSorting,
      defaultHidden: true,
      formatter: (value) => numberFormatter(value, 0, 0),
    }),
    {
      accessorKey: "timeToFirstToken",
      id: "timeToFirstToken",
      header: "Time to First Token",
      size: 150,
      enableHiding: true,
      enableSorting,
      cell: ({ row }) => {
        const timeToFirstToken: number | undefined =
          row.getValue("timeToFirstToken");

        return (
          <span>
            {timeToFirstToken ? (
              formatIntervalSeconds(timeToFirstToken)
            ) : (
              <EmptyValue />
            )}
          </span>
        );
      },
    },
    createTokenUsageTableColumn<
      ObservationsTableRow,
      ObservationsTableRow["usageDetails"]
    >({
      id: "tokens",
      accessorFn: (row) => row.usageDetails,
      header: "Tokens",
      size: 150,
      enableHiding: true,
      enableSorting,
      getCell: (value, { row }) => {
        const aggregatedUsage = calculateAggregatedUsage(value ?? {});
        return {
          type: "usage",
          inputUsage: aggregatedUsage.input,
          outputUsage: aggregatedUsage.output,
          totalUsage: aggregatedUsage.total,
          details: row.original.usageDetails,
          pricingTierName: row.original.usagePricingTierName ?? undefined,
        };
      },
    }),
    {
      accessorKey: "model",
      id: "model",
      header: "Model",
      size: 150,
      enableHiding: true,
      enableSorting,
      cell: ({ row }) => {
        const model = row.getValue("model") as string | null | undefined;
        const modelId = row.getValue("modelId") as string | undefined;

        return model ? (
          <ProvidedModelNameCell
            modelName={model}
            modelId={modelId}
            projectId={projectId}
            usageDetails={row.original.usageDetails}
          />
        ) : undefined;
      },
    },
    createIdTableColumn<ObservationsTableRow>({
      accessorKey: "promptName",
      header: "Prompt",
      headerTooltip: {
        description: "Link to prompt version in Langfuse prompt management.",
        href: "https://langfuse.com/docs/prompt-management/get-started",
      },
      size: 200,
      enableHiding: true,
      enableSorting,
      getValue: (_value, { row }) => {
        const promptName = row.original.promptName;
        const promptVersion = row.original.promptVersion;
        return promptName && promptVersion
          ? `${promptName} (v${promptVersion})`
          : undefined;
      },
    }),
    createTagTableColumn<ObservationsTableRow>({
      accessorKey: "environment",
      header: "Environment",
      size: 150,
      enableHiding: true,
    }),
    createTagsTableColumn<ObservationsTableRow>({
      accessorKey: "traceTags",
      header: "Trace Tags",
      size: 250,
      enableHiding: true,
      shouldWrap: !compactRows,
    }),
    {
      accessorKey: "metadata",
      header: "Metadata",
      size: 300,
      loadingCell: () => (
        <ConnectedIOTableCell isLoading singleLine={compactRows} />
      ),
      headerTooltip: {
        description: "Add metadata to traces to track additional information.",
        href: "https://langfuse.com/docs/observability/features/metadata",
      },
      cell: ({ row }) => {
        const observationId: string = row.getValue("id");
        const traceId: string = row.getValue("traceId");
        return (
          <GenerationsDynamicCell
            observationId={observationId}
            traceId={traceId}
            projectId={projectId}
            startTime={row.getValue("startTime")}
            col="metadata"
            singleLine={compactRows}
          />
        );
      },
      enableHiding: true,
    },
    {
      accessorKey: "scores",
      header: "Scores",
      id: "scores",
      enableHiding: true,
      defaultHidden: true,
      cell: () => {
        return isColumnLoading ? <Skeleton className="h-4 w-1/2" /> : null;
      },
      columns: scoreColumns,
    },
    createDateTableColumn<ObservationsTableRow>({
      accessorKey: "endTime",
      header: "End Time",
      size: 150,
      enableHiding: true,
      enableSorting,
      defaultHidden: true,
    }),
    createIdTableColumn<ObservationsTableRow>({
      accessorKey: "id",
      header: "ObservationID",
      size: 100,
      defaultHidden: true,
      enableSorting,
      enableHiding: true,
      getValue: (observationId, { row }) => {
        const traceId = row.getValue("traceId");
        return typeof observationId === "string" && typeof traceId === "string"
          ? observationId
          : undefined;
      },
    }),
    createTextTableColumn<ObservationsTableRow>({
      accessorKey: "traceName",
      header: "Trace Name",
      size: 150,
      enableHiding: true,
      enableSorting,
      defaultHidden: true,
    }),
    createIdTableColumn<ObservationsTableRow>({
      accessorKey: "traceId",
      header: "Trace ID",
      size: 100,
      enableSorting,
      enableHiding: true,
      defaultHidden: true,
    }),
    createIdTableColumn<ObservationsTableRow>({
      accessorKey: "modelId",
      header: "Model ID",
      size: 100,
      enableHiding: true,
      defaultHidden: true,
    }),
    createTextTableColumn<ObservationsTableRow>({
      accessorKey: "version",
      header: "Version",
      size: 100,
      headerTooltip: {
        description: "Track changes via the version tag.",
        href: "https://langfuse.com/docs/experimentation",
      },
      enableHiding: true,
      enableSorting,
      defaultHidden: true,
    }),
    {
      accessorKey: "usage",
      header: "Usage",
      id: "usage",
      enableHiding: true,
      defaultHidden: true,
      cell: () => {
        return generations.isPending ? (
          <Skeleton className="h-4 w-1/2" />
        ) : null;
      },
      columns: [
        createNumberTableColumn<ObservationsTableRow>({
          id: "tokensPerSecond",
          accessorFn: (row) => {
            if (!row.latency || !row.usage.outputUsage) return null;
            return row.usage.outputUsage / row.latency;
          },
          header: "Tokens per second",
          size: 200,
          formatter: (value) => numberFormatter(value, 0, 1),
          defaultHidden: true,
          enableHiding: true,
          enableSorting,
        }),
        createNumberTableColumn<ObservationsTableRow>({
          accessorFn: (row) => row.usage.inputUsage,
          id: "inputTokens",
          header: "Input Tokens",
          size: 100,
          enableHiding: true,
          defaultHidden: true,
          enableSorting,
          formatter: (value) => numberFormatter(value, 0),
        }),
        createNumberTableColumn<ObservationsTableRow>({
          accessorFn: (row) => row.usage.outputUsage,
          id: "outputTokens",
          header: "Output Tokens",
          size: 100,
          enableHiding: true,
          defaultHidden: true,
          enableSorting,
          formatter: (value) => numberFormatter(value, 0),
        }),
        createNumberTableColumn<ObservationsTableRow>({
          accessorFn: (row) => row.usage.totalUsage,
          id: "totalTokens",
          header: "Total Tokens",
          size: 100,
          enableHiding: true,
          defaultHidden: true,
          enableSorting,
          formatter: (value) => numberFormatter(value, 0),
        }),
      ] satisfies LangfuseColumnDef<ObservationsTableRow>[],
    },
    {
      accessorKey: "cost",
      header: "Cost",
      id: "cost",
      enableHiding: true,
      defaultHidden: true,
      cell: () => {
        return generations.isPending ? (
          <Skeleton className="h-4 w-1/2" />
        ) : null;
      },
      columns: [
        createNumberTableColumn<ObservationsTableRow>({
          accessorFn: (row) => row.cost.inputCost,
          id: "inputCost",
          header: "Input Cost",
          size: 120,
          formatter: (value, { row }) =>
            formatObservationCost(value, row.original.type),
          enableHiding: true,
          defaultHidden: true,
          enableSorting,
        }),
        createNumberTableColumn<ObservationsTableRow>({
          accessorFn: (row) => row.cost.outputCost,
          id: "outputCost",
          header: "Output Cost",
          size: 120,
          formatter: (value, { row }) =>
            formatObservationCost(value, row.original.type),
          enableHiding: true,
          defaultHidden: true,
          enableSorting,
        }),
      ] satisfies LangfuseColumnDef<ObservationsTableRow>[],
    },
  ];

  const [columnVisibility, setColumnVisibilityState] =
    useColumnVisibility<ObservationsTableRow>(
      `observationColumnVisibility-${projectId}`,
      columns,
    );

  const [columnOrder, setColumnOrder] = useColumnOrder<ObservationsTableRow>(
    `observationsColumnOrder-${projectId}`,
    columns,
  );

  const peekNavigationProps = usePeekNavigation({
    queryParams: [
      "observation",
      "display",
      "timestamp",
      "traceId",
      "startTime",
    ],
    tableName: observationsFilterConfig.tableName,
    isV4: false,
    paramsToMirrorPeekValue: ["observation"],
    extractParamsValuesFromRow: (row: ObservationsTableRow) => ({
      traceId: row.traceId || "",
      timestamp: row.timestamp?.toISOString() || "",
      startTime: row.startTime.toISOString(),
    }),
    expandConfig: {
      basePath: `/project/${projectId}/traces`,
      pathParam: "traceId",
    },
  });

  const { isLoading: isViewLoading, ...viewControllers } = useTableViewManager({
    tableName: TableViewPresetTableName.Observations,
    projectId,
    stateUpdaters: {
      setOrderBy: setOrderByState,
      setFilters: setSavedViewFilters,
      setExpandedFilters: queryFilter.onExpandedChange,
      setColumnOrder: setColumnOrder,
      setColumnVisibility: setColumnVisibilityState,
      setSearchQuery: setSearchQuery,
    },
    validationContext: {
      columns,
      filterColumnDefinition: observationsFilterConfig.columnDefinitions,
      expandableFilterColumns: observationsFilterConfig.facets.map(
        (facet) => facet.column,
      ),
    },
    currentFilterState: queryFilter.explicitFilterState,
    currentExpandedFilters: queryFilter.expanded,
    disabled: hideControls,
    onViewSelected: () => {
      setPaginationState({ ...paginationState, pageIndex: 0 });
      observationsTableStore.getState().actions.clearSelection();
    },
  });
  viewControllersRef.current = viewControllers;

  const handleSearchQueryChange = (nextQuery: string | null) => {
    viewControllers.handleUserStateChange(searchQuery ?? "", nextQuery ?? "");
    setSearchQuery(nextQuery);
  };
  const handleSearchTypeChange = (nextType: TracingSearchType[]) => {
    if (searchQuery?.trim()) {
      viewControllers.handleUserStateChange(
        [...searchType].sort(),
        [...nextType].sort(),
      );
    }
    setSearchType(nextType);
  };
  const handleOrderByChange: typeof setOrderByState = (nextOrderBy) => {
    viewControllers.handleUserStateChange(orderByState, nextOrderBy);
    setOrderByState(nextOrderBy);
  };
  const handleColumnOrderChange: typeof setColumnOrder = (updater) => {
    const next = typeof updater === "function" ? updater(columnOrder) : updater;
    viewControllers.handleUserStateChange(columnOrder, next);
    setColumnOrder(next);
  };
  const handleColumnVisibilityChange: typeof setColumnVisibilityState = (
    updater,
  ) => {
    const next =
      typeof updater === "function" ? updater(columnVisibility) : updater;
    viewControllers.handleUserStateChange(columnVisibility, next);
    setColumnVisibilityState(next);
  };

  const peekConfig: DataTablePeekViewProps | undefined = useMemo(() => {
    if (hideControls) return undefined;
    return {
      itemType: "TRACE",
      detailNavigationKey: detailPageListKeys.observations,
      ...peekNavigationProps,
    };
  }, [peekNavigationProps, hideControls]);

  const rows: ObservationsTableRow[] = useMemo(() => {
    return generations.isSuccess
      ? generations.data.generations.map((generation) => {
          return {
            id: generation.id,
            traceId: generation.traceId ?? undefined,
            type: generation.type ?? undefined,
            traceName: generation.traceName ?? "",
            startTime: generation.startTime,
            endTime: generation.endTime ?? undefined,
            timeToFirstToken: generation.timeToFirstToken ?? undefined,
            scores: generation.scores,
            latency: generation.latency ?? undefined,
            totalCost: generation.totalCost ?? undefined,
            cost: {
              inputCost: generation.inputCost ?? undefined,
              outputCost: generation.outputCost ?? undefined,
            },
            name: generation.name ?? undefined,
            version: generation.version ?? "",
            model: generation.model ?? "",
            modelId: generation.internalModelId ?? undefined,
            level: generation.level,
            statusMessage: generation.statusMessage ?? undefined,
            usage: {
              inputUsage: generation.inputUsage,
              outputUsage: generation.outputUsage,
              totalUsage: generation.totalUsage,
            },
            promptId: generation.promptId ?? undefined,
            promptName: generation.promptName ?? undefined,
            promptVersion: generation.promptVersion?.toString() ?? undefined,
            traceTags: generation.traceTags ?? undefined,
            timestamp: generation.traceTimestamp ?? undefined,
            usageDetails: generation.usageDetails ?? {},
            costDetails: generation.costDetails ?? {},
            usagePricingTierName: generation.usagePricingTierName ?? undefined,
            environment: generation.environment ?? undefined,
            toolDefinitions: generation.toolDefinitionsCount ?? undefined,
            toolCalls: generation.toolCallsCount ?? undefined,
          };
        })
      : [];
  }, [generations]);

  const pageRowIds = useMemo(() => rows.map((row) => row.id), [rows]);

  // Layout effect so store-subscribed consumers (toolbar count) update before
  // paint when the page rows change — no one-frame stale selection count.
  useLayoutEffect(() => {
    observationsTableStore.getState().actions.syncPageRows({
      pageRowIds,
      totalCount,
    });
  }, [observationsTableStore, pageRowIds, totalCount]);

  const refreshConfig = {
    onRefresh: handleRefresh,
    isRefreshing: generations.isFetching || totalCountQuery.isFetching,
    interval: refreshInterval,
    setInterval: setRefreshInterval,
  };

  const content = (
    <>
      {showControlsInPageHeader && !hideControls && (
        <TableHeaderControls
          timeRange={timeRange}
          setTimeRange={setTimeRange}
          refresh={refreshConfig}
        />
      )}
      <div className="flex h-full w-full flex-col">
        <SearchableTableFilterLayout
          search={
            !hideControls ? (
              <TableSearchBar
                size={showControlsInPageHeader ? "large" : "default"}
                key={`${viewControllers.filterEditorResetKey}-${queryFilter.draftResetKey}`}
                projectId={projectId}
                tableName={observationsFilterConfig.tableName}
                registry={searchRegistry}
                filterState={queryFilter.searchBarFilterState}
                setFilterState={queryFilter.setFilterState}
                observed={observedOptions}
                isV4={false}
                search={{
                  query: searchQuery,
                  type: searchType,
                  setQuery: handleSearchQueryChange,
                  setType: handleSearchTypeChange,
                }}
              />
            ) : null
          }
          toolbar={
            !hideControls ? (
              <ObservationsDataTableToolbar
                rowClassName="my-1"
                isV4={false}
                columns={columns}
                filterState={queryFilter.explicitFilterState}
                viewConfig={{
                  tableName: TableViewPresetTableName.Observations,
                  projectId,
                  controllers: viewControllers,
                }}
                currentSearchQuery={searchQuery ?? ""}
                columnsWithCustomSelect={[
                  "model",
                  "name",
                  "traceName",
                  "promptName",
                ]}
                columnVisibility={columnVisibility}
                setColumnVisibility={handleColumnVisibilityChange}
                columnOrder={columnOrder}
                setColumnOrder={handleColumnOrderChange}
                orderByState={orderBy}
                rowHeight={rowHeight}
                setRowHeight={setRowHeight}
                customRowHeight={customRowHeightMenu(rowHeights)}
                timeRange={showControlsInPageHeader ? undefined : timeRange}
                setTimeRange={
                  showControlsInPageHeader ? undefined : setTimeRange
                }
                refreshConfig={
                  showControlsInPageHeader ? undefined : refreshConfig
                }
                projectId={projectId}
                backendFilterState={backendFilterState}
                searchQuery={searchQuery}
                searchType={searchType}
                tableActions={tableActions}
                totalCount={totalCount}
                paginationState={paginationState}
              />
            ) : null
          }
        >
          {!hideControls && (
            <DataTableControls
              key={`${viewControllers.filterEditorResetKey}-${queryFilter.draftResetKey}`}
              queryFilter={queryFilter}
            />
          )}

          <div className="flex flex-1 flex-col overflow-hidden">
            <DataTable
              tableName="observations"
              columns={columns}
              peekView={peekConfig}
              selectionStore={observationsTableStore}
              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={
                limitRows
                  ? undefined
                  : {
                      totalCount,
                      onChange: setPaginationState,
                      state: paginationState,
                      options: TRACING_PAGE_SIZE_OPTIONS,
                    }
              }
              setOrderBy={handleOrderByChange}
              orderBy={orderBy}
              columnOrder={columnOrder}
              onColumnOrderChange={handleColumnOrderChange}
              columnVisibility={columnVisibility}
              onColumnVisibilityChange={handleColumnVisibilityChange}
              rowHeight={rowHeight}
              customRowHeightPx={
                hideControls ? undefined : rowHeights.activeHeightPx
              }
              onCustomRowHeightChange={
                hideControls ? undefined : rowHeights.setCustomPx
              }
              onSelectRowHeight={hideControls ? undefined : setRowHeight}
              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) {
                    const observationUrl = buildTracePath({
                      projectId,
                      traceId,
                      observationId,
                      timestamp,
                    });

                    window.open(
                      getSafeRedirectPath(observationUrl),
                      "_blank",
                      "noopener,noreferrer",
                    );
                  }
                }
                // For normal clicks, let the data-table handle opening the peek view
              }}
            />
          </div>
        </SearchableTableFilterLayout>
        {peekConfig && (
          <TablePeekViewObservationDetail
            {...peekConfig}
            projectId={projectId}
          />
        )}
      </div>

      {showAddToDatasetDialog && (
        <ObservationsAddToDatasetDialog
          projectId={projectId}
          rows={rows}
          backendFilterState={backendFilterState}
          orderByState={orderBy}
          searchQuery={searchQuery}
          searchType={searchType}
          totalCount={totalCount}
        />
      )}
    </>
  );

  return (
    <DataTableControlsProvider tableName={observationsFilterConfig.tableName}>
      <ObservationsTableStoreProvider store={observationsTableStore}>
        {content}
      </ObservationsTableStoreProvider>
    </DataTableControlsProvider>
  );
}

type ObservationsDataTableToolbarProps = Omit<
  Parameters<typeof DataTableToolbar<ObservationsTableRow, unknown>>[0],
  "actionButtons" | "multiSelect"
> & {
  backendFilterState: FilterState;
  orderByState: OrderByState;
  paginationState: {
    pageIndex: number;
    pageSize: number;
  };
  projectId: string;
  searchQuery: string | null;
  searchType: TracingSearchType[];
  tableActions: TableAction[];
  totalCount: number | null;
};

function ObservationsDataTableToolbar({
  backendFilterState,
  orderByState,
  paginationState,
  projectId,
  searchQuery,
  searchType,
  tableActions,
  totalCount,
  ...toolbarProps
}: ObservationsDataTableToolbarProps) {
  const hasBatchExportAccess = useHasProjectAccess({
    projectId,
    scope: "batchExports:create",
  });
  const selectedObservationIds = useObservationsTableStore(
    (state) => state.selectedPageRowIds,
  );
  const selectAll = useObservationsTableStore((state) => state.selectAll);
  const actions = useObservationsTableStore((state) => state.actions);
  const selectedObservationCount = selectAll
    ? totalCount
    : selectedObservationIds.length;

  return (
    <DataTableToolbar
      tableName="observations"
      {...toolbarProps}
      orderByState={orderByState}
      actionButtons={[
        hasBatchExportAccess ? (
          <BatchExportTableButton
            {...{
              projectId,
              filterState: backendFilterState,
              orderByState,
              searchQuery,
              searchType,
            }}
            tableName={BatchExportTableName.Observations}
            key="batchExport"
          />
        ) : null,
        selectedObservationIds.length > 0 || selectAll ? (
          <TableActionMenu
            key="observations-multi-select-actions"
            projectId={projectId}
            actions={tableActions}
            tableName={BatchExportTableName.Observations}
            selectedCount={selectedObservationCount}
            onClearSelection={actions.clearSelection}
            onCustomAction={(actionType) => {
              if (actionType === ActionId.ObservationAddToDataset) {
                actions.setShowAddToDatasetDialog(true);
              }
            }}
          />
        ) : null,
      ]}
      multiSelect={{
        selectAll,
        setSelectAll: actions.setSelectAll,
        selectedRowIds: selectedObservationIds,
        setRowSelection: actions.setRowSelection,
        totalCount,
        ...paginationState,
      }}
    />
  );
}

function ObservationsAddToDatasetDialog({
  backendFilterState,
  orderByState,
  projectId,
  rows,
  searchQuery,
  searchType,
  totalCount,
}: {
  backendFilterState: FilterState;
  orderByState: OrderByState;
  projectId: string;
  rows: ObservationsTableRow[];
  searchQuery: string | null;
  searchType: TracingSearchType[];
  totalCount: number | null;
}) {
  const selectedObservationIds = useObservationsTableStore(
    (state) => state.selectedPageRowIds,
  );
  const selectAll = useObservationsTableStore((state) => state.selectAll);
  const actions = useObservationsTableStore((state) => state.actions);

  const firstId = selectedObservationIds[0];
  const firstRow = rows.find((row) => row.id === firstId);

  return (
    <AddObservationsToDatasetDialog
      isV4={false}
      projectId={projectId}
      selectedObservationIds={selectedObservationIds}
      query={{
        filter: backendFilterState,
        orderBy: orderByState,
        searchQuery: searchQuery ?? undefined,
        searchType,
      }}
      selectAll={selectAll}
      totalCount={totalCount ?? 0}
      onClose={() => {
        actions.setShowAddToDatasetDialog(false);
      }}
      onSuccess={actions.clearSelection}
      exampleObservation={{
        id: firstRow?.id ?? "",
        traceId: firstRow?.traceId ?? "",
        startTime: firstRow?.timestamp ?? undefined,
      }}
    />
  );
}

const GenerationsDynamicCell = ({
  traceId,
  observationId,
  projectId,
  startTime,
  col,
  singleLine = false,
}: {
  traceId: string;
  observationId: string;
  projectId: string;
  startTime?: Date;
  col: "input" | "output" | "metadata";
  singleLine: boolean;
}) => {
  const observation = api.observations.byId.useQuery(
    {
      observationId,
      traceId,
      projectId,
      startTime,
      verbosity: "compact",
    },
    {
      enabled: typeof traceId === "string" && typeof observationId === "string",
      refetchOnMount: false, // prevents refetching loops
      staleTime: 60 * 1000, // 1 minute
      meta: { silentHttpCodes: [404] },
    },
  );

  const data = (() => {
    if (col === "output") {
      return observation.data?.output;
    }
    if (col === "input") {
      return observation.data?.input;
    }
    return observation.data?.metadata;
  })();

  if (observation.isPending) {
    return <ConnectedIOTableCell isLoading singleLine={singleLine} />;
  }

  return <ConnectedIOTableCell data={data} singleLine={singleLine} />;
};