πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(peek): unify the trace detail surface into one adaptive, resizable drawer (#14530)
Nikita Kabardin40376a3b39bb
diff --git a/web/src/components/publish-object-switch.tsx b/web/src/components/publish-object-switch.tsxindex a51a94975e..c51f995789 100644--- a/web/src/components/publish-object-switch.tsx+++ b/web/src/components/publish-object-switch.tsx@@ -5,11 +5,17 @@ import {PopoverContent,PopoverTrigger,} from "@/src/components/ui/popover";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { api } from "@/src/utils/api";import { copyTextToClipboard } from "@/src/utils/clipboard";+import { cn } from "@/src/utils/tailwind";import { trpcErrorToast } from "@/src/utils/trpcErrorToast";import { type RouterInput } from "@/src/utils/types";import { CheckIcon, Globe, Link, Share2 } from "lucide-react";@@ -21,6 +27,10 @@ export const PublishTraceSwitch = (props: {timestamp?: Date;isPublic: boolean;size?: "icon" | "icon-xs";+ /** When set, render as a full-width labeled menu item instead of an icon. */+ label?: string;+ /** Hover tooltip for the icon button (suppressed while the popover is open). */+ tooltip?: string;}) => {const { isBetaEnabled } = useV4Beta();const capture = usePostHogClientCapture();@@ -103,6 +113,8 @@ export const PublishTraceSwitch = (props: {itemName="trace"isPublic={props.isPublic}size={props.size}+ label={props.label}+ tooltip={props.tooltip}onChange={(val) => {capture("trace_detail:publish_button_click");return mut.mutateAsync({@@ -164,6 +176,8 @@ const Base = (props: {isPublic: boolean;disabled?: boolean;size?: "icon" | "icon-xs";+ label?: string;+ tooltip?: string;}) => {const [isCopied, setIsCopied] = useState(false);const [isOpen, setIsOpen] = useState(false);@@ -181,34 +195,54 @@ const Base = (props: {};return (- <div className="flex items-center gap-1">- <div className="text-sm font-semibold">+ <div className={cn("flex items-center gap-1", props.label && "w-full")}>+ <div className={cn("text-sm font-semibold", props.label && "w-full")}><Popoveropen={isOpen}onOpenChange={(open) => {if (!props.isLoading) setIsOpen(open);}}>- <PopoverTrigger asChild>- <Button- id="publish-trace"- variant="ghost"- size={props.size}- loading={props.isLoading}- disabled={props.disabled}- >- {props.isPublic ? (- <Globe- className="h-4 w-4"- fill="#b3d9ff"- stroke="#4d94ff"- strokeWidth={2}- />- ) : (- <Share2 className="h-4 w-4" />- )}- </Button>- </PopoverTrigger>+ {(() => {+ const trigger = (+ <PopoverTrigger asChild>+ <Button+ id="publish-trace"+ variant="ghost"+ size={props.label ? "sm" : props.size}+ className={+ props.label+ ? "w-full justify-start gap-2 font-normal"+ : undefined+ }+ loading={props.isLoading}+ disabled={props.disabled}+ >+ {props.isPublic ? (+ <Globe+ className="h-4 w-4"+ fill="#b3d9ff"+ stroke="#4d94ff"+ strokeWidth={2}+ />+ ) : (+ <Share2 className="h-4 w-4" />+ )}+ {props.label ? (+ <span className="text-sm">{props.label}</span>+ ) : null}+ </Button>+ </PopoverTrigger>+ );+ if (!props.tooltip) return trigger;+ // Suppress the hover tooltip while the share popover is open.+ return (+ <Tooltip open={isOpen ? false : undefined}>+ <TooltipTrigger asChild>{trigger}</TooltipTrigger>+ <TooltipContent>{props.tooltip}</TooltipContent>+ </Tooltip>+ );+ })()}<PopoverContent className="flex flex-col gap-3">{props.isPublic ? (<>diff --git a/web/src/components/star-toggle.tsx b/web/src/components/star-toggle.tsxindex 9dc0ad254d..dd134f673f 100644--- a/web/src/components/star-toggle.tsx+++ b/web/src/components/star-toggle.tsx@@ -14,17 +14,21 @@ export function StarToggle({onClick,size = "icon",isLoading,+ label,}: {value: boolean;disabled?: boolean;onClick: (value: boolean) => Promise<unknown>;size?: "icon" | "icon-xs";isLoading: boolean;+ /** When set, render as a full-width labeled menu item instead of an icon. */+ label?: string;}) {return (<Buttonvariant="ghost"- size={size}+ size={label ? "sm" : size}+ className={label ? "w-full justify-start gap-2 font-normal" : undefined}onClick={(e) => {e.stopPropagation();onClick(!value);@@ -39,6 +43,7 @@ export function StarToggle({stroke={value ? "#ca8a04" : "currentColor"}strokeWidth={2}/>+ {label ? <span className="text-sm">{label}</span> : null}</Button>);}@@ -126,11 +131,13 @@ export function StarTraceDetailsToggle({traceId,value,size = "icon",+ label,}: {projectId: string;traceId: string;value: boolean;size?: "icon" | "icon-xs";+ label?: string;}) {const utils = api.useUtils();const hasAccess = useHasProjectAccess({@@ -163,6 +170,7 @@ export function StarTraceDetailsToggle({<StarTogglevalue={optimisticValue}size={size}+ label={label}disabled={!hasAccess}isLoading={isLoading}onClick={(nextValue) => {diff --git a/web/src/components/table/peek.tsx b/web/src/components/table/peek.tsxindex 53bc4077fc..c563c9bb01 100644--- a/web/src/components/table/peek.tsx+++ b/web/src/components/table/peek.tsx@@ -1,21 +1,24 @@-import { Button } from "@/src/components/ui/button";-import {- Sheet,- SheetContent,- SheetHeader,- SheetTitle,-} from "@/src/components/ui/sheet";-import { Expand, ExternalLink } from "lucide-react";-import { Separator } from "@/src/components/ui/separator";-import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";-import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";+import * as SheetPrimitive from "@radix-ui/react-dialog";+import { Sheet, SheetPortal } from "@/src/components/ui/sheet";+import { Drawer, DrawerContent, DrawerTitle } from "@/src/components/ui/drawer";+import { type LangfuseItemType } from "@/src/components/ItemBadge";import { type ListEntry } from "@/src/features/navigate-detail-pages/context";import { cn } from "@/src/utils/tailwind";-import { memo } from "react";+import { memo, useCallback, useEffect, useState } from "react";import { useRouter } from "next/router";+import { useIsMobile } from "@/src/hooks/use-mobile";+import { getPathnameWithoutBasePath } from "@/src/utils/api";+import { urlSearchParamsToQuery } from "@/src/utils/navigation";import { PeekTableStateProvider } from "@/src/components/table/peek/contexts/PeekTableStateContext";+import { PeekHeader } from "@/src/components/table/peek/PeekHeader";+import { usePeekPanelState } from "@/src/components/table/peek/usePeekPanelState";import { shouldIgnoreOutsideInteraction } from "@/src/utils/outside-interaction";+// Peek view-mode URL param (also cleared by usePeekNavigation on close). When+// `expanded`, the desktop peek widens to viewport β sidebar β shareable + back-able.+const PEEK_VIEW_PARAM = "peekView";+const PEEK_VIEW_EXPANDED = "expanded";+type PeekViewItemType = Extract<LangfuseItemType,"TRACE" | "DATASET_ITEM" | "RUNNING_EVALUATOR" | "EVALUATOR"@@ -54,31 +57,30 @@ export type DataTablePeekViewProps = {peekEventOptions?: PeekEventControlOptions;};-export const createPeekEventHandler = (options?: PeekEventControlOptions) => {- if (!options) return () => false;- const { ignoredSelectors = [] } = options;-- return (): boolean => {- for (const selector of ignoredSelectors) {- if (document.activeElement?.closest(selector)) {- return true;- }- }-- return false;- };-};-type TablePeekViewProps = Pick<DataTablePeekViewProps,| "itemType"| "detailNavigationKey"| "resolveDetailNavigationPath"| "closePeek"+ // Drives the header's "Open in new tab" button (wired via expandConfig). The+ // in-place "Expand" is a separate control; this opens the standalone page in+ // a new tab. The old "open in current tab" variant (expandPeek(false)) is no+ // longer rendered.| "expandPeek"| "peekEventOptions"> & {title?: string;+ /**+ * Item-specific header actions (star / publish / delete β¦), shared with the+ * full detail page so the peek and the page expose the same controls.+ */+ actions?: React.ReactNode;+ /**+ * The same actions rendered as labeled menu rows β shown in the header's+ * overflow "β¦" menu when the peek is too narrow for the inline icon row.+ */+ actionsMenu?: React.ReactNode;// Content/*** The content to display in the peek view.@@ -86,96 +88,246 @@ type TablePeekViewProps = Pick<children: React.ReactNode;};+// Shared DataTable selection controls live outside the peek but must never+// dismiss it β clicking a selection checkbox is a selection action, not a+// dismiss. Row checkboxes are already covered by the `[data-row-index]` check+// below; this also covers the header "select all". Applied to every peek so+// tables don't each have to redeclare it (which is easy to forget).+const ALWAYS_KEEP_PEEK_OPEN_SELECTORS = ['[role="checkbox"]'];++/**+ * Decide whether an outside interaction should keep the peek open instead of+ * closing it. The peek closes on a genuine click-outside, with exceptions that+ * preserve power-user behavior:+ * - clicking another table row (`[data-row-index]`) switches the peeked item in+ * place rather than closing (handled by the row's own click handler),+ * - shared selection controls and any table-specific `ignoredSelectors`+ * (bookmark toggles, etc.) don't close it, and+ * - regions that opt out via `data-ignore-outside-interaction` (e.g. the in-app+ * assistant) never trigger a close.+ *+ * All checks run against the pointer event's `target`, not+ * `document.activeElement` β `onPointerDownOutside` fires on pointer-down,+ * before focus has moved to the clicked element.+ */+export const shouldKeepPeekOpenOnOutsideInteraction = (+ target: EventTarget | null,+ ignoredSelectors: string[],+): boolean => {+ if (!(target instanceof Element)) return false;+ // Never dismiss for a target actually inside the peek. Radix usually detects+ // this, but primitives that capture the pointer natively (e.g. the inner+ // react-resizable-panels split handle) can bypass its inside-detection and be+ // misreported as outside β which would close the peek mid-drag and unmount+ // the panel group. This guard keeps interactions within the peek safe.+ if (target.closest("[data-peek-content]")) return true;+ if (shouldIgnoreOutsideInteraction(target)) return true;+ if (target.closest("[data-row-index]")) return true;+ return [...ALWAYS_KEEP_PEEK_OPEN_SELECTORS, ...ignoredSelectors].some(+ (selector) => target.closest(selector),+ );+};+function TablePeekViewComponent(props: TablePeekViewProps) {- const peekView = props;const { title, children } = props;const router = useRouter();- const eventHandler = createPeekEventHandler(peekView.peekEventOptions);const itemId = router.query.peek as string | undefined;+ const isExpanded = router.query[PEEK_VIEW_PARAM] === PEEK_VIEW_EXPANDED;+ const isMobile = useIsMobile();- if (!itemId) return null;+ // Expanded is view state, owned by the peek and reflected in the URL so it is+ // shareable + survives reload. Managed here (not threaded through every table+ // consumer); usePeekNavigation clears the param when the peek closes. Uses+ // replace (not push) so toggling expand/collapse doesn't spam history.+ const setExpanded = useCallback(+ (expanded: boolean) => {+ const params = new URLSearchParams(window.location.search);+ const currentlyExpanded =+ params.get(PEEK_VIEW_PARAM) === PEEK_VIEW_EXPANDED;+ // No-op when the flag already matches: skip the redundant shallow+ // router.replace (and the re-render it would otherwise trigger).+ if (expanded === currentlyExpanded) return;+ if (expanded) params.set(PEEK_VIEW_PARAM, PEEK_VIEW_EXPANDED);+ else params.delete(PEEK_VIEW_PARAM);+ router.replace(+ {+ pathname: getPathnameWithoutBasePath(),+ query: urlSearchParamsToQuery(params),+ },+ undefined,+ { shallow: true },+ );+ },+ [router],+ );++ const panel = usePeekPanelState({+ isOpen: !!itemId,+ isExpanded,+ onExpandedChange: setExpanded,+ });+ const ignoredSelectors = props.peekEventOptions?.ignoredSelectors ?? [];++ // Gate the first render on mount so we never paint the desktop sheet before+ // `useIsMobile` resolves (which would flash the wrong shell on a mobile+ // deep-link). Click-to-open is already post-mount, so it has no delay.+ const [mounted, setMounted] = useState(false);+ useEffect(() => setMounted(true), []);++ // Hooks run unconditionally above this early return so ordering stays stable+ // across open/close. Returning null on close unmounts PeekTableStateProvider,+ // which is what resets nested-table state when the peek closes (see README).+ if (!itemId || !mounted) return null;const handleOpenChange = (open: boolean) => {- // 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();+ // Open is driven by row clicks / detail-page navigation; we only react to+ // close requests (Escape, swipe-down, click-outside, the close button).+ if (open) return;+ props.closePeek();};- const canExpand = typeof peekView.expandPeek === "function";+ const resolvedTitle = title ?? itemId;++ // Distinct from Expand (which widens in place via the URL): this opens the+ // standalone detail page in a NEW tab, leaving the peek untouched β handy for+ // comparing against the full-page view. Only when the consumer wired+ // expandConfig (so expandPeek exists).+ const expandPeek = props.expandPeek;+ const openInNewTab = expandPeek ? () => expandPeek(true) : undefined;++ const header = (+ <PeekHeader+ itemType={props.itemType}+ title={resolvedTitle}+ itemId={itemId}+ detailNavigationKey={props.detailNavigationKey}+ resolveDetailNavigationPath={props.resolveDetailNavigationPath}+ actions={props.actions}+ actionsMenu={props.actionsMenu}+ expand={+ isMobile+ ? undefined+ : {+ isExpanded: panel.isExpanded,+ onToggle: panel.toggleExpanded,+ }+ }+ openInNewTab={openInNewTab}+ onClose={props.closePeek}+ />+ );++ const content = (+ <div className="flex max-h-full min-h-0 flex-1 flex-col overflow-hidden">+ <div className="flex-1 overflow-auto" key={itemId}>+ {children}+ </div>+ </div>+ );+ // One PeekTableStateProvider wraps BOTH shells, above the mobile/desktop+ // branch, so the nested-table state it holds (filters, sort, pagination,+ // search) survives a breakpoint cross β without this, resizing across the+ // mobile/desktop boundary swaps DrawerβSheet and would otherwise remount a+ // fresh provider, dropping that state. It unmounts only on close (the early+ // `return null` above), which is what resets the state (see README).return (- <Sheet open={!!itemId} onOpenChange={handleOpenChange} modal={false}>- <SheetContent- onPointerDownOutside={(e) => {- // Prevent the default behavior of closing when clicking outside when we set modal={false}- e.preventDefault();- }}- onInteractOutside={(e) => {- if (shouldIgnoreOutsideInteraction(e.target)) {- e.preventDefault();- }- }}- side="right"- className="flex max-h-full min-h-0 min-w-[60vw] flex-col gap-0 overflow-hidden p-0"- >- <SheetHeader className="bg-header flex min-h-11 flex-row flex-nowrap items-center justify-between px-2 py-1">- <SheetTitle className="flex min-w-0 flex-row items-center gap-2">- <ItemBadge type={peekView.itemType} showLabel />- <span- className="truncate text-sm font-medium focus:outline-hidden"- tabIndex={0}- >- {title ?? itemId}- </span>- </SheetTitle>- <div- className={cn(- "mt-0! flex shrink-0 flex-row items-center gap-2",- !canExpand && "mr-8",- )}+ <PeekTableStateProvider>+ {isMobile ? (+ // Mobile: a vaul bottom drawer with native swipe-down dismissal.+ <Drawer+ open={!!itemId}+ onOpenChange={handleOpenChange}+ forceDirection="bottom"+ >+ <DrawerContent+ size="full"+ className="min-h-screen-with-banner top-[calc(var(--banner-offset)+10px)] bottom-0 gap-0 p-0">- {itemId &&- peekView.detailNavigationKey &&- peekView.resolveDetailNavigationPath && (- <DetailPageNav- currentId={itemId}- path={peekView.resolveDetailNavigationPath}- listKey={peekView.detailNavigationKey}- />+ <DrawerTitle className="sr-only">{resolvedTitle}</DrawerTitle>+ <div className="flex w-full shrink-0 items-center justify-center pt-2 pb-1">+ <div className="bg-muted h-1.5 w-12 rounded-full" />+ </div>+ {header}+ {content}+ </DrawerContent>+ </Drawer>+ ) : (+ // Desktop: a docked-right, resizable panel that stays on top of the+ // table (non-modal, no overlay) so the table behind stays interactive.+ <Sheet open={!!itemId} onOpenChange={handleOpenChange} modal={false}>+ <SheetPortal>+ <SheetPrimitive.Content+ aria-describedby={undefined}+ data-peek-content=""+ style={panel.panelStyle}+ onPointerDownOutside={(e) => {+ if (+ shouldKeepPeekOpenOnOutsideInteraction(+ e.target,+ ignoredSelectors,+ )+ ) {+ e.preventDefault();+ }+ }}+ onInteractOutside={(e) => {+ if (+ shouldKeepPeekOpenOnOutsideInteraction(+ e.target,+ ignoredSelectors,+ )+ ) {+ e.preventDefault();+ }+ }}+ // Never close because focus moved out (e.g. into a portaled+ // popover or another input); only pointer/Escape/close-button+ // drive dismissal.+ onFocusOutside={(e) => e.preventDefault()}+ className={cn(+ // No overflow-hidden here: the resize handle straddles the left+ // edge (overhangs onto the table) so it's grabbable from either+ // side. The body clips its own content instead.+ "bg-background top-banner-offset h-screen-with-banner fixed right-0 bottom-0 flex max-h-full min-h-0 max-w-none flex-col gap-0 border-l",+ // Soft shadow cast leftward (toward the table) to lift the peek+ // off the content behind it.+ "shadow-[-12px_0_32px_-16px_rgb(0_0_0_/_0.30)]",+ "data-[state=open]:animate-in data-[state=open]:slide-in-from-right data-[state=closed]:animate-out data-[state=closed]:slide-out-to-right data-[state=closed]:duration-100 data-[state=open]:duration-100",+ panel.isResizing && "select-none",)}- {canExpand && (- <div className="mt-0! mr-8 flex h-full flex-row items-center gap-1 border-l">- <Button- variant="ghost"- size="icon-xs"- title="Open in current tab"- className="ml-2"- onClick={() => peekView.expandPeek?.(false)}- >- <Expand className="h-4 w-4" />- </Button>- <Button- variant="ghost"- size="icon-xs"- title="Open in new tab"- onClick={() => peekView.expandPeek?.(true)}- >- <ExternalLink className="h-4 w-4" />- </Button>+ >+ <SheetPrimitive.Title className="sr-only">+ {resolvedTitle}+ </SheetPrimitive.Title>+ {header}+ {content}+ {/* Rendered last so it is not the dialog's initial focus target.+ It STRADDLES the left edge (β4px onto the table β¦ +8px inside)+ so it's an easy, grabbable target from either side; absolutely+ positioned, so DOM order doesn't affect its placement. */}+ <div+ {...panel.resizeHandleProps}+ className="group/resize absolute inset-y-0 -left-1 z-20 flex w-3 cursor-ew-resize touch-none justify-center focus-visible:outline-hidden"+ >+ <div+ aria-hidden="true"+ className={cn(+ // Sits on the panel's left edge; subtle at rest, clearer on+ // hover/drag (neutral, no brand accent β cursor signals it).+ "h-full w-1 rounded-full transition-colors",+ "group-hover/resize:bg-muted-foreground/40 group-focus-visible/resize:bg-muted-foreground/50",+ panel.isResizing+ ? "bg-muted-foreground/60"+ : "bg-transparent",+ )}+ /></div>- )}- </div>- </SheetHeader>- <Separator />- <PeekTableStateProvider>- <div className="flex max-h-full min-h-0 flex-1 flex-col">- <div className="flex-1 overflow-auto" key={itemId}>- {children}- </div>- </div>- </PeekTableStateProvider>- </SheetContent>- </Sheet>+ </SheetPrimitive.Content>+ </SheetPortal>+ </Sheet>+ )}+ </PeekTableStateProvider>);}diff --git a/web/src/components/table/peek/PeekHeader.tsx b/web/src/components/table/peek/PeekHeader.tsxnew file mode 100644index 0000000000..62b76525c4--- /dev/null+++ b/web/src/components/table/peek/PeekHeader.tsx@@ -0,0 +1,313 @@+import { useLayoutEffect, useRef, useState } from "react";+import { Button } from "@/src/components/ui/button";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/src/components/ui/popover";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";+import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";+import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";+import { type ListEntry } from "@/src/features/navigate-detail-pages/context";+import {+ ExternalLink,+ Maximize2,+ Minimize2,+ MoreHorizontal,+ X,+} from "lucide-react";+import { useElementSize } from "@/src/hooks/useElementSize";+import {+ planPeekHeaderLayout,+ type PeekHeaderPlan,+} from "@/src/components/table/peek/peekHeaderOverflow";++type PeekHeaderProps = {+ itemType: LangfuseItemType;+ title: React.ReactNode;+ itemId: string;+ detailNavigationKey?: string;+ resolveDetailNavigationPath?: (entry: ListEntry) => string;+ /** Item actions (star / publish / delete β¦) as the inline icon row. */+ actions?: React.ReactNode;+ /** The same actions as labeled rows for the overflow "β¦" menu. */+ actionsMenu?: React.ReactNode;+ /** Expand-to-max-width toggle. Desktop only; hidden on mobile. */+ expand?: { isExpanded: boolean; onToggle: () => void };+ /** Open the standalone detail page in a new browser tab. Optional. */+ openInNewTab?: () => void;+ onClose: () => void;+};++// The title keeps at least this much width before anything else collapses; the+// type badge falls back to this width when icon-only; the "β¦" trigger is an+// icon-xs button. Tuned by eye β planner `safety` covers inter-control gaps.+const MIN_TITLE_PX = 240;+const BADGE_ICON_PX = 32;+const MORE_BUTTON_PX = 32;+const BADGE_LABEL_FALLBACK_PX = 72;+const NAV_FULL_FALLBACK_PX = 92;+const NAV_COMPACT_FALLBACK_PX = 52;++const samePlan = (a: PeekHeaderPlan, b: PeekHeaderPlan) =>+ a.foldActions === b.foldActions &&+ a.foldOpenInTab === b.foldOpenInTab &&+ a.badgeShowLabel === b.badgeShowLabel &&+ a.navCompact === b.navCompact;++const FULL: PeekHeaderPlan = {+ foldActions: false,+ foldOpenInTab: false,+ badgeShowLabel: true,+ navCompact: false,+};++// Header tooltips appear quickly and share one style (Radix Tooltip, not the+// slow/inconsistent native `title`).+const TOOLTIP_DELAY_MS = 300;++function HeaderIconButton({+ label,+ onClick,+ children,+}: {+ label: string;+ onClick: () => void;+ children: React.ReactNode;+}) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={label}+ onClick={onClick}+ >+ {children}+ </Button>+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ );+}++/**+ * Visible peek chrome shared by the desktop sheet and the mobile drawer. The+ * accessible dialog title is provided (visually hidden) by each shell, so this+ * stays a plain view component that works inside either primitive.+ *+ * The header adapts to the PEEK's own width (measured, not screen breakpoints):+ * it keeps the title readable and, as the peek narrows, folds the trace actions+ * into a labeled "β¦" menu, shrinks the type badge to icon-only, compacts the+ * prev/next nav, then folds open-in-tab β see {@link planPeekHeaderLayout}.+ */+export function PeekHeader({+ itemType,+ title,+ itemId,+ detailNavigationKey,+ resolveDetailNavigationPath,+ actions,+ actionsMenu,+ expand,+ openInNewTab,+ onClose,+}: PeekHeaderProps) {+ const [headerRef, headerSize] = useElementSize<HTMLDivElement>();+ // The header width equals the peek width and so doesn't change when the+ // controls settle (or data loads) after the first measurement β observe the+ // control cluster too, whose width does change, to re-trigger the plan.+ const [clusterRef, clusterSize] = useElementSize<HTMLDivElement>();+ const badgeRef = useRef<HTMLDivElement>(null);+ const actionsRef = useRef<HTMLDivElement>(null);+ const openInTabRef = useRef<HTMLDivElement>(null);+ const navRef = useRef<HTMLDivElement>(null);+ const pinnedRef = useRef<HTMLDivElement>(null);+ // Cached widths survive a part being folded / collapsed (it can't be+ // re-measured while hidden, in the closed popover, or in the other nav mode).+ const widthsRef = useRef<{+ actions?: number;+ openInTab?: number;+ badgeLabel?: number;+ navFull?: number;+ navCompact?: number;+ otherPinned?: number;+ }>({});+ const [plan, setPlan] = useState<PeekHeaderPlan>(FULL);++ const hasActions = Boolean(actions);+ const hasOpenInTab = Boolean(openInNewTab);+ const hasNav = Boolean(detailNavigationKey && resolveDetailNavigationPath);++ // Measure + plan in a layout effect (before paint), reading width from the+ // ref directly β useElementSize's state lands post-paint, which would flash+ // the un-adapted header for a frame.+ useLayoutEffect(() => {+ const width =+ headerRef.current?.getBoundingClientRect().width ?? headerSize?.width;+ if (!width) return;++ if (plan.badgeShowLabel && badgeRef.current) {+ widthsRef.current.badgeLabel = badgeRef.current.offsetWidth;+ }+ if (hasActions && !plan.foldActions && actionsRef.current) {+ widthsRef.current.actions = actionsRef.current.offsetWidth;+ }+ if (hasOpenInTab && !plan.foldOpenInTab && openInTabRef.current) {+ widthsRef.current.openInTab = openInTabRef.current.offsetWidth;+ }+ if (pinnedRef.current) {+ const navW = hasNav && navRef.current ? navRef.current.offsetWidth : 0;+ if (hasNav) {+ if (plan.navCompact) widthsRef.current.navCompact = navW;+ else widthsRef.current.navFull = navW;+ }+ widthsRef.current.otherPinned = pinnedRef.current.offsetWidth - navW;+ }++ const next = planPeekHeaderLayout({+ headerWidth: width,+ minTitle: MIN_TITLE_PX,+ badgeLabelWidth: widthsRef.current.badgeLabel ?? BADGE_LABEL_FALLBACK_PX,+ badgeIconWidth: BADGE_ICON_PX,+ navFullWidth: hasNav+ ? (widthsRef.current.navFull ?? NAV_FULL_FALLBACK_PX)+ : 0,+ navCompactWidth: hasNav+ ? (widthsRef.current.navCompact ?? NAV_COMPACT_FALLBACK_PX)+ : 0,+ otherPinnedWidth: widthsRef.current.otherPinned ?? 0,+ moreWidth: MORE_BUTTON_PX,+ actionsWidth: hasActions ? (widthsRef.current.actions ?? 0) : undefined,+ openInTabWidth: hasOpenInTab+ ? (widthsRef.current.openInTab ?? 0)+ : undefined,+ });+ setPlan((prev) => (samePlan(prev, next) ? prev : next));+ }, [+ headerRef,+ headerSize?.width,+ clusterSize?.width,+ hasActions,+ hasOpenInTab,+ hasNav,+ plan,+ ]);++ const anyFolded = plan.foldActions || plan.foldOpenInTab;++ return (+ <TooltipProvider delayDuration={TOOLTIP_DELAY_MS}>+ <div+ ref={headerRef}+ className="bg-header flex min-h-11 shrink-0 flex-row flex-nowrap items-center justify-between gap-2 overflow-hidden px-2 py-1"+ >+ <div className="flex min-w-0 flex-row items-center gap-2">+ {/* Badge never truncates: it shows the full label or just the icon. */}+ <div ref={badgeRef} className="shrink-0">+ <ItemBadge type={itemType} showLabel={plan.badgeShowLabel} />+ </div>+ <span+ className="truncate text-sm font-medium focus:outline-hidden"+ tabIndex={0}+ title={typeof title === "string" ? title : undefined}+ >+ {title}+ </span>+ </div>+ <div+ ref={clusterRef}+ className="flex shrink-0 flex-row items-center gap-1"+ >+ {/* Overflow: a labeled menu of whatever folded away. */}+ {anyFolded && (+ <Popover>+ <Tooltip>+ <TooltipTrigger asChild>+ <PopoverTrigger asChild>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label="More actions"+ >+ <MoreHorizontal className="h-4 w-4" />+ </Button>+ </PopoverTrigger>+ </TooltipTrigger>+ <TooltipContent>More</TooltipContent>+ </Tooltip>+ <PopoverContent+ align="end"+ className="flex w-auto min-w-44 flex-col gap-0.5 p-1"+ >+ {plan.foldActions ? actionsMenu : null}+ {plan.foldOpenInTab && openInNewTab ? (+ <button+ type="button"+ onClick={openInNewTab}+ className="hover:bg-accent flex w-full items-center gap-2 rounded-sm py-1.5 pr-2 pl-1.5 text-sm"+ >+ <ExternalLink className="h-4 w-4" />+ Open in new tab+ </button>+ ) : null}+ </PopoverContent>+ </Popover>+ )}++ {hasActions && !plan.foldActions ? (+ <div ref={actionsRef} className="flex flex-row items-center gap-1">+ {actions}+ </div>+ ) : null}++ {hasOpenInTab && !plan.foldOpenInTab && openInNewTab ? (+ <div ref={openInTabRef}>+ <HeaderIconButton label="Open in new tab" onClick={openInNewTab}>+ <ExternalLink className="h-4 w-4" />+ </HeaderIconButton>+ </div>+ ) : null}++ {/* Pinned block: nav (keeps K/J live), expand, close. */}+ <div+ ref={pinnedRef}+ className="flex h-full flex-row items-center gap-1"+ >+ {hasNav && (+ <div ref={navRef} className="flex flex-row items-center">+ <DetailPageNav+ currentId={itemId}+ path={resolveDetailNavigationPath!}+ listKey={detailNavigationKey!}+ compact={plan.navCompact}+ />+ </div>+ )}+ {expand && (+ <HeaderIconButton+ label={expand.isExpanded ? "Collapse" : "Expand"}+ onClick={expand.onToggle}+ >+ {expand.isExpanded ? (+ <Minimize2 className="h-4 w-4" />+ ) : (+ <Maximize2 className="h-4 w-4" />+ )}+ </HeaderIconButton>+ )}+ <HeaderIconButton label="Close" onClick={onClose}>+ <X className="h-4 w-4" />+ </HeaderIconButton>+ </div>+ </div>+ </div>+ </TooltipProvider>+ );+}diff --git a/web/src/components/table/peek/README.md b/web/src/components/table/peek/README.mdindex 215a6068f3..5d198d1e5e 100644--- a/web/src/components/table/peek/README.md+++ b/web/src/components/table/peek/README.md@@ -6,6 +6,64 @@ This document describes how table state (filters, sorting, pagination, search) iPeek views allow users to quickly preview table items in a side panel. When navigating between items using K/J shortcuts, tables inside the peek view remount, which would normally reset their state. The peek state management system prevents this by storing table state in a context that persists across navigation.+## Panel shell, resize, and expand++`TablePeekView` ([`../peek.tsx`](../peek.tsx)) is responsive and keeps the peek+**on top of the table** (it does not split the layout):++- **Desktop** β a docked-right, non-modal Radix dialog (no overlay), so the+ table behind stays interactive. A left-edge handle resizes it; dragging to the+ far edge (or the header Expand button) **expands** it to the max width+ (viewport β sidebar; the sidebar stays visible).+- **Mobile** (`useIsMobile`, <768px) β a `vaul` bottom drawer with native+ swipe-down dismissal (Expand is hidden).++Dismissal:++- **Click-outside closes**, with exceptions: a target inside the peek+ (`[data-peek-content]`) never closes it; clicking another table row+ (`[data-row-index]`) **switches** the peeked item in place; and selection+ checkboxes / `data-ignore-outside-interaction` regions / the table's+ `ignoredSelectors` don't close it. Nested Radix popovers/menus opened inside+ the peek don't close it (DismissableLayer stacking).+- **Escape**, the close button, and (mobile) swipe-down also close.++Panel state follows the local-feature-state pattern from+`frontend-large-feature-architecture`:++- [`store/peekPanelStore.ts`](./store/peekPanelStore.ts) β a per-mount vanilla+ Zustand store (lazy `useState`) owning ONLY the widget width + transient drag+ state, mutated through named `actions`. Selectors (`selectWidgetWidth`,+ `selectIsResizing`, `selectDraftExpanded`) return primitives so subscriptions+ bail out cheaply.+- [`actions/resizePeekPanel.ts`](./actions/resizePeekPanel.ts) β the drag+ workflow (window pointer listeners β store actions; on pointer-up commits a+ widget width or flips the expanded flag). Takes the store instance, not hooks.+- [`usePeekPanelState.ts`](./usePeekPanelState.ts) β the integration boundary:+ owns the store, derives the final width (widget vs expanded β measuring the+ sidebar offset for the expanded case), and wires drag/keyboard to the store ++ action. Takes `isExpanded` in / `onExpandedChange` out (the URL owns expanded).++State altitudes:++| State | Altitude | Where it lives |+| ----------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------- |+| expanded | route (shareable, reloadable) | URL `peekView=expanded`, managed in `peek.tsx` (`router.replace`), cleared on close by `usePeekNavigation` |+| width | cross-view persisted preference | store `widthFraction`, mirrored to `localStorage` (`peekViewWidthFraction`) |+| resize drag | high-frequency transient | store `draftFraction` / `draftExpanded` / `isResizing`, committed on pointer-up |+| which item | route | the `peek` URL param (see below) |++The peek and the standalone trace page already share one beta-aware fetch+([`../../trace/useTraceDetailData.ts`](../../trace/useTraceDetailData.ts)), one+body + title+([`../../trace/TraceDetailBody.tsx`](../../trace/TraceDetailBody.tsx) β+`TraceDetailBody` / `traceDetailTitle`), and one action set+([`../../trace/TraceDetailActions.tsx`](../../trace/TraceDetailActions.tsx) β+star / publish / delete) β `usePeekData` is now a thin wrapper over the shared+hook. **Next slice:** collapse the `<Trace context>` branching and fold these+primitives into a single `TraceDetailSurface` wrapper so the peek and `TracePage`+share one component, not four β see the PR discussion.+## ArchitectureThe peek state architecture separates the persisting context provider from the remounting content:diff --git a/web/src/components/table/peek/actions/resizePeekPanel.clienttest.ts b/web/src/components/table/peek/actions/resizePeekPanel.clienttest.tsnew file mode 100644index 0000000000..6bbf85fd8d--- /dev/null+++ b/web/src/components/table/peek/actions/resizePeekPanel.clienttest.ts@@ -0,0 +1,83 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { beginPeekResize } from "@/src/components/table/peek/actions/resizePeekPanel";+import {+ createPeekPanelStore,+ selectDraftExpanded,+} from "@/src/components/table/peek/store/peekPanelStore";++const STORAGE_KEY = "peekViewWidthFraction";++// A primary-button pointerdown β the only kind that begins a drag.+const pointerDown = () =>+ ({ button: 0, preventDefault: () => {} }) as unknown as React.PointerEvent;++// The panel is docked right, so its width fraction is `1 - clientX/innerWidth`.+// Derive the clientX that yields a target fraction from the live viewport width.+const clientXForFraction = (fraction: number) =>+ Math.round((1 - fraction) * window.innerWidth);++const move = (clientX: number) =>+ window.dispatchEvent(new MouseEvent("pointermove", { clientX }));++describe("beginPeekResize", () => {+ beforeEach(() => window.localStorage.clear());+ afterEach(() => window.localStorage.clear());++ it("commits the dragged widget width to localStorage on pointer-up", () => {+ window.localStorage.setItem(STORAGE_KEY, "0.5");+ const store = createPeekPanelStore();+ const commitExpanded = vi.fn();++ beginPeekResize(store, pointerDown(), commitExpanded);+ move(clientXForFraction(0.7));+ window.dispatchEvent(new Event("pointerup"));++ expect(store.getState().widthFraction).toBeCloseTo(0.7);+ expect(+ parseFloat(window.localStorage.getItem(STORAGE_KEY) ?? ""),+ ).toBeCloseTo(0.7);+ expect(commitExpanded).toHaveBeenLastCalledWith(false);+ expect(store.getState().isResizing).toBe(false);+ });++ it("aborts on pointercancel WITHOUT committing the width or expanding", () => {+ // pointercancel is a system abort (palm rejection, gesture intercept, OS+ // interrupt), not a release β the saved width must survive untouched.+ window.localStorage.setItem(STORAGE_KEY, "0.5");+ const store = createPeekPanelStore();+ const commitExpanded = vi.fn();++ beginPeekResize(store, pointerDown(), commitExpanded);+ move(clientXForFraction(0.7)); // would persist 0.7 on a real pointer-up+ window.dispatchEvent(new Event("pointercancel"));++ expect(store.getState().widthFraction).toBeCloseTo(0.5);+ expect(window.localStorage.getItem(STORAGE_KEY)).toBe("0.5");+ expect(commitExpanded).not.toHaveBeenCalled();+ expect(store.getState().draftFraction).toBeNull();+ expect(store.getState().isResizing).toBe(false);+ });++ it("flips to expanded at the sidebar-aligned threshold (not the static 0.95)", () => {+ const store = createPeekPanelStore();+ const commitExpanded = vi.fn();+ // Sidebar edge at fraction 0.8 β dragging to 0.85 expands, no overshoot.+ beginPeekResize(store, pointerDown(), commitExpanded, 0.8);+ move(clientXForFraction(0.85));+ expect(selectDraftExpanded(store.getState())).toBe(true);+ window.dispatchEvent(new Event("pointerup"));+ expect(commitExpanded).toHaveBeenLastCalledWith(true);+ });++ it("removes its window listeners after a cancelled drag", () => {+ const store = createPeekPanelStore();+ const commitExpanded = vi.fn();++ beginPeekResize(store, pointerDown(), commitExpanded);+ window.dispatchEvent(new Event("pointercancel"));+ // A stray move after teardown must not revive draft state.+ move(clientXForFraction(0.7));+ expect(store.getState().draftFraction).toBeNull();+ });+});diff --git a/web/src/components/table/peek/actions/resizePeekPanel.ts b/web/src/components/table/peek/actions/resizePeekPanel.tsnew file mode 100644index 0000000000..858cc2030f--- /dev/null+++ b/web/src/components/table/peek/actions/resizePeekPanel.ts@@ -0,0 +1,100 @@+import { type PointerEvent as ReactPointerEvent } from "react";+import {+ PEEK_EXPAND_ENTER_FRACTION,+ type PeekPanelStore,+} from "@/src/components/table/peek/store/peekPanelStore";++/** Viewport fraction to the RIGHT of the pointer (the panel is docked right). */+function widthFractionFromClientX(clientX: number): number {+ return 1 - clientX / window.innerWidth;+}++/**+ * Drag workflow for the left-edge resize handle. Attaches window pointer+ * listeners, drives the store's transient drag state, and on pointer-up either+ * commits a widget width or flips the expanded flag via `commitExpanded` (which+ * writes the URL). Dragging past {@link PEEK_EXPAND_ENTER_FRACTION} previews+ * (and, on release, commits) the expanded max width β so the drag and the+ * header button are two triggers of the same expanded state.+ *+ * Not a hook β it takes the store instance directly (per the local-feature+ * state pattern). Returns a teardown that ends an in-flight drag; the caller+ * also runs it on unmount / when the peek closes so a drag interrupted mid-flight+ * can't leak listeners or leave the body cursor/selection styles applied.+ */+export function beginPeekResize(+ store: PeekPanelStore,+ event: ReactPointerEvent,+ commitExpanded: (expanded: boolean) => void,+ // Fraction at which the drag flips to "expanded" β the sidebar edge+ // (`viewport β sidebar`), passed live by the hook so the panel stops exactly+ // at the sidebar instead of overshooting onto it and snapping back. Defaults+ // to the static threshold when no sidebar offset is known.+ expandAtFraction: number = PEEK_EXPAND_ENTER_FRACTION,+ // Whether the panel is currently expanded. The drag seeds its draft from+ // this so merely PRESSING the handle doesn't change the width β only moving+ // does (otherwise starting a drag while expanded snaps to the widget width+ // on pointer-down, a visible jump).+ startExpanded = false,+): () => void {+ // Only primary-button drags; the keyboard path handles the rest.+ if (event.button !== 0) return () => {};+ event.preventDefault();++ const onPointerMove = (move: PointerEvent) => {+ const fraction = widthFractionFromClientX(move.clientX);+ const { actions } = store.getState();+ // At/past the sidebar edge (incl. the pointer leaving the window) β+ // expanded; never let the widget width overshoot onto the sidebar.+ if (fraction >= expandAtFraction) {+ actions.setDraftExpanded();+ } else {+ actions.setDraftFraction(fraction);+ }+ };++ const teardown = () => {+ window.removeEventListener("pointermove", onPointerMove);+ window.removeEventListener("pointerup", onPointerUp);+ window.removeEventListener("pointercancel", onPointerCancel);+ document.body.style.removeProperty("user-select");+ document.body.style.removeProperty("cursor");+ };++ const onPointerUp = () => {+ teardown();+ const { draftExpanded, draftFraction, actions } = store.getState();+ if (draftExpanded) {+ // Released past the threshold β expanded (reflected in the URL).+ commitExpanded(true);+ } else if (draftFraction !== null) {+ // Released on a widget width β persist it and ensure we're collapsed.+ actions.commitWidth(draftFraction);+ commitExpanded(false);+ }+ // The hook holds the committed expanded value (pendingExpanded) until the+ // URL catches up, so clearing the drag state here can't flash the old width.+ actions.cancelResize();+ };++ // pointercancel is an ABORT, not a release (system gesture intercept, palm+ // rejection, accessibility tooling, pointer-capture transfer, OS interrupt).+ // Tear down and drop the in-flight draft WITHOUT committing β a cancelled+ // gesture must not overwrite the persisted width or flip the expanded flag.+ const onPointerCancel = () => {+ teardown();+ store.getState().actions.cancelResize();+ };++ window.addEventListener("pointermove", onPointerMove);+ window.addEventListener("pointerup", onPointerUp);+ window.addEventListener("pointercancel", onPointerCancel);+ document.body.style.userSelect = "none";+ document.body.style.cursor = "ew-resize";+ store.getState().actions.setResizing(true);+ // Seed the draft to the current width so pressing the handle is a no-op until+ // the pointer actually moves.+ if (startExpanded) store.getState().actions.setDraftExpanded();++ return teardown;+}diff --git a/web/src/components/table/peek/hooks/usePeekData.ts b/web/src/components/table/peek/hooks/usePeekData.tsindex 5f35fa1330..bb07cdd644 100644--- a/web/src/components/table/peek/hooks/usePeekData.ts+++ b/web/src/components/table/peek/hooks/usePeekData.ts@@ -1,6 +1,4 @@-import { api } from "@/src/utils/api";-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";-import { useEventsTraceData } from "@/src/features/events/hooks/useEventsTraceData";+import { useTraceDetailData } from "@/src/components/trace/useTraceDetailData";type UsePeekDataProps = {projectId: string;@@ -8,49 +6,13 @@ type UsePeekDataProps = {timestamp?: Date;};+/**+ * Peek's trace-data hook β a thin wrapper over the shared+ * {@link useTraceDetailData} so the peek and the standalone trace page fetch+ * through one place. Callers read `data` / `isLoading`.+ */export const usePeekData = ({projectId,traceId,timestamp,-}: UsePeekDataProps) => {- const { isBetaEnabled } = useV4Beta();-- // Old path: fetch from traces table (beta OFF)- const tracesQuery = api.traces.byIdWithObservationsAndScores.useQuery(- {- traceId: traceId as string,- projectId,- timestamp,- },- {- enabled: !!traceId && !isBetaEnabled,- retry(failureCount, error) {- if (error.data?.code === "UNAUTHORIZED") return false;- return failureCount < 3;- },- staleTime: 60 * 1000, // 1 minute- },- );-- // New path: fetch from events table (beta ON)- const eventsData = useEventsTraceData({- projectId,- traceId: traceId ?? "",- timestamp,- enabled: !!traceId && isBetaEnabled,- });-- // Return the appropriate data based on beta toggle- if (isBetaEnabled) {- return {- data: eventsData.data,- isLoading: eventsData.isLoading,- error: eventsData.error,- // Provide stub for other fields to match tracesQuery return type- isError: !!eventsData.error,- isFetching: eventsData.isLoading,- };- }-- return tracesQuery;-};+}: UsePeekDataProps) => useTraceDetailData({ projectId, traceId, timestamp });diff --git a/web/src/components/table/peek/hooks/usePeekNavigation.ts b/web/src/components/table/peek/hooks/usePeekNavigation.tsindex d155093213..2baee4fe3c 100644--- a/web/src/components/table/peek/hooks/usePeekNavigation.ts+++ b/web/src/components/table/peek/hooks/usePeekNavigation.ts@@ -5,6 +5,8 @@ import { useCallback } from "react";import { urlSearchParamsToQuery } from "@/src/utils/navigation";const PEEK_PARAM = "peek";+// View-mode param shared with the peek component (cleared whenever the peek closes).+const PEEK_VIEW_PARAM = "peekView";interface BasePeekConfig {/** Additional URL parameters to clear when closing peek view and persist when expanding peek view */@@ -75,6 +77,7 @@ export function usePeekNavigation(config?: PeekConfig | PeekConfigWithExpand) {if (!id) {// Close peek view - clear all peek-related paramsparams.delete(PEEK_PARAM);+ params.delete(PEEK_VIEW_PARAM);config?.queryParams?.forEach((param) => params.delete(param));} else {// Clear all query params that are set in the config@@ -116,6 +119,7 @@ export function usePeekNavigation(config?: PeekConfig | PeekConfigWithExpand) {// Close peek view - clear all peek-related paramsparams.delete(PEEK_PARAM);+ params.delete(PEEK_VIEW_PARAM);config?.queryParams?.forEach((param) => params.delete(param));router.push(diff --git a/web/src/components/table/peek/outsideInteraction.clienttest.tsx b/web/src/components/table/peek/outsideInteraction.clienttest.tsxnew file mode 100644index 0000000000..37f3457a78--- /dev/null+++ b/web/src/components/table/peek/outsideInteraction.clienttest.tsx@@ -0,0 +1,75 @@+import { afterEach, describe, expect, it } from "vitest";++import { shouldKeepPeekOpenOnOutsideInteraction } from "@/src/components/table/peek";++// Build a detached element tree and return the deepest child as the event target.+function targetWith(+ attrs: Record<string, string>,+ wrap?: Record<string, string>,+) {+ const el = document.createElement("span");+ for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);+ if (wrap) {+ const parent = document.createElement("div");+ for (const [k, v] of Object.entries(wrap)) parent.setAttribute(k, v);+ parent.appendChild(el);+ document.body.appendChild(parent);+ } else {+ document.body.appendChild(el);+ }+ return el;+}++const IGNORED = ['[role="checkbox"]', '[aria-label="bookmark"]'];++describe("shouldKeepPeekOpenOnOutsideInteraction", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ });++ it("closes (returns false) for a plain outside target", () => {+ expect(+ shouldKeepPeekOpenOnOutsideInteraction(targetWith({}), IGNORED),+ ).toBe(false);+ });++ it("keeps open for any target inside the peek content", () => {+ const target = targetWith({}, { "data-peek-content": "" });+ expect(shouldKeepPeekOpenOnOutsideInteraction(target, IGNORED)).toBe(true);+ });++ it("keeps open when clicking another table row (switch, not close)", () => {+ const target = targetWith({}, { "data-row-index": "3" });+ expect(shouldKeepPeekOpenOnOutsideInteraction(target, IGNORED)).toBe(true);+ });++ it("keeps open for an opt-out region", () => {+ const target = targetWith({}, { "data-ignore-outside-interaction": "" });+ expect(shouldKeepPeekOpenOnOutsideInteraction(target, IGNORED)).toBe(true);+ });++ it("keeps open for a selection checkbox even outside any row", () => {+ expect(+ shouldKeepPeekOpenOnOutsideInteraction(+ targetWith({ role: "checkbox" }),+ IGNORED,+ ),+ ).toBe(true);+ });++ it("keeps open for a table-configured ignoredSelector", () => {+ expect(+ shouldKeepPeekOpenOnOutsideInteraction(+ targetWith({ "aria-label": "bookmark" }),+ IGNORED,+ ),+ ).toBe(true);+ });++ it("closes for non-Element targets", () => {+ expect(shouldKeepPeekOpenOnOutsideInteraction(null, IGNORED)).toBe(false);+ expect(+ shouldKeepPeekOpenOnOutsideInteraction(new EventTarget(), IGNORED),+ ).toBe(false);+ });+});diff --git a/web/src/components/table/peek/peek-experiment-item-detail.tsx b/web/src/components/table/peek/peek-experiment-item-detail.tsxindex 5684f59022..3e5961c6fa 100644--- a/web/src/components/table/peek/peek-experiment-item-detail.tsx+++ b/web/src/components/table/peek/peek-experiment-item-detail.tsx@@ -1,7 +1,6 @@import { useRouter } from "next/router";import { usePeekData } from "@/src/components/table/peek/hooks/usePeekData";-import { Trace } from "@/src/components/trace/Trace";-import { Skeleton } from "@/src/components/ui/skeleton";+import { TraceDetailBody } from "@/src/components/trace/TraceDetailBody";import { TablePeekView } from "@/src/components/table/peek";const PeekViewExperimentItemDetail = ({ projectId }: { projectId: string }) => {@@ -23,20 +22,8 @@ const PeekViewExperimentItemDetail = ({ projectId }: { projectId: string }) => {timestamp,});- if (!peekId || !trace.data) {- return <Skeleton className="h-full w-full rounded-none" />;- }-return (- <Trace- key={`${trace.data.id}-${peekId}`}- trace={trace.data}- scores={trace.data.scores}- corrections={trace.data.corrections}- projectId={trace.data.projectId}- observations={trace.data.observations}- context="peek"- />+ <TraceDetailBody trace={trace.data} context="peek" keySuffix={peekId} />);};diff --git a/web/src/components/table/peek/peek-observation-detail.tsx b/web/src/components/table/peek/peek-observation-detail.tsxindex 7183b87be9..30eb82df11 100644--- a/web/src/components/table/peek/peek-observation-detail.tsx+++ b/web/src/components/table/peek/peek-observation-detail.tsx@@ -1,33 +1,12 @@import { TablePeekView } from "@/src/components/table/peek";import { usePeekData } from "@/src/components/table/peek/hooks/usePeekData";-import { Trace } from "@/src/components/trace/Trace";-import { Skeleton } from "@/src/components/ui/skeleton";+import {+ TraceDetailBody,+ traceDetailTitle,+} from "@/src/components/trace/TraceDetailBody";+import { TraceDetailActions } from "@/src/components/trace/TraceDetailActions";import { useRouter } from "next/router";-const PeekViewObservationDetail = ({- peekId,- trace,-}: {- peekId: string | undefined;- trace: ReturnType<typeof usePeekData>;-}) => {- if (!peekId || !trace.data) {- return <Skeleton className="h-full w-full rounded-none" />;- }-- return (- <Trace- key={`${trace.data.id}-${peekId}`}- trace={trace.data}- scores={trace.data.scores}- corrections={trace.data.corrections}- projectId={trace.data.projectId}- observations={trace.data.observations}- context="peek"- />- );-};-export const TablePeekViewObservationDetail = (props: Omit<React.ComponentProps<typeof TablePeekView>,@@ -56,18 +35,32 @@ export const TablePeekViewObservationDetail = (timestamp,});+ const actionProps = trace.data+ ? {+ traceId: trace.data.id,+ projectId: trace.data.projectId,+ bookmarked: trace.data.bookmarked,+ isPublic: trace.data.public,+ name: trace.data.name,+ timestamp,+ onAfterDelete: props.closePeek,+ }+ : null;+return (<TablePeekView{...props}- title={- trace.data- ? trace.data.name- ? `${trace.data.name}: ${trace.data.id}`- : trace.data.id- : traceId+ title={traceDetailTitle(trace.data, traceId)}+ actions={+ actionProps ? <TraceDetailActions {...actionProps} /> : undefined+ }+ actionsMenu={+ actionProps ? (+ <TraceDetailActions {...actionProps} layout="menu" />+ ) : undefined}>- <PeekViewObservationDetail trace={trace} peekId={peekId} />+ <TraceDetailBody trace={trace.data} context="peek" keySuffix={peekId} /></TablePeekView>);};diff --git a/web/src/components/table/peek/peek-trace-detail.tsx b/web/src/components/table/peek/peek-trace-detail.tsxindex ec21a39b5f..f2510bc308 100644--- a/web/src/components/table/peek/peek-trace-detail.tsx+++ b/web/src/components/table/peek/peek-trace-detail.tsx@@ -1,28 +1,11 @@import { usePeekData } from "@/src/components/table/peek/hooks/usePeekData";import { useRouter } from "next/router";-import { Trace } from "@/src/components/trace/Trace";-import { Skeleton } from "@/src/components/ui/skeleton";+import {+ TraceDetailBody,+ traceDetailTitle,+} from "@/src/components/trace/TraceDetailBody";import { TablePeekView } from "@/src/components/table/peek";--const PeekViewTraceDetail = ({- trace,-}: {- trace: ReturnType<typeof usePeekData>;-}) => {- return !trace.data ? (- <Skeleton className="h-full w-full rounded-none" />- ) : (- <Trace- key={trace.data.id}- trace={trace.data}- scores={trace.data.scores}- corrections={trace.data.corrections}- projectId={trace.data.projectId}- observations={trace.data.observations}- context="peek"- />- );-};+import { TraceDetailActions } from "@/src/components/trace/TraceDetailActions";export const TablePeekViewTraceDetail = (props: Omit<@@ -50,18 +33,32 @@ export const TablePeekViewTraceDetail = (timestamp,});+ const actionProps = trace.data+ ? {+ traceId: trace.data.id,+ projectId: trace.data.projectId,+ bookmarked: trace.data.bookmarked,+ isPublic: trace.data.public,+ name: trace.data.name,+ timestamp,+ onAfterDelete: props.closePeek,+ }+ : null;+return (<TablePeekView{...props}- title={- trace.data- ? trace.data.name- ? `${trace.data.name}: ${trace.data.id}`- : trace.data.id- : peekId+ title={traceDetailTitle(trace.data, peekId)}+ actions={+ actionProps ? <TraceDetailActions {...actionProps} /> : undefined+ }+ actionsMenu={+ actionProps ? (+ <TraceDetailActions {...actionProps} layout="menu" />+ ) : undefined}>- <PeekViewTraceDetail trace={trace} />+ <TraceDetailBody trace={trace.data} context="peek" /></TablePeekView>);};diff --git a/web/src/components/table/peek/peekHeaderOverflow.clienttest.ts b/web/src/components/table/peek/peekHeaderOverflow.clienttest.tsnew file mode 100644index 0000000000..4d872a3207--- /dev/null+++ b/web/src/components/table/peek/peekHeaderOverflow.clienttest.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from "vitest";++import { planPeekHeaderLayout } from "@/src/components/table/peek/peekHeaderOverflow";++// Representative measured widths (px).+const base = {+ minTitle: 240,+ badgeLabelWidth: 64,+ badgeIconWidth: 32,+ navFullWidth: 92, // βK βJ with chips+ navCompactWidth: 52, // icon-only arrows+ otherPinnedWidth: 68, // expand + close + divider+ moreWidth: 32,+ actionsWidth: 90,+ openInTabWidth: 28,+ safety: 16,+};++const FULL = {+ foldActions: false,+ foldOpenInTab: false,+ badgeShowLabel: true,+ navCompact: false,+};++describe("planPeekHeaderLayout", () => {+ it("keeps everything when the title has room", () => {+ expect(planPeekHeaderLayout({ ...base, headerWidth: 760 })).toEqual(FULL);+ });++ it("reduces in order as the peek narrows: actions, then badge, then nav", () => {+ // Wide-ish: only the actions fold.+ const a = planPeekHeaderLayout({ ...base, headerWidth: 560 });+ expect(a.foldActions).toBe(true);+ expect(a.badgeShowLabel).toBe(true);+ expect(a.navCompact).toBe(false);++ // Narrower: actions folded + badge icon-only.+ const b = planPeekHeaderLayout({ ...base, headerWidth: 500 });+ expect(b.foldActions).toBe(true);+ expect(b.badgeShowLabel).toBe(false);++ // Narrower still: nav goes compact too.+ const c = planPeekHeaderLayout({ ...base, headerWidth: 430 });+ expect(c.navCompact).toBe(true);+ });++ it("folds open-in-tab last, when very tight", () => {+ const plan = planPeekHeaderLayout({ ...base, headerWidth: 320 });+ expect(plan.foldActions).toBe(true);+ expect(plan.badgeShowLabel).toBe(false);+ expect(plan.navCompact).toBe(true);+ expect(plan.foldOpenInTab).toBe(true);+ });++ it("never folds units that aren't present, but still adapts badge/nav", () => {+ const plan = planPeekHeaderLayout({+ ...base,+ actionsWidth: undefined,+ openInTabWidth: undefined,+ headerWidth: 300,+ });+ expect(plan.foldActions).toBe(false);+ expect(plan.foldOpenInTab).toBe(false);+ expect(plan.badgeShowLabel).toBe(false);+ expect(plan.navCompact).toBe(true);+ });+});diff --git a/web/src/components/table/peek/peekHeaderOverflow.ts b/web/src/components/table/peek/peekHeaderOverflow.tsnew file mode 100644index 0000000000..d4107523c5--- /dev/null+++ b/web/src/components/table/peek/peekHeaderOverflow.ts@@ -0,0 +1,99 @@+/**+ * Layout planner for the peek header. Pure + framework-free so the adaptive+ * behaviour can be unit-tested without a DOM. The header measures its parts and+ * calls this to decide β from the PEEK's own width, not the screen's β how to+ * stay uncluttered while keeping the title readable.+ *+ * The rule: the title always gets at least `minTitle` px. When it wouldn't, we+ * apply reductions in least-painful order until it fits:+ * 1. fold the trace actions into the "β¦" menu (still one click away),+ * 2. shrink the type badge to icon-only (never truncate it to "Trβ¦"),+ * 3. compact the prev/next nav (icon-only arrows, K/J in the tooltip),+ * 4. fold open-in-tab into "β¦".+ * Anything still over budget just lets the title truncate (its natural state).+ */++export type PeekHeaderPlan = {+ foldActions: boolean;+ foldOpenInTab: boolean;+ badgeShowLabel: boolean;+ navCompact: boolean;+};++export type PlanPeekHeaderArgs = {+ /** The peek header's measured width, px (= the peek's width). */+ headerWidth: number;+ /** Minimum width the title keeps before anything else collapses, px. */+ minTitle: number;+ badgeLabelWidth: number;+ badgeIconWidth: number;+ /** Prev/next nav width with K/J chips, px (0 when no nav). */+ navFullWidth: number;+ /** Prev/next nav width as compact icon arrows, px (0 when no nav). */+ navCompactWidth: number;+ /** Pinned controls other than nav (expand + close + divider), px. */+ otherPinnedWidth: number;+ /** Width of the "β¦" overflow trigger, counted once anything folds, px. */+ moreWidth: number;+ /** Trace actions cluster width, px; omit when there are no actions. */+ actionsWidth?: number;+ /** Open-in-tab button width, px; omit when it isn't shown. */+ openInTabWidth?: number;+ /** Slack absorbing inter-control gaps + rounding, px. */+ safety?: number;+};++export function planPeekHeaderLayout({+ headerWidth,+ minTitle,+ badgeLabelWidth,+ badgeIconWidth,+ navFullWidth,+ navCompactWidth,+ otherPinnedWidth,+ moreWidth,+ actionsWidth,+ openInTabWidth,+ safety = 16,+}: PlanPeekHeaderArgs): PeekHeaderPlan {+ const hasActions = actionsWidth != null;+ const hasOpenInTab = openInTabWidth != null;++ let foldActions = false;+ let foldOpenInTab = false;+ let badgeShowLabel = true;+ let navCompact = false;++ const pinnedWidth = () =>+ (navCompact ? navCompactWidth : navFullWidth) + otherPinnedWidth;+ const clusterWidth = () =>+ pinnedWidth() ++ (foldActions || foldOpenInTab ? moreWidth : 0) ++ (hasActions && !foldActions ? (actionsWidth ?? 0) : 0) ++ (hasOpenInTab && !foldOpenInTab ? (openInTabWidth ?? 0) : 0) ++ safety;+ const badgeWidth = () => (badgeShowLabel ? badgeLabelWidth : badgeIconWidth);+ const titleAvailable = () => headerWidth - badgeWidth() - clusterWidth();++ const reductions: Array<() => void> = [+ () => {+ if (hasActions) foldActions = true;+ },+ () => {+ badgeShowLabel = false;+ },+ () => {+ navCompact = true;+ },+ () => {+ if (hasOpenInTab) foldOpenInTab = true;+ },+ ];++ for (const reduce of reductions) {+ if (titleAvailable() >= minTitle) break;+ reduce();+ }++ return { foldActions, foldOpenInTab, badgeShowLabel, navCompact };+}diff --git a/web/src/components/table/peek/store/peekPanelStore.clienttest.ts b/web/src/components/table/peek/store/peekPanelStore.clienttest.tsnew file mode 100644index 0000000000..af6eb9f623--- /dev/null+++ b/web/src/components/table/peek/store/peekPanelStore.clienttest.ts@@ -0,0 +1,100 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import {+ createPeekPanelStore,+ PEEK_DEFAULT_WIDTH_FRACTION,+ PEEK_MAX_WIDGET_WIDTH_FRACTION,+ PEEK_MIN_WIDTH_FRACTION,+ selectDraftExpanded,+ selectWidgetWidth,+} from "@/src/components/table/peek/store/peekPanelStore";++const STORAGE_KEY = "peekViewWidthFraction";+const pct = (fraction: number) => `${fraction * 100}vw`;++describe("peekPanelStore", () => {+ beforeEach(() => window.localStorage.clear());+ afterEach(() => window.localStorage.clear());++ it("defaults to the widget width, not resizing or expanded", () => {+ const store = createPeekPanelStore();+ const state = store.getState();+ expect(state.isResizing).toBe(false);+ expect(state.draftExpanded).toBe(false);+ expect(state.widthFraction).toBeCloseTo(PEEK_DEFAULT_WIDTH_FRACTION);+ expect(selectWidgetWidth(state)).toBe(pct(PEEK_DEFAULT_WIDTH_FRACTION));+ });++ it("reads and clamps the persisted width on creation", () => {+ window.localStorage.setItem(STORAGE_KEY, "0.7");+ expect(createPeekPanelStore().getState().widthFraction).toBeCloseTo(0.7);++ window.localStorage.setItem(STORAGE_KEY, "5");+ expect(createPeekPanelStore().getState().widthFraction).toBeCloseTo(+ PEEK_MAX_WIDGET_WIDTH_FRACTION,+ );+ });++ it("commitWidth clamps, persists, and clears the draft", () => {+ const store = createPeekPanelStore();+ store.getState().actions.setDraftExpanded();+ store.getState().actions.commitWidth(0.72);+ const state = store.getState();+ expect(state.widthFraction).toBeCloseTo(0.72);+ expect(state.draftFraction).toBeNull();+ expect(state.draftExpanded).toBe(false);+ expect(window.localStorage.getItem(STORAGE_KEY)).toBe("0.72");+ });++ it("setDraftFraction drives the live widget width (and clears draftExpanded)", () => {+ const store = createPeekPanelStore();+ store.getState().actions.setDraftExpanded();+ store.getState().actions.setDraftFraction(0.42);+ const state = store.getState();+ expect(state.draftExpanded).toBe(false);+ expect(selectWidgetWidth(state)).toBe(pct(0.42));+ // The committed width preference is untouched until pointer-up.+ expect(state.widthFraction).toBeCloseTo(PEEK_DEFAULT_WIDTH_FRACTION);+ });++ it("setDraftExpanded previews expansion without persisting a width", () => {+ const store = createPeekPanelStore();+ store.getState().actions.setDraftExpanded();+ expect(selectDraftExpanded(store.getState())).toBe(true);+ expect(store.getState().draftFraction).toBeNull();+ expect(window.localStorage.getItem(STORAGE_KEY)).toBeNull();+ });++ it("nudgeWidth grows/shrinks within bounds and persists", () => {+ window.localStorage.setItem(STORAGE_KEY, "0.5");+ const store = createPeekPanelStore();++ store.getState().actions.nudgeWidth("grow");+ expect(store.getState().widthFraction).toBeCloseTo(0.55);+ expect(window.localStorage.getItem(STORAGE_KEY)).toBe("0.55");++ store.getState().actions.nudgeWidth("shrink");+ expect(store.getState().widthFraction).toBeCloseTo(0.5);+ });++ it("nudgeWidth never shrinks below the minimum", () => {+ window.localStorage.setItem(STORAGE_KEY, String(PEEK_MIN_WIDTH_FRACTION));+ const store = createPeekPanelStore();+ store.getState().actions.nudgeWidth("shrink");+ expect(store.getState().widthFraction).toBeCloseTo(PEEK_MIN_WIDTH_FRACTION);+ });++ it("cancelResize abandons the draft without committing a width", () => {+ window.localStorage.setItem(STORAGE_KEY, "0.5");+ const store = createPeekPanelStore();+ store.getState().actions.setResizing(true);+ store.getState().actions.setDraftFraction(0.8);+ store.getState().actions.cancelResize();+ const state = store.getState();+ expect(state.draftFraction).toBeNull();+ expect(state.draftExpanded).toBe(false);+ expect(state.isResizing).toBe(false);+ expect(state.widthFraction).toBeCloseTo(0.5);+ expect(window.localStorage.getItem(STORAGE_KEY)).toBe("0.5");+ });+});diff --git a/web/src/components/table/peek/store/peekPanelStore.ts b/web/src/components/table/peek/store/peekPanelStore.tsnew file mode 100644index 0000000000..67c1d7fe34--- /dev/null+++ b/web/src/components/table/peek/store/peekPanelStore.ts@@ -0,0 +1,138 @@+import { createStore, type StoreApi } from "zustand/vanilla";++/**+ * Per-mount store for the desktop peek panel's WIDTH. Follows the+ * local-feature-state pattern from `frontend-large-feature-architecture` β one+ * store instance per peek host, mutated only through named `actions`; the drag+ * workflow lives in `../actions/resizePeekPanel.ts`.+ *+ * Whether the peek is *expanded* (max width) is NOT stored here β it lives in+ * the URL (`peekView=expanded`, owned by `usePeekNavigation`) so it is shareable+ * and survives back/forward. This store only owns the widget width and the+ * transient drag state:+ * - **widthFraction** β cross-view persisted widget width (localStorage, a+ * resolution-independent viewport fraction).+ * - **draftFraction / draftExpanded / isResizing** β high-frequency transient+ * drag state. On pointer-up the drag either commits a widget width or asks the+ * caller to flip the URL `expanded` flag (see the resize action).+ *+ * Width and expanded are one continuum: dragging the handle past+ * `PEEK_EXPAND_ENTER_FRACTION` previews the expanded width (`draftExpanded`);+ * dragging back returns to a widget width.+ */++const STORAGE_KEY = "peekViewWidthFraction";++// Widget width bounds, as a fraction of the viewport width.+export const PEEK_MIN_WIDTH_FRACTION = 0.4;+export const PEEK_MAX_WIDGET_WIDTH_FRACTION = 0.9;+export const PEEK_DEFAULT_WIDTH_FRACTION = 0.5;+// Dragging the handle beyond this fraction of the viewport previews "expanded".+export const PEEK_EXPAND_ENTER_FRACTION = 0.95;+const KEYBOARD_RESIZE_STEP = 0.05;++export const clampWidthFraction = (fraction: number) =>+ Math.min(+ PEEK_MAX_WIDGET_WIDTH_FRACTION,+ Math.max(PEEK_MIN_WIDTH_FRACTION, fraction),+ );++// Cross-view width preference, persisted as a raw fraction. SSR-safe: reads the+// default on the server and the first client render, the real value after mount.+function readStoredWidthFraction(): number {+ if (typeof window === "undefined") return PEEK_DEFAULT_WIDTH_FRACTION;+ try {+ const raw = window.localStorage.getItem(STORAGE_KEY);+ if (raw === null) return PEEK_DEFAULT_WIDTH_FRACTION;+ const parsed = JSON.parse(raw);+ return typeof parsed === "number"+ ? clampWidthFraction(parsed)+ : PEEK_DEFAULT_WIDTH_FRACTION;+ } catch {+ return PEEK_DEFAULT_WIDTH_FRACTION;+ }+}++function writeStoredWidthFraction(fraction: number): void {+ if (typeof window === "undefined") return;+ try {+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(fraction));+ } catch {+ // Ignore write failures (private mode, quota) β width is a best-effort pref.+ }+}++export interface PeekPanelStoreState {+ /** Committed widget width (persisted), as a fraction of the viewport. */+ widthFraction: number;+ /** Live widget width during a drag; null when not dragging or expanded. */+ draftFraction: number | null;+ /** True while a drag is previewing the expanded (max) width. */+ draftExpanded: boolean;+ /** True while the resize handle is being dragged. */+ isResizing: boolean;+ actions: {+ setResizing: (isResizing: boolean) => void;+ /** Abandon an in-flight drag without committing (e.g. peek closed mid-drag). */+ cancelResize: () => void;+ /** Drag below the expand threshold: live widget width. */+ setDraftFraction: (fraction: number) => void;+ /** Drag past the expand threshold: preview the expanded (max) width. */+ setDraftExpanded: () => void;+ /** End a drag on a widget width: persist it and clear the draft. */+ commitWidth: (fraction: number) => void;+ /** Keyboard resize of the persisted widget width. */+ nudgeWidth: (direction: "grow" | "shrink") => void;+ };+}++export type PeekPanelStore = StoreApi<PeekPanelStoreState>;++export function createPeekPanelStore(): PeekPanelStore {+ return createStore<PeekPanelStoreState>((set, get) => ({+ widthFraction: readStoredWidthFraction(),+ draftFraction: null,+ draftExpanded: false,+ isResizing: false,+ actions: {+ setResizing: (isResizing) => set({ isResizing }),+ cancelResize: () =>+ set({ draftFraction: null, draftExpanded: false, isResizing: false }),+ setDraftFraction: (fraction) =>+ set({+ draftFraction: clampWidthFraction(fraction),+ draftExpanded: false,+ }),+ setDraftExpanded: () => set({ draftExpanded: true, draftFraction: null }),+ commitWidth: (fraction) => {+ const clamped = clampWidthFraction(fraction);+ writeStoredWidthFraction(clamped);+ set({+ widthFraction: clamped,+ draftFraction: null,+ draftExpanded: false,+ });+ },+ nudgeWidth: (direction) => {+ const delta =+ direction === "grow" ? KEYBOARD_RESIZE_STEP : -KEYBOARD_RESIZE_STEP;+ const next = clampWidthFraction(get().widthFraction + delta);+ writeStoredWidthFraction(next);+ set({ widthFraction: next, draftFraction: null, draftExpanded: false });+ },+ },+ }));+}++export const selectIsResizing = (state: PeekPanelStoreState) =>+ state.isResizing;+export const selectDraftExpanded = (state: PeekPanelStoreState) =>+ state.draftExpanded;++/**+ * The widget width as a primitive CSS string (`"50vw"`) so the subscription+ * bails out unless the rendered width changes. The expanded (max) width is+ * computed by the hook, since it depends on the live sidebar offset.+ */+export const selectWidgetWidth = (state: PeekPanelStoreState): string =>+ `${clampWidthFraction(state.draftFraction ?? state.widthFraction) * 100}vw`;diff --git a/web/src/components/table/peek/usePeekPanelState.clienttest.tsx b/web/src/components/table/peek/usePeekPanelState.clienttest.tsxnew file mode 100644index 0000000000..bed728fbd6--- /dev/null+++ b/web/src/components/table/peek/usePeekPanelState.clienttest.tsx@@ -0,0 +1,94 @@+import { act, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { usePeekPanelState } from "@/src/components/table/peek/usePeekPanelState";+import { PEEK_DEFAULT_WIDTH_FRACTION } from "@/src/components/table/peek/store/peekPanelStore";++const STORAGE_KEY = "peekViewWidthFraction";+// Widget width is `min(<n>vw, calc(100vw - <sidebar>px))` β pull the leading+// vw fraction (the widget's own width) out of the min() wrapper.+const widthFraction = (style: React.CSSProperties) => {+ const match = String(style.width).match(/([\d.]+)vw/);+ return match ? parseFloat(match[1]) / 100 : NaN;+};++function setup(isExpanded = false) {+ const onExpandedChange = vi.fn();+ const { result, rerender } = renderHook(+ ({ isExpanded }) =>+ usePeekPanelState({ isOpen: true, isExpanded, onExpandedChange }),+ { initialProps: { isExpanded } },+ );+ return { result, rerender, onExpandedChange };+}++function pressArrow(+ result: { current: ReturnType<typeof usePeekPanelState> },+ key: "ArrowLeft" | "ArrowRight",+) {+ act(() => {+ result.current.resizeHandleProps.onKeyDown({+ key,+ preventDefault: () => {},+ } as unknown as React.KeyboardEvent);+ });+}++describe("usePeekPanelState", () => {+ beforeEach(() => window.localStorage.clear());+ afterEach(() => window.localStorage.clear());++ it("renders the widget width and a stable resize-handle contract", () => {+ const { result } = setup();+ expect(result.current.isExpanded).toBe(false);+ expect(widthFraction(result.current.panelStyle)).toBeCloseTo(+ PEEK_DEFAULT_WIDTH_FRACTION,+ );+ expect(result.current.resizeHandleProps.role).toBe("separator");+ expect(result.current.resizeHandleProps["aria-label"]).toBe(+ "Resize peek view",+ );+ });++ it("renders the expanded (viewport β sidebar) width when expanded", () => {+ const { result } = setup(true);+ expect(result.current.isExpanded).toBe(true);+ // No sidebar element in jsdom β offset 0 β full viewport calc.+ expect(String(result.current.panelStyle.width)).toContain("calc(100vw");+ });++ it("toggleExpanded writes the expanded flag (URL) via the callback", () => {+ const { result, onExpandedChange } = setup(false);+ act(() => result.current.toggleExpanded());+ expect(onExpandedChange).toHaveBeenCalledWith(true);+ });++ it("toggleExpanded toggles against the displayed (pending) state, not the stale URL prop", () => {+ const { result, onExpandedChange } = setup(false);+ // First click commits expanded; the hook holds it as `pending` until the+ // URL (isExpanded prop) catches up β we deliberately do NOT rerender it.+ act(() => result.current.toggleExpanded());+ expect(onExpandedChange).toHaveBeenLastCalledWith(true);+ expect(result.current.isExpanded).toBe(true); // button now shows Collapse+ // A rapid second click in that pending window must collapse (match the+ // button), not re-commit `true` against the stale prop (a no-op).+ act(() => result.current.toggleExpanded());+ expect(onExpandedChange).toHaveBeenLastCalledWith(false);+ });++ it("keyboard resize collapses expanded and nudges the widget width", () => {+ const { result, onExpandedChange } = setup(false);+ pressArrow(result, "ArrowLeft");+ expect(onExpandedChange).toHaveBeenCalledWith(false);+ expect(widthFraction(result.current.panelStyle)).toBeCloseTo(+ PEEK_DEFAULT_WIDTH_FRACTION + 0.05,+ );+ pressArrow(result, "ArrowRight");+ expect(widthFraction(result.current.panelStyle)).toBeCloseTo(+ PEEK_DEFAULT_WIDTH_FRACTION,+ );+ expect(window.localStorage.getItem(STORAGE_KEY)).toBe(+ String(PEEK_DEFAULT_WIDTH_FRACTION),+ );+ });+});diff --git a/web/src/components/table/peek/usePeekPanelState.ts b/web/src/components/table/peek/usePeekPanelState.tsnew file mode 100644index 0000000000..27b8e30e13--- /dev/null+++ b/web/src/components/table/peek/usePeekPanelState.ts@@ -0,0 +1,218 @@+import {+ useCallback,+ useEffect,+ useRef,+ useState,+ type CSSProperties,+ type KeyboardEvent as ReactKeyboardEvent,+ type PointerEvent as ReactPointerEvent,+} from "react";+import { useStore } from "zustand";+import {+ createPeekPanelStore,+ PEEK_EXPAND_ENTER_FRACTION,+ PEEK_MIN_WIDTH_FRACTION,+ selectDraftExpanded,+ selectIsResizing,+ selectWidgetWidth,+} from "@/src/components/table/peek/store/peekPanelStore";+import { beginPeekResize } from "@/src/components/table/peek/actions/resizePeekPanel";++export type PeekPanelView = {+ /** Whether the panel is expanded to max width (viewport β sidebar). */+ isExpanded: boolean;+ /** True while the user is dragging the resize handle. */+ isResizing: boolean;+ /** Inline style (width) for the docked panel. */+ panelStyle: CSSProperties;+ /** Toggle the expanded view (writes the URL via `onExpandedChange`). */+ toggleExpanded: () => void;+ /** Props to spread onto the left-edge resize handle. */+ resizeHandleProps: {+ role: "separator";+ "aria-orientation": "vertical";+ "aria-label": string;+ "aria-valuemin": number;+ "aria-valuemax": number;+ "aria-valuenow": number;+ tabIndex: 0;+ onPointerDown: (event: ReactPointerEvent) => void;+ onKeyDown: (event: ReactKeyboardEvent) => void;+ };+};++/** Right edge of the (left-docked) sidebar = its current width, in px. */+function readSidebarOffsetPx(): number {+ if (typeof document === "undefined") return 0;+ const el = document.querySelector('[data-sidebar="sidebar"]');+ if (!el) return 0;+ const rect = el.getBoundingClientRect();+ // Guard against the off-canvas mobile sidebar (rendered in a Sheet): only a+ // left-docked, on-screen sidebar contributes an offset.+ return rect.left < 100 && rect.width > 0 ? Math.round(rect.right) : 0;+}++/**+ * Integration boundary for the peek panel width: owns the per-mount widget-width+ * store, derives the final width (widget vs expanded), and wires drag/keyboard+ * to the store + resize action. Whether the peek is *expanded* is owned by the+ * URL (`isExpanded` in, `onExpandedChange` out) so it is shareable + reloadable.+ *+ * `pendingExpanded` bridges the async gap: when a drag/button commits a new+ * expanded value we hold it locally until the URL (`isExpanded`) catches up, so+ * the panel never flashes the old width for a frame on release.+ */+export function usePeekPanelState({+ isOpen,+ isExpanded,+ onExpandedChange,+}: {+ isOpen: boolean;+ isExpanded: boolean;+ onExpandedChange: (expanded: boolean) => void;+}): PeekPanelView {+ const [store] = useState(() => createPeekPanelStore());++ const isResizing = useStore(store, selectIsResizing);+ const draftExpanded = useStore(store, selectDraftExpanded);+ const widgetWidth = useStore(store, selectWidgetWidth);++ // Locally-committed expanded value, held until the URL reflects it.+ const [pendingExpanded, setPendingExpanded] = useState<boolean | null>(null);+ useEffect(() => setPendingExpanded(null), [isExpanded]);++ // During a drag the live draft wins; otherwise the just-committed value, then+ // the URL flag.+ const effectiveExpanded = isResizing+ ? draftExpanded+ : (pendingExpanded ?? isExpanded);++ const commitExpanded = useCallback(+ (expanded: boolean) => {+ setPendingExpanded(expanded);+ onExpandedChange(expanded);+ },+ [onExpandedChange],+ );++ // While expanded the panel width is `calc(100vw - sidebarOffset)` so the+ // sidebar stays visible. The peek portals into the `modal` layer, outside the+ // sidebar's CSS-var scope, so the offset is measured from the DOM. Seeded+ // synchronously on mount (lazy initializer, SSR-safe via the guard in+ // readSidebarOffsetPx) so the first expanded paint already uses the real+ // offset rather than calc(100vw - 0px) = full width for one frame.+ const [sidebarOffset, setSidebarOffset] = useState(() =>+ readSidebarOffsetPx(),+ );+ // Track the sidebar continuously β NOT only while expanded β so a sidebar+ // toggle/resize that happens while the peek is collapsed is still reflected+ // by the next expand (no stale-offset flash). The observer is idle unless the+ // sidebar actually resizes, and setSidebarOffset bails on an unchanged value.+ useEffect(() => {+ const measure = () => setSidebarOffset(readSidebarOffsetPx());+ measure();+ window.addEventListener("resize", measure);+ const sidebar = document.querySelector('[data-sidebar="sidebar"]');+ const observer =+ sidebar && typeof ResizeObserver !== "undefined"+ ? new ResizeObserver(measure)+ : null;+ if (sidebar) observer?.observe(sidebar);+ return () => {+ window.removeEventListener("resize", measure);+ observer?.disconnect();+ };+ }, []);++ // Both expanded and widget widths are capped at the sidebar edge+ // (`viewport β sidebar`). Capping the widget too means dragging to the max+ // lands on the exact same width as expanded β no snap-back jump β and the+ // panel never paints over the sidebar even if a stored fraction is large.+ const maxWidth = `calc(100vw - ${sidebarOffset}px)`;+ const panelStyle: CSSProperties = {+ width: effectiveExpanded ? maxWidth : `min(${widgetWidth}, ${maxWidth})`,+ };++ // End an in-flight drag (drop listeners, restore body styles, clear drag+ // state) on unmount and whenever the peek closes β the host outlives+ // open/close.+ const dragTeardownRef = useRef<(() => void) | null>(null);+ const endActiveDrag = useCallback(() => {+ dragTeardownRef.current?.();+ dragTeardownRef.current = null;+ store.getState().actions.cancelResize();+ }, [store]);+ useEffect(() => {+ if (!isOpen) endActiveDrag();+ }, [isOpen, endActiveDrag]);+ useEffect(() => endActiveDrag, [endActiveDrag]);++ const onPointerDown = useCallback(+ (event: ReactPointerEvent) => {+ // The drag flips to expanded at the sidebar edge (viewport β sidebar),+ // clamped to the widget bounds, so it can't overshoot onto the sidebar.+ const vw = typeof window === "undefined" ? 0 : window.innerWidth;+ const expandAtFraction =+ vw > 0+ ? Math.min(+ PEEK_EXPAND_ENTER_FRACTION,+ Math.max(PEEK_MIN_WIDTH_FRACTION, (vw - sidebarOffset) / vw),+ )+ : PEEK_EXPAND_ENTER_FRACTION;+ dragTeardownRef.current = beginPeekResize(+ store,+ event,+ commitExpanded,+ expandAtFraction,+ effectiveExpanded,+ );+ },+ [store, commitExpanded, sidebarOffset, effectiveExpanded],+ );++ const onKeyDown = useCallback(+ (event: ReactKeyboardEvent) => {+ // Left grows the panel (it is docked right), Right shrinks it; either+ // collapses out of the expanded view onto a widget width.+ if (event.key === "ArrowLeft" || event.key === "ArrowRight") {+ event.preventDefault();+ commitExpanded(false);+ store+ .getState()+ .actions.nudgeWidth(event.key === "ArrowLeft" ? "grow" : "shrink");+ }+ },+ [store, commitExpanded],+ );++ // Toggle relative to what the button currently SHOWS (effectiveExpanded),+ // not the URL-derived isExpanded β during the pending window after a commit+ // the two differ for a render, and reading isExpanded there would make a+ // rapid second click re-commit the same value (a no-op) instead of toggling.+ const toggleExpanded = useCallback(+ () => commitExpanded(!effectiveExpanded),+ [effectiveExpanded, commitExpanded],+ );++ const widthPercent = effectiveExpanded+ ? 100+ : Math.round(parseFloat(widgetWidth));++ return {+ isExpanded: effectiveExpanded,+ isResizing,+ panelStyle,+ toggleExpanded,+ resizeHandleProps: {+ role: "separator",+ "aria-orientation": "vertical",+ "aria-label": "Resize peek view",+ "aria-valuemin": Math.round(PEEK_MIN_WIDTH_FRACTION * 100),+ "aria-valuemax": 100,+ "aria-valuenow": widthPercent,+ tabIndex: 0,+ onPointerDown,+ onKeyDown,+ },+ };+}diff --git a/web/src/components/trace/TraceDetailActions.tsx b/web/src/components/trace/TraceDetailActions.tsxnew file mode 100644index 0000000000..2d4d86155a--- /dev/null+++ b/web/src/components/trace/TraceDetailActions.tsx@@ -0,0 +1,136 @@+import { api } from "@/src/utils/api";+import { StarTraceDetailsToggle } from "@/src/components/star-toggle";+import { PublishTraceSwitch } from "@/src/components/publish-object-switch";+import { DeleteTraceButton } from "@/src/components/deleteButton";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";++/**+ * Trace-level header actions (star / publish / delete) shared by the peek and+ * the standalone trace page, so both surfaces expose the same controls. Each+ * sub-component renders DISABLED (not hidden) when the user lacks the relevant+ * project scope, matching the page's long-standing behavior.+ *+ * `layout="toolbar"` (default) is the inline icon row; `layout="menu"` renders+ * the same controls as full-width labeled rows for the peek's overflow popover+ * (whole row clickable) β Share keeps its URL popover, Delete its confirm.+ *+ * Delete always targets the whole trace (same as the page, even when reached+ * from an observation/event row β the surface shows that trace). Behavior+ * differs only by surface:+ * - **page**: pass `deleteRedirectUrl` β navigates to the list after delete.+ * - **peek**: pass `onAfterDelete` (e.g. `closePeek`) β closes in place. We+ * invalidate broadly because the peek is hosted over many different lists+ * (traces, observations, events, sessions, experiments, datasets), each+ * backed by a different query β so the deleted row disappears everywhere.+ */+export function TraceDetailActions({+ traceId,+ projectId,+ bookmarked,+ isPublic,+ name,+ timestamp,+ deleteRedirectUrl,+ onAfterDelete,+ size = "icon-xs",+ layout = "toolbar",+}: {+ traceId: string;+ projectId: string;+ bookmarked: boolean;+ isPublic: boolean;+ name?: string | null;+ timestamp?: Date;+ deleteRedirectUrl?: string;+ onAfterDelete?: () => void;+ size?: "icon" | "icon-xs";+ layout?: "toolbar" | "menu";+}) {+ const utils = api.useUtils();+ const isMenu = layout === "menu";++ // The page path navigates away (redirectUrl) and never calls this. The peek+ // path is hosted over many different lists, so invalidate all queries to+ // refresh whichever list is behind the peek, then close it.+ const onDeleteInvalidate = () => {+ utils.invalidate();+ onAfterDelete?.();+ };++ if (isMenu) {+ return (+ <div className="flex w-full flex-col gap-0.5">+ <StarTraceDetailsToggle+ projectId={projectId}+ traceId={traceId}+ value={bookmarked}+ label={bookmarked ? "Remove bookmark" : "Bookmark"}+ />+ <PublishTraceSwitch+ projectId={projectId}+ traceId={traceId}+ timestamp={timestamp}+ isPublic={isPublic}+ label="Share"+ />+ <DeleteTraceButton+ itemId={traceId}+ projectId={projectId}+ redirectUrl={deleteRedirectUrl}+ invalidateFunc={onDeleteInvalidate}+ deleteConfirmation={name ?? ""}+ variant="ghost"+ size="sm"+ className="w-full justify-start font-normal"+ />+ </div>+ );+ }++ return (+ <div className="flex flex-row items-center gap-1">+ {/* Star/Share are plain icon buttons without their own tooltip, so wrap+ them (delete's IconOnlyButton already has one). The span is the+ tooltip trigger; the control inside keeps its own click behavior. */}+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="flex">+ <StarTraceDetailsToggle+ projectId={projectId}+ traceId={traceId}+ value={bookmarked}+ size={size}+ />+ </span>+ </TooltipTrigger>+ <TooltipContent>+ {bookmarked ? "Remove bookmark" : "Bookmark"}+ </TooltipContent>+ </Tooltip>+ <PublishTraceSwitch+ projectId={projectId}+ traceId={traceId}+ timestamp={timestamp}+ isPublic={isPublic}+ size={size}+ tooltip={isPublic ? "Shared (public)" : "Share"}+ />+ <DeleteTraceButton+ itemId={traceId}+ projectId={projectId}+ redirectUrl={deleteRedirectUrl}+ invalidateFunc={onDeleteInvalidate}+ deleteConfirmation={name ?? ""}+ icon+ // Match Star/Publish so the three icons share one row height and a+ // ghost (not boxed "outline-solid") style.+ size={size}+ variant="ghost"+ />+ </div>+ );+}diff --git a/web/src/components/trace/TraceDetailBody.tsx b/web/src/components/trace/TraceDetailBody.tsxnew file mode 100644index 0000000000..c9079e29c8--- /dev/null+++ b/web/src/components/trace/TraceDetailBody.tsx@@ -0,0 +1,45 @@+import { Trace } from "@/src/components/trace/Trace";+import { Skeleton } from "@/src/components/ui/skeleton";+import { type useTraceDetailData } from "@/src/components/trace/useTraceDetailData";++type TraceDetailData = NonNullable<+ ReturnType<typeof useTraceDetailData>["data"]+>;++/** Detail-view title (`name: id`, or just the id), shared by the peek + page. */+export function traceDetailTitle(+ trace: { name?: string | null; id: string } | undefined,+ fallback?: string,+): string | undefined {+ if (!trace) return fallback;+ return trace.name ? `${trace.name}: ${trace.id}` : trace.id;+}++/**+ * The trace detail body (`<Trace>`), shared by the peek and the standalone+ * page so the invocation isn't copy-pasted. Renders a skeleton until the data+ * arrives. `keySuffix` lets a caller force a remount when the focused item+ * changes (e.g. the observation peek keys on the observation id).+ */+export function TraceDetailBody({+ trace,+ context,+ keySuffix,+}: {+ trace: TraceDetailData | undefined;+ context: "peek" | "fullscreen" | "annotation";+ keySuffix?: string;+}) {+ if (!trace) return <Skeleton className="h-full w-full rounded-none" />;+ return (+ <Trace+ key={keySuffix ? `${trace.id}-${keySuffix}` : trace.id}+ trace={trace}+ scores={trace.scores}+ corrections={trace.corrections}+ projectId={trace.projectId}+ observations={trace.observations}+ context={context}+ />+ );+}diff --git a/web/src/components/trace/TracePage.tsx b/web/src/components/trace/TracePage.tsxindex 5890e0c4b6..cbaa7e6150 100644--- a/web/src/components/trace/TracePage.tsx+++ b/web/src/components/trace/TracePage.tsx@@ -1,20 +1,19 @@-import { PublishTraceSwitch } from "@/src/components/publish-object-switch";import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";import { useRouter } from "next/router";-import { api } from "@/src/utils/api";-import { StarTraceDetailsToggle } from "@/src/components/star-toggle";import { ErrorPage } from "@/src/components/error-page";-import { DeleteTraceButton } from "@/src/components/deleteButton";+import { TraceDetailActions } from "@/src/components/trace/TraceDetailActions";+import { useTraceDetailData } from "@/src/components/trace/useTraceDetailData";import Page from "@/src/components/layouts/page";-import { Trace } from "@/src/components/trace/Trace";+import {+ TraceDetailBody,+ traceDetailTitle,+} from "@/src/components/trace/TraceDetailBody";import { useSession } from "next-auth/react";import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";import { Button } from "@/src/components/ui/button";import Link from "next/link";import { stripBasePath } from "@/src/utils/redirect";import { Badge } from "@/src/components/ui/badge";-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";-import { useEventsTraceData } from "@/src/features/events/hooks/useEventsTraceData";import { showErrorToast } from "@/src/features/notifications/showErrorToast";import { useEffect } from "react";@@ -28,65 +27,33 @@ export function TracePage({const router = useRouter();const session = useSession();const routeProjectId = (router.query.projectId as string) ?? "";- const { isBetaEnabled } = useV4Beta();- // Old path: fetch from traces table (beta OFF)- const tracesQuery = api.traces.byIdWithObservationsAndScores.useQuery(- {- traceId,- timestamp,- projectId: routeProjectId,- },- {- enabled: !isBetaEnabled,- retry(failureCount, error) {- if (- error.data?.code === "UNAUTHORIZED" ||- error.data?.code === "NOT_FOUND"- )- return false;- return failureCount < 3;- },- },- );-- // New path: fetch from events table (beta ON)- const eventsData = useEventsTraceData({+ // Shared, beta-aware fetch (same hook the peek uses).+ const trace = useTraceDetailData({projectId: routeProjectId,traceId,timestamp,- enabled: isBetaEnabled,});- // Use the appropriate data source based on beta toggle- const trace = isBetaEnabled- ? {- data: eventsData.data,- isLoading: eventsData.isLoading,- error: eventsData.error as typeof tracesQuery.error,- }- : tracesQuery;-const projectIdForAccessCheck = trace.data?.projectId ?? routeProjectId;const hasProjectAccess = useIsAuthenticatedAndProjectMember(projectIdForAccessCheck,);useEffect(() => {- if (isBetaEnabled && eventsData.cutoffObservationsAfterMaxCount) {+ if (trace.cutoffObservationsAfterMaxCount) {showErrorToast("Trace truncated","This trace has too many observations for the detail view. Only a subset is shown.","WARNING",);}- }, [isBetaEnabled, eventsData.cutoffObservationsAfterMaxCount]);+ }, [trace.cutoffObservationsAfterMaxCount]);- // Handle errors - for events path, we check if there's no data after loading- if (!isBetaEnabled && tracesQuery.error?.data?.code === "UNAUTHORIZED")+ if (trace.isUnauthorized)return <ErrorPage message="You do not have access to this trace." />;- if (!isBetaEnabled && tracesQuery.error?.data?.code === "NOT_FOUND")+ if (trace.isNotFound)return (<ErrorPagetitle="Trace not found"@@ -98,19 +65,6 @@ export function TracePage({/>);- // For events path: show not found if no observations found after loading- if (isBetaEnabled && !eventsData.isLoading && !eventsData.data)- return (- <ErrorPage- title="Trace not found"- message="No observations found for this trace. The trace may still be processing or has been deleted."- additionalButton={{- label: "Retry",- onClick: () => window.location.reload(),- }}- />- );-if (!trace.data) return <div className="p-3">Loading...</div>;const isSharedTrace = trace.data.public;@@ -152,9 +106,7 @@ export function TracePage({return (<PageheaderProps={{- title: trace.data.name- ? `${trace.data.name}: ${trace.data.id}`- : trace.data.id,+ title: traceDetailTitle(trace.data) ?? trace.data.id,itemType: "TRACE",breadcrumb: [{@@ -165,25 +117,6 @@ export function TracePage({showSidebarTrigger: !showPublicIndicators,leadingControl,breadcrumbBadges: sharedBadge,- actionButtonsLeft: (- <div className="ml-1 flex items-center gap-1">- <div className="flex items-center gap-0">- <StarTraceDetailsToggle- traceId={trace.data.id}- projectId={trace.data.projectId}- value={trace.data.bookmarked}- size="icon-xs"- />- <PublishTraceSwitch- traceId={trace.data.id}- projectId={trace.data.projectId}- timestamp={timestamp}- isPublic={trace.data.public}- size="icon-xs"- />- </div>- </div>- ),actionButtonsRight: (<><DetailPageNav@@ -210,25 +143,24 @@ export function TracePage({return `/project/${projectId as string}/traces/${entry.id}${finalQueryString}`;}}listKey="traces"+ size="sm"/>- <DeleteTraceButton- itemId={traceId}+ <TraceDetailActions+ traceId={trace.data.id}projectId={trace.data.projectId}- redirectUrl={`/project/${router.query.projectId as string}/traces`}- deleteConfirmation={trace.data.name ?? ""}- icon+ bookmarked={trace.data.bookmarked}+ isPublic={trace.data.public}+ name={trace.data.name}+ timestamp={timestamp}+ deleteRedirectUrl={`/project/${router.query.projectId as string}/traces`}/></>),}}><div className="flex max-h-full min-h-0 flex-1 overflow-hidden">- <Trace+ <TraceDetailBodytrace={trace.data}- scores={trace.data.scores}- corrections={trace.data.corrections}- projectId={trace.data.projectId}- observations={trace.data.observations}context={router.query.peek !== undefined ? "peek" : "fullscreen"}/></div>diff --git a/web/src/components/trace/useTraceDetailData.clienttest.tsx b/web/src/components/trace/useTraceDetailData.clienttest.tsxnew file mode 100644index 0000000000..9c4b621b36--- /dev/null+++ b/web/src/components/trace/useTraceDetailData.clienttest.tsx@@ -0,0 +1,85 @@+import { renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { useTraceDetailData } from "@/src/components/trace/useTraceDetailData";++// Created via vi.hoisted so they exist before the hoisted vi.mock factories run.+const { mockUseV4Beta, mockUseEventsTraceData, mockTracesQuery } = vi.hoisted(+ () => ({+ mockUseV4Beta: vi.fn(),+ mockUseEventsTraceData: vi.fn(),+ mockTracesQuery: vi.fn(),+ }),+);++vi.mock("@/src/features/events/hooks/useV4Beta", () => ({+ useV4Beta: () => mockUseV4Beta(),+}));+vi.mock("@/src/features/events/hooks/useEventsTraceData", () => ({+ useEventsTraceData: (args: unknown) => mockUseEventsTraceData(args),+}));+// The traces-table query hook always runs (it's a hook; enabled:false on the+// beta path), so it only needs to return a query-shaped object.+vi.mock("@/src/utils/api", () => ({+ api: {+ traces: {+ byIdWithObservationsAndScores: { useQuery: () => mockTracesQuery() },+ },+ },+}));++const render = () =>+ renderHook(() => useTraceDetailData({ projectId: "p", traceId: "t" })).result+ .current;++describe("useTraceDetailData (beta / events path)", () => {+ beforeEach(() => {+ mockUseV4Beta.mockReturnValue({ isBetaEnabled: true });+ mockTracesQuery.mockReturnValue({+ data: undefined,+ isLoading: false,+ isError: false,+ error: null,+ });+ });++ it("surfaces an UNAUTHORIZED error as isUnauthorized, not isNotFound", () => {+ mockUseEventsTraceData.mockReturnValue({+ data: undefined,+ isLoading: false,+ error: { data: { code: "UNAUTHORIZED" } },+ cutoffObservationsAfterMaxCount: false,+ });+ const r = render();+ expect(r.isUnauthorized).toBe(true);+ // The two flags must be mutually exclusive β an access error is not a+ // missing trace (else the page shows "Trace not found" for a 403).+ expect(r.isNotFound).toBe(false);+ });++ it("does NOT report a non-UNAUTHORIZED error (e.g. 500) as not-found", () => {+ mockUseEventsTraceData.mockReturnValue({+ data: undefined,+ isLoading: false,+ error: { data: { code: "INTERNAL_SERVER_ERROR" } },+ cutoffObservationsAfterMaxCount: false,+ });+ const r = render();+ // A transient server error is neither "not found" nor "unauthorized".+ expect(r.isNotFound).toBe(false);+ expect(r.isUnauthorized).toBe(false);+ expect(r.isError).toBe(true);+ });++ it("treats no-data-after-loading (no error) as a genuine not-found", () => {+ mockUseEventsTraceData.mockReturnValue({+ data: undefined,+ isLoading: false,+ error: null,+ cutoffObservationsAfterMaxCount: false,+ });+ const r = render();+ expect(r.isNotFound).toBe(true);+ expect(r.isUnauthorized).toBe(false);+ });+});diff --git a/web/src/components/trace/useTraceDetailData.ts b/web/src/components/trace/useTraceDetailData.tsnew file mode 100644index 0000000000..1315f9f103--- /dev/null+++ b/web/src/components/trace/useTraceDetailData.ts@@ -0,0 +1,88 @@+import { api } from "@/src/utils/api";+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";+import { useEventsTraceData } from "@/src/features/events/hooks/useEventsTraceData";++/**+ * Single source of truth for fetching a trace's detail data, beta-aware (events+ * table when the v4 preview is on, the traces table otherwise). Both the peek+ * and the standalone trace page use this so the fetch isn't forked β it exposes+ * the union of what each surface needs (the page's not-found / unauthorized+ * pages and the truncation flag; the peek just reads `data`/`isLoading`).+ */+export function useTraceDetailData({+ projectId,+ traceId,+ timestamp,+ enabled = true,+}: {+ projectId: string;+ traceId?: string;+ timestamp?: Date;+ enabled?: boolean;+}) {+ const { isBetaEnabled } = useV4Beta();++ // Old path: traces table (beta OFF).+ const tracesQuery = api.traces.byIdWithObservationsAndScores.useQuery(+ {+ traceId: traceId ?? "",+ projectId,+ timestamp,+ },+ {+ enabled: enabled && !!traceId && !isBetaEnabled,+ retry(failureCount, error) {+ if (+ error.data?.code === "UNAUTHORIZED" ||+ error.data?.code === "NOT_FOUND"+ )+ return false;+ return failureCount < 3;+ },+ staleTime: 60 * 1000,+ },+ );++ // New path: events table (beta ON).+ const eventsData = useEventsTraceData({+ projectId,+ traceId: traceId ?? "",+ timestamp,+ enabled: enabled && !!traceId && isBetaEnabled,+ });++ if (isBetaEnabled) {+ // useEventsTraceData types its error as `unknown`; narrow to the trpc shape+ // to read the code (the non-beta branch gets this for free from the typed+ // tracesQuery.error).+ const eventsErrorCode = (+ eventsData.error as { data?: { code?: string } } | null | undefined+ )?.data?.code;+ const isUnauthorized = eventsErrorCode === "UNAUTHORIZED";+ return {+ data: eventsData.data,+ isLoading: eventsData.isLoading,+ error: eventsData.error,+ isError: !!eventsData.error,+ // The events path surfaces "missing" as no-data after loading rather than+ // a NOT_FOUND error code. Any error (UNAUTHORIZED, a 500, a network blip)+ // also lands as no-data, so "not found" must mean no-data AND no-error β+ // else a transient failure is mislabeled as a deleted/missing trace.+ isNotFound:+ !eventsData.isLoading && !eventsData.data && !eventsData.error,+ isUnauthorized,+ cutoffObservationsAfterMaxCount:+ eventsData.cutoffObservationsAfterMaxCount,+ };+ }++ return {+ data: tracesQuery.data,+ isLoading: tracesQuery.isLoading,+ error: tracesQuery.error,+ isError: tracesQuery.isError,+ isNotFound: tracesQuery.error?.data?.code === "NOT_FOUND",+ isUnauthorized: tracesQuery.error?.data?.code === "UNAUTHORIZED",+ cutoffObservationsAfterMaxCount: false,+ };+}diff --git a/web/src/features/navigate-detail-pages/DetailPageNav.tsx b/web/src/features/navigate-detail-pages/DetailPageNav.tsxindex 46909eea8f..9c024bd6a5 100644--- a/web/src/features/navigate-detail-pages/DetailPageNav.tsx+++ b/web/src/features/navigate-detail-pages/DetailPageNav.tsx@@ -1,4 +1,4 @@-import { Button } from "@/src/components/ui/button";+import { Button, type ButtonProps } from "@/src/components/ui/button";import { InputCommandShortcut } from "@/src/components/ui/input-command";import { KeyboardShortcut } from "@/src/components/ui/keyboard-shortcut";import {@@ -25,8 +25,16 @@ export const DetailPageNav = (props: {path: (entry: ListEntry) => string;listKey: string;onNavigate?: (entry: ListEntry) => void;+ /** Button size; defaults to the cva default. Pass "sm" to match icon-xs rows. */+ size?: ButtonProps["size"];+ /**+ * Compact mode for dense toolbars (e.g. the peek header): icon-only ghost+ * arrows with the K/J hint moved to the tooltip, so the buttons match a row+ * of icon-xs controls instead of standing out. Shortcuts still work.+ */+ compact?: boolean;}) => {- const { currentId, path, listKey, onNavigate } = props;+ const { currentId, path, listKey, onNavigate, size, compact } = props;const { detailPagelists } = useDetailPageLists();const entries = detailPagelists[listKey] ?? [];const [shortcutPulse, setShortcutPulse] = useState<ShortcutPulse>(null);@@ -111,19 +119,22 @@ export const DetailPageNav = (props: {return () => window.removeEventListener("keydown", handleKeyDown);}, [previousPageEntry, nextPageEntry, navigateToEntry, pulseShortcut]);- if (entries.length > 1)+ if (entries.length > 1) {+ const buttonClassName = (active: boolean) =>+ cn(+ "transition-[background-color,border-color,box-shadow,color] duration-150",+ !compact && "gap-1.5 px-2",+ active && "border-primary/60 bg-accent/60 ring-primary/20 ring-2",+ );return (<div className="flex flex-row gap-1"><Tooltip><TooltipTrigger asChild><Button- variant="outline"+ variant={compact ? "ghost" : "outline"}type="button"- className={cn(- "gap-1.5 px-2 transition-[background-color,border-color,box-shadow,color] duration-150",- shortcutPulse === "previous" &&- "border-primary/60 bg-accent/60 ring-primary/20 ring-2",- )}+ size={compact ? "icon-xs" : size}+ className={buttonClassName(shortcutPulse === "previous")}disabled={!previousPageEntry}onClick={() => {if (previousPageEntry) {@@ -133,7 +144,7 @@ export const DetailPageNav = (props: {}}><ArrowUp className="h-4 w-4" />- <KeyboardShortcut>K</KeyboardShortcut>+ {!compact && <KeyboardShortcut>K</KeyboardShortcut>}</Button></TooltipTrigger><TooltipContent>@@ -145,13 +156,10 @@ export const DetailPageNav = (props: {<Tooltip><TooltipTrigger asChild><Button- variant="outline"+ variant={compact ? "ghost" : "outline"}type="button"- className={cn(- "gap-1.5 px-2 transition-[background-color,border-color,box-shadow,color] duration-150",- shortcutPulse === "next" &&- "border-primary/60 bg-accent/60 ring-primary/20 ring-2",- )}+ size={compact ? "icon-xs" : size}+ className={buttonClassName(shortcutPulse === "next")}disabled={!nextPageEntry}onClick={() => {if (nextPageEntry) {@@ -161,7 +169,7 @@ export const DetailPageNav = (props: {}}><ArrowDown className="h-4 w-4" />- <KeyboardShortcut>J</KeyboardShortcut>+ {!compact && <KeyboardShortcut>J</KeyboardShortcut>}</Button></TooltipTrigger><TooltipContent>@@ -171,5 +179,6 @@ export const DetailPageNav = (props: {</Tooltip></div>);+ }return null;};