Skip to content

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

fix(web): keep the previous trace on screen while the next one loads (#18280)

Trang Nguyend5f366887bac
diff --git a/web/src/components/table/peek.tsx b/web/src/components/table/peek.tsx
index 57a4503566..43448eee87 100644
--- a/web/src/components/table/peek.tsx
+++ b/web/src/components/table/peek.tsx
@@ -93,6 +93,8 @@ type TablePeekViewProps = Pick<
*/
actionsMenu?: React.ReactNode;
hideExpandToggle?: boolean;
+ /** Keep the content mounted across items instead of remounting per item. */
+ preserveContentAcrossItems?: boolean;
// Content
/**
* The content to display in the peek view.
@@ -164,7 +166,14 @@ export const shouldClosePeekAfterDelete = (
): boolean => currentPeekTraceId === deletedTraceId;
function TablePeekViewComponent(props: TablePeekViewProps) {
- const { title, children, footer, tableName, isV4 } = props;
+ const {
+ title,
+ children,
+ footer,
+ tableName,
+ isV4,
+ preserveContentAcrossItems,
+ } = props;
const router = useRouter();
const capture = usePostHogClientCapture();
const itemId = router.query.peek as string | undefined;
@@ -289,7 +298,10 @@ function TablePeekViewComponent(props: TablePeekViewProps) {
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}>
+ <div
+ className="flex-1 overflow-auto"
+ key={preserveContentAcrossItems ? undefined : itemId}
+ >
{children}
</div>
{footer && (
diff --git a/web/src/components/table/peek/peek-experiment-item-detail.tsx b/web/src/components/table/peek/peek-experiment-item-detail.tsx
index 3ebaf2f97b..ba95087d35 100644
--- a/web/src/components/table/peek/peek-experiment-item-detail.tsx
+++ b/web/src/components/table/peek/peek-experiment-item-detail.tsx
@@ -35,6 +35,7 @@ const PeekViewExperimentItemDetail = ({ projectId }: { projectId: string }) => {
return (
<TraceDetailBody
trace={trace.data}
+ isPlaceholderData={trace.isPlaceholderData}
context="peek"
keySuffix={peekId}
truncatedAtObservations={trace.truncatedAtObservations}
diff --git a/web/src/components/table/peek/peek-observation-detail.tsx b/web/src/components/table/peek/peek-observation-detail.tsx
index 8f2a7080b0..992620c3af 100644
--- a/web/src/components/table/peek/peek-observation-detail.tsx
+++ b/web/src/components/table/peek/peek-observation-detail.tsx
@@ -68,14 +68,27 @@ export const TablePeekViewObservationDetail = (
{...props}
title={traceId}
hideExpandToggle
- actions={<TraceDetailActions {...actionProps} />}
- actionsMenu={<TraceDetailActions {...actionProps} layout="menu" />}
+ preserveContentAcrossItems
+ actions={
+ <TraceDetailActions
+ isPlaceholderData={trace.isPlaceholderData}
+ {...actionProps}
+ />
+ }
+ actionsMenu={
+ <TraceDetailActions
+ isPlaceholderData={trace.isPlaceholderData}
+ {...actionProps}
+ layout="menu"
+ />
+ }
>
<TraceDetailBody
trace={trace.data}
context="peek"
keySuffix={peekObservationId}
truncatedAtObservations={trace.truncatedAtObservations}
+ isPlaceholderData={trace.isPlaceholderData}
/>
</TablePeekView>
);
diff --git a/web/src/components/table/peek/peek-trace-detail.tsx b/web/src/components/table/peek/peek-trace-detail.tsx
index dd4d739d9e..74dc8d2139 100644
--- a/web/src/components/table/peek/peek-trace-detail.tsx
+++ b/web/src/components/table/peek/peek-trace-detail.tsx
@@ -60,14 +60,27 @@ export const TablePeekViewTraceDetail = (
{...tablePeekViewProps}
title={traceId}
hideExpandToggle
- actions={<TraceDetailActions {...actionProps} />}
- actionsMenu={<TraceDetailActions {...actionProps} layout="menu" />}
+ preserveContentAcrossItems
+ actions={
+ <TraceDetailActions
+ isPlaceholderData={trace.isPlaceholderData}
+ {...actionProps}
+ />
+ }
+ actionsMenu={
+ <TraceDetailActions
+ isPlaceholderData={trace.isPlaceholderData}
+ {...actionProps}
+ layout="menu"
+ />
+ }
>
<TraceDetailBody
trace={trace.data}
context="peek"
layout={layout}
truncatedAtObservations={trace.truncatedAtObservations}
+ isPlaceholderData={trace.isPlaceholderData}
/>
</TablePeekView>
);
diff --git a/web/src/components/ui/skeleton.tsx b/web/src/components/ui/skeleton.tsx
index 4329ee7d0f..5fb4829b02 100644
--- a/web/src/components/ui/skeleton.tsx
+++ b/web/src/components/ui/skeleton.tsx
@@ -30,4 +30,26 @@ function Skeleton({
);
}
-export { Skeleton };
+/**
+ * Skeletons standing in for one surface. Invisible for the first 150ms so a
+ * fast load never flashes them; static fill, no pulse; inert, so real controls
+ * rendered as part of the placeholder take no input.
+ */
+function SkeletonGroup({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) {
+ return (
+ <div
+ aria-hidden="true"
+ inert
+ className={cn(
+ "animate-appear-delayed opacity-0 [&_[data-slot=skeleton]]:animate-none",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export { Skeleton, SkeletonGroup };
diff --git a/web/src/features/events/hooks/useEventsTraceData.clienttest.tsx b/web/src/features/events/hooks/useEventsTraceData.clienttest.tsx
new file mode 100644
index 0000000000..9c73d36ade
--- /dev/null
+++ b/web/src/features/events/hooks/useEventsTraceData.clienttest.tsx
@@ -0,0 +1,119 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { useEventsTraceData } from "@/src/features/events/hooks/useEventsTraceData";
+
+const { mockByTraceId, mockBatchIO, mockScoresForTrace } = vi.hoisted(() => ({
+ mockByTraceId: vi.fn(),
+ mockBatchIO: vi.fn(),
+ mockScoresForTrace: vi.fn(),
+}));
+
+vi.mock("@/src/utils/api", () => ({
+ sendAsPostOption: {},
+ api: {
+ events: {
+ byTraceId: {
+ useQuery: (input: unknown, options: unknown) =>
+ mockByTraceId(input, options),
+ },
+ batchIO: {
+ useQuery: (input: unknown, options: unknown) =>
+ mockBatchIO(input, options),
+ },
+ scoresForTrace: {
+ useQuery: (input: unknown, options: unknown) =>
+ mockScoresForTrace(input, options),
+ },
+ },
+ },
+}));
+
+const date = new Date("2024-01-01T00:00:00.000Z");
+const observation = (id: string) => ({
+ id,
+ projectId: "p",
+ environment: "default",
+ type: "SPAN",
+ name: id,
+ startTime: date,
+ endTime: null,
+ parentObservationId: null,
+ metadata: "{}",
+ tags: [],
+ traceTags: [],
+ bookmarked: false,
+ public: false,
+ release: null,
+ version: null,
+ userId: null,
+ sessionId: null,
+ createdAt: date,
+ updatedAt: date,
+});
+
+const events = (
+ rootId: string,
+ isPlaceholderData: boolean,
+ maxObservationsPerTrace = 100,
+) => ({
+ data: {
+ observations: [observation(rootId)],
+ cutoffObservationsAfterMaxCount: false,
+ maxObservationsPerTrace,
+ },
+ isLoading: false,
+ error: null,
+ isPlaceholderData,
+});
+
+const scores = (isPlaceholderData: boolean) => ({
+ data: [],
+ isLoading: false,
+ error: null,
+ isPlaceholderData,
+});
+
+const batchIOEnabled = () =>
+ (mockBatchIO.mock.calls.at(-1)?.[1] as { enabled: boolean }).enabled;
+
+describe("useEventsTraceData across a trace switch", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockBatchIO.mockReturnValue({ data: undefined });
+ });
+
+ it("keeps the previous trace whole until observations and scores both carry the next one", () => {
+ mockByTraceId.mockReturnValue(events("old-root", false));
+ mockScoresForTrace.mockReturnValue(scores(false));
+ const { result, rerender } = renderHook(
+ ({ traceId }) => useEventsTraceData({ projectId: "p", traceId }),
+ { initialProps: { traceId: "old" } },
+ );
+ expect(result.current.data?.id).toBe("old");
+ expect(batchIOEnabled()).toBe(true);
+
+ // Switch: both queries serve the previous trace as placeholder.
+ mockByTraceId.mockReturnValue(events("old-root", true));
+ mockScoresForTrace.mockReturnValue(scores(true));
+ rerender({ traceId: "new" });
+ expect(result.current.isPlaceholderData).toBe(true);
+ expect(result.current.data?.id).toBe("old");
+ expect(result.current.data?.observations[0]?.traceId).toBe("old");
+ // No root I/O request pairing the old root with the new trace id.
+ expect(batchIOEnabled()).toBe(false);
+
+ // Observations landed, scores still the previous trace's.
+ mockByTraceId.mockReturnValue(events("new-root", false));
+ rerender({ traceId: "new" });
+ expect(result.current.isPlaceholderData).toBe(true);
+ expect(result.current.data?.id).toBe("old");
+ expect(batchIOEnabled()).toBe(true);
+
+ mockScoresForTrace.mockReturnValue(scores(false));
+ rerender({ traceId: "new" });
+ expect(result.current.isPlaceholderData).toBe(false);
+ expect(result.current.data?.id).toBe("new");
+ expect(result.current.data?.observations[0]?.id).toBe("new-root");
+ });
+});
diff --git a/web/src/features/events/hooks/useEventsTraceData.ts b/web/src/features/events/hooks/useEventsTraceData.ts
index f1bc28344e..09026bf4f9 100644
--- a/web/src/features/events/hooks/useEventsTraceData.ts
+++ b/web/src/features/events/hooks/useEventsTraceData.ts
@@ -1,5 +1,7 @@
import { useMemo } from "react";
+import { keepPreviousData } from "@tanstack/react-query";
import { api, sendAsPostOption } from "@/src/utils/api";
+import { useLatched } from "@/src/hooks/useLatched";
import {
adaptEventsToTraceFormat,
type AdaptedTraceData,
@@ -40,6 +42,8 @@ interface UseEventsTraceDataResult {
* server response — never a client-side copy of the constant.
*/
truncatedAtObservations: number | undefined;
+ /** `data` is the previously loaded trace, kept on screen while this one loads. */
+ isPlaceholderData: boolean;
}
/**
@@ -72,6 +76,7 @@ export function useEventsTraceData(
return failureCount < 3;
},
staleTime: 60 * 1000, // 1 minute
+ placeholderData: keepPreviousData,
},
);
@@ -120,8 +125,14 @@ export function useEventsTraceData(
},
{
...sendAsPostOption,
+ // Not while the observations are the previous trace's: the request would
+ // pair its root with the new trace id.
enabled:
- enabled && !!primaryObservation && !!timeRange && !!eventsQuery.data,
+ enabled &&
+ !!primaryObservation &&
+ !!timeRange &&
+ !!eventsQuery.data &&
+ !eventsQuery.isPlaceholderData,
staleTime: 60 * 1000,
},
);
@@ -132,6 +143,7 @@ export function useEventsTraceData(
{
enabled: enabled && !!traceId,
staleTime: 60 * 1000,
+ placeholderData: keepPreviousData,
},
);
@@ -178,12 +190,26 @@ export function useEventsTraceData(
};
}, [observations, traceId, rootIOQuery.data, scoresQuery.data]);
+ // After a trace switch the two queries resolve independently, so the previous
+ // trace stays whole (observations, I/O, scores) until both carry the new one.
+ const isPlaceholderData =
+ eventsQuery.isPlaceholderData || scoresQuery.isPlaceholderData;
+ const live = useMemo(
+ () => ({
+ data: transformed ?? undefined,
+ truncatedAtObservations: eventsQuery.data?.cutoffObservationsAfterMaxCount
+ ? eventsQuery.data.maxObservationsPerTrace
+ : undefined,
+ }),
+ [transformed, eventsQuery.data],
+ );
+ const shown = useLatched(live, isPlaceholderData);
+
return {
- data: transformed ?? undefined,
+ data: shown.data,
isLoading: eventsQuery.isLoading || scoresQuery.isLoading,
error: eventsQuery.error || scoresQuery.error,
- truncatedAtObservations: eventsQuery.data?.cutoffObservationsAfterMaxCount
- ? eventsQuery.data.maxObservationsPerTrace
- : undefined,
+ truncatedAtObservations: shown.truncatedAtObservations,
+ isPlaceholderData,
};
}
diff --git a/web/src/features/traces/TracePage.tsx b/web/src/features/traces/TracePage.tsx
index b01564cf08..74495e25af 100644
--- a/web/src/features/traces/TracePage.tsx
+++ b/web/src/features/traces/TracePage.tsx
@@ -98,7 +98,9 @@ export function TracePage({
return (
<Page
headerProps={{
- title: trace.data.id,
+ // Route id, not the loaded one: the loaded trace may be the previous
+ // one kept as placeholder.
+ title: traceId,
itemType: "TRACE",
divider: false,
breadcrumb: [
@@ -139,6 +141,7 @@ export function TracePage({
compact
/>
<TraceDetailActions
+ isPlaceholderData={trace.isPlaceholderData}
trace={trace.data}
traceContext={traceContext}
timestamp={timestamp}
@@ -151,6 +154,7 @@ export function TracePage({
// inline icon toolbar. Trace-to-trace nav is desktop-only.
actionButtonsMenu: (
<TraceDetailActions
+ isPlaceholderData={trace.isPlaceholderData}
trace={trace.data}
traceContext={traceContext}
timestamp={timestamp}
@@ -165,6 +169,7 @@ export function TracePage({
trace={trace.data}
context={traceContext}
truncatedAtObservations={trace.truncatedAtObservations}
+ isPlaceholderData={trace.isPlaceholderData}
/>
</div>
</Page>
diff --git a/web/src/features/traces/components/SpanContent.tsx b/web/src/features/traces/components/SpanContent.tsx
index af6514b08a..41150b7268 100644
--- a/web/src/features/traces/components/SpanContent.tsx
+++ b/web/src/features/traces/components/SpanContent.tsx
@@ -22,6 +22,7 @@ import { type TreeNode } from "../types/treeNode";
import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
import { ObservationLevelBadge } from "@/src/features/traces/components/ObservationLevelBadge";
import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";
+import { Skeleton } from "@/src/components/ui/skeleton";
import { cn } from "@/src/utils/tailwind";
import { formatIntervalSeconds } from "@/src/utils/dates";
import { usdFormatter, numberFormatter } from "@/src/utils/numbers";
@@ -42,7 +43,31 @@ interface SpanContentProps {
className?: string;
}
-export function SpanContent({
+const rootClassName =
+ "peer relative flex min-w-0 flex-1 items-start gap-2 rounded-md py-1 pr-2 pl-1 text-left";
+
+export function SpanContent(props: SpanContentProps | { isLoading: true }) {
+ if ("isLoading" in props) return <SpanContentLoading />;
+ return <LoadedSpanContent {...props} />;
+}
+
+/** Name and metrics lines at their text heights, so rows keep their height. */
+function SpanContentLoading() {
+ return (
+ <div className={rootClassName}>
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <div className="flex h-5 items-center">
+ <Skeleton className="h-3.5 w-32" />
+ </div>
+ <div className="flex h-4 items-center">
+ <Skeleton className="h-3 w-10" />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function LoadedSpanContent({
node,
emphasis,
commentCount,
@@ -101,10 +126,7 @@ export function SpanContent({
// No row-level title: it would pop a native tooltip from ANYWHERE in the
// row — stacking on the score chips' own titles and the ScoreTag level
// tooltip. The truncating name span below carries its own title.
- className={cn(
- "peer relative flex min-w-0 flex-1 items-start gap-2 rounded-md py-1 pr-2 pl-1 text-left",
- className,
- )}
+ className={cn(rootClassName, className)}
>
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
{/* Name and badges row */}
diff --git a/web/src/features/traces/components/Trace.tsx b/web/src/features/traces/components/Trace.tsx
index c638363e1f..9b84faf992 100644
--- a/web/src/features/traces/components/Trace.tsx
+++ b/web/src/features/traces/components/Trace.tsx
@@ -35,8 +35,12 @@ import { getCommentDrawerInitialStateFromUrl } from "@/src/features/comments/Com
import { TraceReviewPanelProvider } from "@/src/features/traces/contexts/TraceReviewPanelContext";
import { TraceReviewPanel } from "./TraceReviewPanel";
import { useHasProjectAccess } from "@/src/features/rbac";
+import { staleProps } from "@/src/features/traces/fns/staleProps";
+import { cn } from "@/src/utils/tailwind";
+import { SkeletonGroup } from "@/src/components/ui/skeleton";
export type TraceProps = {
+ isLoading?: false;
observations: Array<ObservationReturnTypeWithMetadata>;
trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {
input: string | null;
@@ -49,6 +53,8 @@ export type TraceProps = {
layout?: "default" | "observation-focused";
/** Observation cap this trace was loaded under, when it hit it. */
truncatedAtObservations?: number;
+ /** This is the previous trace, kept on screen while the next one loads. */
+ isPlaceholderData?: boolean;
};
const DESKTOP_LAYOUTS = {
@@ -81,10 +87,10 @@ type DesktopLayout = (typeof DESKTOP_LAYOUTS)[keyof typeof DESKTOP_LAYOUTS];
* resolved before the tree is built: past the observation cap the selected row is
* missing from the loaded list and has to be fetched and merged in.
*/
-export function Trace({ context, layout = "default", ...props }: TraceProps) {
- const traceContext = context ?? "fullscreen";
+export function Trace(props: TraceProps | TraceLoadingProps) {
+ const traceContext = props.context ?? "fullscreen";
const desktopLayoutKey =
- traceContext === "peek" && layout === "observation-focused"
+ traceContext === "peek" && props.layout === "observation-focused"
? "peek-observation-focused"
: traceContext;
const desktopLayout = DESKTOP_LAYOUTS[desktopLayoutKey];
@@ -92,12 +98,21 @@ export function Trace({ context, layout = "default", ...props }: TraceProps) {
return (
<ViewPreferencesProvider traceContext={traceContext}>
<SelectionProvider>
- <TraceWithSelection {...props} desktopLayout={desktopLayout} />
+ {props.isLoading === true ? (
+ <TraceLoading desktopLayout={desktopLayout} />
+ ) : (
+ <TraceWithSelection {...props} desktopLayout={desktopLayout} />
+ )}
</SelectionProvider>
</ViewPreferencesProvider>
);
}
+/** Layout only, before the trace arrives; each panel draws its own placeholder. */
+type TraceLoadingProps = Pick<TraceProps, "context" | "layout"> & {
+ isLoading: true;
+};
+
function TraceWithSelection({
trace,
observations: loadedObservations,
@@ -105,6 +120,7 @@ function TraceWithSelection({
corrections,
projectId,
truncatedAtObservations,
+ isPlaceholderData = false,
desktopLayout,
}: Omit<TraceProps, "context"> & {
desktopLayout: DesktopLayout;
@@ -133,6 +149,7 @@ function TraceWithSelection({
traceId: trace.id,
projectId,
observations: loadedObservations,
+ enabled: !isPlaceholderData,
});
const detachedObservation =
selected.kind === "observation" && selected.isOutsideLoadedList
@@ -168,6 +185,7 @@ function TraceWithSelection({
detachedObservationId={detachedObservation?.id ?? null}
detachedObservationIsMisplaced={detachedIsMisplaced}
truncatedAtObservations={truncatedAtObservations}
+ isPlaceholderData={isPlaceholderData}
>
<TraceGraphDataProvider
projectId={trace.projectId}
@@ -199,6 +217,8 @@ function TraceWithSelection({
function TraceContent({ desktopLayout }: { desktopLayout: DesktopLayout }) {
const isMobile = useIsMobile();
const { isGraphViewAvailable } = useTraceGraphData();
+ const { isPlaceholderData } = useTraceData();
+ const stale = staleProps(isPlaceholderData);
const panels = isMobile ? (
<MobileTraceContent shouldShowGraph={isGraphViewAvailable} />
@@ -207,13 +227,42 @@ function TraceContent({ desktopLayout }: { desktopLayout: DesktopLayout }) {
);
return (
- <div className="flex h-full w-full min-w-0 flex-col overflow-hidden">
+ <div
+ inert={stale.inert}
+ className={cn(traceContentClassName, stale.className)}
+ >
<TraceHeader />
<div className="min-h-0 flex-1">{panels}</div>
</div>
);
}
+const traceContentClassName =
+ "flex h-full w-full min-w-0 flex-col overflow-hidden";
+
+function TraceLoading({ desktopLayout }: { desktopLayout: DesktopLayout }) {
+ const isMobile = useIsMobile();
+ return (
+ <SkeletonGroup className={traceContentClassName}>
+ <TraceHeader isLoading />
+ <div className="min-h-0 flex-1">
+ {isMobile ? (
+ <TraceLayoutMobile
+ isLoading
+ showGraph={false}
+ tree={<TraceTree isLoading />}
+ timeline={<TraceTree isLoading />}
+ graph={null}
+ info={<TracePanelDetail isLoading />}
+ />
+ ) : (
+ <DesktopTraceWorkspace desktopLayout={desktopLayout} isLoading />
+ )}
+ </div>
+ </SkeletonGroup>
+ );
+}
+
/**
* DesktopTraceContent - Desktop layout composition
*
@@ -294,10 +343,12 @@ function DesktopTraceWorkspace({
desktopLayout,
reviewOpen = false,
reviewPanel,
+ isLoading = false,
}: {
desktopLayout: DesktopLayout;
reviewOpen?: boolean;
reviewPanel?: ReactNode;
+ isLoading?: boolean;
}) {
return (
<div className="h-full" data-trace-review-open={reviewOpen || undefined}>
@@ -308,13 +359,13 @@ function DesktopTraceWorkspace({
reviewPanel={reviewPanel}
>
<TraceLayoutDesktop.NavigationPanel>
- <TracePanelNavigationLayoutDesktop>
- <TracePanelNavigation />
+ <TracePanelNavigationLayoutDesktop isLoading={isLoading}>
+ {isLoading ? <TraceTree isLoading /> : <TracePanelNavigation />}
</TracePanelNavigationLayoutDesktop>
</TraceLayoutDesktop.NavigationPanel>
<TraceLayoutDesktop.ResizeHandle />
<TraceLayoutDesktop.DetailPanel>
- <TracePanelDetail />
+ <TracePanelDetail isLoading={isLoading} />
</TraceLayoutDesktop.DetailPanel>
</TraceLayoutDesktop>
</div>
diff --git a/web/src/features/traces/components/TraceDetailActions.tsx b/web/src/features/traces/components/TraceDetailActions.tsx
index 42baf7dc36..04d8096801 100644
--- a/web/src/features/traces/components/TraceDetailActions.tsx
+++ b/web/src/features/traces/components/TraceDetailActions.tsx
@@ -12,8 +12,10 @@ import {
import { useShareMenuItems } from "@/src/components/useShareMenuItems";
import { ConnectedDetailHeaderActionsMenuController } from "@/src/features/traces/components/DetailHeaderActionsMenuController";
import { DeleteTraceDialogController } from "@/src/features/traces/components/DeleteTraceDialogController";
+import { staleProps } from "@/src/features/traces/fns/staleProps";
import { useDownloadTraceAsJson } from "@/src/features/traces/hooks/useDownloadTraceAsJson";
import { type useTraceDetailData } from "@/src/features/traces/hooks/useTraceDetailData";
+import { cn } from "@/src/utils/tailwind";
type TraceDetailData = NonNullable<
ReturnType<typeof useTraceDetailData>["data"]
@@ -30,6 +32,8 @@ type TraceDetailActionsProps = {
deleteRedirectUrl?: string;
onAfterDelete?: (deletedTraceId: string) => void;
layout?: TraceDetailActionsLayout;
+ /** `trace` is the previous trace, kept while the next one loads. */
+ isPlaceholderData?: boolean;
};
/**
@@ -50,10 +54,22 @@ type TraceDetailActionsProps = {
export function TraceDetailActions({
trace,
layout = "toolbar",
+ isPlaceholderData = false,
...props
}: TraceDetailActionsProps) {
if (!trace) return <DisabledTraceDetailActions layout={layout} />;
- return <LoadedTraceDetailActions trace={trace} layout={layout} {...props} />;
+ const { key, ...stale } = staleProps(isPlaceholderData, {
+ remountOnStale: true,
+ });
+ return (
+ <LoadedTraceDetailActions
+ key={key}
+ trace={trace}
+ layout={layout}
+ stale={stale}
+ {...props}
+ />
+ );
}
function DisabledTraceDetailActions({
@@ -95,9 +111,11 @@ function LoadedTraceDetailActions({
deleteRedirectUrl,
onAfterDelete,
layout,
-}: Omit<TraceDetailActionsProps, "trace" | "layout"> & {
+ stale,
+}: Omit<TraceDetailActionsProps, "trace" | "layout" | "isPlaceholderData"> & {
trace: TraceDetailData;
layout: TraceDetailActionsLayout;
+ stale: Omit<ReturnType<typeof staleProps>, "key">;
}) {
const shareItems = useShareMenuItems({
kind: "trace",
@@ -154,7 +172,13 @@ function LoadedTraceDetailActions({
if (layout === "menu") {
return (
- <div className="flex w-full flex-col gap-0.5">
+ <div
+ inert={stale.inert}
+ className={cn(
+ "flex w-full flex-col gap-0.5",
+ stale.className,
+ )}
+ >
<HeaderActionMenuRow
label="Download JSON"
icon={downloadIcon}
@@ -167,7 +191,13 @@ function LoadedTraceDetailActions({
}
return (
- <div className="flex flex-row items-center gap-1">
+ <div
+ inert={stale.inert}
+ className={cn(
+ "flex flex-row items-center gap-1",
+ stale.className,
+ )}
+ >
<HeaderActionButton
label="Download JSON"
icon={downloadIcon}
diff --git a/web/src/features/traces/components/TraceDetailBody.tsx b/web/src/features/traces/components/TraceDetailBody.tsx
index c3558ae618..31c39d5700 100644
--- a/web/src/features/traces/components/TraceDetailBody.tsx
+++ b/web/src/features/traces/components/TraceDetailBody.tsx
@@ -1,6 +1,6 @@
import { Trace, type TraceProps } from "@/src/features/traces/components/Trace";
-import { Skeleton } from "@/src/components/ui/skeleton";
import { type useTraceDetailData } from "@/src/features/traces/hooks/useTraceDetailData";
+import { useLatched } from "@/src/hooks/useLatched";
type TraceDetailData = NonNullable<
ReturnType<typeof useTraceDetailData>["data"]
@@ -8,36 +8,48 @@ type TraceDetailData = NonNullable<
/**
* 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).
+ * page so the invocation isn't copy-pasted. A cold load renders `<Trace>` in
+ * its loading state; while `isPlaceholderData`, `<Trace>` keeps the previous
+ * trace on screen dimmed and inert. `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,
truncatedAtObservations,
+ isPlaceholderData = false,
layout,
}: {
trace: TraceDetailData | undefined;
- context: "peek" | "fullscreen" | "annotation";
+ context: NonNullable<TraceProps["context"]>;
keySuffix?: string;
layout?: TraceProps["layout"];
/** Observation cap this trace was loaded under, when it hit it. */
truncatedAtObservations?: number;
+ /** `trace` is the previous trace, kept while the next one loads. */
+ isPlaceholderData?: boolean;
}) {
- if (!trace) return <Skeleton className="h-full w-full rounded-none" />;
+ // Held while placeholder: `keySuffix` already names the next item, and a key
+ // mixing it with the previous trace's id would remount twice per switch.
+ const traceKey = useLatched(
+ keySuffix ? `${trace?.id}-${keySuffix}` : trace?.id,
+ isPlaceholderData,
+ );
+ if (!trace) return <Trace isLoading context={context} layout={layout} />;
return (
<Trace
- key={keySuffix ? `${trace.id}-${keySuffix}` : trace.id}
+ key={traceKey}
trace={trace}
scores={trace.scores}
corrections={trace.corrections}
- projectId={trace.projectId}
observations={trace.observations}
+ projectId={trace.projectId}
context={context}
layout={layout}
truncatedAtObservations={truncatedAtObservations}
+ isPlaceholderData={isPlaceholderData}
/>
);
}
diff --git a/web/src/features/traces/components/TraceDetailTabsBarList.tsx b/web/src/features/traces/components/TraceDetailTabsBarList.tsx
index 4321baf518..4bdf340910 100644
--- a/web/src/features/traces/components/TraceDetailTabsBarList.tsx
+++ b/web/src/features/traces/components/TraceDetailTabsBarList.tsx
@@ -1,12 +1,27 @@
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 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 LOADING_TAB_WIDTHS = ["w-14", "w-16", "w-12"];
+
/**
* 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
@@ -18,19 +33,40 @@ import type { DetailTab } from "../contexts/SelectionContext";
* width would have to assume the widest tab set and would collapse the narrow
* ones while there is still room for them.
*/
-export function TraceDetailTabsBarList({
+export function TraceDetailTabsBarList(
+ props: TraceDetailTabsBarListProps | { isLoading: true },
+) {
+ if ("isLoading" in props) return <TraceDetailTabsBarListLoading />;
+ return <LoadedTraceDetailTabsBarList {...props} />;
+}
+
+/** Real triggers with placeholder labels; 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>
+ <div className="ml-auto h-fit shrink-0 py-0.5 pr-4 pl-2">
+ <Skeleton className="h-6 w-32 rounded-md" />
+ </div>
+ </Tabs.List>
+ );
+}
+
+function LoadedTraceDetailTabsBarList({
tabs,
selectedTab,
onSelect,
triggers,
trailingControls,
-}: {
- tabs: DetailTab[];
- selectedTab: DetailTab;
- onSelect: (tab: DetailTab) => void;
- triggers: ReactNode;
- trailingControls: ReactNode;
-}) {
+}: TraceDetailTabsBarListProps) {
const { availableRef, contentRef, fits } = useFitsAvailableWidth<
HTMLDivElement,
HTMLDivElement
@@ -41,10 +77,7 @@ export function TraceDetailTabsBarList({
{/* 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="relative flex h-full min-w-0 flex-1 items-center overflow-hidden"
- >
+ <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.
@@ -52,7 +85,7 @@ export function TraceDetailTabsBarList({
<div
ref={contentRef}
className={cn(
- "flex h-full w-max shrink-0 items-center",
+ triggersClassName,
fits !== true && "invisible",
fits === false && "absolute",
)}
diff --git a/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx b/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
index 45fdc0977a..ecaadde4f4 100644
--- a/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
+++ b/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
@@ -7,6 +7,7 @@ import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers
import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
import { Tabs } from "@/src/components/design-system/Tabs/Tabs";
import { Switch } from "@/src/components/design-system/Switch/Switch";
+import { Skeleton } from "@/src/components/ui/skeleton";
import { useCallback, useMemo, useState } from "react";
import { cn } from "@/src/utils/tailwind";
import {
@@ -63,6 +64,7 @@ import { TraceMessagesView } from "../TraceMessagesView/TraceMessagesView";
import { TraceDetailTabsBarList } from "../TraceDetailTabsBarList";
export interface TraceDetailViewProps {
+ isLoading?: false;
trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {
latency?: number;
input: string | null;
@@ -74,7 +76,42 @@ export interface TraceDetailViewProps {
projectId: string;
}
-export function TraceDetailView({
+const rootClassName = "flex h-full flex-col overflow-hidden";
+
+const LOADING_SECTIONS = ["input", "output", "metadata"];
+
+export function TraceDetailView(
+ props: TraceDetailViewProps | { isLoading: true },
+) {
+ if (props.isLoading === true) return <TraceDetailViewLoading />;
+ return <LoadedTraceDetailView {...props} />;
+}
+
+/** Header, tab bar and preview sections as placeholders in their own slots. */
+function TraceDetailViewLoading() {
+ return (
+ <div className={rootClassName}>
+ <TraceDetailViewHeader isLoading />
+ <Tabs value="none" layout="fill">
+ <TraceDetailTabsBarList isLoading />
+ <Tabs.Content value="none" layout="fill">
+ <div className="flex min-h-0 w-full flex-1 flex-col gap-6 overflow-auto px-4 pt-4 pb-4">
+ {LOADING_SECTIONS.map((section) => (
+ <div key={section} className="space-y-2">
+ <Skeleton className="h-4 w-20" />
+ <Skeleton className="h-3 w-full" />
+ <Skeleton className="h-3 w-11/12" />
+ <Skeleton className="h-3 w-2/3" />
+ </div>
+ ))}
+ </div>
+ </Tabs.Content>
+ </Tabs>
+ </div>
+ );
+}
+
+function LoadedTraceDetailView({
trace,
observations,
scores,
@@ -256,7 +293,7 @@ export function TraceDetailView({
count={comments.get(trace.id)}
>
{({ disabled, openDrawer }) => (
- <div className="flex h-full flex-col overflow-hidden">
+ <div className={rootClassName}>
{/* Header section (extracted component) */}
<TraceDetailViewHeader
trace={trace}
diff --git a/web/src/features/traces/components/TraceDetailView/components/TraceDetailViewHeader.tsx b/web/src/features/traces/components/TraceDetailView/components/TraceDetailViewHeader.tsx
index f1349c1410..db97921b88 100644
--- a/web/src/features/traces/components/TraceDetailView/components/TraceDetailViewHeader.tsx
+++ b/web/src/features/traces/components/TraceDetailView/components/TraceDetailViewHeader.tsx
@@ -23,7 +23,9 @@ import {
import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
import { EntityTitle } from "@/src/components/EntityTitle";
import { DetailViewHeaderShell } from "@/src/features/traces/components/DetailViewHeaderShell";
-import { Badge } from "@/src/components/design-system/Badge/Badge";
+import { Badge, BadgeShell } from "@/src/components/design-system/Badge/Badge";
+import { Skeleton } from "@/src/components/ui/skeleton";
+import { cn } from "@/src/utils/tailwind";
import { ConnectedDetailHeaderActionsMenuController } from "@/src/features/traces/components/DetailHeaderActionsMenuController";
import { AnnotateDrawerController } from "@/src/features/scores";
import { ActionButtonCountBadge } from "@/src/components/ui/action-button-count-badge";
@@ -52,6 +54,7 @@ import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/Dropdo
import { buildLocalIsoDatePresentation } from "@/src/utils/dates";
export interface TraceDetailViewHeaderProps {
+ isLoading?: false;
trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {
latency?: number;
input: string | null;
@@ -67,7 +70,53 @@ export interface TraceDetailViewHeaderProps {
};
}
-export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({
+const titleRowClassName =
+ "grid w-full grid-cols-1 items-center gap-2 @md:grid-cols-[minmax(0,1fr)_auto]";
+const titleClassName = "flex w-full min-w-0 flex-row items-center gap-2";
+const actionsClassName =
+ "flex flex-wrap content-start items-center justify-start gap-1 @md:justify-end";
+
+const LOADING_BADGE_WIDTHS = ["w-36", "w-24", "w-32", "w-32"];
+
+export const TraceDetailViewHeader = memo(function TraceDetailViewHeader(
+ props: TraceDetailViewHeaderProps | { isLoading: true },
+) {
+ if (props.isLoading === true) return <TraceDetailViewHeaderLoading />;
+ return <LoadedTraceDetailViewHeader {...props} />;
+});
+
+function TraceDetailViewHeaderLoading() {
+ const isMobile = useIsMobile();
+ return (
+ <DetailViewHeaderShell>
+ <div className={titleRowClassName}>
+ <div className={cn(titleClassName, "min-h-7")}>
+ <Skeleton className="size-6 rounded-sm" />
+ <Skeleton className="h-4 w-48" />
+ {isMobile && <Skeleton className="ml-auto size-8 rounded-md" />}
+ </div>
+ {!isMobile && (
+ <div className={actionsClassName}>
+ <Skeleton className="h-6 w-20 rounded-md" />
+ <Skeleton className="h-6 w-24 rounded-md" />
+ <Skeleton className="h-6 w-24 rounded-md" />
+ </div>
+ )}
+ </div>
+ <div className="flex flex-col gap-2">
+ <CollapsibleBadgeRow>
+ {LOADING_BADGE_WIDTHS.map((width, index) => (
+ <BadgeShell key={index} color="ghost">
+ <Skeleton className={cn("h-3", width)} />
+ </BadgeShell>
+ ))}
+ </CollapsibleBadgeRow>
+ </div>
+ </DetailViewHeaderShell>
+ );
+}
+
+function LoadedTraceDetailViewHeader({
trace,
parsedMetadata,
projectId,
@@ -106,8 +155,8 @@ export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({
return (
<DetailViewHeaderShell>
{/* Title row with actions */}
- <div className="grid w-full grid-cols-1 items-center gap-2 @md:grid-cols-[minmax(0,1fr)_auto]">
- <div className="flex w-full min-w-0 flex-row items-center gap-2">
+ <div className={titleRowClassName}>
+ <div className={titleClassName}>
<EntityTitle as="span" type="TRACE" title={trace.name || trace.id} />
{!isMobile && (
<ConnectedDetailHeaderActionsMenuController
@@ -243,7 +292,7 @@ export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({
</div>
{/* Action buttons (desktop inline cluster) */}
{!isMobile && (
- <div className="flex flex-wrap content-start items-center justify-start gap-1 @md:justify-end">
+ <div className={actionsClassName}>
<ConnectedTraceObservationAddToDropdownMenuController
analyticsData={{ source: "TraceDetail", isV4 }}
projectId={projectId}
@@ -344,4 +393,4 @@ export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({
</div>
</DetailViewHeaderShell>
);
-});
+}
diff --git a/web/src/features/traces/components/TraceHeader.tsx b/web/src/features/traces/components/TraceHeader.tsx
index 79754e7add..97a9c50424 100644
--- a/web/src/features/traces/components/TraceHeader.tsx
+++ b/web/src/features/traces/components/TraceHeader.tsx
@@ -1,10 +1,12 @@
import { OverflowCountBadge } from "@/src/components/OverflowCountBadge";
/** Trace totals, session/user links and tags, above the panels. */
-import { useMemo, useState } from "react";
+import { useMemo, useState, type ReactNode } from "react";
import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
+import { BadgeShell } from "@/src/components/design-system/Badge/Badge";
import { Button } from "@/src/components/ui/button";
+import { Skeleton } from "@/src/components/ui/skeleton";
import { TagButton } from "@/src/features/tag";
import {
SessionBadge,
@@ -24,9 +26,46 @@ import { cn } from "@/src/utils/tailwind";
const MAX_VISIBLE_TAGS = 3;
-export function TraceHeader() {
- const { trace, observations, mergedScores } = useTraceData();
+const LOADING_BADGE_WIDTHS = ["w-16", "w-14", "w-24", "w-20", "w-40"];
+
+export function TraceHeader({ isLoading = false }: { isLoading?: boolean }) {
+ if (isLoading) return <TraceHeaderLoading />;
+ return <LoadedTraceHeader />;
+}
+
+function TraceHeaderFrame({ children }: { children: ReactNode }) {
const { traceContext } = useViewPreferences();
+ return (
+ <div
+ className={cn(
+ "shrink-0 border-b",
+ traceContext === "fullscreen" && "px-4 pt-1 pb-1.5",
+ // Peek's title bar already pads above, so no top padding here.
+ traceContext === "peek" && "pt-0 pr-2 pb-2 pl-4",
+ traceContext !== "fullscreen" && traceContext !== "peek" && "px-2 py-2",
+ )}
+ >
+ {children}
+ </div>
+ );
+}
+
+function TraceHeaderLoading() {
+ return (
+ <TraceHeaderFrame>
+ <CollapsibleBadgeRow>
+ {LOADING_BADGE_WIDTHS.map((width) => (
+ <BadgeShell key={width} color="ghost">
+ <Skeleton className={cn("h-3", width)} />
+ </BadgeShell>
+ ))}
+ </CollapsibleBadgeRow>
+ </TraceHeaderFrame>
+ );
+}
+
+function LoadedTraceHeader() {
+ const { trace, observations, mergedScores } = useTraceData();
const [showAllTags, setShowAllTags] = useState(false);
const aggregatedMetrics = useMemo(
@@ -45,15 +84,7 @@ export function TraceHeader() {
const hiddenTagCount = trace.tags.length - visibleTags.length;
return (
- <div
- className={cn(
- "shrink-0 border-b",
- traceContext === "fullscreen" && "px-4 pt-1 pb-1.5",
- // Peek's title bar already pads above, so no top padding here.
- traceContext === "peek" && "pt-0 pr-2 pb-2 pl-4",
- traceContext !== "fullscreen" && traceContext !== "peek" && "px-2 py-2",
- )}
- >
+ <TraceHeaderFrame>
<CollapsibleBadgeRow>
{trace.latency != null && (
<LatencyBadge latencySeconds={trace.latency} />
@@ -112,6 +143,6 @@ export function TraceHeader() {
</div>
)}
</CollapsibleBadgeRow>
- </div>
+ </TraceHeaderFrame>
);
}
diff --git a/web/src/features/traces/components/TraceLayoutMobile.tsx b/web/src/features/traces/components/TraceLayoutMobile.tsx
index b215764fca..977fba7ba9 100644
--- a/web/src/features/traces/components/TraceLayoutMobile.tsx
+++ b/web/src/features/traces/components/TraceLayoutMobile.tsx
@@ -67,6 +67,7 @@ export function TraceLayoutMobile({
graph,
info,
showGraph,
+ isLoading = false,
}: {
tree: ReactNode;
timeline: ReactNode;
@@ -74,6 +75,8 @@ export function TraceLayoutMobile({
info: ReactNode;
/** Reused from TraceContent; hides the Graph tab when the trace has no graph. */
showGraph: boolean;
+ /** Skips the data-bound notice while the panels show placeholders. */
+ isLoading?: boolean;
}) {
const [tabParam, setTabParam] = useQueryParam("mobileTab", StringParam);
const { selectedNodeId } = useSelection();
@@ -131,7 +134,7 @@ export function TraceLayoutMobile({
{/* Above the tab bodies, not inside one: the truncation applies to every
tab, and the navigators own their own scroll containers. */}
- <TraceTruncationNotice />
+ {!isLoading && <TraceTruncationNotice />}
{/* Inactive tabs unmount (Radix default). On memory-constrained mobile
that keeps a single heavy subtree live at a time (two virtualizers,
diff --git a/web/src/features/traces/components/TracePanelDetail.tsx b/web/src/features/traces/components/TracePanelDetail.tsx
index 06bdf2e39c..dca9d98441 100644
--- a/web/src/features/traces/components/TracePanelDetail.tsx
+++ b/web/src/features/traces/components/TracePanelDetail.tsx
@@ -19,7 +19,7 @@
import { useSelection } from "@/src/features/traces/contexts/SelectionContext";
import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";
import { useSelectedObservation } from "@/src/features/traces/hooks/useSelectedObservation";
-import { Skeleton } from "@/src/components/ui/skeleton";
+import { SkeletonGroup } from "@/src/components/ui/skeleton";
import { TraceDetailView } from "./TraceDetailView/TraceDetailView";
import { ConnectedObservationDetailView } from "./ObservationDetailView/ConnectedObservationDetailView";
import { useMemo } from "react";
@@ -33,13 +33,26 @@ function PanelMessage({ title, body }: { title: string; body: string }) {
);
}
-export function TracePanelDetail() {
+export function TracePanelDetail({
+ isLoading = false,
+}: {
+ isLoading?: boolean;
+}) {
+ return (
+ <div className="bg-surface-sunken h-full w-full overflow-y-auto [--surface-context:hsl(var(--surface-sunken))]">
+ {isLoading ? <TraceDetailView isLoading /> : <TracePanelDetailContent />}
+ </div>
+ );
+}
+
+function TracePanelDetailContent() {
const { selectedNodeId } = useSelection();
const {
trace,
observations,
serverScores: scores,
corrections,
+ isPlaceholderData,
} = useTraceData();
// Resolved from the selected id, not from the tree: the observation list is
@@ -50,10 +63,11 @@ export function TracePanelDetail() {
traceId: trace.id,
projectId: trace.projectId,
observations,
+ enabled: !isPlaceholderData,
});
// Memoize to prevent recreation when deps haven't changed
- const content = useMemo(() => {
+ return useMemo(() => {
switch (selected.kind) {
case "observation":
return (
@@ -64,7 +78,12 @@ export function TracePanelDetail() {
/>
);
case "loading":
- return <Skeleton className="h-full w-full rounded-none" />;
+ // The observation view shares this shell, so nothing moves when it lands.
+ return (
+ <SkeletonGroup className="h-full w-full">
+ <TraceDetailView isLoading />
+ </SkeletonGroup>
+ );
case "not-found":
return (
<PanelMessage
@@ -91,10 +110,4 @@ export function TracePanelDetail() {
);
}
}, [selected, trace, observations, scores, corrections]);
-
- return (
- <div className="bg-surface-sunken h-full w-full overflow-y-auto [--surface-context:hsl(var(--surface-sunken))]">
- {content}
- </div>
- );
}
diff --git a/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx b/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx
index bfb1f734a0..59ac8eabab 100644
--- a/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx
+++ b/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx
@@ -23,6 +23,7 @@ import {
} from "@/src/components/ui/tooltip";
import { Command, CommandInput } from "@/src/components/ui/command";
import { Button } from "@/src/components/ui/button";
+import { Skeleton } from "@/src/components/ui/skeleton";
import { Tabs } from "@/src/components/design-system/Tabs/Tabs";
import {
ChevronDown,
@@ -58,15 +59,56 @@ interface TracePanelNavigationHeaderProps {
onTogglePanel: () => void;
}
-export function TracePanelNavigationHeader(
- props: TracePanelNavigationHeaderProps,
-) {
+export function TracePanelNavigationHeader({
+ isLoading = false,
+ ...props
+}: TracePanelNavigationHeaderProps & { isLoading?: boolean }) {
if (props.isPanelCollapsed) {
return <TracePanelNavigationHeaderCollapsed {...props} />;
}
+ if (isLoading) {
+ return <TracePanelNavigationHeaderLoading {...props} />;
+ }
return <TracePanelNavigationHeaderExpanded {...props} />;
}
+const frameClassName =
+ "h-auto shrink-0 overflow-hidden rounded-none border-b bg-transparent";
+const gridClassName =
+ "grid min-h-8 grid-cols-[auto_minmax(0,1fr)_auto] items-center py-1 pr-3 pl-1 @max-[299px]/navheader:min-h-0 @max-[299px]/navheader:gap-y-1 @max-[299px]/navheader:pt-1 @max-[299px]/navheader:pb-1.5";
+const toggleSlotClassName =
+ "col-start-1 row-start-1 flex flex-row items-center p-0.5";
+const toolsSlotClassName =
+ "col-start-3 row-start-1 flex shrink-0 flex-row items-center gap-0.5";
+
+/** Same frame and toggle; search, tools and the view switch as placeholders. */
+function TracePanelNavigationHeaderLoading({
+ isPanelCollapsed,
+ onTogglePanel,
+}: TracePanelNavigationHeaderProps) {
+ return (
+ <Command className={frameClassName}>
+ <div className="@container/navheader">
+ <div className={gridClassName}>
+ <div className={toggleSlotClassName}>
+ <TracePanelNavigationButton
+ isPanelCollapsed={isPanelCollapsed}
+ onTogglePanel={onTogglePanel}
+ />
+ </div>
+ <div className="col-start-2 row-start-1 flex h-7 min-w-0 items-center px-2">
+ <Skeleton className="h-3 w-16" />
+ </div>
+ <div className={toolsSlotClassName}>
+ <Skeleton className="size-7 rounded-md" />
+ <Skeleton className="ml-2 h-7 w-56 rounded-md" />
+ </div>
+ </div>
+ </div>
+ </Command>
+ );
+}
+
function TracePanelNavigationHeaderCollapsed({
isPanelCollapsed,
onTogglePanel,
@@ -206,20 +248,17 @@ function TracePanelNavigationHeaderExpanded({
);
return (
- <Command className="h-auto shrink-0 overflow-hidden rounded-none border-b bg-transparent">
+ <Command className={frameClassName}>
{/* Container queries keep the primary view switch visible for as long as
it fits. Search moves below the controls before that switch collapses,
and remains the same input across every layout. */}
<div ref={headerContainerRef} className="@container/navheader">
- <div className="grid min-h-8 grid-cols-[auto_minmax(0,1fr)_auto] items-center py-1 pr-3 pl-1 @max-[299px]/navheader:min-h-0 @max-[299px]/navheader:gap-y-1 @max-[299px]/navheader:pt-1 @max-[299px]/navheader:pb-1.5">
+ <div className={gridClassName}>
{/* Panel Toggle Button; special p-0.5 offset to pixel align with closed
version. Hidden while the detail panel is closed (nothing useful to
collapse the full-width tree/timeline into). */}
{!isDetailPanelCollapsed && (
- <div
- key="toggle"
- className="col-start-1 row-start-1 flex flex-row items-center p-0.5"
- >
+ <div key="toggle" className={toggleSlotClassName}>
<TracePanelNavigationButton
isPanelCollapsed={isPanelCollapsed}
onTogglePanel={onTogglePanel}
@@ -230,10 +269,7 @@ function TracePanelNavigationHeaderExpanded({
The keyed element is moved rather than duplicated, preserving its
value and focus across panel resizing. */}
{!isSearchWrapped ? searchControl : null}
- <div
- key="tools"
- className="col-start-3 row-start-1 flex shrink-0 flex-row items-center gap-0.5"
- >
+ <div key="tools" className={toolsSlotClassName}>
{/* Minor tools — inline when the panel is wide enough. */}
<div className="hidden flex-row items-center gap-0.5 @min-[510px]/navheader:flex">
<Button
diff --git a/web/src/features/traces/components/TracePanelNavigationLayoutDesktop/TracePanelNavigationLayoutDesktop.tsx b/web/src/features/traces/components/TracePanelNavigationLayoutDesktop/TracePanelNavigationLayoutDesktop.tsx
index dc9eb935cd..f98ccb60c5 100644
--- a/web/src/features/traces/components/TracePanelNavigationLayoutDesktop/TracePanelNavigationLayoutDesktop.tsx
+++ b/web/src/features/traces/components/TracePanelNavigationLayoutDesktop/TracePanelNavigationLayoutDesktop.tsx
@@ -19,8 +19,10 @@ import { cn } from "@/src/utils/tailwind";
export function TracePanelNavigationLayoutDesktop({
children,
+ isLoading = false,
}: {
children: ReactNode;
+ isLoading?: boolean;
}) {
const { isNavigationPanelCollapsed, handleTogglePanel } =
useDesktopLayoutContext();
@@ -30,6 +32,7 @@ export function TracePanelNavigationLayoutDesktop({
<TracePanelNavigationHeader
isPanelCollapsed={isNavigationPanelCollapsed}
onTogglePanel={handleTogglePanel}
+ isLoading={isLoading}
/>
<div
className={cn(
@@ -38,8 +41,12 @@ export function TracePanelNavigationLayoutDesktop({
)}
inert={isNavigationPanelCollapsed}
>
- <TraceTruncationNotice />
- <TracePanelNavigationHiddenNotice />
+ {!isLoading && (
+ <>
+ <TraceTruncationNotice />
+ <TracePanelNavigationHiddenNotice />
+ </>
+ )}
<div className="flex-1 overflow-hidden">{children}</div>
</div>
</div>
diff --git a/web/src/features/traces/components/TraceTree.tsx b/web/src/features/traces/components/TraceTree.tsx
index c1a8322d9f..271a4e2d75 100644
--- a/web/src/features/traces/components/TraceTree.tsx
+++ b/web/src/features/traces/components/TraceTree.tsx
@@ -1,3 +1,13 @@
+import { VirtualizedTree } from "./VirtualizedTree";
+import { VirtualizedTreeNodeWrapper } from "./VirtualizedTreeNodeWrapper";
+import { SpanContent } from "./SpanContent";
+import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";
+import { useSelection } from "@/src/features/traces/contexts/SelectionContext";
+import { useHandlePrefetchObservation } from "@/src/features/traces/hooks/useHandlePrefetchObservation";
+import { useSelectTraceNode } from "@/src/features/traces/hooks/useSelectTraceNode";
+import { type TreeNode } from "../types/treeNode";
+import { metricEmphasisFor } from "@/src/features/traces/fns/metricEmphasis";
+
/**
* TraceTree - Composition of VirtualizedTree + TreeNodeWrapper + SpanContent.
*
@@ -9,17 +19,41 @@
* This composition pattern allows each component to have a single responsibility.
*/
-import { VirtualizedTree } from "./VirtualizedTree";
-import { VirtualizedTreeNodeWrapper } from "./VirtualizedTreeNodeWrapper";
-import { SpanContent } from "./SpanContent";
-import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";
-import { useSelection } from "@/src/features/traces/contexts/SelectionContext";
-import { useHandlePrefetchObservation } from "@/src/features/traces/hooks/useHandlePrefetchObservation";
-import { useSelectTraceNode } from "@/src/features/traces/hooks/useSelectTraceNode";
-import { type TreeNode } from "../types/treeNode";
-import { metricEmphasisFor } from "@/src/features/traces/fns/metricEmphasis";
+export function TraceTree({ isLoading = false }: { isLoading?: boolean }) {
+ if (isLoading) return <TraceTreeLoading />;
+ return <LoadedTraceTree />;
+}
-export function TraceTree() {
+/** A small tree's rows, so the placeholder has the shape of a trace. */
+const LOADING_ROWS = [
+ { depth: 0, hasChildren: true, isLastSibling: true, treeLines: [] },
+ { depth: 1, hasChildren: false, isLastSibling: false, treeLines: [] },
+ { depth: 1, hasChildren: true, isLastSibling: false, treeLines: [] },
+ { depth: 2, hasChildren: false, isLastSibling: false, treeLines: [true] },
+ { depth: 2, hasChildren: false, isLastSibling: true, treeLines: [true] },
+ { depth: 1, hasChildren: true, isLastSibling: true, treeLines: [] },
+ { depth: 2, hasChildren: false, isLastSibling: false, treeLines: [false] },
+ { depth: 2, hasChildren: false, isLastSibling: true, treeLines: [false] },
+];
+
+function TraceTreeLoading() {
+ return (
+ <div className="h-full overflow-y-auto">
+ {LOADING_ROWS.map(({ hasChildren, ...metadata }, index) => (
+ <VirtualizedTreeNodeWrapper
+ key={index}
+ isLoading
+ metadata={metadata}
+ hasChildren={hasChildren}
+ >
+ <SpanContent isLoading />
+ </VirtualizedTreeNodeWrapper>
+ ))}
+ </div>
+ );
+}
+
+function LoadedTraceTree() {
const { roots, comments, metricEmphasis } = useTraceData();
const { selectedNodeId, collapsedNodes, toggleCollapsed } = useSelection();
const { handleHover } = useHandlePrefetchObservation();
@@ -41,7 +75,6 @@ export function TraceTree() {
onSelect,
}) => {
const typedNode = node as TreeNode;
-
return (
<VirtualizedTreeNodeWrapper
metadata={treeMetadata}
diff --git a/web/src/features/traces/components/VirtualizedTreeNodeWrapper.tsx b/web/src/features/traces/components/VirtualizedTreeNodeWrapper.tsx
index 553f42c99c..baf21097a9 100644
--- a/web/src/features/traces/components/VirtualizedTreeNodeWrapper.tsx
+++ b/web/src/features/traces/components/VirtualizedTreeNodeWrapper.tsx
@@ -20,6 +20,7 @@ import {
ItemTypeIcon,
type LangfuseItemType,
} from "@/src/components/ItemBadge";
+import { Skeleton } from "@/src/components/ui/skeleton";
import { ChevronRight } from "lucide-react";
import { cn } from "@/src/utils/tailwind";
@@ -36,6 +37,7 @@ export interface TreeNodeMetadata {
}
interface TreeNodeWrapperProps {
+ isLoading?: false;
// Tree structure data
metadata: TreeNodeMetadata;
nodeType: LangfuseItemType; // For the icon badge (e.g., "SPAN", "GENERATION", "TRACE")
@@ -54,17 +56,22 @@ interface TreeNodeWrapperProps {
className?: string;
}
-export function VirtualizedTreeNodeWrapper({
- metadata,
- nodeType,
- hasChildren,
- isCollapsed,
- onToggleCollapse,
- isSelected,
- onSelect,
- children,
- className,
-}: TreeNodeWrapperProps) {
+/** Placeholder row: same geometry, a skeleton in the icon slot, no actions. */
+interface TreeNodeWrapperLoadingProps {
+ isLoading: true;
+ metadata: TreeNodeMetadata;
+ hasChildren?: boolean;
+ children: ReactNode;
+}
+
+export function VirtualizedTreeNodeWrapper(
+ props: TreeNodeWrapperProps | TreeNodeWrapperLoadingProps,
+) {
+ const loaded = props.isLoading === true ? null : props;
+ const { metadata, children } = props;
+ const hasChildren = props.hasChildren ?? false;
+ const isCollapsed = loaded?.isCollapsed ?? false;
+ const isSelected = loaded?.isSelected ?? false;
const { depth, treeLines, isLastSibling } = metadata;
const maxVisualDepth = metadata.maxVisualDepth ?? Infinity;
// Visual depth: real depth, capped so indentation never exceeds the
@@ -77,23 +84,29 @@ export function VirtualizedTreeNodeWrapper({
return (
<div
className={cn(
- "group relative flex w-full cursor-pointer px-0",
+ "group relative flex w-full px-0",
+ loaded && "cursor-pointer",
// Dim unselected rows in dark only — in light the gray read as washed
// out, an accepted light/dark inconsistency.
- isSelected
- ? "bg-muted text-foreground"
- : "hover:bg-accent dark:text-muted-foreground",
- className,
+ loaded &&
+ (isSelected
+ ? "bg-muted text-foreground"
+ : "hover:bg-accent dark:text-muted-foreground"),
+ loaded?.className,
)}
style={{
paddingTop: 0,
paddingBottom: 0,
}}
- onClick={(e) => {
- if (!e.currentTarget?.closest("[data-expand-button]")) {
- onSelect();
- }
- }}
+ onClick={
+ loaded
+ ? (e) => {
+ if (!e.currentTarget?.closest("[data-expand-button]")) {
+ loaded.onSelect();
+ }
+ }
+ : undefined
+ }
>
<div className="flex w-full pl-2">
{/* 1. Indents: ancestor level indicators (capped at visualDepth) */}
@@ -128,7 +141,11 @@ export function VirtualizedTreeNodeWrapper({
{/* 3. Icon + child connector: fixed width container */}
<div className="relative flex w-6 shrink-0 flex-col py-1.5">
<div className="relative z-10 flex h-4 items-center justify-center">
- <ItemTypeIcon type={nodeType} className="icon-base" />
+ {loaded ? (
+ <ItemTypeIcon type={loaded.nodeType} className="icon-base" />
+ ) : (
+ <Skeleton className="size-4 rounded-sm" />
+ )}
</div>
{/* Vertical bar downwards if there are expanded children (skipped
when children render capped at this same indent — the spine
@@ -148,7 +165,7 @@ export function VirtualizedTreeNodeWrapper({
{/* 5. Expand/Collapse button. Leaf rows keep the slot so right-aligned
content lines up across rows. */}
<div className="flex w-7 shrink-0 items-start justify-end py-0.5 pr-1">
- {hasChildren && (
+ {loaded && hasChildren && (
<Button
aria-expanded={!isCollapsed}
data-expand-button
@@ -156,7 +173,7 @@ export function VirtualizedTreeNodeWrapper({
variant="ghost"
onClick={(ev) => {
ev.stopPropagation();
- onToggleCollapse();
+ loaded.onToggleCollapse();
}}
className="text-muted-foreground hover:text-foreground hover:bg-primary/10 h-6 w-6 shrink-0"
>
diff --git a/web/src/features/traces/contexts/TraceDataContext.tsx b/web/src/features/traces/contexts/TraceDataContext.tsx
index acbd05a028..ee0a495872 100644
--- a/web/src/features/traces/contexts/TraceDataContext.tsx
+++ b/web/src/features/traces/contexts/TraceDataContext.tsx
@@ -77,6 +77,8 @@ interface TraceDataContextValue {
detachedObservationIsMisplaced: boolean;
/** Observation cap this trace was loaded under, when it hit it. */
truncatedAtObservations?: number;
+ /** This is the previous trace, kept on screen while the next one loads. */
+ isPlaceholderData: boolean;
comments: Map<string, number>;
}
@@ -99,6 +101,7 @@ interface TraceDataProviderProps {
detachedObservationId?: string | null;
detachedObservationIsMisplaced?: boolean;
truncatedAtObservations?: number;
+ isPlaceholderData?: boolean;
children: ReactNode;
}
@@ -115,6 +118,7 @@ export function TraceDataProvider({
detachedObservationId = null,
detachedObservationIsMisplaced = false,
truncatedAtObservations,
+ isPlaceholderData = false,
children,
}: TraceDataProviderProps) {
const { minObservationLevel } = useViewPreferences();
@@ -201,6 +205,7 @@ export function TraceDataProvider({
detachedObservationId,
detachedObservationIsMisplaced,
truncatedAtObservations,
+ isPlaceholderData,
comments,
}),
[
@@ -216,6 +221,7 @@ export function TraceDataProvider({
detachedObservationId,
detachedObservationIsMisplaced,
truncatedAtObservations,
+ isPlaceholderData,
uiData.nodeMap,
uiData.metricEmphasis,
comments,
diff --git a/web/src/features/traces/fns/staleProps.ts b/web/src/features/traces/fns/staleProps.ts
new file mode 100644
index 0000000000..640f0fa26d
--- /dev/null
+++ b/web/src/features/traces/fns/staleProps.ts
@@ -0,0 +1,18 @@
+import { cn } from "@/src/utils/tailwind";
+
+/**
+ * Props for the root of content that belongs to the previous item while the
+ * next one loads: dimmed, and `inert` so it takes no pointer, keyboard or focus
+ * input. `inert` does not reach portalled menus and dialogs; `remountOnStale`
+ * flips `key` so they close. Set `key` directly, React rejects it in a spread.
+ */
+export function staleProps(
+ stale: boolean,
+ { remountOnStale = false }: { remountOnStale?: boolean } = {},
+) {
+ return {
+ key: remountOnStale && stale ? "stale" : "live",
+ inert: stale,
+ className: cn(stale && "pointer-events-none opacity-60 select-none"),
+ };
+}
diff --git a/web/src/features/traces/hooks/useSelectedObservation.clienttest.tsx b/web/src/features/traces/hooks/useSelectedObservation.clienttest.tsx
index cf1bdf19f4..e9116a273c 100644
--- a/web/src/features/traces/hooks/useSelectedObservation.clienttest.tsx
+++ b/web/src/features/traces/hooks/useSelectedObservation.clienttest.tsx
@@ -27,13 +27,14 @@ const observation = (id: string) =>
const loaded = [observation("in-list")];
-const render = (selectedNodeId: string | null) =>
+const render = (selectedNodeId: string | null, enabled?: boolean) =>
renderHook(() =>
useSelectedObservation({
selectedNodeId,
traceId: "t",
projectId: "p",
observations: loaded,
+ enabled,
}),
).result.current;
@@ -66,6 +67,21 @@ describe("useSelectedObservation", () => {
).toBe("t");
});
+ it("stays loading while disabled, even when the by-id query serves a cached row", () => {
+ mockByIdQuery.mockReturnValue({
+ data: { ...observation("next-trace-row"), traceId: null },
+ error: null,
+ });
+
+ const result = render("next-trace-row", false);
+
+ expect(result).toEqual({
+ kind: "loading",
+ observationId: "next-trace-row",
+ });
+ expect(queryEnabled()).toBe(false);
+ });
+
it("serves a loaded observation from the list without firing a request", () => {
const result = render("in-list");
diff --git a/web/src/features/traces/hooks/useSelectedObservation.ts b/web/src/features/traces/hooks/useSelectedObservation.ts
index 2a519288fa..ac1bcae595 100644
--- a/web/src/features/traces/hooks/useSelectedObservation.ts
+++ b/web/src/features/traces/hooks/useSelectedObservation.ts
@@ -31,11 +31,18 @@ export function useSelectedObservation({
traceId,
projectId,
observations,
+ enabled = true,
}: {
selectedNodeId: string | null;
traceId: string;
projectId: string;
observations: ObservationReturnTypeWithMetadata[];
+ /**
+ * False while `observations` are the previous trace's placeholder: the
+ * selected id belongs to the next trace, so a by-id fetch scoped to this
+ * trace would flash "not found". Stays `loading` instead.
+ */
+ enabled?: boolean;
}): SelectedObservation {
// A loaded row wins over the synthetic trace-node id shape: observation ids
// are caller-supplied, so an observation really can be called
@@ -74,7 +81,7 @@ export function useSelectedObservation({
verbosity: "compact",
},
{
- enabled: !!observationId && !loadedRow,
+ enabled: enabled && !!observationId && !loadedRow,
staleTime: 5 * 60 * 1000,
// The panel renders the missing-observation state itself; a global error
// toast on top of it would just be alarming noise.
@@ -97,6 +104,8 @@ export function useSelectedObservation({
observation: loadedRow,
isOutsideLoadedList: false,
};
+ // A disabled query still serves a cached row.
+ if (!enabled) return { kind: "loading", observationId };
if (byId.data)
return {
kind: "observation",
@@ -114,5 +123,13 @@ export function useSelectedObservation({
};
}
return { kind: "loading", observationId };
- }, [observationId, loadedRow, byId.data, hasError, isNotFound, traceId]);
+ }, [
+ observationId,
+ loadedRow,
+ enabled,
+ byId.data,
+ hasError,
+ isNotFound,
+ traceId,
+ ]);
}
diff --git a/web/src/features/traces/hooks/useTraceDetailData.ts b/web/src/features/traces/hooks/useTraceDetailData.ts
index 523cd0f5b4..f334da7a0b 100644
--- a/web/src/features/traces/hooks/useTraceDetailData.ts
+++ b/web/src/features/traces/hooks/useTraceDetailData.ts
@@ -1,4 +1,5 @@
import { api } from "@/src/utils/api";
+import { keepPreviousData } from "@tanstack/react-query";
import { useEventsTraceData, useReadPath } from "@/src/features/events";
import { useSession } from "next-auth/react";
@@ -59,6 +60,7 @@ export function useTraceDetailData({
return failureCount < 3;
},
staleTime: 60 * 1000,
+ placeholderData: keepPreviousData,
},
);
@@ -84,6 +86,7 @@ export function useTraceDetailData({
isNotFound: false,
isUnauthorized: false,
truncatedAtObservations: undefined,
+ isPlaceholderData: false,
};
}
@@ -108,6 +111,7 @@ export function useTraceDetailData({
!eventsData.isLoading && !eventsData.data && !eventsData.error,
isUnauthorized,
truncatedAtObservations: eventsData.truncatedAtObservations,
+ isPlaceholderData: eventsData.isPlaceholderData,
};
}
@@ -120,5 +124,6 @@ export function useTraceDetailData({
isUnauthorized: tracesQuery.error?.data?.code === "UNAUTHORIZED",
// The traces-table read path has no row cap.
truncatedAtObservations: undefined,
+ isPlaceholderData: tracesQuery.isPlaceholderData,
};
}
diff --git a/web/src/hooks/useLatched.ts b/web/src/hooks/useLatched.ts
new file mode 100644
index 0000000000..da3a2b5747
--- /dev/null
+++ b/web/src/hooks/useLatched.ts
@@ -0,0 +1,11 @@
+import { useState } from "react";
+
+/**
+ * Returns `value`, except while `hold` is true, when it keeps returning the
+ * last value seen unheld.
+ */
+export function useLatched<T>(value: T, hold: boolean): T {
+ const [latched, setLatched] = useState(value);
+ if (!hold && !Object.is(latched, value)) setLatched(value);
+ return hold ? latched : value;
+}
diff --git a/web/src/styles/globals.css b/web/src/styles/globals.css
index 5da64ac6b6..0bb37d82ee 100644
--- a/web/src/styles/globals.css
+++ b/web/src/styles/globals.css
@@ -226,6 +226,7 @@
--animate-accordion-down: accordion-down 0.2s ease-out;
--animate-accordion-up: accordion-up 0.2s ease-out;
--animate-appear: appear 0.2s ease-out forwards;
+ --animate-appear-delayed: appear 0s linear 150ms forwards;
/* Cycle length comes from REFETCH_SWEEP_MS in components/table/data-table.tsx,
which sets --table-refetch-cycle on the element: the same number also
releases the busy flag on a whole sweep, so the two must not drift. */