Skip to content

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

fix(trace): Consistently show attributes tab (#18487)

Ben Bachem4cf82155b83d
diff --git a/web/src/features/sessions/SessionPages.tsx b/web/src/features/sessions/SessionPages.tsx
index 69f106bc21..9179dae1e4 100644
--- a/web/src/features/sessions/SessionPages.tsx
+++ b/web/src/features/sessions/SessionPages.tsx
@@ -527,8 +527,12 @@ export const SessionPage: React.FC<{
queryParams: ["observation", "display", "timestamp", "traceId"],
tableName: "sessions",
isV4: false,
- extractParamsValuesFromRow: (row: any) => ({
+ extractParamsValuesFromRow: (row: {
+ timestamp: Date;
+ observationId?: string;
+ }) => ({
timestamp: row.timestamp.toISOString(),
+ ...(row.observationId ? { observation: row.observationId } : {}),
}),
}),
[projectId],
@@ -1199,7 +1203,10 @@ const LoadedSessionEventsPage: React.FC<{
isV4: true,
// observationId: set by a card's "Open in trace view" on a truncated
// observation so the peek opens AT that observation (LFE-10958).
- extractParamsValuesFromRow: (row: any) => ({
+ extractParamsValuesFromRow: (row: {
+ timestamp: Date;
+ observationId?: string;
+ }) => ({
timestamp: row.timestamp.toISOString(),
...(row.observationId ? { observation: row.observationId } : {}),
}),
diff --git a/web/src/features/traces/components/DetailAttributesTab.clienttest.tsx b/web/src/features/traces/components/DetailAttributesTab.clienttest.tsx
new file mode 100644
index 0000000000..285e385eae
--- /dev/null
+++ b/web/src/features/traces/components/DetailAttributesTab.clienttest.tsx
@@ -0,0 +1,83 @@
+/** @vitest-environment jsdom */
+import { cleanup, render } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
+import { DetailAttributesTab } from "./DetailAttributesTab";
+import { MediaContentType } from "@langfuse/shared";
+import { MediaEnabledFields } from "@/src/features/media/validation";
+
+vi.mock("@/src/components/ui/PrettyJsonView", () => ({
+ PrettyJsonView: vi.fn(() => null),
+}));
+vi.mock("./ObservationDetailView/AttributeRowActions", () => ({
+ AttributeRowActions: () => null,
+}));
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("DetailAttributesTab metadata expansion", () => {
+ it("forwards only metadata attachments", () => {
+ const attachment = {
+ mediaId: "media-id",
+ contentType: MediaContentType.TXT,
+ contentLength: 1,
+ url: "https://example.com/media.txt",
+ urlExpiry: "2099-01-01T00:00:00.000Z",
+ field: MediaEnabledFields.Metadata,
+ };
+ render(
+ <DetailAttributesTab
+ metadata={{ file: "attachment" }}
+ objectId="trace"
+ projectId="project"
+ currentView="pretty"
+ media={[
+ attachment,
+ {
+ ...attachment,
+ mediaId: "input-media",
+ field: MediaEnabledFields.Input,
+ },
+ ]}
+ />,
+ );
+ expect(vi.mocked(PrettyJsonView).mock.calls[0]?.[0].media).toEqual([
+ attachment,
+ ]);
+ });
+ it.each(["pretty", "json"] as const)(
+ "restores and saves %s expansion",
+ (currentView) => {
+ const onMetadataExpansionChange = vi.fn();
+ const onJsonMetadataExpandedChange = vi.fn();
+ const metadataExpansionState = { nested: false };
+ render(
+ <DetailAttributesTab
+ metadata={{ nested: { value: 1 } }}
+ objectId="trace"
+ projectId="project"
+ currentView={currentView}
+ metadataExpansionState={metadataExpansionState}
+ onMetadataExpansionChange={onMetadataExpansionChange}
+ jsonMetadataExpanded={false}
+ onJsonMetadataExpandedChange={onJsonMetadataExpandedChange}
+ />,
+ );
+ const props = vi.mocked(PrettyJsonView).mock.calls[0]?.[0];
+ if (!props) throw new Error("Metadata viewer was not rendered");
+ expect(props.externalExpansionState).toEqual(
+ currentView === "pretty" ? metadataExpansionState : false,
+ );
+ const nextExpansion = currentView === "pretty" ? { nested: true } : true;
+ props.onExternalExpansionChange?.(nextExpansion);
+ expect(
+ currentView === "pretty"
+ ? onMetadataExpansionChange
+ : onJsonMetadataExpandedChange,
+ ).toHaveBeenCalledWith(nextExpansion);
+ },
+ );
+});
diff --git a/web/src/features/traces/components/ObservationDetailView/ObservationAttributesTab.tsx b/web/src/features/traces/components/DetailAttributesTab.tsx
similarity index 55%
rename from web/src/features/traces/components/ObservationDetailView/ObservationAttributesTab.tsx
rename to web/src/features/traces/components/DetailAttributesTab.tsx
index f0f28751af..ab3c4995db 100644
--- a/web/src/features/traces/components/ObservationDetailView/ObservationAttributesTab.tsx
+++ b/web/src/features/traces/components/DetailAttributesTab.tsx
@@ -1,43 +1,55 @@
-/** Attributes, model parameters and metadata as three tables. */
+/** Trace metadata, or observation attributes, model parameters and metadata. */
import { useMemo } from "react";
+import { type MediaReturnType } from "@/src/features/media";
import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
import { cn } from "@/src/utils/tailwind";
import { IO_SECTIONS_FLUSH_CLASS } from "@/src/features/traces/constants/ioSectionClasses";
import { type MetadataFilterActions } from "@/src/components/table/ValueCell";
-import { AttributeRowActions } from "./AttributeRowActions";
+import { AttributeRowActions } from "./ObservationDetailView/AttributeRowActions";
import { LargeJsonFieldFallback } from "@/src/features/traces/components/IOPreview/components/LargeJsonFieldFallback";
import {
JSON_VIEW_RENDER_CHAR_LIMIT,
probeJsonField,
} from "@/src/features/traces/components/IOPreview/fns/jsonViewSizeGate";
-export function ObservationAttributesTab({
- attributes,
- attributesAnchorTime,
- modelParameters,
+export function DetailAttributesTab({
+ observation,
metadata,
parsedMetadata,
- observationId,
+ objectId,
projectId,
currentView,
+ media,
+ metadataExpansionState,
+ onMetadataExpansionChange,
+ jsonMetadataExpanded,
+ onJsonMetadataExpandedChange,
}: {
- attributes: Record<string, unknown>;
- attributesAnchorTime: Date;
- modelParameters: Record<string, unknown> | null;
+ observation?: {
+ attributes: Record<string, unknown>;
+ attributesAnchorTime: Date;
+ modelParameters: Record<string, unknown> | null;
+ };
metadata: unknown;
/** Avoids re-parsing. */
parsedMetadata?: unknown;
- observationId: string;
+ objectId: string;
projectId: string;
currentView: "pretty" | "json";
+ media?: MediaReturnType[];
+ metadataExpansionState?: Record<string, boolean>;
+ onMetadataExpansionChange?: (expansion: Record<string, boolean>) => void;
+ jsonMetadataExpanded?: boolean;
+ onJsonMetadataExpandedChange?: (expanded: boolean) => void;
}) {
const metadataActions: MetadataFilterActions = {
projectId,
- filterTarget: "observations",
+ filterTarget: observation ? "observations" : "traces",
};
- const hasAttributes = Object.keys(attributes).length > 0;
+ const hasAttributes =
+ observation && Object.keys(observation.attributes).length > 0;
const hasMetadata =
metadata !== null &&
metadata !== undefined &&
@@ -49,26 +61,26 @@ export function ObservationAttributesTab({
return (
<div className="flex min-h-0 w-full flex-1 flex-col overflow-auto px-4 pb-4">
<div className={cn("space-y-3 pt-3", IO_SECTIONS_FLUSH_CLASS)}>
- {hasAttributes ? (
+ {observation && hasAttributes ? (
<PrettyJsonView
title="Attributes"
- json={attributes}
+ json={observation.attributes}
currentView={currentView}
rowActions={(row) => (
<AttributeRowActions
row={row}
projectId={projectId}
filterTarget="observations"
- anchorTime={attributesAnchorTime}
+ anchorTime={observation.attributesAnchorTime}
analyticsTable="attributes"
/>
)}
/>
) : null}
- {modelParameters ? (
+ {observation?.modelParameters ? (
<PrettyJsonView
title="Model parameters"
- json={modelParameters}
+ json={observation.modelParameters}
currentView={currentView}
/>
) : null}
@@ -80,7 +92,7 @@ export function ObservationAttributesTab({
serialized={metadataProbe.serialized}
isString={metadataProbe.isString}
charCount={metadataProbe.size}
- downloadFileBase={`metadata-${observationId}`}
+ downloadFileBase={`metadata-${objectId}`}
/>
) : (
<PrettyJsonView
@@ -89,13 +101,30 @@ export function ObservationAttributesTab({
parsedJson={parsedMetadata}
currentView={currentView}
metadataActions={metadataActions}
+ media={media?.filter(
+ (attachment) => attachment.field === "metadata",
+ )}
+ externalExpansionState={
+ currentView === "pretty"
+ ? metadataExpansionState
+ : jsonMetadataExpanded
+ }
+ onExternalExpansionChange={(expansion) => {
+ if (typeof expansion === "boolean") {
+ onJsonMetadataExpandedChange?.(expansion);
+ return;
+ }
+ onMetadataExpansionChange?.(expansion);
+ }}
/>
)}
</div>
) : null}
- {!hasAttributes && !modelParameters && !hasMetadata ? (
+ {!hasAttributes && !observation?.modelParameters && !hasMetadata ? (
<p className="text-muted-foreground text-base">
- No attributes, model parameters or metadata on this observation.
+ {observation
+ ? "No attributes, model parameters or metadata on this observation."
+ : "No metadata on this trace."}
</p>
) : null}
</div>
diff --git a/web/src/features/traces/components/IOPreview/IOPreview.tsx b/web/src/features/traces/components/IOPreview/IOPreview.tsx
index 2fbe715ec2..2af60be740 100644
--- a/web/src/features/traces/components/IOPreview/IOPreview.tsx
+++ b/web/src/features/traces/components/IOPreview/IOPreview.tsx
@@ -83,9 +83,6 @@ export interface IOPreviewProps extends ExpansionStateProps {
enableInlineComments?: boolean;
onAddInlineComment?: IOPreviewJSONProps["onAddInlineComment"];
commentedPathsByField?: IOPreviewJSONProps["commentedPathsByField"];
- // Whether to show metadata section in pretty view (default: false)
- // JSON view always shows metadata
- showMetadata?: boolean;
// Callback to inform parent if virtualization is being used (for scroll handling)
onVirtualizationChange?: (isVirtualized: boolean) => void;
// For CorrectedOutputField
@@ -147,7 +144,6 @@ export function IOPreview({
enableInlineComments,
onAddInlineComment,
commentedPathsByField,
- showMetadata = false,
onVirtualizationChange,
observationId,
projectId,
@@ -248,14 +244,12 @@ export function IOPreview({
*/}
{selectedView === "json-beta" ? (
<IOPreviewJSON
- hideMetadata={!showMetadata}
+ hideMetadata
input={input}
output={output}
status={status}
- metadata={metadata}
parsedInput={parsedInput}
parsedOutput={parsedOutput}
- parsedMetadata={parsedMetadata}
outputCorrection={outputCorrection}
isParsing={isParsing}
hideIfNull={hideIfNull}
@@ -276,15 +270,13 @@ export function IOPreview({
/>
) : selectedView === "json" ? (
<IOPreviewJSONSimple
- hideMetadata={!showMetadata}
+ hideMetadata
input={input}
output={output}
status={status}
- metadata={metadata}
outputCorrection={outputCorrection}
parsedInput={parsedInput}
parsedOutput={parsedOutput}
- parsedMetadata={parsedMetadata}
isLoading={isLoading}
isParsing={isParsing}
hideIfNull={hideIfNull}
@@ -306,7 +298,6 @@ export function IOPreview({
) : (
<IOPreviewPretty
{...sharedProps}
- showMetadata={showMetadata}
contentMode={contentMode}
showSystemPrompt={showSystemPrompt}
/>
diff --git a/web/src/features/traces/components/IOPreview/IOPreviewPretty.stories.tsx b/web/src/features/traces/components/IOPreview/IOPreviewPretty.stories.tsx
index a8c9702c54..d6d351cc7b 100644
--- a/web/src/features/traces/components/IOPreview/IOPreviewPretty.stories.tsx
+++ b/web/src/features/traces/components/IOPreview/IOPreviewPretty.stories.tsx
@@ -160,7 +160,7 @@ export const ToolCall = meta.story({
},
});
-export const WithMetadata = meta.story({
+export const MetadataNotInPreview = meta.story({
args: {
input: "Summarize this support conversation.",
output: "The customer needs help configuring prompt caching.",
@@ -169,7 +169,6 @@ export const WithMetadata = meta.story({
region: "eu-west-1",
cached: true,
},
- showMetadata: true,
},
});
diff --git a/web/src/features/traces/components/IOPreview/IOPreviewPretty.tsx b/web/src/features/traces/components/IOPreview/IOPreviewPretty.tsx
index 62c4d08680..1401bd646f 100644
--- a/web/src/features/traces/components/IOPreview/IOPreviewPretty.tsx
+++ b/web/src/features/traces/components/IOPreview/IOPreviewPretty.tsx
@@ -3,7 +3,6 @@ import { useMemo } from "react";
import { cn } from "@/src/utils/tailwind";
import { type Prisma, type ScoreDomain, deepParseJson } from "@langfuse/shared";
import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
-import { type MetadataFilterActions } from "@/src/components/table/ValueCell";
import { useMarkdownRenderCharacterLimit } from "@/src/hooks/useMarkdownRenderCharacterLimit";
import { type MediaReturnType } from "@/src/features/media";
import { type ChatMLParserResult } from "../../hooks/useChatMLParser";
@@ -105,8 +104,6 @@ export interface IOPreviewPrettyProps extends ExpansionStateProps {
media?: MediaReturnType[];
hideOutput?: boolean;
hideInput?: boolean;
- // Whether to show metadata section (default: false)
- showMetadata?: boolean;
observationId?: string;
projectId: string;
traceId: string;
@@ -146,11 +143,8 @@ export function IOPreviewPretty({
media,
inputExpansionState,
outputExpansionState,
- metadataExpansionState,
onInputExpansionChange,
onOutputExpansionChange,
- onMetadataExpansionChange,
- showMetadata = false,
observationId,
projectId,
traceId,
@@ -175,16 +169,6 @@ export function IOPreviewPretty({
: (preParsedMetadata ??
deepParseJson(metadata, { maxSize: 100_000, maxDepth: 2 }));
- // Enable the metadata rows' actions menu (copy + add-to-filter). Observation
- // metadata filters the observations table; trace metadata the traces table.
- const metadataActions = useMemo<MetadataFilterActions>(
- () => ({
- projectId,
- filterTarget: observationId ? "observations" : "traces",
- }),
- [projectId, observationId],
- );
-
// Parse into the shared preview contract.
const parserResult = useIOPreviewParser(
input,
@@ -269,8 +253,6 @@ export function IOPreviewPretty({
onOutputExpansionChange,
};
- // Determine if metadata should be shown
- const shouldShowMetadata = showMetadata && parsedMetadata !== undefined;
const showData = contentMode !== "conversation";
const shouldRenderMessages = hasRenderableChatMessages(parserResult);
@@ -328,21 +310,6 @@ export function IOPreviewPretty({
)}
</div>
) : null}
-
- {/* Metadata Section */}
- {showData && shouldShowMetadata && (
- <PrettyJsonView
- title="Metadata"
- json={parsedMetadata}
- isLoading={isLoading}
- isParsing={isParsing}
- media={media?.filter((m) => m.field === "metadata") ?? []}
- currentView="pretty"
- externalExpansionState={metadataExpansionState}
- onExternalExpansionChange={onMetadataExpansionChange}
- metadataActions={metadataActions}
- />
- )}
</div>
);
}
diff --git a/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx b/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
index 266904df2d..5a9ad1885f 100644
--- a/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
+++ b/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
@@ -31,6 +31,8 @@ import {
} from "@/src/features/comments";
import { useRouter } from "next/router";
import { TraceDetailTabsBarList } from "../TraceDetailTabsBarList";
+import { getDetailTabs } from "../../fns/getDetailTabs";
+import { resolveDetailTab } from "../../fns/resolveDetailTab";
import { ScoresTable } from "@/src/features/scores";
import { getMostRecentCorrection } from "@/src/features/corrections";
import { useJsonExpansion } from "@/src/features/traces/contexts/JsonExpansionContext";
@@ -66,7 +68,7 @@ import { useSession } from "next-auth/react";
import { ObservationPreview } from "./ObservationPreview";
import { useInternalFeaturesEnabled } from "@/src/features/feature-flags";
import { TraceMessagesView } from "../TraceMessagesView/TraceMessagesView";
-import { ObservationAttributesTab } from "./ObservationAttributesTab";
+import { DetailAttributesTab } from "../DetailAttributesTab";
import { buildModelParameters } from "@/src/features/traces/fns/buildModelParameters";
import { buildObservationAttributes } from "@/src/features/traces/fns/buildObservationAttributes";
@@ -94,7 +96,6 @@ export function ConnectedObservationDetailView({
// V4 beta mode and observations for log tab
const { isV4: isV4Enabled } = useReadPath();
const internalFeaturesEnabled = useInternalFeaturesEnabled();
- const showMessagesTab = internalFeaturesEnabled && isV4Enabled;
const {
observations,
roots,
@@ -116,9 +117,16 @@ export function ConnectedObservationDetailView({
} = useViewPreferences();
// Tab visibility: hide Log View and Scores tabs in annotation mode
- const showLogViewTab =
- isV4Enabled && observations.length > 0 && !isAnnotationMode;
- const showScoresTab = !isAnnotationMode;
+ const tabs = getDetailTabs({
+ target: "observation",
+ isV4: isV4Enabled,
+ internalFeaturesEnabled,
+ isAnnotationMode,
+ hasObservations: observations.length > 0,
+ canViewScores: true,
+ });
+ const showLogViewTab = tabs.includes("log");
+ const showScoresTab = tabs.includes("scores");
const attributes = buildObservationAttributes({
model: observation.model,
environment: observation.environment,
@@ -165,15 +173,7 @@ export function ConnectedObservationDetailView({
return aggregateTraceMetrics(allObservations);
}, [isRoot, treeNode, observations, observation]);
- // "log" is v4-only and needs observations; everything else falls back to preview.
- const selectedTab = useMemo(() => {
- if (globalSelectedTab === "messages" && showMessagesTab)
- return "messages" as const;
- if (globalSelectedTab === "scores") return "scores" as const;
- if (globalSelectedTab === "attributes") return "attributes" as const;
- if (globalSelectedTab === "log" && showLogViewTab) return "log" as const;
- return "preview" as const;
- }, [globalSelectedTab, showLogViewTab, showMessagesTab]);
+ const selectedTab = resolveDetailTab(globalSelectedTab, tabs);
const refreshTraceScores = useCallback(() => {
utils.traces.byIdWithObservationsAndScores.invalidate({
@@ -370,13 +370,7 @@ export function ConnectedObservationDetailView({
onValueChange={(value) => setSelectedTab(value as DetailTab)}
>
<TraceDetailTabsBarList
- tabs={[
- "preview",
- ...(showMessagesTab ? ["messages" as const] : []),
- "attributes",
- ...(showScoresTab ? ["scores" as const] : []),
- ...(showLogViewTab ? ["log" as const] : []),
- ]}
+ tabs={tabs}
logViewDescription={
isLogViewVirtualized
? `Shows all ${observations.length} observations with virtualization enabled.`
@@ -544,8 +538,6 @@ export function ConnectedObservationDetailView({
objectStartTime: observation.startTime,
}),
commentedPathsByField,
- // Metadata lives in the Attributes tab now.
- showMetadata: false,
observationId: observation.id,
projectId,
traceId,
@@ -555,13 +547,15 @@ export function ConnectedObservationDetailView({
</Tabs.Content>
<Tabs.Content value="attributes" layout="fill">
- <ObservationAttributesTab
- attributes={attributes}
- attributesAnchorTime={observation.startTime}
- modelParameters={modelParameters}
+ <DetailAttributesTab
+ observation={{
+ attributes,
+ attributesAnchorTime: observation.startTime,
+ modelParameters,
+ }}
metadata={observationWithIOCompat.data?.metadata ?? undefined}
parsedMetadata={parsedMetadata}
- observationId={observation.id}
+ objectId={observation.id}
projectId={projectId}
currentView={selectedViewTab}
/>
diff --git a/web/src/features/traces/components/ObservationDetailView/ObservationPreview.stories.tsx b/web/src/features/traces/components/ObservationDetailView/ObservationPreview.stories.tsx
index b307a0c8c3..6614778f39 100644
--- a/web/src/features/traces/components/ObservationDetailView/ObservationPreview.stories.tsx
+++ b/web/src/features/traces/components/ObservationDetailView/ObservationPreview.stories.tsx
@@ -23,7 +23,6 @@ export const Default = meta.story({
},
projectId: "storybook-project",
traceId: "storybook-trace",
- showMetadata: true,
showCorrections: false,
},
},
@@ -48,7 +47,6 @@ export const Error = meta.story({
},
projectId: "storybook-project",
traceId: "storybook-trace",
- showMetadata: true,
showCorrections: false,
},
},
@@ -84,7 +82,6 @@ export const JsonError = meta.story({
},
projectId: "storybook-project",
traceId: "storybook-trace",
- showMetadata: true,
showCorrections: false,
},
},
@@ -112,7 +109,6 @@ export const Warning = meta.story({
},
projectId: "storybook-project",
traceId: "storybook-trace",
- showMetadata: true,
showCorrections: false,
},
},
@@ -140,7 +136,6 @@ export const Debug = meta.story({
},
projectId: "storybook-project",
traceId: "storybook-trace",
- showMetadata: true,
showCorrections: false,
},
},
@@ -168,7 +163,6 @@ export const Info = meta.story({
},
projectId: "storybook-project",
traceId: "storybook-trace",
- showMetadata: true,
showCorrections: false,
},
},
diff --git a/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx b/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
index 23e9a5ff92..e90a0ae07a 100644
--- a/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
+++ b/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
@@ -21,6 +21,7 @@ import { HoverCard } from "@/src/components/design-system/HoverCard/HoverCard";
// Preview tab components
import { IOPreview } from "@/src/features/traces/components/IOPreview/IOPreview";
+import { IOPreviewJSON } from "@/src/features/traces/components/IOPreview/IOPreviewJSON";
import { useJsonExpansion } from "@/src/features/traces/contexts/JsonExpansionContext";
import { useMedia } from "@/src/features/traces/hooks/useMedia";
import { useParsedTrace } from "@/src/hooks/useParsedTrace";
@@ -52,6 +53,9 @@ import { useInternalFeaturesEnabled } from "@/src/features/feature-flags";
import { useReadPath } from "@/src/features/events";
import { TraceMessagesView } from "../TraceMessagesView/TraceMessagesView";
import { TraceDetailTabsBarList } from "../TraceDetailTabsBarList";
+import { DetailAttributesTab } from "../DetailAttributesTab";
+import { getDetailTabs } from "../../fns/getDetailTabs";
+import { resolveDetailTab } from "../../fns/resolveDetailTab";
export interface TraceDetailViewProps {
isLoading?: false;
@@ -113,13 +117,6 @@ function LoadedTraceDetailView({
const { selectedTab: globalSelectedTab, setSelectedTab } = useSelection();
const internalFeaturesEnabled = useInternalFeaturesEnabled();
const { isV4 } = useReadPath();
- const showMessagesTab = internalFeaturesEnabled && isV4;
- // Unsupported tabs fall back to Preview instead of rendering an empty panel.
- const selectedTab =
- globalSelectedTab === "attributes" ||
- (globalSelectedTab === "messages" && !showMessagesTab)
- ? "preview"
- : globalSelectedTab;
const utils = api.useUtils();
const capture = usePostHogClientCapture();
const analyticsDimensions = useTraceAnalyticsDimensions();
@@ -136,6 +133,20 @@ function LoadedTraceDetailView({
isAnnotationMode,
} = useViewPreferences();
+ const isAuthenticatedAndProjectMember =
+ useIsAuthenticatedAndProjectMember(projectId);
+ const tabs = getDetailTabs({
+ target: "trace",
+ isV4,
+ internalFeaturesEnabled,
+ isAnnotationMode,
+ hasObservations: observations.length > 0,
+ canViewScores: isAuthenticatedAndProjectMember,
+ });
+ const selectedTab = resolveDetailTab(globalSelectedTab, tabs);
+ const showScoresTab = tabs.includes("scores");
+ const showLogViewTab = tabs.includes("log");
+
// Map jsonViewPreference to currentView format expected by child components
const currentView = jsonViewPreference;
@@ -235,21 +246,10 @@ function LoadedTraceDetailView({
const outputCorrection = getMostRecentCorrection(traceCorrections);
- // Tab visibility: hide Log View and Scores tabs in annotation mode
- const showLogViewTab = observations.length > 0 && !isAnnotationMode;
-
// Check if log view will be virtualized (affects JSON tab availability)
const isLogViewVirtualized =
observations.length >= TRACE_VIEW_CONFIG.logView.virtualizationThreshold;
- // Scores tab visibility: hide for public trace viewers and in annotation mode
- const isAuthenticatedAndProjectMember =
- useIsAuthenticatedAndProjectMember(projectId);
- const showScoresTab = isAuthenticatedAndProjectMember && !isAnnotationMode;
-
- // Hide entire tabs bar when only Preview tab remains (cleaner annotation mode UI)
- const showTabsBar = showLogViewTab || showScoresTab || showMessagesTab;
-
const refreshTraceScores = useCallback(() => {
utils.traces.byIdWithObservationsAndScores.invalidate({
projectId,
@@ -308,38 +308,33 @@ function LoadedTraceDetailView({
layout="fill"
onValueChange={handleTabChange}
>
- {/* Hide the tabs bar when only Preview remains. */}
- {showTabsBar && (
+ {tabs.length > 1 && (
<TraceDetailTabsBarList
- tabs={[
- "preview",
- ...(showMessagesTab ? ["messages" as const] : []),
- ...(showLogViewTab ? ["log" as const] : []),
- ...(showScoresTab ? ["scores" as const] : []),
- ]}
+ tabs={tabs}
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. */
+ /* 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",
)}
>
- {/* Stays mounted so the row keeps its width; the virtualized log has no Raw view. */}
+ {/* Stays mounted so the row keeps its width; attributes and the virtualized log have no Beta view. */}
{selectedViewTab === "json" && (
<div
className={cn(
"flex items-center gap-1.5",
- selectedTab === "log" &&
- isLogViewVirtualized &&
+ (selectedTab === "attributes" ||
+ (selectedTab === "log" && isLogViewVirtualized)) &&
"invisible",
)}
>
@@ -436,7 +431,7 @@ function LoadedTraceDetailView({
currentView !== "json-beta" && "px-4",
)}
>
- {/* I/O Preview (includes metadata in both views) */}
+ {/* I/O Preview */}
<IOPreview
key={trace.id + "-io"}
input={trace.input ?? undefined}
@@ -472,7 +467,17 @@ function LoadedTraceDetailView({
)
}
advancedJsonExpansionState={advancedJsonExpansion}
- onAdvancedJsonExpansionChange={setAdvancedJsonExpansion}
+ onAdvancedJsonExpansionChange={(expansion) =>
+ setAdvancedJsonExpansion({
+ ...Object.fromEntries(
+ Object.entries(advancedJsonExpansion).filter(
+ ([path]) =>
+ path === "metadata" || path.startsWith("metadata."),
+ ),
+ ),
+ ...expansion,
+ })
+ }
jsonInputExpanded={jsonExpansion.input}
jsonOutputExpanded={jsonExpansion.output}
jsonMetadataExpanded={jsonExpansion.metadata}
@@ -495,7 +500,6 @@ function LoadedTraceDetailView({
})
}
commentedPathsByField={commentedPathsByField}
- showMetadata
onVirtualizationChange={setIsJSONBetaVirtualized}
projectId={projectId}
traceId={trace.id}
@@ -504,16 +508,75 @@ function LoadedTraceDetailView({
</div>
</Tabs.Content>
- {/* Log View tab content */}
- <Tabs.Content value="log" layout="fill">
- <TraceLogView
- traceId={trace.id}
- projectId={projectId}
- currentView={isLogViewVirtualized ? "pretty" : currentView}
- target="trace"
- />
+ <Tabs.Content value="attributes" layout="fill">
+ {currentView === "json-beta" ? (
+ <IOPreviewJSON
+ key={trace.id + "-metadata"}
+ metadata={trace.metadata ?? undefined}
+ parsedMetadata={parsedMetadata}
+ isParsing={isParsing}
+ media={traceMedia.data}
+ hideInput
+ hideOutput
+ showCorrections={false}
+ projectId={projectId}
+ traceId={trace.id}
+ expansionState={advancedJsonExpansion}
+ onExpansionChange={(expansion) =>
+ setAdvancedJsonExpansion({
+ ...Object.fromEntries(
+ Object.entries(advancedJsonExpansion).filter(
+ ([path]) =>
+ path !== "metadata" &&
+ !path.startsWith("metadata."),
+ ),
+ ),
+ ...expansion,
+ })
+ }
+ enableInlineComments
+ onAddInlineComment={(selection) =>
+ openDrawer({
+ type: "inline-comment",
+ selection,
+ objectId: trace.id,
+ objectType: "TRACE",
+ })
+ }
+ commentedPathsByField={commentedPathsByField}
+ />
+ ) : (
+ <DetailAttributesTab
+ metadata={trace.metadata}
+ parsedMetadata={parsedMetadata}
+ objectId={trace.id}
+ projectId={projectId}
+ currentView={selectedViewTab}
+ media={traceMedia.data}
+ metadataExpansionState={formattedExpansion.metadata}
+ onMetadataExpansionChange={(expansion) =>
+ setFormattedFieldExpansion("metadata", expansion)
+ }
+ jsonMetadataExpanded={jsonExpansion.metadata}
+ onJsonMetadataExpandedChange={(expanded) =>
+ setJsonFieldExpansion("metadata", expanded)
+ }
+ />
+ )}
</Tabs.Content>
+ {/* Log View tab content */}
+ {showLogViewTab && (
+ <Tabs.Content value="log" layout="fill">
+ <TraceLogView
+ traceId={trace.id}
+ projectId={projectId}
+ currentView={isLogViewVirtualized ? "pretty" : currentView}
+ target="trace"
+ />
+ </Tabs.Content>
+ )}
+
{/* Scores tab content */}
{showScoresTab && (
<Tabs.Content value="scores" layout="fill">
diff --git a/web/src/features/traces/constants/detailTabs.ts b/web/src/features/traces/constants/detailTabs.ts
new file mode 100644
index 0000000000..5cfcbe9e10
--- /dev/null
+++ b/web/src/features/traces/constants/detailTabs.ts
@@ -0,0 +1,9 @@
+export const DETAIL_TABS = [
+ "preview",
+ "messages",
+ "attributes",
+ "scores",
+ "log",
+] as const;
+
+export type DetailTab = (typeof DETAIL_TABS)[number];
diff --git a/web/src/features/traces/contexts/SelectionContext.tsx b/web/src/features/traces/contexts/SelectionContext.tsx
index c7ed9b6ea4..c2d666af59 100644
--- a/web/src/features/traces/contexts/SelectionContext.tsx
+++ b/web/src/features/traces/contexts/SelectionContext.tsx
@@ -5,7 +5,7 @@
* - Tracks selected node ID (synced to URL query param)
* - Manages collapsed/expanded state for tree nodes
* - Handles search query with debounced input
- * - Tracks selected tab (preview/log/scores) - synced to URL query param `traceTab`
+ * - Tracks selected detail tab - synced to URL query param `traceTab`
* - Tracks view preference (formatted/json) - synced to URL query param AND localStorage
*
* View Preference Behavior:
@@ -34,20 +34,8 @@ import {
type JsonViewPreference,
} from "@/src/components/ui/jsonViewPreference";
-// Valid tab values for detail view
-export type DetailTab =
- | "preview"
- | "attributes"
- | "log"
- | "scores"
- | "messages";
-const VALID_TABS: DetailTab[] = [
- "preview",
- "attributes",
- "log",
- "scores",
- "messages",
-];
+import { DETAIL_TABS, type DetailTab } from "../constants/detailTabs";
+export type { DetailTab } from "../constants/detailTabs";
const DEFAULT_TAB: DetailTab = "preview";
// Valid view preference values
@@ -102,7 +90,7 @@ export function SelectionProvider({ children }: SelectionProviderProps) {
const [searchQuery, setSearchQuery] = useState("");
// Validate and provide defaults for tab
- const selectedTab: DetailTab = VALID_TABS.includes(tabParam as DetailTab)
+ const selectedTab: DetailTab = DETAIL_TABS.includes(tabParam as DetailTab)
? (tabParam as DetailTab)
: DEFAULT_TAB;
diff --git a/web/src/features/traces/fns/getDetailTabs.ts b/web/src/features/traces/fns/getDetailTabs.ts
new file mode 100644
index 0000000000..275a266f14
--- /dev/null
+++ b/web/src/features/traces/fns/getDetailTabs.ts
@@ -0,0 +1,26 @@
+import { DETAIL_TABS, type DetailTab } from "../constants/detailTabs";
+
+export function getDetailTabs({
+ target,
+ isV4,
+ internalFeaturesEnabled,
+ isAnnotationMode,
+ hasObservations,
+ canViewScores,
+}: {
+ target: "trace" | "observation";
+ isV4: boolean;
+ internalFeaturesEnabled: boolean;
+ isAnnotationMode: boolean;
+ hasObservations: boolean;
+ canViewScores: boolean;
+}) {
+ const visibility: Record<DetailTab, boolean> = {
+ preview: true,
+ messages: isV4 && internalFeaturesEnabled,
+ attributes: true,
+ scores: canViewScores && !isAnnotationMode,
+ log: (target === "trace" || isV4) && hasObservations && !isAnnotationMode,
+ };
+ return DETAIL_TABS.filter((tab) => visibility[tab]);
+}
diff --git a/web/src/features/traces/fns/resolveDetailTab.ts b/web/src/features/traces/fns/resolveDetailTab.ts
new file mode 100644
index 0000000000..c450d3da04
--- /dev/null
+++ b/web/src/features/traces/fns/resolveDetailTab.ts
@@ -0,0 +1,5 @@
+import { type DetailTab } from "../constants/detailTabs";
+
+export function resolveDetailTab(tab: DetailTab, tabs: readonly DetailTab[]) {
+ return tabs.includes(tab) ? tab : "preview";
+}