Skip to content

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

chore(peek): remove polling logic and dependency on table state from peek implementation (#8885)

marliessophiea7e3dec6f0e0
diff --git a/web/src/components/table/data-table.tsx b/web/src/components/table/data-table.tsx
index 8dbf3fbf8d..3a8dafd438 100644
--- a/web/src/components/table/data-table.tsx
+++ b/web/src/components/table/data-table.tsx
@@ -40,9 +40,10 @@ import {
type VisibilityState,
type Row,
} from "@tanstack/react-table";
-import { TablePeekView } from "@/src/components/table/peek";
-import { type PeekViewProps } from "@/src/components/table/peek/hooks/usePeekView";
-import { usePeekView } from "@/src/components/table/peek/hooks/usePeekView";
+import {
+ type DataTablePeekViewProps,
+ TablePeekView,
+} from "@/src/components/table/peek";
import { isEqual } from "lodash";
import { useRouter } from "next/router";
import { useColumnSizing } from "@/src/components/table/hooks/useColumnSizing";
@@ -70,7 +71,7 @@ interface DataTableProps<TData, TValue> {
className?: string;
shouldRenderGroupHeaders?: boolean;
onRowClick?: (row: TData) => void;
- peekView?: PeekViewProps<TData>;
+ peekView?: DataTablePeekViewProps;
hidePagination?: boolean;
tableName: string;
getRowClassName?: (row: TData) => string;
@@ -235,27 +236,14 @@ export function DataTable<TData extends object, TValue>({
columnResizeMode: "onChange",
});
- const getRowMemoized = useCallback(
- (id: string) => table.getRow(id)?.original,
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const {
- row: peekRow,
- handleOnRowClickPeek,
- peekViewId,
- } = usePeekView({
- getRow: getRowMemoized,
- peekView,
- });
-
const handleOnRowClick = useCallback(
(row: TData) => {
- handleOnRowClickPeek?.(row);
+ if ("id" in row && typeof row.id === "string") {
+ peekView?.openPeek(row.id, row);
+ }
onRowClick?.(row);
},
- [handleOnRowClickPeek, onRowClick],
+ [peekView, onRowClick],
);
const hasRowClickAction = !!onRowClick || !!peekView;
@@ -414,6 +402,7 @@ export function DataTable<TData extends object, TValue>({
data={data}
help={help}
onRowClick={hasRowClickAction ? handleOnRowClick : undefined}
+ getRowClassName={getRowClassName}
tableSnapshot={{
tableDataUpdatedAt: peekView?.tableDataUpdatedAt,
columnVisibility,
@@ -436,13 +425,7 @@ export function DataTable<TData extends object, TValue>({
</div>
<div className="grow"></div>
</div>
- {peekView && (
- <TablePeekView
- peekView={peekView}
- row={peekRow}
- selectedRowId={peekViewId}
- />
- )}
+ {peekView && <TablePeekView peekView={peekView} />}
{!hidePagination && pagination !== undefined ? (
<div
className={cn(
@@ -500,6 +483,7 @@ function TableRowComponent<TData>({
}) {
const router = useRouter();
const selectedRowId = router.query.peek as string | undefined;
+
return (
<TableRow
data-row-index={row.index}
diff --git a/web/src/components/table/peek.tsx b/web/src/components/table/peek.tsx
index df6c18d08a..89e75c92d5 100644
--- a/web/src/components/table/peek.tsx
+++ b/web/src/components/table/peek.tsx
@@ -12,7 +12,7 @@ import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNa
import { type ListEntry } from "@/src/features/navigate-detail-pages/context";
import { cn } from "@/src/utils/tailwind";
import { memo } from "react";
-import { type PeekViewProps } from "@/src/components/table/peek/hooks/usePeekView";
+import { useRouter } from "next/router";
type PeekViewItemType = Extract<
LangfuseItemType,
@@ -25,52 +25,49 @@ type PeekViewItemType = Extract<
*/
export type PeekEventControlOptions = {
ignoredSelectors?: string[];
- customCheck?: (event?: Event) => boolean;
};
/**
* Configuration for a data table peek view.
*/
-export type DataTablePeekViewProps<TData> = {
+export type DataTablePeekViewProps = {
// Core identification
/** The type of item being peeked at */
itemType: PeekViewItemType;
/** Key used for detail page navigation */
- listKey?: string;
+ detailNavigationKey?: string;
/** Custom prefix for the peek view title */
customTitlePrefix?: string;
// Navigation and URL handling
- /** Function to get navigation path for a list entry */
- getNavigationPath?: (entry: ListEntry) => string;
- /** Whether to update the row when the peekViewId changes on detail page navigation. Defaults to false. */
- shouldUpdateRowOnDetailPageNavigation?: boolean;
+ /** Function to resolve the navigation path for a list entry */
+ resolveDetailNavigationPath?: (entry: ListEntry) => string;
// Event handlers
- /** Called when the peek view is opened or closed */
- onOpenChange: (open: boolean, id?: string, timestamp?: string) => void;
+ /** Called to open the peek view*/
+ openPeek: (id?: string, row?: any) => void;
+ /** Called to close the peek view*/
+ closePeek: () => void;
/** Called when the peek view is expanded to full view */
- onExpand?: (openInNewTab: boolean, row?: TData) => void;
+ expandPeek?: (openInNewTab: boolean) => void;
/** Additional peek event options */
peekEventOptions?: PeekEventControlOptions;
// Content
/**
* The content to display in the peek view.
- * Can be either a React node or a function that receives the row data and returns a React node.
*/
- children: React.ReactNode | ((row?: TData) => React.ReactNode);
+ children: React.ReactNode;
+
+ /** The timestamp of the last time the table data was updated */
+ tableDataUpdatedAt: number;
};
export const createPeekEventHandler = (options?: PeekEventControlOptions) => {
if (!options) return () => false;
- const { ignoredSelectors = [], customCheck } = options;
+ const { ignoredSelectors = [] } = options;
return (): boolean => {
- if (customCheck?.()) {
- return true;
- }
-
for (const selector of ignoredSelectors) {
if (document.activeElement?.closest(selector)) {
return true;
@@ -81,37 +78,28 @@ export const createPeekEventHandler = (options?: PeekEventControlOptions) => {
};
};
-type TablePeekViewProps<T> = {
- peekView: PeekViewProps<T>;
- row?: T;
- selectedRowId?: string | null;
+type TablePeekViewProps = {
+ peekView: DataTablePeekViewProps;
};
-function TablePeekViewComponent<TData>(props: TablePeekViewProps<TData>) {
- const { peekView, row, selectedRowId } = props;
+function TablePeekViewComponent(props: TablePeekViewProps) {
+ const { peekView } = props;
+ const router = useRouter();
const eventHandler = createPeekEventHandler(peekView.peekEventOptions);
+ const itemId = router.query.peek as string | undefined;
- if (!selectedRowId) return null;
+ if (!itemId) return null;
const handleOpenChange = (open: boolean) => {
- if (!open && eventHandler()) {
- return;
- }
- if (!!row && typeof row === "object" && "timestamp" in row) {
- peekView.onOpenChange(
- open,
- selectedRowId,
- (row as any).timestamp.toISOString(),
- );
- } else {
- peekView.onOpenChange(open, selectedRowId);
- }
+ // Note: Only handles close events as open events are handled by user clicking on a row in the table or navigating via detail page navigation
+ if (open || eventHandler()) return;
+ peekView.closePeek();
};
- const canExpand = typeof peekView.onExpand === "function";
+ const canExpand = typeof peekView.expandPeek === "function";
return (
- <Sheet open={!!selectedRowId} onOpenChange={handleOpenChange} modal={false}>
+ <Sheet open={!!itemId} onOpenChange={handleOpenChange} modal={false}>
<SheetContent
onPointerDownOutside={(e) => {
// Prevent the default behavior of closing when clicking outside when we set modal={false}
@@ -128,8 +116,8 @@ function TablePeekViewComponent<TData>(props: TablePeekViewProps<TData>) {
tabIndex={0}
>
{peekView.customTitlePrefix
- ? `${peekView.customTitlePrefix} ${selectedRowId}`
- : selectedRowId}
+ ? `${peekView.customTitlePrefix} ${itemId}`
+ : itemId}
</span>
</SheetTitle>
<div
@@ -138,13 +126,13 @@ function TablePeekViewComponent<TData>(props: TablePeekViewProps<TData>) {
!canExpand && "mr-8",
)}
>
- {selectedRowId &&
- peekView.listKey &&
- peekView.getNavigationPath && (
+ {itemId &&
+ peekView.detailNavigationKey &&
+ peekView.resolveDetailNavigationPath && (
<DetailPageNav
- currentId={selectedRowId}
- path={peekView.getNavigationPath}
- listKey={peekView.listKey}
+ currentId={itemId}
+ path={peekView.resolveDetailNavigationPath}
+ listKey={peekView.detailNavigationKey}
/>
)}
{canExpand && (
@@ -154,7 +142,7 @@ function TablePeekViewComponent<TData>(props: TablePeekViewProps<TData>) {
size="icon-xs"
title="Open in current tab"
className="ml-2"
- onClick={() => peekView.onExpand?.(false, row)}
+ onClick={() => peekView.expandPeek?.(false)}
>
<Expand className="h-4 w-4" />
</Button>
@@ -162,7 +150,7 @@ function TablePeekViewComponent<TData>(props: TablePeekViewProps<TData>) {
variant="ghost"
size="icon-xs"
title="Open in new tab"
- onClick={() => peekView.onExpand?.(true, row)}
+ onClick={() => peekView.expandPeek?.(true)}
>
<ExternalLink className="h-4 w-4" />
</Button>
@@ -172,10 +160,8 @@ function TablePeekViewComponent<TData>(props: TablePeekViewProps<TData>) {
</SheetHeader>
<Separator />
<div className="flex max-h-full min-h-0 flex-1 flex-col">
- <div className="flex-1 overflow-auto" key={selectedRowId}>
- {typeof peekView.children === "function"
- ? peekView.children(row)
- : peekView.children}
+ <div className="flex-1 overflow-auto" key={itemId}>
+ {peekView.children}
</div>
</div>
</SheetContent>
@@ -184,5 +170,6 @@ function TablePeekViewComponent<TData>(props: TablePeekViewProps<TData>) {
}
export const TablePeekView = memo(TablePeekViewComponent, (prev, next) => {
- return prev.selectedRowId === next.selectedRowId && !!prev.row && !!next.row;
+ // TODO LFE-6627: drop tableDataUpdatedAt and allow memoization to work independently of table data updates
+ return prev.peekView.tableDataUpdatedAt === next.peekView.tableDataUpdatedAt;
}) as typeof TablePeekViewComponent;
diff --git a/web/src/components/table/peek/hooks/useDatasetComparePeekNavigation.ts b/web/src/components/table/peek/hooks/useDatasetComparePeekNavigation.ts
deleted file mode 100644
index 66f3075463..0000000000
--- a/web/src/components/table/peek/hooks/useDatasetComparePeekNavigation.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { type ListEntry } from "@/src/features/navigate-detail-pages/context";
-import { getPathnameWithoutBasePath } from "@/src/utils/api";
-
-export const useDatasetComparePeekNavigation = () => {
- const getNavigationPath = (entry: ListEntry) => {
- const url = new URL(window.location.href);
- const pathname = getPathnameWithoutBasePath();
-
- // Update the path part
- url.pathname = pathname;
-
- // Keep all existing query params
- const params = new URLSearchParams(url.search);
-
- // Update peek param to the new id
- params.set("peek", entry.id);
-
- // Set the search part of the URL
- return `${url.pathname}?${params.toString()}`;
- };
-
- return { getNavigationPath, shouldUpdateRowOnDetailPageNavigation: true };
-};
diff --git a/web/src/components/table/peek/hooks/useDatasetComparePeekState.ts b/web/src/components/table/peek/hooks/useDatasetComparePeekState.ts
deleted file mode 100644
index 514a07ce74..0000000000
--- a/web/src/components/table/peek/hooks/useDatasetComparePeekState.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { useRouter } from "next/router";
-import { useCallback, useState } from "react";
-import { getPathnameWithoutBasePath } from "@/src/utils/api";
-
-export const useDatasetComparePeekState = () => {
- const router = useRouter();
- const { peek: datasetItem } = router.query;
-
- const [selectedRunItemProps, setSelectedRunItemProps] = useState<{
- runId: string;
- traceId: string;
- observationId?: string;
- } | null>(null);
-
- const setPeekView = useCallback(
- (open: boolean, itemId?: string) => {
- const url = new URL(window.location.href);
- const params = new URLSearchParams(url.search);
- const pathname = getPathnameWithoutBasePath();
-
- if (!open || !itemId) {
- // close peek view
- params.delete("peek");
- } else if (open && itemId !== datasetItem) {
- // open peek view or update peek view
- params.set("peek", itemId);
- } else {
- return;
- }
-
- router.push(
- {
- pathname,
- query: params.toString(),
- },
- undefined,
- { shallow: true },
- );
- },
- [router, datasetItem],
- );
-
- return {
- datasetItemId: datasetItem as string | undefined,
- selectedRunItemProps,
- setSelectedRunItemProps,
- setPeekView,
- };
-};
diff --git a/web/src/components/table/peek/hooks/useEvalTemplatesPeekNavigation.ts b/web/src/components/table/peek/hooks/useEvalTemplatesPeekNavigation.ts
deleted file mode 100644
index 3b8946853b..0000000000
--- a/web/src/components/table/peek/hooks/useEvalTemplatesPeekNavigation.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { type EvalsTemplateRow } from "@/src/features/evals/components/eval-templates-table";
-import { type ListEntry } from "@/src/features/navigate-detail-pages/context";
-import { useRouter } from "next/router";
-import { getPathnameWithoutBasePath } from "@/src/utils/api";
-
-export const useEvalTemplatesPeekNavigation = () => {
- const router = useRouter();
- const { projectId, peek } = router.query;
-
- const getNavigationPath = (entry: ListEntry) => {
- const url = new URL(window.location.href);
- const pathname = getPathnameWithoutBasePath();
-
- // Update the path part
- url.pathname = pathname;
-
- // Keep all existing query params
- const params = new URLSearchParams(url.search);
-
- // Update peek param to the new id
- params.set("peek", entry.id);
-
- // Set the search part of the URL
- return `${url.pathname}?${params.toString()}`;
- };
-
- const expandPeek = (openInNewTab: boolean, row?: EvalsTemplateRow) => {
- if (!row) return;
- const pathname = `/project/${projectId}/evals/templates/${encodeURIComponent(peek as string)}`;
-
- if (openInNewTab) {
- const pathnameWithBasePath = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${pathname}`;
- window.open(pathnameWithBasePath, "_blank");
- } else {
- router.push(pathname);
- }
- };
-
- return { getNavigationPath, expandPeek };
-};
diff --git a/web/src/components/table/peek/hooks/useObservationPeekNavigation.ts b/web/src/components/table/peek/hooks/useObservationPeekNavigation.ts
deleted file mode 100644
index ee995ae2bb..0000000000
--- a/web/src/components/table/peek/hooks/useObservationPeekNavigation.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { type ListEntry } from "@/src/features/navigate-detail-pages/context";
-import { useRouter } from "next/router";
-import { type ObservationsTableRow } from "@/src/components/table/use-cases/observations";
-import { getPathnameWithoutBasePath } from "@/src/utils/api";
-
-export const useObservationPeekNavigation = () => {
- const router = useRouter();
- const { projectId, peek } = router.query;
-
- const getNavigationPath = (entry: ListEntry) => {
- const url = new URL(window.location.href);
- const pathname = getPathnameWithoutBasePath();
-
- // Update the path part
- url.pathname = pathname;
-
- // Keep all existing query params
- const params = new URLSearchParams(url.search);
-
- // Update timestamp if it exists in entry.params
- if (entry.params) {
- if (entry.params.timestamp)
- params.set("timestamp", encodeURIComponent(entry.params.timestamp));
- params.delete("observation");
- }
-
- // Update peek param to the new id
- params.set("peek", entry.id);
- params.set("observation", entry.id);
-
- // Set the search part of the URL
- return `${url.pathname}?${params.toString()}`;
- };
-
- const expandPeek = (openInNewTab: boolean, row?: ObservationsTableRow) => {
- const url = new URL(window.location.href);
- const params = new URLSearchParams(url.search);
- const timestamp = params.get("timestamp");
- const display = params.get("display") ?? "details";
-
- if (!row) return;
-
- const pathname = `/project/${projectId}/traces/${encodeURIComponent(row.traceId as string)}?timestamp=${timestamp}&display=${display}&observation=${peek as string}`;
-
- if (openInNewTab) {
- const pathnameWithBasePath = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${pathname}`;
- window.open(pathnameWithBasePath, "_blank");
- } else {
- router.push(pathname);
- }
- };
-
- return { getNavigationPath, expandPeek };
-};
diff --git a/web/src/components/table/peek/hooks/useObservationPeekState.ts b/web/src/components/table/peek/hooks/useObservationPeekState.ts
deleted file mode 100644
index 67a39739d9..0000000000
--- a/web/src/components/table/peek/hooks/useObservationPeekState.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { useRouter } from "next/router";
-import { useCallback } from "react";
-import { getPathnameWithoutBasePath } from "@/src/utils/api";
-
-export const useObservationPeekState = () => {
- const router = useRouter();
- const { peek, timestamp } = router.query;
-
- const setPeekView = useCallback(
- (open: boolean, id?: string, time?: string) => {
- const url = new URL(window.location.href);
- const params = new URLSearchParams(url.search);
- const pathname = getPathnameWithoutBasePath();
-
- if (!open || !id) {
- // close peek view
- params.delete("observation");
- params.delete("peek");
- params.delete("timestamp");
- params.delete("display");
- } else if (open && id !== peek) {
- // open peek view or update peek view
- params.set("observation", id);
- params.set("peek", id);
- const relevantTimestamp = time ?? (timestamp as string);
- if (relevantTimestamp) params.set("timestamp", relevantTimestamp);
- } else {
- return;
- }
-
- router.push(
- {
- pathname,
- query: params.toString(),
- },
- undefined,
- { shallow: true },
- );
- },
- [router, peek, timestamp],
- );
-
- return {
- peekId: peek as string | undefined,
- timestamp: timestamp ? new Date(timestamp as string) : undefined,
- setPeekView,
- };
-};
diff --git a/web/src/components/table/peek/hooks/usePeekCompareDetail.ts b/web/src/components/table/peek/hooks/usePeekCompareDetail.ts
new file mode 100644
index 0000000000..2e4e01371e
--- /dev/null
+++ b/web/src/components/table/peek/hooks/usePeekCompareDetail.ts
@@ -0,0 +1,60 @@
+import { useRouter } from "next/router";
+import { useState, useCallback } from "react";
+
+export function usePeekCompareDetail(projectId: string) {
+ const [collapsedNodes, setCollapsedNodes] = useState<string[]>([]);
+
+ const router = useRouter();
+ const traceId = router.query.traceId as string;
+
+ const toggleCollapsedNode = useCallback((id: string) => {
+ setCollapsedNodes((prevNodes) => {
+ if (prevNodes.includes(id)) {
+ return prevNodes.filter((i) => i !== id);
+ } else {
+ return [...prevNodes, id];
+ }
+ });
+ }, []);
+
+ const handleSetCurrentObservationId = (id?: string) => {
+ if (id && traceId) {
+ // Only open observations in new tabs; root selection passes undefined
+ const pathname = `/project/${projectId}/traces/${encodeURIComponent(traceId)}?observation=${encodeURIComponent(id)}`;
+ const pathnameWithBasePath = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${pathname}`;
+ window.open(pathnameWithBasePath, "_blank", "noopener noreferrer");
+ }
+ };
+
+ const handleToggleTrace = (newTraceId: string) => {
+ const pathname = window.location.pathname;
+ if (newTraceId === router.query.traceId) {
+ // remove traceId from query params
+ router.push({
+ pathname: pathname,
+ query: {
+ ...router.query,
+ traceId: undefined,
+ },
+ });
+ } else {
+ // update traceId in query params
+ router.push({
+ pathname: pathname,
+ query: {
+ ...router.query,
+ traceId: encodeURIComponent(newTraceId),
+ },
+ });
+ }
+
+ setCollapsedNodes([]); // Reset collapsed state for new trace
+ };
+
+ return {
+ collapsedNodes,
+ toggleCollapsedNode,
+ handleSetCurrentObservationId,
+ handleToggleTrace,
+ };
+}
diff --git a/web/src/components/table/peek/hooks/usePeekNavigation.ts b/web/src/components/table/peek/hooks/usePeekNavigation.ts
new file mode 100644
index 0000000000..d155093213
--- /dev/null
+++ b/web/src/components/table/peek/hooks/usePeekNavigation.ts
@@ -0,0 +1,206 @@
+import { getPathnameWithoutBasePath } from "@/src/utils/api";
+import { type ListEntry } from "@/src/features/navigate-detail-pages/context";
+import { useRouter } from "next/router";
+import { useCallback } from "react";
+import { urlSearchParamsToQuery } from "@/src/utils/navigation";
+
+const PEEK_PARAM = "peek";
+
+interface BasePeekConfig {
+ /** Additional URL parameters to clear when closing peek view and persist when expanding peek view */
+ queryParams?: string[];
+ /**
+ * Creates semantic URL parameters alongside the universal "peek" parameter.
+ *
+ * Detail navigation components always set peek=itemId universally. We may need to semantically track additional params due to implementation details in
+ * peek detail child components. Please note that you should not be expected to use this setting often, unless you have complex prebuilt URL param
+ * expectations in your child component.
+ *
+ * Example for observations table with paramsToMirrorPeekValue: ["observation"]:
+ * - Opening observation "obs123" sets: peek=obs123 AND observation=obs123
+ * - When user navigates in the trace tree, changes to the observation param occur, but the peek param remains the same.
+ */
+ paramsToMirrorPeekValue?: string[];
+ /** Function to extract additional URL parameters values from a row when opening peek view */
+ extractParamsValuesFromRow?: (row: any) => Record<string, string>;
+}
+
+interface PeekConfig extends BasePeekConfig {
+ expandConfig?: never;
+}
+
+interface PeekConfigWithExpand extends BasePeekConfig {
+ /** Configuration for expanding peek view */
+ expandConfig: {
+ basePath: string;
+ /** URL parameter to use for path param (defaults to "peek") */
+ pathParam?: string;
+ };
+}
+
+interface BasePeekNavigation {
+ /** Open or close peek view. Pass id to open */
+ openPeek: (id?: string, row?: any) => void;
+ /** Close the peek view */
+ closePeek: () => void;
+ /** Resolve the navigation path for a detail entry */
+ resolveDetailNavigationPath: (entry: ListEntry) => string;
+}
+
+interface PeekNavigation extends BasePeekNavigation {}
+
+interface PeekNavigationWithExpand extends BasePeekNavigation {
+ /** Expand the peek view to the full detail page */
+ expandPeek: (openInNewTab: boolean) => void;
+}
+
+/**
+ * Hook for managing peek navigation. Returns expandPeek function only when expandConfig is provided.
+ * @param config Configuration for peek behavior. Include expandConfig to get expandPeek functionality.
+ * @returns Navigation functions. Includes expandPeek when expandConfig is provided.
+ */
+export function usePeekNavigation(
+ config: PeekConfigWithExpand,
+): PeekNavigationWithExpand;
+export function usePeekNavigation(config?: PeekConfig): PeekNavigation;
+export function usePeekNavigation(config?: PeekConfig | PeekConfigWithExpand) {
+ const router = useRouter();
+
+ const openPeek = useCallback(
+ (id?: string, row?: any) => {
+ const pathname = getPathnameWithoutBasePath();
+ const url = new URL(window.location.href);
+ const params = new URLSearchParams(url.search);
+
+ if (!id) {
+ // Close peek view - clear all peek-related params
+ params.delete(PEEK_PARAM);
+ config?.queryParams?.forEach((param) => params.delete(param));
+ } else {
+ // Clear all query params that are set in the config
+ config?.queryParams?.forEach((param) => params.delete(param));
+
+ // Open peek view
+ params.set(PEEK_PARAM, id);
+
+ // Set URL params to the same value as peek ID
+ config?.paramsToMirrorPeekValue?.forEach((param) => {
+ params.set(param, id);
+ });
+
+ // Set additional parameters from row transformation
+ if (row && config?.extractParamsValuesFromRow) {
+ const additionalParams = config.extractParamsValuesFromRow(row);
+ Object.entries(additionalParams).forEach(([key, value]) => {
+ params.set(key, value);
+ });
+ }
+ }
+
+ router.push(
+ {
+ pathname,
+ query: urlSearchParamsToQuery(params),
+ },
+ undefined,
+ { shallow: true },
+ );
+ },
+ [router, config],
+ );
+
+ const closePeek = useCallback(() => {
+ const pathname = getPathnameWithoutBasePath();
+ const url = new URL(window.location.href);
+ const params = new URLSearchParams(url.search);
+
+ // Close peek view - clear all peek-related params
+ params.delete(PEEK_PARAM);
+ config?.queryParams?.forEach((param) => params.delete(param));
+
+ router.push(
+ {
+ pathname,
+ query: urlSearchParamsToQuery(params),
+ },
+ undefined,
+ { shallow: true },
+ );
+ }, [router, config]);
+
+ const resolveDetailNavigationPath = useCallback(
+ (entry: ListEntry) => {
+ const url = new URL(window.location.href);
+ const pathname = getPathnameWithoutBasePath();
+
+ // Update the path part
+ url.pathname = pathname;
+
+ // Keep all existing query params
+ const params = new URLSearchParams(url.search);
+
+ // Update any query params that exist in entry.params
+ if (entry.params) {
+ // Clear all query params that are set in the config
+ config?.queryParams?.forEach((param) => params.delete(param));
+
+ Object.entries(entry.params).forEach(([key, value]) => {
+ params.set(key, encodeURIComponent(value));
+ });
+ }
+
+ // Update peek param to the new id
+ params.set(PEEK_PARAM, entry.id);
+
+ // Set URL params to the same value as peek ID
+ config?.paramsToMirrorPeekValue?.forEach((param) => {
+ params.set(param, entry.id);
+ });
+
+ // Set the search part of the URL
+ return `${url.pathname}?${params.toString()}`;
+ },
+ [config],
+ );
+
+ const expandPeek = useCallback(
+ (openInNewTab: boolean) => {
+ const url = new URL(window.location.href);
+ const params = new URLSearchParams(url.search);
+ const pathParam = config?.expandConfig?.pathParam ?? PEEK_PARAM;
+
+ const pathname = `${config?.expandConfig?.basePath}/${params.get(pathParam)}`;
+ const queryParams = config?.queryParams
+ ?.map((param) => {
+ const value = params.get(param);
+ return value ? `${param}=${value}` : null;
+ })
+ .filter(Boolean)
+ .join("&");
+ const pathnameWithQuery = `${pathname}?${queryParams}`;
+
+ if (openInNewTab) {
+ const pathnameWithBasePath = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${pathnameWithQuery}`;
+ window.open(pathnameWithBasePath, "_blank");
+ } else {
+ router.push(pathnameWithQuery);
+ }
+ },
+ [router, config],
+ );
+
+ const baseNavigation = {
+ openPeek,
+ closePeek,
+ resolveDetailNavigationPath,
+ };
+
+ if (config?.expandConfig) {
+ return {
+ ...baseNavigation,
+ expandPeek,
+ } as PeekNavigationWithExpand;
+ }
+
+ return baseNavigation as PeekNavigation;
+}
diff --git a/web/src/components/table/peek/hooks/usePeekRunsCompareData.ts b/web/src/components/table/peek/hooks/usePeekRunsCompareData.ts
new file mode 100644
index 0000000000..388f4a412b
--- /dev/null
+++ b/web/src/components/table/peek/hooks/usePeekRunsCompareData.ts
@@ -0,0 +1,64 @@
+import { api } from "@/src/utils/api";
+
+type UsePeekRunsCompareDataProps = {
+ projectId: string;
+ datasetId?: string;
+ datasetItemId?: string;
+ traceId?: string;
+ timestamp?: Date;
+ runs?: string[];
+};
+
+export const usePeekRunsCompareData = ({
+ projectId,
+ traceId,
+ timestamp,
+ datasetId,
+ datasetItemId,
+ runs,
+}: UsePeekRunsCompareDataProps) => {
+ const trace = api.traces.byIdWithObservationsAndScores.useQuery(
+ {
+ traceId: traceId as string,
+ projectId,
+ timestamp,
+ },
+ {
+ enabled: !!traceId,
+ retry(failureCount, error) {
+ if (error.data?.code === "UNAUTHORIZED") return false;
+ return failureCount < 3;
+ },
+ staleTime: 60 * 1000, // 1 minute
+ },
+ );
+
+ const datasetItem = api.datasets.itemById.useQuery(
+ {
+ projectId,
+ datasetId: datasetId as string,
+ datasetItemId: datasetItemId as string,
+ },
+ {
+ enabled: !!datasetId && !!datasetItemId,
+ },
+ );
+
+ const runItems = api.datasets.runItemsByItemId.useQuery(
+ {
+ projectId,
+ datasetId: datasetId as string,
+ datasetItemId: datasetItemId as string,
+ datasetRunIds: runs as string[] | undefined,
+ },
+ {
+ enabled: !!datasetId && !!datasetItemId && !!runs && runs.length > 0,
+ },
+ );
+
+ return {
+ trace,
+ datasetItem,
+ runItems,
+ };
+};
diff --git a/web/src/components/table/peek/hooks/usePeekState.ts b/web/src/components/table/peek/hooks/usePeekState.ts
deleted file mode 100644
index 26f6a74c75..0000000000
--- a/web/src/components/table/peek/hooks/usePeekState.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { useRouter } from "next/router";
-import { useCallback } from "react";
-import { getPathnameWithoutBasePath } from "@/src/utils/api";
-
-export const usePeekState = () => {
- const router = useRouter();
- const { peek } = router.query;
-
- const setPeekView = useCallback(
- (open: boolean, id?: string) => {
- const url = new URL(window.location.href);
- const params = new URLSearchParams(url.search);
- const pathname = getPathnameWithoutBasePath();
-
- if (!open || !id) {
- // close peek view
- params.delete("peek");
- } else if (open && id !== peek) {
- // open peek view or update peek view
- params.set("peek", id);
- } else {
- return;
- }
-
- router.push(
- {
- pathname,
- query: params.toString(),
- },
- undefined,
- { shallow: true },
- );
- },
- [router, peek],
- );
-
- return {
- peekId: peek as string | undefined,
- setPeekView,
- };
-};
diff --git a/web/src/components/table/peek/hooks/usePeekView.ts b/web/src/components/table/peek/hooks/usePeekView.ts
deleted file mode 100644
index 0404e454af..0000000000
--- a/web/src/components/table/peek/hooks/usePeekView.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import { type DataTablePeekViewProps } from "@/src/components/table/peek";
-import { useRouter } from "next/router";
-import { useEffect, useRef, useState } from "react";
-
-/**
- * Props for configuring a peek view in a data table.
- *
- * @template TData The type of data in the table rows
- *
- * @property isTableDataComplete - Indicates whether all data (including asynchronously loaded data like metrics)
- * has finished loading. This is critical for proper table memoization - when false, it ensures the table
- * continues to re-render as additional data loads, even when the primary data reference remains stable.
- * Set this to true only when ALL data needed for rendering the table is fully loaded.
- *
- * Common usage pattern:
- * ```
- * isTableDataComplete: !metricsQuery.isLoading && metricsQuery.data !== undefined
- * ```
- */
-export type PeekViewProps<TData> = DataTablePeekViewProps<TData> & {
- tableDataUpdatedAt: number;
-};
-
-function getInitialRow<TData>(
- peekViewId: string | undefined,
- getRow: (id: string) => TData | undefined,
-): TData | undefined {
- if (!peekViewId) return undefined;
- try {
- const row = getRow(peekViewId);
- return row ? row : undefined;
- } catch (error) {
- return undefined;
- }
-}
-
-type UsePeekViewProps<TData> = {
- getRow: (id: string) => TData | undefined;
- peekView?: PeekViewProps<TData>;
-};
-
-/**
- * A hook that manages the peek view state for a data table.
- *
- * @param getRow - The React Table's getRow function
- * @param peekView - Optional configuration for the peek view
- *
- * @returns An object containing:
- * - handleOnRowClickPeek: Function to handle row clicks for peek view
- * - peekViewId: The ID of the currently selected row for peek view
- * - row: The currently selected row for peek view
- *
- * The peek view allows users to preview details of a row without navigating away from the table.
- * It manages the URL state via query parameters and handles row selection/deselection.
- */
-
-export const usePeekView = <TData extends object>({
- getRow,
- peekView,
-}: UsePeekViewProps<TData>) => {
- const router = useRouter();
-
- const peekViewId = router.query.peek as string | undefined;
- const [row, setRow] = useState<TData | undefined>(
- getInitialRow(peekViewId, getRow),
- );
-
- // Populate the row after the table is mounted
- const attemptRef = useRef(false);
-
- // Try to find the row with delayed attempts
- useEffect(() => {
- if (peekView && peekViewId && !row && !attemptRef.current) {
- attemptRef.current = true;
- let foundOnce = false;
- let intervalId = setInterval(() => {
- const foundRow = getInitialRow(peekViewId, getRow);
- if (foundRow) {
- setRow(foundRow);
- if (foundOnce) clearInterval(intervalId);
- foundOnce = true;
- }
- }, 500);
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- // Update the row state when the user clicks on a row
- const handleOnRowClickPeek = (row: TData) => {
- if (peekView) {
- const rowId =
- "id" in row && typeof row.id === "string" ? row.id : undefined;
- // If clicking the same row that's already open, close it
- if (rowId === peekViewId) {
- peekView.onOpenChange(false);
- setRow(undefined);
- }
- // If clicking a different row update the row data and URL
- else {
- const timestamp =
- "timestamp" in row ? (row.timestamp as Date) : undefined;
- peekView.onOpenChange(true, rowId, timestamp?.toISOString());
- setRow(row);
- }
- }
- };
-
- // Update the row state when the peekViewId changes on detail page navigation
- useEffect(() => {
- if (!peekView || !peekView.shouldUpdateRowOnDetailPageNavigation) return;
-
- const rowId =
- row && "id" in row && typeof row.id === "string" ? row.id : undefined;
-
- if (peekViewId !== rowId) {
- if (peekViewId && peekView) {
- try {
- const row = getRow(peekViewId);
- if (row) {
- setRow(row);
- }
- } catch (error) {
- console.log("Row not found in table:", error);
- }
- }
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [peekViewId]);
-
- return {
- handleOnRowClickPeek: peekView ? handleOnRowClickPeek : undefined,
- peekViewId,
- row,
- };
-};
diff --git a/web/src/components/table/peek/hooks/useRunningEvaluatorsPeekNavigation.ts b/web/src/components/table/peek/hooks/useRunningEvaluatorsPeekNavigation.ts
deleted file mode 100644
index 2b15f0064d..0000000000
--- a/web/src/components/table/peek/hooks/useRunningEvaluatorsPeekNavigation.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { type ListEntry } from "@/src/features/navigate-detail-pages/context";
-import { getPathnameWithoutBasePath } from "@/src/utils/api";
-
-export const useRunningEvaluatorsPeekNavigation = () => {
- const getNavigationPath = (entry: ListEntry) => {
- const url = new URL(window.location.href);
- const pathname = getPathnameWithoutBasePath();
-
- // Update the path part
- url.pathname = pathname;
-
- // Keep all existing query params
- const params = new URLSearchParams(url.search);
-
- // Update peek param to the new id
- params.set("peek", entry.id);
-
- // Set the search part of the URL
- return `${url.pathname}?${params.toString()}`;
- };
-
- return { getNavigationPath };
-};
diff --git a/web/src/components/table/peek/hooks/useTracePeekNavigation.ts b/web/src/components/table/peek/hooks/useTracePeekNavigation.ts
deleted file mode 100644
index c2616f8155..0000000000
--- a/web/src/components/table/peek/hooks/useTracePeekNavigation.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { type ListEntry } from "@/src/features/navigate-detail-pages/context";
-import { useRouter } from "next/router";
-import { getPathnameWithoutBasePath } from "@/src/utils/api";
-
-export const useTracePeekNavigation = () => {
- const router = useRouter();
- const { projectId, peek } = router.query;
-
- const getNavigationPath = (entry: ListEntry) => {
- const url = new URL(window.location.href);
- const pathname = getPathnameWithoutBasePath();
-
- // Update the path part
- url.pathname = pathname;
-
- // Keep all existing query params
- const params = new URLSearchParams(url.search);
-
- // Update timestamp if it exists in entry.params
- if (entry.params) {
- if (entry.params.timestamp)
- params.set("timestamp", encodeURIComponent(entry.params.timestamp));
- params.delete("observation");
- }
-
- // Update peek param to the new id
- params.set("peek", entry.id);
-
- // Set the search part of the URL
- return `${url.pathname}?${params.toString()}`;
- };
-
- const expandPeek = (openInNewTab: boolean) => {
- const url = new URL(window.location.href);
- const params = new URLSearchParams(url.search);
- const timestamp = params.get("timestamp");
- const display = params.get("display") ?? "details";
-
- const pathname = `/project/${projectId}/traces/${encodeURIComponent(peek as string)}?timestamp=${timestamp}&display=${display}`;
-
- if (openInNewTab) {
- const pathnameWithBasePath = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${pathname}`;
- window.open(pathnameWithBasePath, "_blank");
- } else {
- router.push(pathname);
- }
- };
-
- return { getNavigationPath, expandPeek };
-};
diff --git a/web/src/components/table/peek/hooks/useTracePeekState.ts b/web/src/components/table/peek/hooks/useTracePeekState.ts
deleted file mode 100644
index ef6f74cc4f..0000000000
--- a/web/src/components/table/peek/hooks/useTracePeekState.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { useRouter } from "next/router";
-import { useCallback } from "react";
-import { getPathnameWithoutBasePath } from "@/src/utils/api";
-
-export const useTracePeekState = () => {
- const router = useRouter();
- const { peek, timestamp } = router.query;
-
- const setPeekView = useCallback(
- (open: boolean, id?: string, time?: string) => {
- const url = new URL(window.location.href);
- const params = new URLSearchParams(url.search);
- const pathname = getPathnameWithoutBasePath();
-
- if (!open || !id) {
- // close peek view
- params.delete("peek");
- params.delete("timestamp");
- params.delete("observation");
- params.delete("display");
- } else if (open && id !== peek) {
- // open peek view or update peek view
- params.set("peek", id);
- const relevantTimestamp = time ?? (timestamp as string);
- if (relevantTimestamp) params.set("timestamp", relevantTimestamp);
- params.delete("observation");
- } else {
- return;
- }
-
- router.push(
- {
- pathname,
- query: params.toString(),
- },
- undefined,
- { shallow: true },
- );
- },
- [router, peek, timestamp],
- );
-
- return {
- peekId: peek as string | undefined,
- timestamp: timestamp ? new Date(timestamp as string) : undefined,
- setPeekView,
- };
-};
diff --git a/web/src/components/table/peek/peek-dataset-compare-detail.tsx b/web/src/components/table/peek/peek-dataset-compare-detail.tsx
index 61fab89dad..33d3226c19 100644
--- a/web/src/components/table/peek/peek-dataset-compare-detail.tsx
+++ b/web/src/components/table/peek/peek-dataset-compare-detail.tsx
@@ -1,4 +1,3 @@
-import { useDatasetComparePeekState } from "@/src/components/table/peek/hooks/useDatasetComparePeekState";
import {
ResizablePanelGroup,
ResizablePanel,
@@ -13,42 +12,65 @@ import { Button } from "@/src/components/ui/button";
import { PanelLeftOpen, PanelLeftClose, ListTree } from "lucide-react";
import { cn } from "@/src/utils/tailwind";
import { Command } from "@/src/components/ui/command";
-import DocPopup from "@/src/components/layouts/doc-popup";
-import type { DatasetCompareRunRowData } from "@/src/features/datasets/components/DatasetCompareRunsTable";
-import { useRouter } from "next/router";
-import { usePeekData } from "@/src/components/table/peek/hooks/usePeekData";
-import React, { useState, useCallback, useMemo } from "react";
+import React, { useMemo } from "react";
import { buildTraceUiData } from "@/src/components/trace/lib/helpers";
+import { usePeekRunsCompareData } from "@/src/components/table/peek/hooks/usePeekRunsCompareData";
+import { type RunMetrics } from "@/src/features/datasets/components/DatasetCompareRunsTable";
+import { useRouter } from "next/router";
+import { usePeekCompareDetail } from "@/src/components/table/peek/hooks/usePeekCompareDetail";
+
+const convertRunDataToRunMetrics = (
+ runData: RouterOutputs["datasets"]["runitemsByRunIdOrItemId"]["runItems"][number],
+): RunMetrics => {
+ return {
+ id: runData.id,
+ scores: runData.scores,
+ resourceMetrics: {
+ latency: runData.observation?.latency ?? runData.trace.duration,
+ totalCost:
+ runData.observation?.calculatedTotalCost.toString() ??
+ runData.trace.totalCost.toString(),
+ },
+ traceId: runData.trace.id,
+ observationId: runData.observation?.id,
+ };
+};
export type PeekDatasetCompareDetailProps = {
projectId: string;
- runsData: RouterOutputs["datasets"]["baseRunDataByDatasetId"];
scoreKeyToDisplayName: Map<string, string>;
- row?: DatasetCompareRunRowData;
};
export const PeekDatasetCompareDetail = ({
projectId,
- runsData,
scoreKeyToDisplayName,
- row,
}: PeekDatasetCompareDetailProps) => {
const router = useRouter();
- const [collapsedNodes, setCollapsedNodes] = useState<string[]>([]);
-
+ // path params
+ const datasetId = router.query.datasetId as string | undefined;
+ // query params
const timestamp =
router.query.timestamp && typeof router.query.timestamp === "string"
? new Date(decodeURIComponent(router.query.timestamp))
: undefined;
+ const traceId = router.query.traceId as string | undefined;
+ const datasetItemId = router.query.peek as string | undefined;
+ const runs = router.query.runs as string[] | undefined;
- const { datasetItemId, selectedRunItemProps, setSelectedRunItemProps } =
- useDatasetComparePeekState();
- const { runId, traceId } = selectedRunItemProps ?? {};
+ const {
+ collapsedNodes,
+ toggleCollapsedNode,
+ handleSetCurrentObservationId,
+ handleToggleTrace,
+ } = usePeekCompareDetail(projectId);
- const trace = usePeekData({
+ const { trace, runItems, datasetItem } = usePeekRunsCompareData({
projectId,
traceId: traceId,
+ datasetId,
+ datasetItemId,
timestamp,
+ runs,
});
const tree = useMemo(() => {
@@ -63,45 +85,9 @@ export const PeekDatasetCompareDetail = ({
return tree;
}, [trace.data]);
- const toggleCollapsedNode = useCallback((id: string) => {
- setCollapsedNodes((prevNodes) => {
- if (prevNodes.includes(id)) {
- return prevNodes.filter((i) => i !== id);
- } else {
- return [...prevNodes, id];
- }
- });
- }, []);
-
- const handleSetCurrentObservationId = (id?: string) => {
- if (id && traceId) {
- // Only open observations in new tabs; root selection passes undefined
- const pathname = `/project/${projectId}/traces/${encodeURIComponent(traceId)}?observation=${encodeURIComponent(id)}`;
- const pathnameWithBasePath = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${pathname}`;
- window.open(pathnameWithBasePath, "_blank", "noopener noreferrer");
- }
- };
-
- const handleToggleTrace = (
- newTraceId?: string,
- newRunId?: string,
- newObservationId?: string,
- ) => {
- if (!newTraceId || !newRunId) return;
-
- if (newTraceId === traceId) {
- setSelectedRunItemProps(null);
- } else {
- setSelectedRunItemProps({
- runId: newRunId,
- traceId: newTraceId,
- observationId: newObservationId,
- });
- setCollapsedNodes([]); // Reset collapsed state for new trace
- }
- };
-
- if (!row) return <Skeleton className="min-h-full w-full" />;
+ if (!runItems.data || !datasetItem.data) {
+ return <Skeleton className="min-h-full w-full" />;
+ }
return (
<div
@@ -117,11 +103,9 @@ export const PeekDatasetCompareDetail = ({
<h3 className="mb-3 font-semibold">
Run:{" "}
{
- runsData?.find(
- (
- r: RouterOutputs["datasets"]["baseRunDataByDatasetId"][number],
- ) => r.id === runId,
- )?.name
+ runItems.data.runItems?.find(
+ (runItem) => runItem.trace.id === traceId,
+ )?.datasetRunName
}
</h3>
{tree && (
@@ -157,7 +141,7 @@ export const PeekDatasetCompareDetail = ({
<div className="h-[calc(100%-1.75rem)] space-y-2 overflow-y-auto">
<IOPreview
key={datasetItemId + "-input"}
- input={row?.input ?? null}
+ input={datasetItem.data.input ?? null}
hideOutput
/>
</div>
@@ -167,7 +151,7 @@ export const PeekDatasetCompareDetail = ({
<div className="h-[calc(100%-1.75rem)] space-y-2 overflow-y-auto">
<IOPreview
key={datasetItemId + "-output"}
- output={row?.expectedOutput ?? null}
+ output={datasetItem.data.expectedOutput ?? null}
hideInput
/>
</div>
@@ -181,31 +165,31 @@ export const PeekDatasetCompareDetail = ({
className="mt-2 min-h-0 overflow-hidden p-2 pl-3"
>
<h3 className="mb-1 font-semibold">Run outputs</h3>
- {row?.runs && (
+ {runItems.data.runItems && (
<div className="flex h-[calc(100%-2rem)] w-full gap-4 overflow-x-auto">
- {Object.entries(row.runs).map(([id, run]) => {
- const runData = runsData?.find(
- (
- r: RouterOutputs["datasets"]["baseRunDataByDatasetId"][number],
- ) => r.id === id,
+ {runItems.data.runItems.map((runItem) => {
+ const runData = runItems.data.runItems.find(
+ (r) => r.id === runItem.id,
);
+ if (!runData) return null;
+ const runMetrics = convertRunDataToRunMetrics(runData);
+
return (
<div
- key={id}
+ key={runItem.id}
className="flex w-[45%] flex-none flex-col overflow-hidden"
>
<div className="mb-1 flex items-center text-sm font-medium">
- {runData?.name ?? id}
- {runData?.description && (
- <DocPopup description={runData?.description} />
- )}
+ {runData.datasetRunName ?? runMetrics.id}
</div>
<DatasetAggregateTableCell
- value={run}
+ value={runMetrics}
projectId={projectId}
scoreKeyToDisplayName={scoreKeyToDisplayName}
- output={row.expectedOutput}
- isHighlighted={id === runId}
+ expectedOutput={
+ datasetItem.data?.expectedOutput ?? null
+ }
+ isHighlighted={runItem.trace.id === traceId}
actionButtons={
<div className="absolute right-1 top-1 z-10 hidden items-center justify-center gap-1 group-hover:flex">
<Button
@@ -213,9 +197,9 @@ export const PeekDatasetCompareDetail = ({
size="icon"
title="View full trace"
onClick={() => {
- const pathname = run?.observationId
- ? `/project/${projectId}/traces/${encodeURIComponent(run.traceId)}?observation=${encodeURIComponent(run.observationId)}`
- : `/project/${projectId}/traces/${encodeURIComponent(run.traceId)}`;
+ const pathname = runMetrics?.observationId
+ ? `/project/${projectId}/traces/${encodeURIComponent(runMetrics.traceId)}?observation=${encodeURIComponent(runMetrics.observationId)}`
+ : `/project/${projectId}/traces/${encodeURIComponent(runMetrics.traceId)}`;
const pathnameWithBasePath = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${pathname}`;
window.open(
pathnameWithBasePath,
@@ -230,19 +214,15 @@ export const PeekDatasetCompareDetail = ({
variant="outline"
size="icon"
title={
- traceId === run.traceId
+ traceId === runMetrics.traceId
? "Hide trace tree"
: "View trace tree"
}
onClick={() =>
- handleToggleTrace(
- run.traceId,
- id,
- run.observationId,
- )
+ handleToggleTrace(runMetrics.traceId)
}
>
- {traceId === run.traceId ? (
+ {traceId === runMetrics.traceId ? (
<PanelLeftClose className="h-4 w-4" />
) : (
<PanelLeftOpen className="h-4 w-4" />
diff --git a/web/src/components/table/peek/peek-evaluator-config-detail.tsx b/web/src/components/table/peek/peek-evaluator-config-detail.tsx
index e4f4ba7698..e612360133 100644
--- a/web/src/components/table/peek/peek-evaluator-config-detail.tsx
+++ b/web/src/components/table/peek/peek-evaluator-config-detail.tsx
@@ -1,5 +1,4 @@
-import { usePeekState } from "@/src/components/table/peek/hooks/usePeekState";
-import { type EvaluatorDataRow } from "@/src/features/evals/components/evaluator-table";
+import { useRouter } from "next/router";
import { Skeleton } from "@/src/components/ui/skeleton";
import TableLink from "@/src/components/table/table-link";
import { CardDescription } from "@/src/components/ui/card";
@@ -23,12 +22,11 @@ import { api } from "@/src/utils/api";
export const PeekViewEvaluatorConfigDetail = ({
projectId,
- row,
}: {
projectId: string;
- row?: EvaluatorDataRow;
}) => {
- const { peekId } = usePeekState();
+ const router = useRouter();
+ const peekId = router.query.peek as string | undefined;
const [isEditMode, setIsEditMode] = useState(false);
const utils = api.useUtils();
@@ -79,23 +77,25 @@ export const PeekViewEvaluatorConfigDetail = ({
</div>
<CardDescription className="flex items-center text-sm">
<span className="mr-2 text-sm font-medium">Referenced Evaluator</span>
- {row?.template && (
+ {evalConfig.evalTemplate && (
<TableLink
- path={`/project/${projectId}/evals/templates/${row?.template.id}`}
- value={row?.template.name}
+ path={`/project/${projectId}/evals/templates/${evalConfig.evalTemplate.id}`}
+ value={evalConfig.evalTemplate.name}
className="mr-1 flex min-h-6 items-center"
/>
)}
- {row?.maintainer && (
+ {evalConfig.evalTemplate && (
<Tooltip>
<TooltipTrigger>
- {row.maintainer.includes("Langfuse") ? (
+ {evalConfig.evalTemplate.projectId === null ? (
<LangfuseIcon size={16} />
) : (
<UserCircle2Icon className="h-4 w-4" />
)}
</TooltipTrigger>
- <TooltipContent>{row.maintainer}</TooltipContent>
+ <TooltipContent>
+ {evalConfig.evalTemplate.partner ?? "Langfuse"}
+ </TooltipContent>
</Tooltip>
)}
</CardDescription>
diff --git a/web/src/components/table/peek/peek-evaluator-template-detail.tsx b/web/src/components/table/peek/peek-evaluator-template-detail.tsx
index 141c94a95f..66b56bef2f 100644
--- a/web/src/components/table/peek/peek-evaluator-template-detail.tsx
+++ b/web/src/components/table/peek/peek-evaluator-template-detail.tsx
@@ -1,4 +1,4 @@
-import { usePeekState } from "@/src/components/table/peek/hooks/usePeekState";
+import { useRouter } from "next/router";
import { Skeleton } from "@/src/components/ui/skeleton";
import { usePeekEvalTemplateData } from "@/src/components/table/peek/hooks/usePeekEvalTemplateData";
import { EvalTemplateForm } from "@/src/features/evals/components/template-form";
@@ -10,7 +10,8 @@ export const PeekViewEvaluatorTemplateDetail = ({
}: {
projectId: string;
}) => {
- const { peekId } = usePeekState();
+ const router = useRouter();
+ const peekId = router.query.peek as string | undefined;
const { data: template } = usePeekEvalTemplateData({
templateId: peekId,
diff --git a/web/src/components/table/peek/peek-observation-detail.tsx b/web/src/components/table/peek/peek-observation-detail.tsx
index a8c1fa5d68..94dd582bc6 100644
--- a/web/src/components/table/peek/peek-observation-detail.tsx
+++ b/web/src/components/table/peek/peek-observation-detail.tsx
@@ -1,24 +1,25 @@
-import { useObservationPeekState } from "@/src/components/table/peek/hooks/useObservationPeekState";
+import { useRouter } from "next/router";
import { usePeekData } from "@/src/components/table/peek/hooks/usePeekData";
-import { type ObservationsTableRow } from "@/src/components/table/use-cases/observations";
import { Trace } from "@/src/components/trace";
import { Skeleton } from "@/src/components/ui/skeleton";
import { StringParam, useQueryParam, withDefault } from "use-query-params";
export const PeekViewObservationDetail = ({
projectId,
- row,
}: {
projectId: string;
- row?: ObservationsTableRow;
}) => {
- const { peekId, timestamp } = useObservationPeekState();
- const effectiveTimestamp = row?.timestamp ?? timestamp;
+ const router = useRouter();
+ const peekId = router.query.peek as string | undefined;
+ const timestamp = router.query.timestamp
+ ? new Date(router.query.timestamp as string)
+ : undefined;
+ const traceId = router.query.traceId as string | undefined;
const trace = usePeekData({
projectId,
- traceId: row?.traceId,
- timestamp: effectiveTimestamp,
+ traceId,
+ timestamp,
});
const [selectedTab, setSelectedTab] = useQueryParam(
@@ -26,7 +27,7 @@ export const PeekViewObservationDetail = ({
withDefault(StringParam, "details"),
);
- if (!peekId || !row?.traceId || !trace.data || row.id !== peekId) {
+ if (!peekId || !trace.data) {
return <Skeleton className="h-full w-full" />;
}
diff --git a/web/src/components/table/peek/peek-trace-detail.tsx b/web/src/components/table/peek/peek-trace-detail.tsx
index e160fbf1bc..3edfbf8853 100644
--- a/web/src/components/table/peek/peek-trace-detail.tsx
+++ b/web/src/components/table/peek/peek-trace-detail.tsx
@@ -1,11 +1,15 @@
import { usePeekData } from "@/src/components/table/peek/hooks/usePeekData";
-import { useTracePeekState } from "@/src/components/table/peek/hooks/useTracePeekState";
+import { useRouter } from "next/router";
import { Trace } from "@/src/components/trace";
import { Skeleton } from "@/src/components/ui/skeleton";
import { StringParam, useQueryParam, withDefault } from "use-query-params";
export const PeekViewTraceDetail = ({ projectId }: { projectId: string }) => {
- const { peekId, timestamp } = useTracePeekState();
+ const router = useRouter();
+ const peekId = router.query.peek as string | undefined;
+ const timestamp = router.query.timestamp
+ ? new Date(router.query.timestamp as string)
+ : undefined;
const trace = usePeekData({
projectId,
traceId: peekId,
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index 102a869331..7e6d86a1cc 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -45,18 +45,17 @@ import TableIdOrName from "@/src/components/table/table-id";
import { ItemBadge } from "@/src/components/ItemBadge";
import { Skeleton } from "@/src/components/ui/skeleton";
import { PeekViewObservationDetail } from "@/src/components/table/peek/peek-observation-detail";
-import { useObservationPeekState } from "@/src/components/table/peek/hooks/useObservationPeekState";
+import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
-import { useObservationPeekNavigation } from "@/src/components/table/peek/hooks/useObservationPeekNavigation";
import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";
import { useRouter } from "next/router";
import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";
-import { type PeekViewProps } from "@/src/components/table/peek/hooks/usePeekView";
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";
import { useScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";
import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";
@@ -311,7 +310,10 @@ export default function ObservationsTable({
generations.data.generations.map((g) => ({
id: g.id,
params: g.traceTimestamp
- ? { timestamp: g.traceTimestamp.toISOString() }
+ ? {
+ timestamp: g.traceTimestamp.toISOString(),
+ traceId: g.traceId || "",
+ }
: undefined,
})),
);
@@ -949,8 +951,19 @@ export default function ObservationsTable({
columns,
);
- const { getNavigationPath, expandPeek } = useObservationPeekNavigation();
- const { setPeekView } = useObservationPeekState();
+ const peekNavigationProps = usePeekNavigation({
+ queryParams: ["observation", "display", "timestamp", "traceId"],
+ paramsToMirrorPeekValue: ["observation"],
+ extractParamsValuesFromRow: (row: ObservationsTableRow) => ({
+ traceId: row.traceId || "",
+ timestamp: row.timestamp?.toISOString() || "",
+ }),
+ expandConfig: {
+ basePath: `/project/${projectId}/traces`,
+ pathParam: "traceId",
+ },
+ });
+
const { isLoading: isViewLoading, ...viewControllers } = useTableViewManager({
tableName: TableViewPresetTableName.Observations,
projectId,
@@ -967,27 +980,16 @@ export default function ObservationsTable({
},
});
- const peekConfig: PeekViewProps<ObservationsTableRow> = useMemo(
+ const peekConfig: DataTablePeekViewProps = useMemo(
() => ({
itemType: "TRACE",
customTitlePrefix: "Observation ID:",
- listKey: "observations",
- onOpenChange: setPeekView,
- onExpand: expandPeek,
- shouldUpdateRowOnDetailPageNavigation: true,
- getNavigationPath,
- children: (row?: ObservationsTableRow) => (
- <PeekViewObservationDetail projectId={projectId} row={row} />
- ),
+ detailNavigationKey: "observations",
+ children: <PeekViewObservationDetail projectId={projectId} />,
tableDataUpdatedAt: generations.dataUpdatedAt,
+ ...peekNavigationProps,
}),
- [
- projectId,
- generations.dataUpdatedAt,
- getNavigationPath,
- expandPeek,
- setPeekView,
- ],
+ [projectId, generations.dataUpdatedAt, peekNavigationProps],
);
const rows: ObservationsTableRow[] = useMemo(() => {
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index 56f0c6f2cb..0e167270f4 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -73,8 +73,7 @@ import {
convertSelectedEnvironmentsToFilter,
} from "@/src/hooks/use-environment-filter";
import { PeekViewTraceDetail } from "@/src/components/table/peek/peek-trace-detail";
-import { useTracePeekNavigation } from "@/src/components/table/peek/hooks/useTracePeekNavigation";
-import { useTracePeekState } from "@/src/components/table/peek/hooks/useTracePeekState";
+import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";
import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";
import { type TableDateRange } from "@/src/utils/date-range-utils";
@@ -1012,32 +1011,35 @@ export default function TracesTable({
columns,
);
- const { getNavigationPath, expandPeek } = useTracePeekNavigation();
- const { setPeekView } = useTracePeekState();
+ const peekNavigationProps = usePeekNavigation({
+ queryParams: ["observation", "display", "timestamp"],
+ extractParamsValuesFromRow: (row: TracesTableRow) => ({
+ timestamp: row.timestamp?.toISOString() || "",
+ }),
+ expandConfig: {
+ basePath: `/project/${projectId}/traces`,
+ },
+ });
const peekConfig = useMemo(() => {
if (hideControls) return undefined;
return {
itemType: "TRACE" as const,
- listKey: "traces",
+ detailNavigationKey: "traces",
peekEventOptions: {
ignoredSelectors: ['[role="checkbox"]', '[aria-label="bookmark"]'],
},
- onOpenChange: setPeekView,
- onExpand: expandPeek,
- getNavigationPath,
children: <PeekViewTraceDetail projectId={projectId} />,
tableDataUpdatedAt: Math.max(
traces.dataUpdatedAt,
traceMetrics.dataUpdatedAt,
),
+ ...peekNavigationProps,
};
}, [
projectId,
hideControls,
- setPeekView,
- expandPeek,
- getNavigationPath,
+ peekNavigationProps,
traces.dataUpdatedAt,
traceMetrics.dataUpdatedAt,
]);
diff --git a/web/src/features/datasets/components/DatasetAggregateTableCell.tsx b/web/src/features/datasets/components/DatasetAggregateTableCell.tsx
index fc09593536..f98964edf2 100644
--- a/web/src/features/datasets/components/DatasetAggregateTableCell.tsx
+++ b/web/src/features/datasets/components/DatasetAggregateTableCell.tsx
@@ -35,13 +35,13 @@ const DatasetAggregateCell = ({
observationId,
scoreKeyToDisplayName,
actionButtons,
- output,
+ expectedOutput: output,
isHighlighted = false,
}: RunMetrics & {
projectId: string;
scoreKeyToDisplayName: Map<string, string>;
actionButtons?: ReactNode;
- output?: Prisma.JsonValue;
+ expectedOutput?: Prisma.JsonValue;
isHighlighted?: boolean;
}) => {
const [isOpen, setIsOpen] = useState(false);
@@ -237,28 +237,30 @@ const DatasetAggregateCell = ({
);
};
+type DatasetAggregateTableCellProps = {
+ projectId: string;
+ scoreKeyToDisplayName: Map<string, string>;
+ value?: RunMetrics;
+ actionButtons?: ReactNode;
+ expectedOutput?: Prisma.JsonValue;
+ isHighlighted?: boolean;
+};
+
export const DatasetAggregateTableCell = ({
- value,
projectId,
scoreKeyToDisplayName,
+ value,
actionButtons,
- output,
+ expectedOutput,
isHighlighted = false,
-}: {
- value: RunMetrics;
- projectId: string;
- scoreKeyToDisplayName: Map<string, string>;
- actionButtons?: ReactNode;
- output?: Prisma.JsonValue;
- isHighlighted?: boolean;
-}) => {
+}: DatasetAggregateTableCellProps) => {
return value ? (
<DatasetAggregateCell
projectId={projectId}
{...value}
scoreKeyToDisplayName={scoreKeyToDisplayName}
actionButtons={actionButtons}
- output={output}
+ expectedOutput={expectedOutput}
isHighlighted={isHighlighted}
/>
) : null;
diff --git a/web/src/features/datasets/components/DatasetCompareRunsTable.tsx b/web/src/features/datasets/components/DatasetCompareRunsTable.tsx
index 6c71e79ccf..1abe768e72 100644
--- a/web/src/features/datasets/components/DatasetCompareRunsTable.tsx
+++ b/web/src/features/datasets/components/DatasetCompareRunsTable.tsx
@@ -24,11 +24,10 @@ import {
import { getQueryKey } from "@trpc/react-query";
import { useQueryClient } from "@tanstack/react-query";
import _ from "lodash";
-import { useDatasetComparePeekState } from "@/src/components/table/peek/hooks/useDatasetComparePeekState";
+import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
import { PeekDatasetCompareDetail } from "@/src/components/table/peek/peek-dataset-compare-detail";
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
-import { useDatasetComparePeekNavigation } from "@/src/components/table/peek/hooks/useDatasetComparePeekNavigation";
import {
DatasetCompareMetricsProvider,
useDatasetCompareMetrics,
@@ -402,9 +401,9 @@ function DatasetCompareRunsTableInternal(props: {
columns,
);
- const { setPeekView } = useDatasetComparePeekState();
- const { getNavigationPath, shouldUpdateRowOnDetailPageNavigation } =
- useDatasetComparePeekNavigation();
+ const peekNavigationProps = usePeekNavigation({
+ queryParams: ["traceId"],
+ });
return (
<>
@@ -481,18 +480,15 @@ function DatasetCompareRunsTableInternal(props: {
baseDatasetItems.dataUpdatedAt,
...runs.map(({ items }) => items.dataUpdatedAt),
),
- onOpenChange: setPeekView,
- getNavigationPath,
- shouldUpdateRowOnDetailPageNavigation,
- listKey: "datasetCompareRuns",
- children: (row?: DatasetCompareRunRowData) => (
+
+ detailNavigationKey: "datasetCompareRuns",
+ children: (
<PeekDatasetCompareDetail
projectId={props.projectId}
scoreKeyToDisplayName={scoreKeyToDisplayName}
- runsData={props.runsData ?? []}
- row={row}
/>
),
+ ...peekNavigationProps,
}}
/>
</>
diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.ts
index 072863a8a0..89b3f13421 100644
--- a/web/src/features/datasets/server/dataset-router.ts
+++ b/web/src/features/datasets/server/dataset-router.ts
@@ -969,6 +969,7 @@ export const datasetRouter = createTRPCRouter({
projectId: z.string(),
datasetId: z.string(),
datasetItemId: z.string(),
+ datasetRunIds: z.array(z.string()).optional(),
...optionalPaginationZod,
}),
)
@@ -982,6 +983,16 @@ export const datasetRouter = createTRPCRouter({
value: [datasetItemId],
type: "stringOptions" as const,
},
+ ...(input.datasetRunIds && input.datasetRunIds.length > 0
+ ? [
+ {
+ column: "datasetRunId",
+ operator: "any of",
+ value: input.datasetRunIds,
+ type: "stringOptions" as const,
+ },
+ ]
+ : []),
] as FilterState;
const datasetItem = await ctx.prisma.datasetItem.findFirst({
diff --git a/web/src/features/evals/components/eval-templates-table.tsx b/web/src/features/evals/components/eval-templates-table.tsx
index b1d06f9928..74a74c8e56 100644
--- a/web/src/features/evals/components/eval-templates-table.tsx
+++ b/web/src/features/evals/components/eval-templates-table.tsx
@@ -16,8 +16,7 @@ import {
import { useEffect, useState } from "react";
import TableIdOrName from "@/src/components/table/table-id";
import { PeekViewEvaluatorTemplateDetail } from "@/src/components/table/peek/peek-evaluator-template-detail";
-import { useEvalTemplatesPeekNavigation } from "@/src/components/table/peek/hooks/useEvalTemplatesPeekNavigation";
-import { usePeekState } from "@/src/components/table/peek/hooks/usePeekState";
+import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
import { Button } from "@/src/components/ui/button";
import { useRouter } from "next/router";
@@ -292,8 +291,11 @@ export default function EvalsTemplateTable({
columns,
);
- const { getNavigationPath, expandPeek } = useEvalTemplatesPeekNavigation();
- const { setPeekView } = usePeekState();
+ const peekNavigationProps = usePeekNavigation({
+ expandConfig: {
+ basePath: `/project/${projectId}/evals/templates`,
+ },
+ });
const convertToTableRow = (
template: RouterOutputs["evals"]["templateNames"]["templates"][number],
@@ -330,20 +332,15 @@ export default function EvalsTemplateTable({
columns={columns}
peekView={{
itemType: "EVALUATOR",
- listKey: "eval-templates",
- onOpenChange: setPeekView,
- onExpand: expandPeek,
- shouldUpdateRowOnDetailPageNavigation: true,
- getNavigationPath,
- children: () => (
- <PeekViewEvaluatorTemplateDetail projectId={projectId} />
- ),
+ detailNavigationKey: "eval-templates",
peekEventOptions: {
ignoredSelectors: [
"[aria-label='apply'], [aria-label='actions'], [aria-label='edit'], [aria-label='clone']",
],
},
tableDataUpdatedAt: templates.dataUpdatedAt,
+ children: <PeekViewEvaluatorTemplateDetail projectId={projectId} />,
+ ...peekNavigationProps,
}}
data={
templates.isLoading
diff --git a/web/src/features/evals/components/evaluator-table.tsx b/web/src/features/evals/components/evaluator-table.tsx
index a684b66304..d00688a1c4 100644
--- a/web/src/features/evals/components/evaluator-table.tsx
+++ b/web/src/features/evals/components/evaluator-table.tsx
@@ -24,8 +24,7 @@ import { generateJobExecutionCounts } from "@/src/features/evals/utils/job-execu
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import TableIdOrName from "@/src/components/table/table-id";
import { MoreVertical, Loader2, ExternalLinkIcon, Edit } from "lucide-react";
-import { usePeekState } from "@/src/components/table/peek/hooks/usePeekState";
-import { useRunningEvaluatorsPeekNavigation } from "@/src/components/table/peek/hooks/useRunningEvaluatorsPeekNavigation";
+import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
import { PeekViewEvaluatorConfigDetail } from "@/src/components/table/peek/peek-evaluator-config-detail";
import {
DropdownMenu,
@@ -320,8 +319,7 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
columns,
);
- const { getNavigationPath } = useRunningEvaluatorsPeekNavigation();
- const { setPeekView } = usePeekState();
+ const peekNavigationProps = usePeekNavigation();
const convertToTableRow = (
jobConfig: RouterOutputs["evals"]["allConfigs"]["configs"][number],
@@ -377,19 +375,15 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
columns={columns}
peekView={{
itemType: "RUNNING_EVALUATOR",
- listKey: "evals",
- onOpenChange: setPeekView,
- shouldUpdateRowOnDetailPageNavigation: true,
+ detailNavigationKey: "evals",
peekEventOptions: {
ignoredSelectors: [
"[aria-label='edit'], [aria-label='actions'], [aria-label='view-logs'], [aria-label='delete']",
],
},
- getNavigationPath,
- children: (row) => (
- <PeekViewEvaluatorConfigDetail projectId={projectId} row={row} />
- ),
tableDataUpdatedAt: evaluators.dataUpdatedAt,
+ children: <PeekViewEvaluatorConfigDetail projectId={projectId} />,
+ ...peekNavigationProps,
}}
data={
evaluators.isLoading
diff --git a/web/src/utils/navigation.ts b/web/src/utils/navigation.ts
new file mode 100644
index 0000000000..a43bb98c91
--- /dev/null
+++ b/web/src/utils/navigation.ts
@@ -0,0 +1,14 @@
+// Convert URLSearchParams to Next.js router query object while preserving arrays
+export function urlSearchParamsToQuery(
+ params: URLSearchParams,
+): Record<string, string | string[]> {
+ const query: Record<string, string | string[]> = {};
+ const keys = Array.from(new Set(params.keys())); // Get unique keys
+
+ for (const key of keys) {
+ const allValues = params.getAll(key);
+ query[key] = allValues.length === 1 ? allValues[0] : allValues;
+ }
+
+ return query;
+}