Skip to content

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

fix(web): detail tabs show what fits, the rest behind a more menu (#18469)

Trang Nguyen783fae67f06f
diff --git a/web/src/components/design-system/Tabs/Tabs.stories.tsx b/web/src/components/design-system/Tabs/Tabs.stories.tsx
index 1b2e6d2bc1..7aeaaa0c22 100644
--- a/web/src/components/design-system/Tabs/Tabs.stories.tsx
+++ b/web/src/components/design-system/Tabs/Tabs.stories.tsx
@@ -1,4 +1,5 @@
import React from "react";
+import { cn } from "@/src/utils/tailwind";
import { KeyRound, User } from "lucide-react";
import { expect, userEvent, waitFor, within } from "storybook/test";
@@ -66,6 +67,99 @@ function ResizableSlidingTabs() {
);
}
+const overflowTabs = [
+ { value: "preview", label: "Preview" },
+ { value: "messages", label: "Messages", internal: true },
+ { value: "attributes", label: "Attributes" },
+ { value: "scores", label: "Scores" },
+ {
+ value: "log",
+ label: "Log View",
+ tooltip: "Shows all observations concatenated.",
+ },
+];
+
+const overflowTriggers = overflowTabs.map((tab) => (
+ <Tabs.Trigger
+ key={tab.value}
+ value={tab.value}
+ label={tab.label}
+ internal={tab.internal}
+ tooltip={tab.tooltip}
+ />
+));
+
+const overflowPanels = overflowTabs.map((tab) => (
+ <Tabs.Content key={tab.value} value={tab.value}>
+ {tab.label} panel
+ </Tabs.Content>
+));
+
+/** The row sits in a fixed-width box so each story shows one overflow case. */
+function OverflowTabs({
+ initialValue,
+ width,
+}: {
+ initialValue: string;
+ width: "w-40" | "w-sm" | "w-2xl";
+}) {
+ const [value, setValue] = React.useState(initialValue);
+
+ return (
+ <div className={width}>
+ <Tabs value={value} onValueChange={setValue}>
+ <div className="flex h-9 items-center border-b">
+ <Tabs.List
+ variant="underline"
+ overflow="menu"
+ aria-label="Detail views"
+ >
+ {overflowTriggers}
+ </Tabs.List>
+ <span className="text-muted-foreground shrink-0 px-2 text-xs">
+ trailing
+ </span>
+ </div>
+ {overflowPanels}
+ </Tabs>
+ </div>
+ );
+}
+
+/**
+ * Like the detail panels: a view toggle sits after the tabs except on Scores,
+ * so picking Scores from the menu frees enough room for every tab and the
+ * overflow trigger disappears.
+ */
+function OverflowTabsWithTrailing() {
+ const [value, setValue] = React.useState("preview");
+
+ return (
+ <div className="w-xl">
+ <Tabs value={value} onValueChange={setValue}>
+ <div className="flex h-9 items-center border-b">
+ <Tabs.List
+ variant="underline"
+ overflow="menu"
+ aria-label="Detail views"
+ >
+ {overflowTriggers}
+ </Tabs.List>
+ <span
+ className={cn(
+ "text-muted-foreground w-64 shrink-0 px-2 text-xs",
+ value === "scores" && "invisible",
+ )}
+ >
+ trailing
+ </span>
+ </div>
+ {overflowPanels}
+ </Tabs>
+ </div>
+ );
+}
+
function LinkTabs() {
return (
<Tabs.List variant="underline" aria-label="Page sections">
@@ -129,6 +223,36 @@ export const Underline = meta.story({
},
});
+const overflowStoryParameters = {
+ controls: {
+ disable: true,
+ },
+};
+
+/** Wide enough for every tab: no overflow trigger. */
+export const OverflowAllFit = meta.story({
+ parameters: overflowStoryParameters,
+ render: () => <OverflowTabs initialValue="preview" width="w-2xl" />,
+});
+
+/** Three tabs fit; Scores and Log View sit behind the overflow trigger. */
+export const OverflowThreeFit = meta.story({
+ parameters: overflowStoryParameters,
+ render: () => <OverflowTabs initialValue="preview" width="w-sm" />,
+});
+
+/** The active Log View tab takes the last slot and displaces Attributes. */
+export const OverflowActiveTab = meta.story({
+ parameters: overflowStoryParameters,
+ render: () => <OverflowTabs initialValue="log" width="w-sm" />,
+});
+
+/** Only the active tab fits next to the overflow trigger. */
+export const OverflowOneFits = meta.story({
+ parameters: overflowStoryParameters,
+ render: () => <OverflowTabs initialValue="scores" width="w-40" />,
+});
+
/** Link tabs render outside a `Tabs` root: navigation, not a tablist. */
export const Links = meta.story({
parameters: {
@@ -363,6 +487,97 @@ export const RendersLinksAsNavigation = meta.story({
},
});
+export const ShowsNoOverflowWhenTabsFit = meta.story({
+ name: "(Test) Shows No Overflow When Tabs Fit",
+ parameters: overflowStoryParameters,
+ render: () => <OverflowTabs initialValue="preview" width="w-2xl" />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await expect(canvas.getAllByRole("tab")).toHaveLength(5);
+ await expect(
+ canvas.queryByRole("button", { name: "More tabs" }),
+ ).not.toBeInTheDocument();
+ },
+});
+
+export const KeepsActiveTabVisibleInOverflow = meta.story({
+ name: "(Test) Keeps Active Tab Visible In Overflow",
+ parameters: overflowStoryParameters,
+ render: () => <OverflowTabs initialValue="log" width="w-40" />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const logTab = canvas.getByRole("tab", { name: "Log View" });
+ const trigger = canvas.getByRole("button", { name: "More tabs" });
+
+ await expect(logTab).toHaveAttribute("aria-selected", "true");
+ await expect(canvas.queryByRole("tab", { name: "Preview" })).toBeNull();
+ // The trigger shares the row with the tab instead of hanging below it.
+ const tabRect = logTab.getBoundingClientRect();
+ const triggerRect = trigger.getBoundingClientRect();
+ await expect(
+ Math.abs(
+ tabRect.top +
+ tabRect.height / 2 -
+ (triggerRect.top + triggerRect.height / 2),
+ ),
+ ).toBeLessThan(2);
+ },
+});
+
+export const SelectsHiddenTabFromOverflowMenu = meta.story({
+ name: "(Test) Selects Hidden Tab From Overflow Menu",
+ parameters: overflowStoryParameters,
+ render: () => <OverflowTabs initialValue="preview" width="w-40" />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(document.body);
+
+ await userEvent.click(canvas.getByRole("button", { name: "More tabs" }));
+ const messagesItem = await body.findByRole("menuitem", {
+ name: /Messages/,
+ });
+ await expect(messagesItem).toHaveTextContent("Internal");
+
+ await userEvent.click(body.getByRole("menuitem", { name: "Attributes" }));
+ await waitFor(() => {
+ expect(canvas.getByRole("tab", { name: "Attributes" })).toHaveAttribute(
+ "aria-selected",
+ "true",
+ );
+ expect(canvas.queryByRole("tab", { name: "Preview" })).toBeNull();
+ });
+ await expect(canvas.getByText("Attributes panel")).toBeVisible();
+ },
+});
+
+export const FocusesTabSelectedFromOverflowMenu = meta.story({
+ name: "(Test) Focuses Tab Selected From Overflow Menu",
+ parameters: overflowStoryParameters,
+ render: () => <OverflowTabsWithTrailing />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(document.body);
+ const trigger = canvas.getByRole("button", { name: "More tabs" });
+
+ await expect(canvas.queryByRole("tab", { name: "Scores" })).toBeNull();
+
+ trigger.focus();
+ await userEvent.keyboard("{Enter}");
+ const scoresItem = await body.findByRole("menuitem", { name: "Scores" });
+ scoresItem.focus();
+ await userEvent.keyboard("{Enter}");
+
+ // The trailing slot keeps its width, so Scores swaps into the row.
+ await waitFor(() => {
+ expect(canvas.getByRole("button", { name: "More tabs" })).toBeTruthy();
+ expect(document.activeElement).toBe(
+ canvas.getByRole("tab", { name: "Scores" }),
+ );
+ });
+ },
+});
+
export const TracksTriggerResize = meta.story({
name: "(Test) Tracks Trigger Resize",
render: () => <ResizableSlidingTabs />,
diff --git a/web/src/components/design-system/Tabs/Tabs.tsx b/web/src/components/design-system/Tabs/Tabs.tsx
index f807c3b07b..7093783ba2 100644
--- a/web/src/components/design-system/Tabs/Tabs.tsx
+++ b/web/src/components/design-system/Tabs/Tabs.tsx
@@ -3,9 +3,15 @@
import * as React from "react";
import * as TabsPrimitive from "@radix-ui/react-tabs";
import { cva } from "class-variance-authority";
-import { type LucideIcon } from "lucide-react";
+import { EllipsisVertical, type LucideIcon } from "lucide-react";
import Link, { type LinkProps } from "next/link";
+import { flushSync } from "react-dom";
+import { Badge } from "@/src/components/design-system/Badge/Badge";
+import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";
+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";
+import { Tooltip } from "@/src/components/design-system/Tooltip/Tooltip";
+import { getVisibleRowItemIndices } from "@/src/utils/getVisibleRowItemIndices";
import { cn } from "@/src/utils/tailwind";
type TabsVariant = "inset" | "underline";
@@ -16,6 +22,10 @@ type TabsLook = TabsVariant | "navigation";
const rootFillClassName =
"flex h-full min-h-0 w-full flex-1 flex-col overflow-hidden";
+const tabsTriggerLabelClassName = "min-w-0 truncate leading-normal";
+
+const overflowTriggerLabel = "More tabs";
+
const tabsListVariants = cva(
"items-center [&>:not([role=tab])]:flex [&>:not([role=tab])>[role=tab]]:w-full",
{
@@ -91,7 +101,11 @@ type TabsRootProps = {
| { defaultValue?: never; value: string }
);
-const TabsRootContext = React.createContext(false);
+/** The root's own props; `Tabs.List overflow="menu"` reads the active value from a controlled root. */
+const TabsRootContext = React.createContext<{
+ value?: string;
+ onValueChange?: (value: string) => void;
+} | null>(null);
function TabsRoot({
activationMode,
@@ -103,7 +117,7 @@ function TabsRoot({
value,
}: TabsRootProps) {
return (
- <TabsRootContext value={true}>
+ <TabsRootContext value={{ value, onValueChange }}>
<TabsPrimitive.Root
activationMode={activationMode}
className={layout === "fill" ? rootFillClassName : undefined}
@@ -124,8 +138,17 @@ type TabsListProps = {
gap?: "none" | "sm" | "lg";
layout?: "default" | "full" | "packed";
} & (
- | { variant: "inset"; size: TabsInsetSize }
- | { variant: "underline"; size?: never }
+ | { variant: "inset"; size: TabsInsetSize; overflow?: never }
+ | {
+ variant: "underline";
+ size?: never;
+ /**
+ * `menu`: shows the `Tabs.Trigger` children that fit, the active one
+ * always, and lists the rest in a menu. Needs a controlled root; the
+ * list fills a flex row the caller owns, which sets height and divider.
+ */
+ overflow?: "menu";
+ }
);
const TabsListContext = React.createContext<{
@@ -139,10 +162,11 @@ function TabsList({
children,
gap,
layout,
+ overflow,
size,
variant,
}: TabsListProps) {
- const inRoot = React.use(TabsRootContext);
+ const inRoot = React.use(TabsRootContext) !== null;
const look: TabsLook =
variant === "underline" && !inRoot ? "navigation" : variant;
const listRef = React.useRef<HTMLDivElement>(null);
@@ -234,6 +258,12 @@ function TabsList({
};
}, [hasSlidingIndicator]);
+ if (overflow === "menu" && inRoot) {
+ return (
+ <TabsOverflowList aria-label={ariaLabel}>{children}</TabsOverflowList>
+ );
+ }
+
const className = tabsListVariants({ gap, layout, look, size });
if (look === "navigation") {
@@ -270,15 +300,20 @@ function TabsList({
type TabsTriggerProps = {
disabled?: boolean;
icon?: LucideIcon;
+ /** Marks an internal-only feature with the Internal badge, in the row and in the overflow menu. */
+ internal?: boolean;
} & (
| {
/** Preferred for plain-text trigger content. */
label: string;
+ /** Rich tooltip on the label; replaces the native title. */
+ tooltip?: string;
children?: never;
title?: never;
}
| {
label?: never;
+ tooltip?: never;
/** Rich-content escape hatch. */
children: React.ReactNode;
title?: string;
@@ -298,19 +333,18 @@ type TabsTriggerProps = {
function TabsTrigger(props: TabsTriggerProps) {
// Outside a Tabs.List, fall back to the underline look instead of crashing.
const list = React.use(TabsListContext) ?? { look: "underline" as const };
- const { children, disabled, icon: Icon, label, title } = props;
+ const { children, disabled, icon, internal, label, title, tooltip } = props;
const className = tabsTriggerVariants({ look: list.look, size: list.size });
+ const nativeTitle = tooltip ? undefined : (label ?? title);
const content = (
- <>
- {Icon ? <Icon aria-hidden="true" className="icon-base shrink-0" /> : null}
- {label !== undefined ? (
- <span className="min-w-0 truncate" title={label}>
- {label}
- </span>
- ) : (
- children
- )}
- </>
+ <TabsTriggerContent
+ icon={icon}
+ internal={internal}
+ label={label}
+ tooltip={tooltip}
+ >
+ {children}
+ </TabsTriggerContent>
);
if (props.href !== undefined) {
@@ -322,7 +356,7 @@ function TabsTrigger(props: TabsTriggerProps) {
aria-disabled={disabled || undefined}
tabIndex={disabled ? -1 : undefined}
data-state={props.active ? "active" : "inactive"}
- title={label ?? title}
+ title={nativeTitle}
className={className}
>
{content}
@@ -334,7 +368,7 @@ function TabsTrigger(props: TabsTriggerProps) {
<TabsPrimitive.Trigger
value={props.value}
disabled={disabled}
- title={label ?? title}
+ title={nativeTitle}
className={className}
>
{content}
@@ -342,6 +376,280 @@ function TabsTrigger(props: TabsTriggerProps) {
);
}
+function TabsTriggerContent({
+ children,
+ icon: Icon,
+ internal,
+ label,
+ tooltip,
+}: Pick<
+ TabsTriggerProps,
+ "children" | "icon" | "internal" | "label" | "tooltip"
+>) {
+ return (
+ <>
+ {Icon ? <Icon aria-hidden="true" className="icon-base shrink-0" /> : null}
+ {label === undefined ? (
+ children
+ ) : (
+ <TabsTriggerLabel label={label} tooltip={tooltip} />
+ )}
+ {/* In a tight row the badge gives way before the label. */}
+ {internal ? (
+ <span className="flex min-w-0 shrink-100 overflow-hidden">
+ <TabsInternalBadge />
+ </span>
+ ) : null}
+ </>
+ );
+}
+
+function TabsTriggerLabel({
+ label,
+ tooltip,
+}: Pick<TabsTriggerProps, "tooltip"> & { label: string }) {
+ if (!tooltip) {
+ return (
+ <span className={tabsTriggerLabelClassName} title={label}>
+ {label}
+ </span>
+ );
+ }
+
+ return (
+ <Tooltip label={tooltip}>
+ {({ getTriggerProps }) => (
+ <span {...getTriggerProps()} className={tabsTriggerLabelClassName}>
+ {label}
+ </span>
+ )}
+ </Tooltip>
+ );
+}
+
+function TabsInternalBadge() {
+ return <Badge text="Internal" color="yellow" size="sm" />;
+}
+
+/** The underline list with `overflow="menu"`; only direct `Tabs.Trigger` children take part. */
+function TabsOverflowList({
+ "aria-label": ariaLabel,
+ children,
+}: Pick<TabsListProps, "aria-label" | "children">) {
+ const root = React.use(TabsRootContext);
+ const triggers =
+ React.Children.toArray(children).filter(isTabsTriggerElement);
+ const activeIndex = triggers.findIndex(
+ (trigger) => trigger.props.value === root?.value,
+ );
+ const measureKey = JSON.stringify(
+ triggers.map((trigger) => [
+ trigger.props.value,
+ trigger.props.label ?? trigger.props.title ?? null,
+ ]),
+ );
+ const { availableRef, measureRef, visibleIndices } = useTabsOverflow<
+ HTMLDivElement,
+ HTMLDivElement
+ >(measureKey, activeIndex);
+ const visible = new Set(visibleIndices ?? triggers.map((_, index) => index));
+ const hiddenTriggers = triggers.filter((_, index) => !visible.has(index));
+ const replicaClassName = tabsTriggerVariants({ look: "underline" });
+ const rowRef = React.useRef<HTMLDivElement>(null);
+
+ const selectFromMenu = (value: string) => {
+ root?.onValueChange?.(value);
+ // The menu hands focus back to its trigger in a microtask, and that
+ // trigger is gone once every tab fits; the selected tab takes focus after.
+ requestAnimationFrame(() => {
+ rowRef.current
+ ?.querySelector<HTMLElement>('[role="tab"][data-state="active"]')
+ ?.focus();
+ });
+ };
+
+ return (
+ <TabsListContext value={{ look: "underline" }}>
+ {/* A zero flex basis makes the list the space left over by the caller's
+ controls, so the triggers never feed back into the width they are
+ compared against. */}
+ <TabsPrimitive.List
+ ref={availableRef}
+ aria-label={ariaLabel}
+ className="relative flex h-full min-w-0 flex-1 items-center justify-start overflow-x-clip"
+ >
+ {/* Non-interactive replicas keep every trigger measurable, including
+ the hidden ones, without duplicating tab semantics. */}
+ <div
+ ref={measureRef}
+ aria-hidden="true"
+ className="invisible absolute flex h-full w-max items-center"
+ >
+ {triggers.map((trigger) => (
+ <span key={trigger.props.value} className={replicaClassName}>
+ <TabsTriggerContent
+ icon={trigger.props.icon}
+ internal={trigger.props.internal}
+ label={trigger.props.label}
+ >
+ {trigger.props.children}
+ </TabsTriggerContent>
+ </span>
+ ))}
+ <TabsOverflowTrigger tabIndex={-1} />
+ </div>
+ <div
+ ref={rowRef}
+ className={cn(
+ // A tab wider than the row truncates; the overflow trigger never clips.
+ "flex h-full min-w-0 items-center [&>[role=tab]]:min-w-0",
+ visibleIndices === null && "invisible",
+ )}
+ >
+ {triggers.map((trigger, index) =>
+ visible.has(index) ? trigger : null,
+ )}
+ {hiddenTriggers.length > 0 ? (
+ <span className="flex shrink-0">
+ <DropdownMenu
+ ariaLabel={overflowTriggerLabel}
+ items={hiddenTriggers.map((trigger) => ({
+ badge: trigger.props.internal ? (
+ <TabsInternalBadge />
+ ) : undefined,
+ disabled: trigger.props.disabled
+ ? { reason: trigger.props.tooltip ?? "Not available" }
+ : undefined,
+ id: trigger.props.value,
+ onClick: () => selectFromMenu(trigger.props.value),
+ title:
+ trigger.props.label ??
+ trigger.props.title ??
+ trigger.props.value,
+ tooltip: trigger.props.tooltip,
+ type: "item" as const,
+ }))}
+ >
+ {({ getTriggerProps }) => (
+ <TabsOverflowTrigger {...getTriggerProps()} />
+ )}
+ </DropdownMenu>
+ </span>
+ ) : null}
+ </div>
+ </TabsPrimitive.List>
+ </TabsListContext>
+ );
+}
+
+function TabsOverflowTrigger(
+ props: Omit<
+ React.ComponentProps<typeof IconButton>,
+ "icon" | "label" | "size" | "variant"
+ >,
+) {
+ return (
+ <IconButton
+ {...props}
+ icon={EllipsisVertical}
+ label={overflowTriggerLabel}
+ size="md"
+ variant="ghost"
+ />
+ );
+}
+
+/**
+ * Measures every tab from a hidden replica row and reports which ones fit next
+ * to the overflow trigger inside the list on `availableRef`.
+ *
+ * The replica row on `measureRef` holds one child per tab, in order, followed
+ * by a replica of the overflow trigger. It stays mounted and sized to its
+ * content, so hidden tabs remain measurable and the row can bring them back.
+ *
+ * `measureKey` must change whenever the tabs' identity, order or labels change,
+ * so the widths are read again in the new order. Size changes inside a replica,
+ * such as a badge appearing, are picked up by observing each replica.
+ *
+ * `visibleIndices` is null until the first measurement, so callers can hold
+ * the row back instead of painting the wrong set. Every later change is
+ * committed before the browser paints, so the swap never flashes.
+ *
+ * The list must not derive its width from the visible tabs, otherwise the two
+ * measurements feed back into each other. A flex item with a zero flex basis
+ * satisfies this.
+ */
+function useTabsOverflow<
+ TAvailable extends HTMLElement,
+ TMeasure extends HTMLElement,
+>(measureKey: string, activeIndex: number) {
+ const availableRef = React.useRef<TAvailable>(null);
+ const measureRef = React.useRef<TMeasure>(null);
+ const [metrics, setMetrics] = React.useState<{
+ availableWidth: number;
+ overflowWidth: number;
+ widths: number[];
+ }>();
+
+ React.useLayoutEffect(() => {
+ const available = availableRef.current;
+ const measure = measureRef.current;
+ if (!available || !measure) return;
+
+ const read = () => {
+ const widths = Array.from(
+ measure.children,
+ (child) => child.getBoundingClientRect().width,
+ );
+ const overflowWidth = widths.pop() ?? 0;
+ return {
+ availableWidth: available.getBoundingClientRect().width,
+ overflowWidth,
+ widths,
+ };
+ };
+
+ setMetrics(read());
+
+ if (typeof ResizeObserver === "undefined") return;
+
+ // Resize callbacks run before paint; a synchronous commit keeps it that way.
+ const resizeObserver = new ResizeObserver(() => {
+ flushSync(() => setMetrics(read()));
+ });
+ resizeObserver.observe(available);
+ for (const replica of measure.children) {
+ resizeObserver.observe(replica);
+ }
+
+ return () => resizeObserver.disconnect();
+ }, [measureKey]);
+
+ const visibleIndices = React.useMemo(
+ () =>
+ metrics
+ ? getVisibleRowItemIndices({ ...metrics, pinnedIndex: activeIndex })
+ : null,
+ [activeIndex, metrics],
+ );
+
+ return { availableRef, measureRef, visibleIndices };
+}
+
+function isTabsTriggerElement(
+ child: React.ReactNode,
+): child is TabsTriggerElement {
+ return (
+ React.isValidElement(child) &&
+ child.type === TabsTrigger &&
+ typeof (child.props as TabsTriggerProps).value === "string"
+ );
+}
+
+type TabsTriggerElement = React.ReactElement<
+ Extract<TabsTriggerProps, { value: string }>
+>;
+
type TabsContentProps = {
children: React.ReactNode;
/** `fill`: a column that takes the remaining height of a `layout="fill"` root. */
diff --git a/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx b/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
index 0679cef905..fd22e1090a 100644
--- a/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
+++ b/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
@@ -19,16 +19,11 @@
*/
import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";
+import { cn } from "@/src/utils/tailwind";
import { useCallback, useMemo, useState } from "react";
import { Switch } from "@/src/components/design-system/Switch/Switch";
import { HoverCard } from "@/src/components/design-system/HoverCard/HoverCard";
import { Tabs } from "@/src/components/design-system/Tabs/Tabs";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/src/components/ui/tooltip";
import {
CommentDrawerController,
getCommentDrawerInitialStateFromUrl,
@@ -69,10 +64,7 @@ import {
import { useHasProjectAccess } from "@/src/features/rbac";
import { useSession } from "next-auth/react";
import { ObservationPreview } from "./ObservationPreview";
-import {
- InternalFeatureBadge,
- useInternalFeaturesEnabled,
-} from "@/src/features/feature-flags";
+import { useInternalFeaturesEnabled } from "@/src/features/feature-flags";
import { TraceMessagesView } from "../TraceMessagesView/TraceMessagesView";
import { ObservationAttributesTab } from "./ObservationAttributesTab";
import { buildModelParameters } from "@/src/features/traces/fns/buildModelParameters";
@@ -377,126 +369,111 @@ export function ConnectedObservationDetailView({
layout="fill"
onValueChange={(value) => setSelectedTab(value as DetailTab)}
>
- <TooltipProvider>
- <TraceDetailTabsBarList
- selectedTab={selectedTab}
- onSelect={setSelectedTab}
- tabs={[
- "preview",
- ...(showMessagesTab ? ["messages" as const] : []),
- "attributes",
- ...(showScoresTab ? ["scores" as const] : []),
- ...(showLogViewTab ? ["log" as const] : []),
- ]}
- triggers={
- <>
- <Tabs.Trigger value="preview" label="Preview" />
- {showMessagesTab && (
- <Tabs.Trigger value="messages">
- Messages <InternalFeatureBadge />
- </Tabs.Trigger>
- )}
- <Tabs.Trigger value="attributes" label="Attributes" />
- {showScoresTab ? (
- <Tabs.Trigger value="scores" label="Scores" />
- ) : null}
- {showLogViewTab ? (
- <Tabs.Trigger value="log">
- <Tooltip>
- <TooltipTrigger asChild>
- <span>Log View</span>
- </TooltipTrigger>
- <TooltipContent className="text-xs">
- {isLogViewVirtualized
- ? `Shows all ${observations.length} observations with virtualization enabled.`
- : "Shows all observations concatenated. Great for quickly scanning through them."}
- </TooltipContent>
- </Tooltip>
- </Tabs.Trigger>
- ) : null}
- </>
- }
- trailingControls={
- (selectedTab === "log" ||
- selectedTab === "attributes" ||
- (selectedTab === "preview" && isPrettyViewAvailable)) && (
- <>
- <div className="ml-auto h-fit shrink-0 py-0.5 pr-4 pl-2">
- <Tabs
- value={
- selectedTab === "log" && isLogViewVirtualized
- ? "pretty"
- : selectedViewTab
- }
- onValueChange={(value) => {
- if (
- selectedTab === "log" &&
- isLogViewVirtualized &&
- value === "json"
- ) {
- return;
+ <TraceDetailTabsBarList
+ tabs={[
+ "preview",
+ ...(showMessagesTab ? ["messages" as const] : []),
+ "attributes",
+ ...(showScoresTab ? ["scores" as const] : []),
+ ...(showLogViewTab ? ["log" as const] : []),
+ ]}
+ logViewDescription={
+ isLogViewVirtualized
+ ? `Shows all ${observations.length} observations with virtualization enabled.`
+ : "Shows all observations concatenated. Great for quickly scanning through them."
+ }
+ trailingControls={
+ /* View toggle where it applies; invisible on other tabs so the row keeps its width. */
+ <div
+ className={cn(
+ "flex shrink-0 items-center",
+ !(
+ selectedTab === "log" ||
+ selectedTab === "attributes" ||
+ (selectedTab === "preview" && isPrettyViewAvailable)
+ ) && "invisible",
+ )}
+ >
+ <div className="h-fit shrink-0 py-0.5 pr-4 pl-2">
+ <Tabs
+ value={
+ selectedTab === "log" && isLogViewVirtualized
+ ? "pretty"
+ : selectedViewTab
+ }
+ onValueChange={(value) => {
+ if (
+ selectedTab === "log" &&
+ isLogViewVirtualized &&
+ value === "json"
+ ) {
+ return;
+ }
+ handleViewTabChange(value);
+ }}
+ >
+ <Tabs.List variant="inset" size="sm">
+ <Tabs.Trigger value="pretty" label="Formatted" />
+ {selectedTab === "log" && isLogViewVirtualized ? (
+ <HoverCard
+ openDelay={200}
+ sideOffset={8}
+ placement="bottom-end"
+ content={
+ <div className="w-64 p-3 text-sm">
+ <p className="font-bold">
+ Raw view unavailable
+ </p>
+ <p className="text-muted-foreground mt-1">
+ Disabled for traces with{" "}
+ {
+ TRACE_VIEW_CONFIG.logView
+ .virtualizationThreshold
+ }
+ + observations to maintain performance.
+ </p>
+ </div>
}
- handleViewTabChange(value);
- }}
- >
- <Tabs.List variant="inset" size="sm">
- <Tabs.Trigger value="pretty" label="Formatted" />
- {selectedTab === "log" && isLogViewVirtualized ? (
- <HoverCard
- openDelay={200}
- sideOffset={8}
- placement="bottom-end"
- content={
- <div className="w-64 p-3 text-sm">
- <p className="font-bold">
- Raw view unavailable
- </p>
- <p className="text-muted-foreground mt-1">
- Disabled for traces with{" "}
- {
- TRACE_VIEW_CONFIG.logView
- .virtualizationThreshold
- }
- + observations to maintain performance.
- </p>
- </div>
- }
- >
- {({ getTriggerProps }) => (
- <span tabIndex={0} {...getTriggerProps()}>
- <Tabs.Trigger
- value="json"
- disabled
- label="Raw"
- />
- </span>
- )}
- </HoverCard>
- ) : (
- <Tabs.Trigger value="json" label="Raw" />
+ >
+ {({ getTriggerProps }) => (
+ <span tabIndex={0} {...getTriggerProps()}>
+ <Tabs.Trigger
+ value="json"
+ disabled
+ label="Raw"
+ />
+ </span>
)}
- </Tabs.List>
- </Tabs>
- </div>
- {selectedViewTab === "json" &&
- selectedTab !== "attributes" &&
- !(selectedTab === "log" && isLogViewVirtualized) && (
- <div className="mr-1 flex items-center gap-1.5">
- <Switch
- size="sm"
- checked={jsonBetaEnabled}
- onCheckedChange={handleBetaToggle}
- />
- <span className="text-muted-foreground text-xs">
- Beta
- </span>
- </div>
+ </HoverCard>
+ ) : (
+ <Tabs.Trigger value="json" label="Raw" />
)}
- </>
- )
- }
- />
- </TooltipProvider>
+ </Tabs.List>
+ </Tabs>
+ </div>
+ {/* Stays mounted so the row keeps its width; attributes and the virtualized log have no Beta view. */}
+ {selectedViewTab === "json" && (
+ <div
+ className={cn(
+ "mr-1 flex items-center gap-1.5",
+ (selectedTab === "attributes" ||
+ (selectedTab === "log" && isLogViewVirtualized)) &&
+ "invisible",
+ )}
+ >
+ <Switch
+ size="sm"
+ checked={jsonBetaEnabled}
+ onCheckedChange={handleBetaToggle}
+ />
+ <span className="text-muted-foreground text-xs">
+ Beta
+ </span>
+ </div>
+ )}
+ </div>
+ }
+ />
{selectedTab === "messages" && (
<Tabs.Content value="messages" layout="fill">
diff --git a/web/src/features/traces/components/TraceDetailTabMenu.tsx b/web/src/features/traces/components/TraceDetailTabMenu.tsx
deleted file mode 100644
index b0483bdae3..0000000000
--- a/web/src/features/traces/components/TraceDetailTabMenu.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { DropdownIndicator } from "@/src/components/design-system/DropdownIndicator/DropdownIndicator";
-import { Button } from "@/src/components/ui/button";
-import {
- DropdownMenuController,
- DropdownMenuRadioGroup,
- DropdownMenuRadioItem,
-} from "@/src/components/ui/dropdown-menu";
-import { InternalFeatureBadge } from "@/src/features/feature-flags";
-import type { DetailTab } from "../contexts/SelectionContext";
-
-const labels: Record<DetailTab, string> = {
- preview: "Preview",
- messages: "Messages",
- attributes: "Attributes",
- scores: "Scores",
- log: "Log View",
-};
-
-export function TraceDetailTabMenu({
- tabs,
- selectedTab,
- onSelect,
-}: {
- tabs: DetailTab[];
- selectedTab: DetailTab;
- onSelect: (tab: DetailTab) => void;
-}) {
- return (
- <DropdownMenuController
- align="start"
- renderMenu={() => (
- <DropdownMenuRadioGroup
- value={selectedTab}
- onValueChange={(value) => {
- const tab = tabs.find((tab) => tab === value);
- if (tab) onSelect(tab);
- }}
- >
- {tabs.map((tab) => (
- <DropdownMenuRadioItem key={tab} value={tab}>
- <span className="flex items-center gap-2">
- {labels[tab]}
- {tab === "messages" && <InternalFeatureBadge />}
- </span>
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- )}
- >
- {({ Trigger }) => (
- <Trigger asChild>
- <Button
- variant="ghost"
- size="sm"
- aria-label={`Detail view: ${labels[selectedTab]}`}
- className="h-7 gap-1.5"
- >
- {labels[selectedTab]}
- {selectedTab === "messages" && <InternalFeatureBadge />}
- <DropdownIndicator nudge />
- </Button>
- </Trigger>
- )}
- </DropdownMenuController>
- );
-}
diff --git a/web/src/features/traces/components/TraceDetailTabsBarList.clienttest.tsx b/web/src/features/traces/components/TraceDetailTabsBarList.clienttest.tsx
deleted file mode 100644
index 49075f140a..0000000000
--- a/web/src/features/traces/components/TraceDetailTabsBarList.clienttest.tsx
+++ /dev/null
@@ -1,136 +0,0 @@
-/** @vitest-environment jsdom */
-import { act, cleanup, render, screen } from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { Tabs } from "@/src/components/design-system/Tabs/Tabs";
-
-import { TraceDetailTabsBarList } from "./TraceDetailTabsBarList";
-
-// jsdom has no layout engine, so every width is 0 and the component would
-// always believe the triggers fit. These two widths stand in for the layout the
-// browser would compute: the space left for the triggers next to the trailing
-// controls, and the width the triggers need.
-let availableWidth = 1000;
-let triggersWidth = 400;
-const resizeCallbacks: ResizeObserverCallback[] = [];
-
-function isAvailableElement(element: HTMLElement) {
- // The measured container is the only element the component puts directly
- // inside the tab list.
- return element.parentElement?.getAttribute("role") === "tablist";
-}
-
-function setAvailableWidth(width: number) {
- availableWidth = width;
- act(() => {
- for (const callback of resizeCallbacks) {
- callback([], {} as ResizeObserver);
- }
- });
-}
-
-function renderTabsBar() {
- return render(
- <Tabs value="preview" onValueChange={vi.fn()}>
- <TraceDetailTabsBarList
- tabs={["preview", "scores"]}
- selectedTab="preview"
- onSelect={vi.fn()}
- triggers={
- <>
- <Tabs.Trigger value="preview" label="Preview" />
- <Tabs.Trigger value="scores" label="Scores" />
- </>
- }
- trailingControls={<div>Trailing</div>}
- />
- </Tabs>,
- );
-}
-
-beforeEach(() => {
- availableWidth = 1000;
- triggersWidth = 400;
- resizeCallbacks.length = 0;
-
- vi.stubGlobal(
- "ResizeObserver",
- class {
- constructor(callback: ResizeObserverCallback) {
- resizeCallbacks.push(callback);
- }
- observe() {}
- unobserve() {}
- disconnect() {}
- },
- );
-
- Object.defineProperty(HTMLElement.prototype, "clientWidth", {
- configurable: true,
- get(this: HTMLElement) {
- return isAvailableElement(this) ? availableWidth : 0;
- },
- });
- Object.defineProperty(HTMLElement.prototype, "scrollWidth", {
- configurable: true,
- get(this: HTMLElement) {
- const parent = this.parentElement;
- return parent && isAvailableElement(parent) ? triggersWidth : 0;
- },
- });
-});
-
-afterEach(() => {
- cleanup();
- vi.unstubAllGlobals();
- Reflect.deleteProperty(HTMLElement.prototype, "clientWidth");
- Reflect.deleteProperty(HTMLElement.prototype, "scrollWidth");
-});
-
-describe("TraceDetailTabsBarList", () => {
- it("shows the tab triggers and no dropdown while they fit", () => {
- renderTabsBar();
-
- expect(screen.getByRole("tab", { name: "Preview" })).toBeTruthy();
- expect(screen.getByRole("tab", { name: "Scores" })).toBeTruthy();
- expect(screen.queryByRole("button", { name: /Detail view/ })).toBeNull();
- });
-
- it("falls back to the dropdown once the triggers no longer fit", () => {
- triggersWidth = 400;
- availableWidth = 200;
- renderTabsBar();
-
- expect(
- screen.getByRole("button", { name: "Detail view: Preview" }),
- ).toBeTruthy();
- // The triggers have to stay mounted behind the dropdown, otherwise their
- // natural width is no longer measurable and the bar can never tell that
- // there is room for them again.
- expect(screen.getByRole("tab", { name: "Preview" })).toBeTruthy();
- expect(screen.getByRole("tab", { name: "Scores" })).toBeTruthy();
- });
-
- it("restores the tab triggers when space becomes available again", () => {
- triggersWidth = 400;
- availableWidth = 200;
- renderTabsBar();
-
- expect(
- screen.getByRole("button", { name: "Detail view: Preview" }),
- ).toBeTruthy();
-
- setAvailableWidth(800);
-
- expect(screen.queryByRole("button", { name: /Detail view/ })).toBeNull();
- expect(screen.getByRole("tab", { name: "Preview" })).toBeTruthy();
- });
-
- it("keeps the triggers when they fit the available width exactly", () => {
- triggersWidth = 400;
- availableWidth = 400;
- renderTabsBar();
-
- expect(screen.queryByRole("button", { name: /Detail view/ })).toBeNull();
- });
-});
diff --git a/web/src/features/traces/components/TraceDetailTabsBarList.tsx b/web/src/features/traces/components/TraceDetailTabsBarList.tsx
index 4bdf340910..ac63f5142b 100644
--- a/web/src/features/traces/components/TraceDetailTabsBarList.tsx
+++ b/web/src/features/traces/components/TraceDetailTabsBarList.tsx
@@ -2,36 +2,33 @@ import { type ReactNode } from "react";
import { Tabs } from "@/src/components/design-system/Tabs/Tabs";
import { Skeleton } from "@/src/components/ui/skeleton";
-import { useFitsAvailableWidth } from "@/src/hooks/useFitsAvailableWidth";
import { cn } from "@/src/utils/tailwind";
-import { TraceDetailTabMenu } from "./TraceDetailTabMenu";
import type { DetailTab } from "../contexts/SelectionContext";
-type TraceDetailTabsBarListProps = {
- tabs: DetailTab[];
- selectedTab: DetailTab;
- onSelect: (tab: DetailTab) => void;
- triggers: ReactNode;
- trailingControls: ReactNode;
+const labels: Record<DetailTab, string> = {
+ preview: "Preview",
+ messages: "Messages",
+ attributes: "Attributes",
+ scores: "Scores",
+ log: "Log View",
};
-const availableClassName =
- "relative flex h-full min-w-0 flex-1 items-center overflow-hidden";
-const triggersClassName = "flex h-full w-max shrink-0 items-center";
+const rowClassName = "flex h-9 shrink-0 items-center border-b";
const LOADING_TAB_WIDTHS = ["w-14", "w-16", "w-12"];
+type TraceDetailTabsBarListProps = {
+ tabs: DetailTab[];
+ logViewDescription: string;
+ trailingControls: ReactNode;
+};
+
/**
- * Tab bar for the trace and observation detail panels. Keeps the tab triggers
- * visible for as long as they fit next to the trailing controls and replaces
- * them with a dropdown once they stop fitting.
- *
- * Which tabs a panel shows depends on the trace, the project role, and the
- * enabled features, so the row is anywhere between two and five tabs wide. The
- * swap therefore follows the measured width of the triggers: a fixed panel
- * width would have to assume the widest tab set and would collapse the narrow
- * ones while there is still room for them.
+ * Tab bar for the trace and observation detail panels. Which tabs a panel
+ * shows depends on the trace, the project role, and the enabled features, so
+ * the row is anywhere between two and five tabs wide; the ones that do not fit
+ * next to the trailing controls move behind an overflow menu.
*/
export function TraceDetailTabsBarList(
props: TraceDetailTabsBarListProps | { isLoading: true },
@@ -40,67 +37,43 @@ export function TraceDetailTabsBarList(
return <LoadedTraceDetailTabsBarList {...props} />;
}
-/** Real triggers with placeholder labels; the view toggle as one block. */
+/** Label bars in trigger-sized slots, no menu; the view toggle as one block. */
function TraceDetailTabsBarListLoading() {
return (
- <Tabs.List variant="underline">
- <div className={availableClassName}>
- <div className={triggersClassName}>
- {LOADING_TAB_WIDTHS.map((width, index) => (
- <Tabs.Trigger key={width} value={`loading-${index}`}>
- <Skeleton className={cn("h-3.5", width)} />
- </Tabs.Trigger>
- ))}
- </div>
+ <div className={rowClassName}>
+ <div className="flex min-w-0 flex-1 items-center overflow-hidden">
+ {LOADING_TAB_WIDTHS.map((width) => (
+ <div key={width} className="px-4">
+ <Skeleton className={cn("h-3.5", width)} />
+ </div>
+ ))}
</div>
- <div className="ml-auto h-fit shrink-0 py-0.5 pr-4 pl-2">
+ <div className="h-fit shrink-0 py-0.5 pr-4 pl-2">
<Skeleton className="h-6 w-32 rounded-md" />
</div>
- </Tabs.List>
+ </div>
);
}
function LoadedTraceDetailTabsBarList({
tabs,
- selectedTab,
- onSelect,
- triggers,
+ logViewDescription,
trailingControls,
}: TraceDetailTabsBarListProps) {
- const { availableRef, contentRef, fits } = useFitsAvailableWidth<
- HTMLDivElement,
- HTMLDivElement
- >();
-
return (
- <Tabs.List variant="underline">
- {/* A zero flex basis makes this the row space left over by the trailing
- controls, so the triggers are compared against the width they can
- actually occupy without that width depending on them in turn. */}
- <div ref={availableRef} className={availableClassName}>
- {/* The triggers stay mounted while the dropdown is shown so their
- natural width remains measurable and the row can come back once
- there is room. Hiding them also takes them out of the tab order.
- Until the first measurement neither presentation shows. */}
- <div
- ref={contentRef}
- className={cn(
- triggersClassName,
- fits !== true && "invisible",
- fits === false && "absolute",
- )}
- >
- {triggers}
- </div>
- {fits === false && (
- <TraceDetailTabMenu
- tabs={tabs}
- selectedTab={selectedTab}
- onSelect={onSelect}
+ <div className={rowClassName}>
+ <Tabs.List variant="underline" overflow="menu" aria-label="Detail views">
+ {tabs.map((tab) => (
+ <Tabs.Trigger
+ key={tab}
+ value={tab}
+ label={labels[tab]}
+ internal={tab === "messages"}
+ tooltip={tab === "log" ? logViewDescription : undefined}
/>
- )}
- </div>
+ ))}
+ </Tabs.List>
{trailingControls}
- </Tabs.List>
+ </div>
);
}
diff --git a/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx b/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
index d34a8f1d73..da8c34912a 100644
--- a/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
+++ b/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
@@ -17,12 +17,6 @@ import {
} from "@/src/features/comments";
import { api } from "@/src/utils/api";
import { useRouter } from "next/router";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/src/components/ui/tooltip";
import { HoverCard } from "@/src/components/design-system/HoverCard/HoverCard";
// Preview tab components
@@ -54,10 +48,7 @@ import { TraceLogView } from "../TraceLogView/TraceLogView";
import { TRACE_VIEW_CONFIG } from "@/src/features/traces/constants/traceViewConfig";
import { ScoresTable } from "@/src/features/scores";
import { getMostRecentCorrection } from "@/src/features/corrections";
-import {
- InternalFeatureBadge,
- useInternalFeaturesEnabled,
-} from "@/src/features/feature-flags";
+import { useInternalFeaturesEnabled } from "@/src/features/feature-flags";
import { useReadPath } from "@/src/features/events";
import { TraceMessagesView } from "../TraceMessagesView/TraceMessagesView";
import { TraceDetailTabsBarList } from "../TraceDetailTabsBarList";
@@ -319,126 +310,110 @@ function LoadedTraceDetailView({
>
{/* Hide the tabs bar when only Preview remains. */}
{showTabsBar && (
- <TooltipProvider>
- <TraceDetailTabsBarList
- selectedTab={selectedTab}
- onSelect={handleTabChange}
- tabs={[
- "preview",
- ...(showMessagesTab ? ["messages" as const] : []),
- ...(showLogViewTab ? ["log" as const] : []),
- ...(showScoresTab ? ["scores" as const] : []),
- ]}
- triggers={
- <>
- <Tabs.Trigger value="preview" label="Preview" />
- {showMessagesTab && (
- <Tabs.Trigger value="messages">
- Messages <InternalFeatureBadge />
- </Tabs.Trigger>
- )}
- {showLogViewTab && (
- <Tabs.Trigger value="log">
- <Tooltip>
- <TooltipTrigger asChild>
- <span>Log View</span>
- </TooltipTrigger>
- <TooltipContent className="text-xs">
- {isLogViewVirtualized
- ? `Shows all ${observations.length} observations with virtualization enabled.`
- : "Shows all observations concatenated. Great for quickly scanning through them."}
- </TooltipContent>
- </Tooltip>
- </Tabs.Trigger>
- )}
- {showScoresTab && (
- <Tabs.Trigger value="scores" label="Scores" />
- )}
- </>
- }
- trailingControls={
- /* View toggle (Formatted/JSON) - show for preview and log tabs when pretty view available */
- /* JSON views are disabled for virtualized log view (large traces) */
- (selectedTab === "log" ||
- (selectedTab === "preview" && isPrettyViewAvailable)) && (
- <>
- <div className="ml-auto h-fit shrink-0 py-0.5 pr-4 pl-2">
- <Tabs
- value={
- selectedTab === "log" && isLogViewVirtualized
- ? "pretty"
- : selectedViewTab
- }
- onValueChange={(value) => {
- // Don't allow JSON views for virtualized log view
- if (
- selectedTab === "log" &&
- isLogViewVirtualized &&
- value === "json"
- ) {
- return;
+ <TraceDetailTabsBarList
+ tabs={[
+ "preview",
+ ...(showMessagesTab ? ["messages" as const] : []),
+ ...(showLogViewTab ? ["log" as const] : []),
+ ...(showScoresTab ? ["scores" as const] : []),
+ ]}
+ logViewDescription={
+ isLogViewVirtualized
+ ? `Shows all ${observations.length} observations with virtualization enabled.`
+ : "Shows all observations concatenated. Great for quickly scanning through them."
+ }
+ trailingControls={
+ /* View toggle for preview and log; invisible on other tabs so the row keeps its width. */
+ <div
+ className={cn(
+ "flex shrink-0 items-center",
+ !(
+ selectedTab === "log" ||
+ (selectedTab === "preview" && isPrettyViewAvailable)
+ ) && "invisible",
+ )}
+ >
+ <div className="h-fit shrink-0 py-0.5 pr-4 pl-2">
+ <Tabs
+ value={
+ selectedTab === "log" && isLogViewVirtualized
+ ? "pretty"
+ : selectedViewTab
+ }
+ onValueChange={(value) => {
+ // Don't allow JSON views for virtualized log view
+ if (
+ selectedTab === "log" &&
+ isLogViewVirtualized &&
+ value === "json"
+ ) {
+ return;
+ }
+ handleViewTabChange(value);
+ }}
+ >
+ <Tabs.List variant="inset" size="sm">
+ <Tabs.Trigger value="pretty" label="Formatted" />
+ {selectedTab === "log" && isLogViewVirtualized ? (
+ <HoverCard
+ openDelay={200}
+ sideOffset={8}
+ placement="bottom-end"
+ content={
+ <div className="w-64 p-3 text-sm">
+ <p className="font-bold">
+ Raw view unavailable
+ </p>
+ <p className="text-muted-foreground mt-1">
+ Disabled for traces with{" "}
+ {
+ TRACE_VIEW_CONFIG.logView
+ .virtualizationThreshold
+ }
+ + observations to maintain performance.
+ </p>
+ </div>
}
- handleViewTabChange(value);
- }}
- >
- <Tabs.List variant="inset" size="sm">
- <Tabs.Trigger value="pretty" label="Formatted" />
- {selectedTab === "log" && isLogViewVirtualized ? (
- <HoverCard
- openDelay={200}
- sideOffset={8}
- placement="bottom-end"
- content={
- <div className="w-64 p-3 text-sm">
- <p className="font-bold">
- Raw view unavailable
- </p>
- <p className="text-muted-foreground mt-1">
- Disabled for traces with{" "}
- {
- TRACE_VIEW_CONFIG.logView
- .virtualizationThreshold
- }
- + observations to maintain performance.
- </p>
- </div>
- }
- >
- {({ getTriggerProps }) => (
- <span tabIndex={0} {...getTriggerProps()}>
- <Tabs.Trigger
- value="json"
- disabled
- label="Raw"
- />
- </span>
- )}
- </HoverCard>
- ) : (
- <Tabs.Trigger value="json" label="Raw" />
+ >
+ {({ getTriggerProps }) => (
+ <span tabIndex={0} {...getTriggerProps()}>
+ <Tabs.Trigger
+ value="json"
+ disabled
+ label="Raw"
+ />
+ </span>
)}
- </Tabs.List>
- </Tabs>
- </div>
- {/* Beta toggle - only show when JSON is selected and not in virtualized log view */}
- {selectedViewTab === "json" &&
- !(selectedTab === "log" && isLogViewVirtualized) && (
- <div className="mr-1 flex items-center gap-1.5">
- <Switch
- size="sm"
- checked={jsonBetaEnabled}
- onCheckedChange={handleBetaToggle}
- />
- <span className="text-muted-foreground text-xs">
- Beta
- </span>
- </div>
+ </HoverCard>
+ ) : (
+ <Tabs.Trigger value="json" label="Raw" />
)}
- </>
- )
- }
- />
- </TooltipProvider>
+ </Tabs.List>
+ </Tabs>
+ </div>
+ {/* Stays mounted so the row keeps its width; the virtualized log has no Raw view. */}
+ {selectedViewTab === "json" && (
+ <div
+ className={cn(
+ "mr-1 flex items-center gap-1.5",
+ selectedTab === "log" &&
+ isLogViewVirtualized &&
+ "invisible",
+ )}
+ >
+ <Switch
+ size="sm"
+ checked={jsonBetaEnabled}
+ onCheckedChange={handleBetaToggle}
+ />
+ <span className="text-muted-foreground text-xs">
+ Beta
+ </span>
+ </div>
+ )}
+ </div>
+ }
+ />
)}
{selectedTab === "messages" && (
diff --git a/web/src/hooks/useFitsAvailableWidth.ts b/web/src/hooks/useFitsAvailableWidth.ts
deleted file mode 100644
index cd7d49309b..0000000000
--- a/web/src/hooks/useFitsAvailableWidth.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { useLayoutEffect, useRef, useState } from "react";
-import { flushSync } from "react-dom";
-
-/**
- * Reports whether the natural width of the element on `contentRef` still fits
- * the width available inside the element on `availableRef`. Lets a caller swap
- * a wide presentation for a compact one at the width where the wide one
- * actually stops fitting, instead of at a fixed breakpoint that has to assume
- * the widest possible content.
- *
- * `fits` is undefined until the first measurement, so callers can hold back
- * both presentations instead of painting the wrong one. Every later change is
- * committed before the browser paints, so the swap never flashes.
- *
- * The measured content has to stay mounted and sized to its content while the
- * compact presentation is shown. Once it unmounts its natural width is no
- * longer observable and the caller can never go back to the wide presentation.
- *
- * The available element must not derive its own width from the measured
- * content, otherwise the two measurements feed back into each other and the
- * result oscillates. A flex item with a zero flex basis satisfies this.
- */
-export function useFitsAvailableWidth<
- TAvailable extends HTMLElement,
- TContent extends HTMLElement,
->() {
- const availableRef = useRef<TAvailable>(null);
- const contentRef = useRef<TContent>(null);
- const [fits, setFits] = useState<boolean>();
-
- useLayoutEffect(() => {
- const available = availableRef.current;
- const content = contentRef.current;
-
- if (!available || !content) {
- return;
- }
-
- // Sub-pixel layout rounds against the content at the exact boundary, so
- // spend a pixel of slack rather than collapsing a row that just fits.
- const measure = () => content.scrollWidth <= available.clientWidth + 1;
-
- setFits(measure());
-
- if (typeof ResizeObserver === "undefined") {
- return;
- }
-
- // Resize callbacks run before paint; a synchronous commit keeps it that way.
- const resizeObserver = new ResizeObserver(() => {
- flushSync(() => setFits(measure()));
- });
- resizeObserver.observe(available);
- resizeObserver.observe(content);
-
- return () => resizeObserver.disconnect();
- }, []);
-
- return { availableRef, contentRef, fits };
-}
diff --git a/web/src/utils/getVisibleRowItemIndices.clienttest.ts b/web/src/utils/getVisibleRowItemIndices.clienttest.ts
new file mode 100644
index 0000000000..5356342f67
--- /dev/null
+++ b/web/src/utils/getVisibleRowItemIndices.clienttest.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it } from "vitest";
+
+import { getVisibleRowItemIndices } from "./getVisibleRowItemIndices";
+
+// E.g. the detail tabs Preview, Messages, Attributes, Scores, Log View.
+const widths = [90, 150, 100, 80, 95];
+const overflowWidth = 32;
+
+describe("getVisibleRowItemIndices", () => {
+ it("tolerates sub-pixel rounding at the boundary, but no more", () => {
+ // The five tabs are 515 wide.
+ expect(
+ getVisibleRowItemIndices({
+ widths,
+ availableWidth: 514.6,
+ overflowWidth,
+ pinnedIndex: 0,
+ }),
+ ).toEqual([0, 1, 2, 3, 4]);
+ expect(
+ getVisibleRowItemIndices({
+ widths,
+ availableWidth: 514.4,
+ overflowWidth,
+ pinnedIndex: 0,
+ }),
+ ).toEqual([0, 1, 2, 3]);
+ });
+
+ it("fills the row in order and leaves room for the overflow trigger", () => {
+ // 90 + 150 + 100 = 340 fits next to the 32px trigger; Scores would not.
+ expect(
+ getVisibleRowItemIndices({
+ widths,
+ availableWidth: 400,
+ overflowWidth,
+ pinnedIndex: 0,
+ }),
+ ).toEqual([0, 1, 2]);
+ });
+
+ it("fills the row in order when no item is pinned", () => {
+ expect(
+ getVisibleRowItemIndices({
+ widths,
+ availableWidth: 400,
+ overflowWidth,
+ pinnedIndex: -1,
+ }),
+ ).toEqual([0, 1, 2]);
+ });
+
+ it("keeps the pinned item visible by displacing the items after the prefix", () => {
+ // Log View (95) takes the slot Attributes (100) would have had.
+ expect(
+ getVisibleRowItemIndices({
+ widths,
+ availableWidth: 400,
+ overflowWidth,
+ pinnedIndex: 4,
+ }),
+ ).toEqual([0, 1, 4]);
+ });
+
+ it("keeps the order: nothing after the pinned item jumps a spilled one", () => {
+ // Messages spills before the pinned Attributes, so Scores stays hidden too.
+ expect(
+ getVisibleRowItemIndices({
+ widths,
+ availableWidth: 320,
+ overflowWidth,
+ pinnedIndex: 2,
+ }),
+ ).toEqual([0, 2]);
+ });
+
+ it("shows only the pinned item when nothing else fits, even itself", () => {
+ expect(
+ getVisibleRowItemIndices({
+ widths,
+ availableWidth: 60,
+ overflowWidth,
+ pinnedIndex: 2,
+ }),
+ ).toEqual([2]);
+ });
+});
diff --git a/web/src/utils/getVisibleRowItemIndices.ts b/web/src/utils/getVisibleRowItemIndices.ts
new file mode 100644
index 0000000000..b98bc83502
--- /dev/null
+++ b/web/src/utils/getVisibleRowItemIndices.ts
@@ -0,0 +1,51 @@
+/**
+ * Picks which items of a single row stay visible when they do not all fit.
+ * Items fill the row in order until the next one would spill, and the rest go
+ * behind an overflow trigger that needs `overflowWidth` of the row itself.
+ *
+ * The pinned item always stays visible: when it would overflow, it takes the
+ * last slot and the items it displaces move behind the trigger instead. Items
+ * keep their order, so once one spills no later item is shown.
+ */
+export function getVisibleRowItemIndices({
+ widths,
+ availableWidth,
+ overflowWidth,
+ pinnedIndex,
+}: {
+ widths: number[];
+ availableWidth: number;
+ overflowWidth: number;
+ pinnedIndex: number;
+}): number[] {
+ // Fractional widths carry rounding noise; the slack is far below a pixel.
+ const limit = availableWidth + 0.5;
+ const total = widths.reduce((sum, width) => sum + width, 0);
+ if (total <= limit) return widths.map((_, index) => index);
+
+ const budget = limit - overflowWidth;
+ const pinned =
+ pinnedIndex >= 0 && pinnedIndex < widths.length ? pinnedIndex : null;
+ const visible: number[] = [];
+ let used = pinned === null ? 0 : widths[pinned];
+
+ /** False once a tab spills. */
+ const take = (from: number, to: number) => {
+ for (let index = from; index < to; index++) {
+ if (used + widths[index] > budget) return false;
+ used += widths[index];
+ visible.push(index);
+ }
+ return true;
+ };
+
+ if (pinned === null) {
+ take(0, widths.length);
+ return visible;
+ }
+
+ const prefixFits = take(0, pinned);
+ visible.push(pinned);
+ if (prefixFits) take(pinned + 1, widths.length);
+ return visible;
+}