Skip to content

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

feat(sessions): cleaner more compact view (#15190)

Nimar523f1663b67f
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.test.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.test.ts
index 0e9b93f5f2..aec8e22457 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.test.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.test.ts
@@ -2,10 +2,25 @@ import { describe, expect, it } from "vitest";
import {
buildEventsFullTableSplitQuery,
+ EventsAggregationQueryBuilder,
EventsQueryBuilder,
EventsSessionAggregationQueryBuilder,
} from "./event-query-builder";
+describe("EventsAggregationQueryBuilder", () => {
+ it("counts distinct non-synthetic observations per trace", () => {
+ const { query } = new EventsAggregationQueryBuilder({
+ projectId: "test-project",
+ })
+ .selectFieldSet("all")
+ .buildWithParams();
+
+ expect(query).toContain(
+ "length(groupUniqArrayIf(span_id, span_id <> '' AND span_id <> concat('t-', trace_id))) AS observation_count",
+ );
+ });
+});
+
describe("EventsSessionAggregationQueryBuilder", () => {
it("selects metadata arrays from the same deterministic latest observation", () => {
const { query } = new EventsSessionAggregationQueryBuilder({
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
index 564cd1af8d..e561dab66f 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
@@ -536,6 +536,8 @@ const EVENTS_AGGREGATION_FIELDS = {
"date_diff('millisecond', min(start_time), greatest(max(start_time), max(end_time))) AS latency_milliseconds",
observation_ids:
"groupUniqArrayIf(span_id, span_id <> '') AS observation_ids",
+ observation_count:
+ "length(groupUniqArrayIf(span_id, span_id <> '' AND span_id <> concat('t-', trace_id))) AS observation_count",
bookmarked:
"argMaxIf(bookmarked, event_ts, parent_span_id = '') AS bookmarked",
diff --git a/packages/shared/src/server/services/sessions-ui-table-events-service.ts b/packages/shared/src/server/services/sessions-ui-table-events-service.ts
index 15155ea7b7..207e5453ae 100644
--- a/packages/shared/src/server/services/sessions-ui-table-events-service.ts
+++ b/packages/shared/src/server/services/sessions-ui-table-events-service.ts
@@ -53,6 +53,7 @@ export type SessionTraceFromEvents = {
timestamp: Date;
environment: string | null;
userId: string | null;
+ observationCount: number;
};
export const getSessionTracesFromEvents = async (props: {
@@ -92,6 +93,7 @@ export const getSessionTracesFromEvents = async (props: {
timestamp: string;
environment: string | null;
user_id: string | null;
+ observation_count: number | string;
}>({
query,
params: input.params,
@@ -107,6 +109,7 @@ export const getSessionTracesFromEvents = async (props: {
timestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),
environment: row.environment,
userId: row.user_id,
+ observationCount: Number(row.observation_count),
}));
};
diff --git a/web/src/__tests__/server/userAccount.servertest.ts b/web/src/__tests__/server/userAccount.servertest.ts
index dedb09eee8..40d93fe09d 100644
--- a/web/src/__tests__/server/userAccount.servertest.ts
+++ b/web/src/__tests__/server/userAccount.servertest.ts
@@ -18,38 +18,42 @@ describe("userAccountRouter.setFeaturePreviewEnabled", () => {
(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
});
- it("enables the search bar preview, leaving other flags intact", async () => {
+ it("enables the Modern Session preview, leaving other flags intact", async () => {
const { caller, userId } = await createCaller({
featureFlags: ["templateFlag"],
});
const result = await caller.userAccount.setFeaturePreviewEnabled({
- flag: "searchBar",
+ flag: "modernSession",
enabled: true,
});
- expect(result).toEqual({ success: true, flag: "searchBar", enabled: true });
+ expect(result).toEqual({
+ success: true,
+ flag: "modernSession",
+ enabled: true,
+ });
const user = await prisma.user.findUniqueOrThrow({
where: { id: userId },
select: { featureFlags: true },
});
- expect(user.featureFlags).toEqual(["templateFlag", "searchBar"]);
+ expect(user.featureFlags).toEqual(["templateFlag", "modernSession"]);
});
it("disables a preview flag without touching the others", async () => {
const { caller, userId } = await createCaller({
- featureFlags: ["templateFlag", "searchBar"],
+ featureFlags: ["templateFlag", "modernSession"],
});
const result = await caller.userAccount.setFeaturePreviewEnabled({
- flag: "searchBar",
+ flag: "modernSession",
enabled: false,
});
expect(result).toEqual({
success: true,
- flag: "searchBar",
+ flag: "modernSession",
enabled: false,
});
@@ -66,7 +70,7 @@ describe("userAccountRouter.setFeaturePreviewEnabled", () => {
await expect(
caller.userAccount.setFeaturePreviewEnabled({
- flag: "searchBar",
+ flag: "modernSession",
enabled: true,
}),
).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });
@@ -146,6 +150,7 @@ async function createCaller({
},
],
featureFlags: {
+ modernSession: featureFlags.includes("modernSession"),
searchBar: featureFlags.includes("searchBar"),
templateFlag: featureFlags.includes("templateFlag"),
excludeClickhouseRead: false,
diff --git a/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx b/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx
index 95a3915b8b..4bcb90291d 100644
--- a/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx
+++ b/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx
@@ -113,8 +113,7 @@ export function AuthenticatedLayout({
}),
);
- // Currently there are no feature previews available
- const hasFeaturePreviews = false;
+ const hasFeaturePreviews = isLangfuseCloud;
// User navigation items for sidebar dropdown
const userNavProps = {
diff --git a/web/src/components/session/LazySessionTraceEventsRow.tsx b/web/src/components/session/LazySessionTraceEventsRow.tsx
index 312a78f41a..640f1aa01b 100644
--- a/web/src/components/session/LazySessionTraceEventsRow.tsx
+++ b/web/src/components/session/LazySessionTraceEventsRow.tsx
@@ -2,10 +2,12 @@ import React from "react";
import {
TraceEventsRow,
TraceEventsSkeleton,
+ type TraceEventsSurface,
} from "@/src/components/session/TraceEventsRow";
import { useSessionDetailStore } from "@/src/components/session/SessionDetailStoreProvider";
import { type RouterOutputs } from "@/src/utils/api";
import { type FilterState } from "@langfuse/shared";
+import { type IOPreviewContentMode } from "@/src/components/trace/components/IOPreview/IOPreview";
type LazySessionTraceEventsRowProps = {
trace: RouterOutputs["sessions"]["tracesFromEvents"][number];
@@ -17,6 +19,10 @@ type LazySessionTraceEventsRowProps = {
filterState: FilterState;
viewLabel: string | null;
hideTracePanel?: boolean;
+ surface?: TraceEventsSurface;
+ contentMode?: IOPreviewContentMode;
+ showSystemPrompt?: boolean;
+ isActive?: boolean;
};
const LazySessionTraceEventsRowInner = (
@@ -43,10 +49,20 @@ const LazySessionTraceEventsRowInner = (
internalRef.current = node;
}, []);
+ const isModern = props.surface === "modern";
+
return (
- <div ref={setRowRef} className="pb-3" data-session-row-index={index}>
+ <div
+ ref={setRowRef}
+ className={isModern ? undefined : "pb-3"}
+ data-session-row-index={index}
+ >
{shouldLoad ? (
<TraceEventsRow {...rowProps} showCorrections={showCorrections} />
+ ) : isModern ? (
+ <div className="flex h-80 items-center justify-center px-6 py-8">
+ <TraceEventsSkeleton />
+ </div>
) : (
<TraceEventsSkeleton />
)}
diff --git a/web/src/components/session/ModernSession.tsx b/web/src/components/session/ModernSession.tsx
new file mode 100644
index 0000000000..6964b1a4c2
--- /dev/null
+++ b/web/src/components/session/ModernSession.tsx
@@ -0,0 +1,328 @@
+import React, { useCallback, useRef, useState } from "react";
+import { useVirtualizer } from "@tanstack/react-virtual";
+import { type FilterState } from "@langfuse/shared";
+
+import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
+import { ItemBadge } from "@/src/components/ItemBadge";
+import { LazySessionTraceEventsRow } from "@/src/components/session/LazySessionTraceEventsRow";
+import { SessionVirtualizedRow } from "@/src/components/session/SessionVirtualizedRow";
+import { SessionTraceActionButtons } from "@/src/components/session/SessionTraceActionButtons";
+import { type EventSessionTrace } from "@/src/components/session/sessionDetailPageTypes";
+import { cn } from "@/src/utils/tailwind";
+import { usdFormatter } from "@/src/utils/numbers";
+
+const MODERN_SESSION_OVERSCAN = 5;
+
+type OpenPeek = (id: string, row: any) => void;
+
+type ModernSessionProps = {
+ traces: EventSessionTrace[];
+ projectId: string;
+ sessionId: string;
+ openPeek: OpenPeek;
+ traceCommentCounts: Map<string, number> | undefined;
+ filterState: FilterState;
+ filterMeasurementKey: string;
+ viewLabel: string | null;
+ totalCost: number;
+ showInlineToolCalls: boolean;
+ showSystemPrompt: boolean;
+};
+
+const ModernSessionMinimapItem = React.memo(
+ ({
+ trace,
+ index,
+ isActive,
+ projectId,
+ traceCommentCounts,
+ openPeek,
+ onSelect,
+ }: {
+ trace: EventSessionTrace;
+ index: number;
+ isActive: boolean;
+ projectId: string;
+ traceCommentCounts: Map<string, number> | undefined;
+ openPeek: OpenPeek;
+ onSelect: (index: number) => void;
+ }) => {
+ const observationCount = trace.observationCount ?? 0;
+ const observationLabel = `${observationCount} observation${observationCount === 1 ? "" : "s"}`;
+
+ return (
+ <div
+ className={cn(
+ "group relative border-b border-l-2 transition-colors",
+ isActive
+ ? "border-l-primary bg-accent/60"
+ : "hover:bg-muted/60 border-l-transparent",
+ )}
+ data-modern-session-minimap-active={isActive}
+ >
+ <button
+ type="button"
+ className="flex w-full min-w-0 flex-col gap-1.5 px-3 py-3 text-left"
+ onClick={() =>
+ isActive ? openPeek(trace.id, trace) : onSelect(index)
+ }
+ aria-current={isActive ? "true" : undefined}
+ >
+ <span className="flex min-w-0 items-center gap-1.5">
+ <ItemBadge type="TRACE" isSmall />
+ <span
+ className="min-w-0 flex-1 truncate text-xs font-bold"
+ title={trace.name ?? "Trace"}
+ >
+ {trace.name ?? "Trace"}
+ </span>
+ </span>
+ <time className="text-muted-foreground text-xs">
+ {trace.timestamp.toLocaleString()}
+ </time>
+ <span
+ className="text-muted-foreground truncate font-mono text-[11px]"
+ title={trace.id}
+ >
+ {trace.id}
+ </span>
+ <span className="text-muted-foreground flex flex-wrap items-center gap-1 text-xs">
+ <span>{observationLabel}</span>
+ <span>·</span>
+ {trace.scores.length > 0 ? (
+ <span>{trace.scores.length} scores</span>
+ ) : (
+ <span>no scores</span>
+ )}
+ </span>
+ {isActive && trace.scores.length > 0 ? (
+ <span className="flex max-h-10 flex-wrap gap-1 overflow-hidden">
+ <GroupedScoreBadges scores={trace.scores} />
+ </span>
+ ) : null}
+ </button>
+
+ {isActive ? (
+ <div
+ className="px-3 pb-2"
+ onClick={(event) => event.stopPropagation()}
+ >
+ <SessionTraceActionButtons
+ projectId={projectId}
+ traceId={trace.id}
+ timestamp={trace.timestamp}
+ environment={trace.environment}
+ scores={trace.scores}
+ traceCommentCounts={traceCommentCounts}
+ density="compact"
+ className="gap-1"
+ />
+ </div>
+ ) : null}
+ </div>
+ );
+ },
+);
+ModernSessionMinimapItem.displayName = "ModernSessionMinimapItem";
+
+const ModernSessionMinimap = React.memo(
+ ({
+ traces,
+ activeTraceId,
+ projectId,
+ traceCommentCounts,
+ openPeek,
+ onSelect,
+ totalCost,
+ }: {
+ traces: EventSessionTrace[];
+ activeTraceId: string | undefined;
+ projectId: string;
+ traceCommentCounts: Map<string, number> | undefined;
+ openPeek: OpenPeek;
+ onSelect: (index: number) => void;
+ totalCost: number;
+ }) => {
+ const minimapRef = useRef<HTMLDivElement>(null);
+ const virtualizer = useVirtualizer({
+ count: traces.length,
+ getScrollElement: () => minimapRef.current,
+ estimateSize: () => 105,
+ overscan: MODERN_SESSION_OVERSCAN,
+ getItemKey: (index) => traces[index]?.id ?? index,
+ });
+
+ return (
+ <div
+ ref={minimapRef}
+ role="complementary"
+ aria-label="Session traces"
+ className="bg-muted/10 min-h-0 overflow-y-auto border-r"
+ >
+ <div className="bg-background sticky top-0 z-10 flex items-center justify-between gap-2 border-b px-3 py-2">
+ <span className="text-muted-foreground text-xs font-bold tracking-wide uppercase">
+ Traces · {traces.length}
+ </span>
+ <span className="text-muted-foreground text-xs font-bold">
+ Total cost · {usdFormatter(totalCost, 2)}
+ </span>
+ </div>
+ <div
+ style={{
+ height: `${virtualizer.getTotalSize()}px`,
+ position: "relative",
+ width: "100%",
+ }}
+ >
+ {virtualizer.getVirtualItems().map((virtualItem) => {
+ const trace = traces[virtualItem.index];
+ if (!trace) return null;
+ const isActive = trace.id === activeTraceId;
+
+ return (
+ <SessionVirtualizedRow
+ key={virtualItem.key}
+ itemKey={String(virtualItem.key)}
+ measurementKey={`${String(virtualItem.key)}:${isActive}`}
+ source="modern"
+ virtualItem={virtualItem}
+ virtualizer={virtualizer}
+ >
+ <ModernSessionMinimapItem
+ trace={trace}
+ index={virtualItem.index}
+ isActive={isActive}
+ projectId={projectId}
+ traceCommentCounts={traceCommentCounts}
+ openPeek={openPeek}
+ onSelect={onSelect}
+ />
+ </SessionVirtualizedRow>
+ );
+ })}
+ </div>
+ </div>
+ );
+ },
+);
+ModernSessionMinimap.displayName = "ModernSessionMinimap";
+
+export function ModernSession({
+ traces,
+ projectId,
+ sessionId,
+ openPeek,
+ traceCommentCounts,
+ filterState,
+ filterMeasurementKey,
+ viewLabel,
+ totalCost,
+ showInlineToolCalls,
+ showSystemPrompt,
+}: ModernSessionProps) {
+ const feedRef = useRef<HTMLDivElement>(null);
+ const [selectedTraceId, setSelectedTraceId] = useState<string>();
+ const virtualizer = useVirtualizer({
+ count: traces.length,
+ getScrollElement: () => feedRef.current,
+ estimateSize: () => 520,
+ overscan: MODERN_SESSION_OVERSCAN,
+ getItemKey: (index) => traces[index]?.id ?? index,
+ });
+ const virtualItems = virtualizer.getVirtualItems();
+ const scrollOffset = virtualizer.scrollOffset ?? 0;
+ const activeVirtualItem =
+ virtualItems.find(
+ (item) => item.start <= scrollOffset + 1 && item.end > scrollOffset + 1,
+ ) ?? virtualItems.find((item) => item.start > scrollOffset);
+ const scrollSpyTraceId =
+ traces[activeVirtualItem?.index ?? 0]?.id ?? traces[0]?.id;
+ const activeTraceId = selectedTraceId ?? scrollSpyTraceId;
+
+ const scrollToTrace = useCallback(
+ (index: number) => {
+ const feed = feedRef.current;
+ const offset = virtualizer.getOffsetForIndex(index, "start")?.[0];
+ if (!feed || offset === undefined) return;
+ // TanStack retries smooth scrolls against dynamic row measurements and
+ // can stop one row early. Native scrolling uses its measured target once
+ // and preserves the requested smooth minimap navigation.
+ feed.scrollTo({ top: offset, behavior: "smooth" });
+ },
+ [virtualizer],
+ );
+
+ const selectTrace = useCallback(
+ (index: number) => {
+ const trace = traces[index];
+ if (!trace) return;
+ setSelectedTraceId(trace.id);
+ scrollToTrace(index);
+ },
+ [scrollToTrace, traces],
+ );
+
+ const restoreScrollSpy = () => setSelectedTraceId(undefined);
+
+ return (
+ <div className="grid min-h-0 flex-1 grid-rows-[minmax(10rem,13rem)_minmax(0,1fr)] overflow-hidden lg:grid-cols-[300px_minmax(0,1fr)] lg:grid-rows-1">
+ <ModernSessionMinimap
+ traces={traces}
+ activeTraceId={activeTraceId}
+ projectId={projectId}
+ traceCommentCounts={traceCommentCounts}
+ openPeek={openPeek}
+ onSelect={selectTrace}
+ totalCost={totalCost}
+ />
+ <div
+ ref={feedRef}
+ className="min-h-0 overflow-y-auto scroll-smooth"
+ onWheel={restoreScrollSpy}
+ onTouchMove={restoreScrollSpy}
+ onPointerDown={(event) => {
+ if (event.target === event.currentTarget) restoreScrollSpy();
+ }}
+ >
+ <div
+ style={{
+ height: `${virtualizer.getTotalSize()}px`,
+ width: "100%",
+ position: "relative",
+ }}
+ >
+ {virtualItems.map((virtualItem) => {
+ const trace = traces[virtualItem.index];
+ if (!trace) return null;
+
+ return (
+ <SessionVirtualizedRow
+ key={virtualItem.key}
+ itemKey={String(virtualItem.key)}
+ measurementKey={`${String(virtualItem.key)}:${showInlineToolCalls}:${showSystemPrompt}:${filterMeasurementKey}`}
+ source="modern"
+ virtualItem={virtualItem}
+ virtualizer={virtualizer}
+ >
+ <LazySessionTraceEventsRow
+ trace={trace}
+ projectId={projectId}
+ sessionId={sessionId}
+ openPeek={openPeek}
+ traceCommentCounts={traceCommentCounts}
+ index={virtualItem.index}
+ filterState={filterState}
+ viewLabel={viewLabel}
+ surface="modern"
+ contentMode={showInlineToolCalls ? "all" : "conversation"}
+ showSystemPrompt={showSystemPrompt}
+ isActive={trace.id === activeTraceId}
+ />
+ </SessionVirtualizedRow>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/components/session/NewDatasetItemFromTrace.tsx b/web/src/components/session/NewDatasetItemFromTrace.tsx
index 14e91770f5..491580bdf6 100644
--- a/web/src/components/session/NewDatasetItemFromTrace.tsx
+++ b/web/src/components/session/NewDatasetItemFromTrace.tsx
@@ -7,6 +7,7 @@ export const NewDatasetItemFromTraceId = (props: {
traceId: string;
timestamp: Date;
buttonVariant?: ButtonProps["variant"];
+ size?: ButtonProps["size"];
}) => {
// SessionIO already fetches the trace, so this doesn't add an extra request
const trace = api.traces.byId.useQuery(
@@ -36,6 +37,7 @@ export const NewDatasetItemFromTraceId = (props: {
output={trace.data.output ?? null}
metadata={trace.data.metadata ?? null}
buttonVariant={props.buttonVariant}
+ size={props.size}
/>
);
};
diff --git a/web/src/components/session/README.md b/web/src/components/session/README.md
new file mode 100644
index 0000000000..272cc24033
--- /dev/null
+++ b/web/src/components/session/README.md
@@ -0,0 +1,34 @@
+# Session detail ownership
+
+`index.tsx` owns session queries, header actions, filters, saved views, and the
+feature-flagged choice between the existing card layout and Modern Session.
+
+## Render boundaries
+
+- `TraceRow.tsx`: legacy trace card and lazy-load boundary.
+- `TraceEventsRow.tsx`: events-backed trace content for card and Modern Session
+ feed surfaces.
+- `ModernSession.tsx`: minimap, scroll-spy derivation, smooth navigation, and
+ the continuous virtualized feed.
+- `SessionVirtualizedRow.tsx` + `useStableVirtualRowMeasurement.ts`: translated
+ DOM-safe dynamic row measurement.
+- `SessionObservationIO.tsx`: bounded observation payload rendering and the
+ bridge into `IOPreview` full/conversation modes.
+
+Modern Session prepares each events-backed observation once inside its narrow
+row container and passes the parsed I/O plus ChatML result through `IOPreview`.
+The existing card surface keeps its lazy parser path.
+
+## State
+
+`sessionDetailStore.ts` is a per-page store. It owns loaded trace IDs,
+correction visibility, inline-tool visibility, and system-prompt visibility so
+virtual row remounts do not reset view state. On the events-backed session
+page, `modernSession` is a user Feature Preview flag; disabled users retain the
+card layout without a page-level layout control. The preview toggle is disabled
+unless Fast (Preview) selects this events-backed page.
+
+Server/query state remains in tRPC and React Query. Active Modern Session state
+is derived from TanStack Virtual's current scroll offset unless the user
+explicitly selects a minimap item that cannot reach the feed's top edge. User
+scrolling restores scroll-spy ownership; no effect mirrors either state.
diff --git a/web/src/components/session/SessionObservationIO.tsx b/web/src/components/session/SessionObservationIO.tsx
index c12fbfe951..ff367f1b89 100644
--- a/web/src/components/session/SessionObservationIO.tsx
+++ b/web/src/components/session/SessionObservationIO.tsx
@@ -1,12 +1,17 @@
import React from "react";
import { Download, ExternalLinkIcon, Loader2 } from "lucide-react";
import { Button } from "@/src/components/ui/button";
-import { IOPreview } from "@/src/components/trace/components/IOPreview/IOPreview";
+import {
+ IOPreview,
+ type IOPreviewContentMode,
+ type ViewMode,
+} from "@/src/components/trace/components/IOPreview/IOPreview";
import { api, type RouterOutputs } from "@/src/utils/api";
import { downloadJsonFile } from "@/src/components/session/actions/downloadSessionAsJson";
import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { compactNumberFormatter } from "@/src/utils/numbers";
+import { type ChatMLParserResult } from "@/src/components/trace/components/IOPreview/hooks/useChatMLParser";
export type SessionTraceObservation =
RouterOutputs["sessions"]["observationsForTraceFromEvents"][number];
@@ -74,6 +79,13 @@ export const SessionObservationIO = ({
environment,
showCorrections,
onOpenInTraceView,
+ contentMode = "all",
+ showSystemPrompt,
+ currentView,
+ parsedInput,
+ parsedOutput,
+ parsedMetadata,
+ chatMLParserResult,
}: {
observation: SessionTraceObservation;
projectId: string;
@@ -82,6 +94,13 @@ export const SessionObservationIO = ({
environment?: string;
showCorrections: boolean;
onOpenInTraceView: (observationId: string) => void;
+ contentMode?: IOPreviewContentMode;
+ showSystemPrompt?: boolean;
+ currentView?: ViewMode;
+ parsedInput?: unknown;
+ parsedOutput?: unknown;
+ parsedMetadata?: unknown;
+ chatMLParserResult?: ChatMLParserResult;
}) => {
const capture = usePostHogClientCapture();
const utils = api.useUtils();
@@ -132,21 +151,32 @@ export const SessionObservationIO = ({
onOpenInTraceView(observation.id);
};
+ const ioPreview = (
+ <IOPreview
+ input={observation.input ?? undefined}
+ output={observation.output ?? undefined}
+ metadata={observation.metadata ?? undefined}
+ observationName={observation.name ?? undefined}
+ hideIfNull
+ projectId={projectId}
+ traceId={traceId}
+ observationId={observation.id}
+ environment={environment}
+ showCorrections={showCorrections}
+ contentMode={contentMode}
+ showSystemPrompt={showSystemPrompt}
+ currentView={currentView}
+ parsedInput={parsedInput}
+ parsedOutput={parsedOutput}
+ parsedMetadata={parsedMetadata}
+ chatMLParserResult={chatMLParserResult}
+ />
+ );
+
if (!isIOTruncated) {
return (
<>
- <IOPreview
- input={observation.input ?? undefined}
- output={observation.output ?? undefined}
- metadata={observation.metadata ?? undefined}
- observationName={observation.name ?? undefined}
- hideIfNull
- projectId={projectId}
- traceId={traceId}
- observationId={observation.id}
- environment={environment}
- showCorrections={showCorrections}
- />
+ {ioPreview}
{observation.metadataTruncated && (
<p className="text-muted-foreground text-xs">
Some metadata values are too large to show here.{" "}
diff --git a/web/src/components/session/SessionTraceActionButtons.tsx b/web/src/components/session/SessionTraceActionButtons.tsx
new file mode 100644
index 0000000000..6e3cbecdff
--- /dev/null
+++ b/web/src/components/session/SessionTraceActionButtons.tsx
@@ -0,0 +1,80 @@
+import { type RouterOutputs } from "@/src/utils/api";
+import { getNumberFromMap } from "@/src/utils/map-utils";
+import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";
+import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
+import { NewDatasetItemFromTraceId } from "@/src/components/session/NewDatasetItemFromTrace";
+import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";
+import { cn } from "@/src/utils/tailwind";
+
+type TraceScores =
+ RouterOutputs["sessions"]["byIdWithScores"]["traces"][number]["scores"];
+
+export function SessionTraceActionButtons({
+ projectId,
+ traceId,
+ timestamp,
+ environment,
+ scores,
+ traceCommentCounts,
+ density = "default",
+ className,
+}: {
+ projectId: string;
+ traceId: string;
+ timestamp: Date;
+ environment?: string | null;
+ scores: TraceScores;
+ traceCommentCounts: Map<string, number> | undefined;
+ density?: "default" | "compact";
+ className?: string;
+}) {
+ const size = density === "compact" ? "xs" : "default";
+
+ return (
+ <div className={cn("flex flex-wrap items-start gap-2", className)}>
+ <NewDatasetItemFromTraceId
+ projectId={projectId}
+ traceId={traceId}
+ timestamp={timestamp}
+ buttonVariant="outline"
+ size={size}
+ />
+ <div className="flex items-start">
+ <AnnotateDrawer
+ key={`annotation-drawer-${traceId}`}
+ projectId={projectId}
+ scoreTarget={{
+ type: "trace",
+ traceId,
+ }}
+ scores={scores}
+ buttonVariant="outline"
+ size={size}
+ analyticsData={{
+ type: "trace",
+ source: "SessionDetail",
+ }}
+ scoreMetadata={{
+ projectId,
+ environment: environment ?? undefined,
+ }}
+ />
+ <CreateNewAnnotationQueueItem
+ projectId={projectId}
+ objectId={traceId}
+ objectType="TRACE"
+ variant="outline"
+ size={size}
+ />
+ </div>
+ <CommentDrawerButton
+ projectId={projectId}
+ variant="outline"
+ objectId={traceId}
+ objectType="TRACE"
+ count={getNumberFromMap(traceCommentCounts, traceId)}
+ size={size}
+ />
+ </div>
+ );
+}
diff --git a/web/src/components/session/SessionVirtualizedRow.tsx b/web/src/components/session/SessionVirtualizedRow.tsx
index 24a21d9108..142a9b46bf 100644
--- a/web/src/components/session/SessionVirtualizedRow.tsx
+++ b/web/src/components/session/SessionVirtualizedRow.tsx
@@ -13,7 +13,7 @@ export function SessionVirtualizedRow({
children: ReactNode;
itemKey: string | number;
measurementKey?: string | number;
- source: "legacy" | "events";
+ source: "legacy" | "events" | "modern";
virtualItem: VirtualItem;
virtualizer: Virtualizer<HTMLDivElement, Element>;
}) {
@@ -31,10 +31,14 @@ export function SessionVirtualizedRow({
data-session-virtualizer-row={source}
style={{
position: "absolute",
- top: 0,
+ // Transforms offset sticky descendants from their actual row position.
+ top: source === "modern" ? virtualItem.start : 0,
left: 0,
width: "100%",
- transform: `translateY(${virtualItem.start}px)`,
+ transform:
+ source === "modern"
+ ? undefined
+ : `translateY(${virtualItem.start}px)`,
}}
>
{children}
diff --git a/web/src/components/session/TraceEventsRow.tsx b/web/src/components/session/TraceEventsRow.tsx
index 0004d88de8..fb6c04e3d9 100644
--- a/web/src/components/session/TraceEventsRow.tsx
+++ b/web/src/components/session/TraceEventsRow.tsx
@@ -2,20 +2,24 @@ import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
import { JsonSkeleton } from "@/src/components/ui/CodeJsonViewer";
import { Card } from "@/src/components/ui/card";
import { type RouterOutputs } from "@/src/utils/api";
-import { getNumberFromMap } from "@/src/utils/map-utils";
import Link from "next/link";
import React from "react";
-import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";
-import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
import { ItemBadge } from "@/src/components/ItemBadge";
-import { NewDatasetItemFromTraceId } from "@/src/components/session/NewDatasetItemFromTrace";
-import { type FilterState } from "@langfuse/shared";
-import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";
+import { deepParseJson, type FilterState } from "@langfuse/shared";
import { SessionObservationIO } from "@/src/components/session/SessionObservationIO";
import { api } from "@/src/utils/api";
import { FilterX } from "lucide-react";
import isEqual from "lodash/isEqual";
import { SESSION_DETAIL_VIEW_TRIGGER_ID } from "@/src/components/session/session-detail-presets";
+import { SessionTraceActionButtons } from "@/src/components/session/SessionTraceActionButtons";
+import { type IOPreviewContentMode } from "@/src/components/trace/components/IOPreview/IOPreview";
+import { useChatMLParser } from "@/src/components/trace/components/IOPreview/hooks/useChatMLParser";
+import {
+ hasRenderableConversationMessages,
+ isOnlyJsonMessage,
+} from "@/src/components/trace/components/IOPreview/components/chat-message-utils";
+
+export type TraceEventsSurface = "card" | "modern";
// Display copy for the per-card observation cap; the authoritative limit is
// SESSION_OBSERVATIONS_PER_TRACE_LIMIT in the sessions router (LFE-10958).
@@ -31,6 +35,121 @@ const observationHasIO = (observation: {
output?: unknown;
}): boolean => hasContent(observation.input) || hasContent(observation.output);
+type SessionObservation =
+ RouterOutputs["sessions"]["observationsForTraceFromEvents"][number];
+
+const ModernSessionObservation = ({
+ observation,
+ projectId,
+ sessionId,
+ traceId,
+ environment,
+ showCorrections,
+ contentMode,
+ showSystemPrompt,
+ onOpenInTraceView,
+}: {
+ observation: SessionObservation;
+ projectId: string;
+ sessionId: string;
+ traceId: string;
+ environment?: string;
+ showCorrections: boolean;
+ contentMode: IOPreviewContentMode;
+ showSystemPrompt?: boolean;
+ onOpenInTraceView: (observationId: string) => void;
+}) => {
+ const parsed = React.useMemo(
+ () => ({
+ input: deepParseJson(observation.input, {
+ maxSize: 300_000,
+ maxDepth: 2,
+ }),
+ output: deepParseJson(observation.output, {
+ maxSize: 300_000,
+ maxDepth: 2,
+ }),
+ metadata: deepParseJson(observation.metadata, {
+ maxSize: 100_000,
+ maxDepth: 2,
+ }),
+ }),
+ [observation.input, observation.output, observation.metadata],
+ );
+ const chatMLParserResult = useChatMLParser(
+ observation.input ?? undefined,
+ observation.output ?? undefined,
+ observation.metadata ?? undefined,
+ observation.name ?? undefined,
+ parsed.input,
+ parsed.output,
+ parsed.metadata,
+ );
+ const isConversation =
+ chatMLParserResult.canDisplayAsChat &&
+ (contentMode === "conversation"
+ ? hasRenderableConversationMessages(
+ chatMLParserResult.allMessages,
+ showSystemPrompt,
+ )
+ : !chatMLParserResult.allMessages.every(isOnlyJsonMessage));
+
+ return (
+ <div
+ className={
+ isConversation
+ ? "flex flex-col gap-2"
+ : "bg-muted/20 flex flex-col gap-2 rounded-md border p-3"
+ }
+ >
+ {!isConversation ? <ObservationHeader observation={observation} /> : null}
+ <SessionObservationIO
+ observation={observation}
+ projectId={projectId}
+ sessionId={sessionId}
+ traceId={traceId}
+ environment={environment}
+ showCorrections={showCorrections}
+ onOpenInTraceView={onOpenInTraceView}
+ contentMode={isConversation ? contentMode : "all"}
+ showSystemPrompt={showSystemPrompt}
+ currentView={isConversation ? "pretty" : undefined}
+ parsedInput={parsed.input}
+ parsedOutput={parsed.output}
+ parsedMetadata={parsed.metadata}
+ chatMLParserResult={chatMLParserResult}
+ />
+ </div>
+ );
+};
+
+const ObservationHeader = ({
+ observation,
+}: {
+ observation: SessionObservation;
+}) => (
+ <div className="text-muted-foreground flex flex-wrap items-center gap-2 text-xs">
+ <span className="min-w-0 wrap-break-word">
+ {observation.name ?? "Observation"}
+ </span>
+ <span className="-mr-1">•</span>
+ <span className="inline-flex items-center gap-1">
+ <ItemBadge
+ type={observation.type ?? "EVENT"}
+ isSmall
+ className="h-3 w-3"
+ />
+ <span>
+ {String(observation.type ?? "EVENT")
+ .toLowerCase()
+ .replace(/_/g, " ")}
+ </span>
+ </span>
+ <span>•</span>
+ <span>{observation.startTime.toLocaleString()}</span>
+ </div>
+);
+
// Opens the session-detail "View" drawer by activating its trigger — the empty
// notice's action routes through the one shared View control (no per-card state).
const openSessionViewMenu = () => {
@@ -90,6 +209,10 @@ type LazyTraceEventsRowProps = {
/** Selected view's display name, for the empty-state notice (null = custom). */
viewLabel: string | null;
hideTracePanel?: boolean;
+ surface?: TraceEventsSurface;
+ contentMode?: IOPreviewContentMode;
+ showSystemPrompt?: boolean;
+ isActive?: boolean;
};
const areLazyTraceEventsRowPropsEqual = (
@@ -105,7 +228,11 @@ const areLazyTraceEventsRowPropsEqual = (
previous.showCorrections === next.showCorrections &&
previous.filterState === next.filterState &&
previous.viewLabel === next.viewLabel &&
- previous.hideTracePanel === next.hideTracePanel;
+ previous.hideTracePanel === next.hideTracePanel &&
+ previous.surface === next.surface &&
+ previous.contentMode === next.contentMode &&
+ previous.showSystemPrompt === next.showSystemPrompt &&
+ previous.isActive === next.isActive;
export const TraceEventsRow = React.memo(
({
@@ -118,6 +245,10 @@ export const TraceEventsRow = React.memo(
filterState,
viewLabel,
hideTracePanel = false,
+ surface = "card",
+ contentMode = "all",
+ showSystemPrompt,
+ isActive = false,
}: {
trace: RouterOutputs["sessions"]["tracesFromEvents"][number];
projectId: string;
@@ -128,6 +259,10 @@ export const TraceEventsRow = React.memo(
filterState: FilterState;
viewLabel: string | null;
hideTracePanel?: boolean;
+ surface?: TraceEventsSurface;
+ contentMode?: IOPreviewContentMode;
+ showSystemPrompt?: boolean;
+ isActive?: boolean;
}) => {
const observationsQuery =
api.sessions.observationsForTraceFromEvents.useQuery(
@@ -240,16 +375,61 @@ export const TraceEventsRow = React.memo(
return { visibleObservations, hasMoreObservations };
}, [observations, trace.id]);
+ const Frame = surface === "card" ? Card : "div";
+ const showTracePanel = surface === "card" && !hideTracePanel;
+
return (
- <Card className="border-border shadow-none">
+ <Frame
+ className={
+ surface === "card"
+ ? "border-border shadow-none"
+ : isActive
+ ? "bg-background border-l-primary border-l-2"
+ : "bg-background border-l-2 border-l-transparent"
+ }
+ data-modern-session-active={surface === "modern" && isActive}
+ >
<div
className={
- hideTracePanel
- ? "grid"
+ !showTracePanel
+ ? "grid min-w-0"
: "grid md:grid-cols-[1fr_1px_358px] lg:grid-cols-[1fr_1px_30rem]"
}
>
- <div className="overflow-hidden py-4 pr-4 pl-4">
+ <div
+ className={
+ surface === "card"
+ ? "overflow-hidden py-4 pr-4 pl-4"
+ : "min-w-0 px-6 pb-10"
+ }
+ >
+ {surface === "modern" ? (
+ <div className="bg-background/95 sticky top-0 z-10 -mx-6 mb-5 flex min-w-0 items-center justify-between gap-3 px-6 py-3 backdrop-blur">
+ <button
+ type="button"
+ aria-label={`Open trace ${trace.name ?? "Trace"} (${trace.id})`}
+ className="group focus-visible:ring-ring flex min-w-0 items-center gap-2 rounded-sm text-left focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none"
+ onClick={() => openPeek(trace.id, trace)}
+ >
+ <ItemBadge type="TRACE" isSmall />
+ <span
+ className="truncate text-sm font-bold"
+ title={trace.name ?? "Trace"}
+ >
+ {trace.name ?? "Trace"}
+ </span>
+ <span
+ className="text-muted-foreground min-w-0 truncate font-mono text-xs group-hover:underline"
+ title={trace.id}
+ >
+ {trace.id}
+ </span>
+ </button>
+ <time className="text-muted-foreground shrink-0 text-xs">
+ {trace.timestamp.toLocaleString()}
+ </time>
+ </div>
+ ) : null}
{observationsQuery.isLoading ? (
<JsonSkeleton className="h-full w-full" numRows={8} />
) : observationsQuery.isError ? (
@@ -258,45 +438,49 @@ export const TraceEventsRow = React.memo(
</div>
) : visibleObservations && visibleObservations.length > 0 ? (
<div className="flex flex-col gap-4">
- {visibleObservations.map((observation) => (
- <div key={observation.id} className="flex flex-col gap-2">
- <div className="text-muted-foreground flex flex-wrap items-center gap-2 text-xs">
- {/* min-w-0 + wrap-break-word: unbroken long names must
- wrap inside the card, not escape it */}
- <span className="min-w-0 wrap-break-word">
- {observation.name ?? "Observation"}
- </span>
- <span className="-mr-1">•</span>
- <span className="inline-flex items-center gap-1">
- <ItemBadge
- type={observation.type ?? "EVENT"}
- isSmall
- className="h-3 w-3"
- />
- <span>
- {String(observation.type ?? "EVENT")
- .toLowerCase()
- .replace(/_/g, " ")}
- </span>
- </span>
- <span>•</span>
- <span>{observation.startTime.toLocaleString()}</span>
+ {visibleObservations.map((observation) => {
+ if (surface === "modern") {
+ return (
+ <ModernSessionObservation
+ key={observation.id}
+ observation={observation}
+ projectId={projectId}
+ sessionId={sessionId}
+ traceId={trace.id}
+ environment={
+ observation.environment ??
+ trace.environment ??
+ undefined
+ }
+ showCorrections={showCorrections}
+ contentMode={contentMode}
+ showSystemPrompt={showSystemPrompt}
+ onOpenInTraceView={openObservationInTraceView}
+ />
+ );
+ }
+
+ return (
+ <div key={observation.id} className="flex flex-col gap-2">
+ <ObservationHeader observation={observation} />
+ <SessionObservationIO
+ observation={observation}
+ projectId={projectId}
+ sessionId={sessionId}
+ traceId={trace.id}
+ environment={
+ observation.environment ??
+ trace.environment ??
+ undefined
+ }
+ showCorrections={showCorrections}
+ onOpenInTraceView={openObservationInTraceView}
+ contentMode={contentMode}
+ showSystemPrompt={showSystemPrompt}
+ />
</div>
- <SessionObservationIO
- observation={observation}
- projectId={projectId}
- sessionId={sessionId}
- traceId={trace.id}
- environment={
- observation.environment ??
- trace.environment ??
- undefined
- }
- showCorrections={showCorrections}
- onOpenInTraceView={openObservationInTraceView}
- />
- </div>
- ))}
+ );
+ })}
{hasMoreObservations && (
<p className="text-muted-foreground text-xs">
Only the first {SESSION_CARD_OBSERVATIONS_NOTICE_COUNT}{" "}
@@ -325,7 +509,7 @@ export const TraceEventsRow = React.memo(
<ViewMismatchNotice viewLabel={viewLabel} />
)}
</div>
- {!hideTracePanel && (
+ {showTracePanel && (
<>
<div className="bg-border hidden md:block"></div>
<div className="flex flex-col border-t py-4 pr-4 pl-4 md:border-0">
@@ -352,47 +536,14 @@ export const TraceEventsRow = React.memo(
</span>
</div>
</Link>
- <div className="flex flex-wrap gap-2">
- <NewDatasetItemFromTraceId
- projectId={projectId}
- traceId={trace.id}
- timestamp={new Date(trace.timestamp)}
- buttonVariant="outline"
- />
- <div className="flex items-start">
- <AnnotateDrawer
- key={"annotation-drawer" + trace.id}
- projectId={projectId}
- scoreTarget={{
- type: "trace",
- traceId: trace.id,
- }}
- scores={trace.scores}
- buttonVariant="outline"
- analyticsData={{
- type: "trace",
- source: "SessionDetail",
- }}
- scoreMetadata={{
- projectId: projectId,
- environment: trace.environment ?? undefined,
- }}
- />
- <CreateNewAnnotationQueueItem
- projectId={projectId}
- objectId={trace.id}
- objectType="TRACE"
- variant="outline"
- />
- </div>
- <CommentDrawerButton
- projectId={projectId}
- variant="outline"
- objectId={trace.id}
- objectType="TRACE"
- count={getNumberFromMap(traceCommentCounts, trace.id)}
- />
- </div>
+ <SessionTraceActionButtons
+ projectId={projectId}
+ traceId={trace.id}
+ timestamp={new Date(trace.timestamp)}
+ environment={trace.environment}
+ scores={trace.scores}
+ traceCommentCounts={traceCommentCounts}
+ />
</div>
<div className="flex-1">
<p className="mb-1 font-bold">Scores</p>
@@ -404,7 +555,7 @@ export const TraceEventsRow = React.memo(
</>
)}
</div>
- </Card>
+ </Frame>
);
},
);
diff --git a/web/src/components/session/TraceRow.tsx b/web/src/components/session/TraceRow.tsx
index 5633a8a1fc..81768a58e0 100644
--- a/web/src/components/session/TraceRow.tsx
+++ b/web/src/components/session/TraceRow.tsx
@@ -3,15 +3,11 @@ import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
import { JsonSkeleton } from "@/src/components/ui/CodeJsonViewer";
import { Card } from "@/src/components/ui/card";
import { type RouterOutputs } from "@/src/utils/api";
-import { getNumberFromMap } from "@/src/utils/map-utils";
import Link from "next/link";
import React, { useEffect, useCallback, useRef } from "react";
-import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";
-import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
import { ItemBadge } from "@/src/components/ItemBadge";
-import { NewDatasetItemFromTraceId } from "@/src/components/session/NewDatasetItemFromTrace";
-import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";
import { useSessionDetailStore } from "@/src/components/session/SessionDetailStoreProvider";
+import { SessionTraceActionButtons } from "@/src/components/session/SessionTraceActionButtons";
const TraceSkeleton = () => {
return (
@@ -92,47 +88,14 @@ const TraceRow = React.memo(
</span>
</div>
</Link>
- <div className="flex flex-wrap gap-2">
- <NewDatasetItemFromTraceId
- projectId={projectId}
- traceId={trace.id}
- timestamp={new Date(trace.timestamp)}
- buttonVariant="outline"
- />
- <div className="flex items-start">
- <AnnotateDrawer
- key={"annotation-drawer" + trace.id}
- projectId={projectId}
- scoreTarget={{
- type: "trace",
- traceId: trace.id,
- }}
- scores={trace.scores}
- buttonVariant="outline"
- analyticsData={{
- type: "trace",
- source: "SessionDetail",
- }}
- scoreMetadata={{
- projectId: projectId,
- environment: trace.environment,
- }}
- />
- <CreateNewAnnotationQueueItem
- projectId={projectId}
- objectId={trace.id}
- objectType="TRACE"
- variant="outline"
- />
- </div>
- <CommentDrawerButton
- projectId={projectId}
- variant="outline"
- objectId={trace.id}
- objectType="TRACE"
- count={getNumberFromMap(traceCommentCounts, trace.id)}
- />
- </div>
+ <SessionTraceActionButtons
+ projectId={projectId}
+ traceId={trace.id}
+ timestamp={new Date(trace.timestamp)}
+ environment={trace.environment}
+ scores={trace.scores}
+ traceCommentCounts={traceCommentCounts}
+ />
</div>
<div className="flex-1">
<p className="mb-1 font-bold">Scores</p>
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index de7d679e3f..4fd43479cd 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -18,12 +18,19 @@ import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer"
import { Button } from "@/src/components/ui/button";
import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
import { useSession } from "next-auth/react";
-import { CheckIcon, CopyIcon, Download, ExternalLinkIcon } from "lucide-react";
+import {
+ CheckIcon,
+ ChevronDown,
+ CopyIcon,
+ Download,
+ ExternalLinkIcon,
+} from "lucide-react";
import { useCopyToClipboard } from "@/src/hooks/useCopyToClipboard";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import Page from "@/src/components/layouts/page";
import {
Popover,
+ PopoverClose,
PopoverContent,
PopoverTrigger,
} from "@/src/components/ui/popover";
@@ -66,6 +73,7 @@ import {
type ColumnOrderState,
} from "@tanstack/react-table";
import {
+ SESSION_DETAIL_LLM_CALL_PRESETS,
SESSION_DETAIL_SYSTEM_PRESETS,
type SessionDetailSystemPreset,
getSessionDetailPresetToApply,
@@ -76,6 +84,9 @@ import { downloadSessionAsJson } from "@/src/components/session/actions/download
import { SessionDetailStoreProvider } from "@/src/components/session/SessionDetailStoreProvider";
import { SessionVirtualizedRow } from "@/src/components/session/SessionVirtualizedRow";
import { createSessionDetailStore } from "@/src/components/session/sessionDetailStore";
+import { ModernSession } from "@/src/components/session/ModernSession";
+import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";
+import { useStore } from "zustand";
import { useHistoryEntryRevisit } from "@/src/components/session/useHistoryEntryRevisit";
import {
areDetailPageListsEqual,
@@ -90,7 +101,7 @@ import {
import { getSessionFilterOptionsStartTimeFilters } from "@/src/components/session/sessionFilterOptions";
// some projects have thousands of users in a session, paginate to avoid rendering all at once
-const INITIAL_USERS_DISPLAY_COUNT = 10;
+const INITIAL_USERS_DISPLAY_COUNT = 3;
const USERS_PER_PAGE_IN_POPOVER = 50;
// Keep this near TanStack's default to avoid waking too many lazy row loaders.
const SESSION_VIRTUALIZER_OVERSCAN = 5;
@@ -414,16 +425,6 @@ export const SessionPage: React.FC<{
),
actionButtonsRight: (
<>
- {!router.query.peek && (
- <DetailPageNav
- key="nav"
- currentId={encodeURIComponent(sessionId)}
- path={(entry) =>
- `/project/${projectId}/sessions/${encodeURIComponent(entry.id)}`
- }
- listKey="sessions"
- />
- )}
<WebCalloutButton
projectId={projectId}
traceId={null}
@@ -438,6 +439,16 @@ export const SessionPage: React.FC<{
>
<Download className="h-4 w-4" />
</Button>
+ {!router.query.peek && (
+ <DetailPageNav
+ key="nav"
+ currentId={encodeURIComponent(sessionId)}
+ path={(entry) =>
+ `/project/${projectId}/sessions/${encodeURIComponent(entry.id)}`
+ }
+ listKey="sessions"
+ />
+ )}
<CommentDrawerButton
key="comment"
variant="outline"
@@ -641,6 +652,10 @@ const LoadedSessionEventsPage: React.FC<{
const router = useRouter();
const { setDetailPageList, detailPagelists } = useDetailPageLists();
const userSession = useSession();
+ const capture = usePostHogClientCapture();
+ const isModernSessionEnabled = useIsFeatureEnabled("modernSession", {
+ enableForAdmins: false,
+ });
const parentRef = useRef<HTMLDivElement>(null);
const defaultPresetAppliedRef = useRef(false);
@@ -659,6 +674,14 @@ const LoadedSessionEventsPage: React.FC<{
initialShowCorrections: showCorrections,
}),
);
+ const showInlineToolCalls = useStore(
+ sessionDetailStore,
+ (state) => state.showInlineToolCalls,
+ );
+ const showSystemPrompt = useStore(
+ sessionDetailStore,
+ (state) => state.showSystemPrompt,
+ );
useEffect(() => {
sessionDetailStore.getState().actions.resetForSession(sessionId);
@@ -678,6 +701,37 @@ const LoadedSessionEventsPage: React.FC<{
[sessionDetailStore, setShowCorrections],
);
+ const setInlineToolCallsForSession = (isEnabled: boolean) => {
+ capture("session_detail:inline_tools_toggled", { isEnabled, isV4: true });
+ sessionDetailStore.getState().actions.setShowInlineToolCalls(isEnabled);
+ };
+
+ const setShowSystemPromptForSession = (isEnabled: boolean) => {
+ capture("session_detail:system_prompt_toggled", {
+ isEnabled,
+ isV4: true,
+ });
+ sessionDetailStore.getState().actions.setShowSystemPrompt(isEnabled);
+ };
+
+ const displayOptions = [
+ {
+ label: "corrections",
+ checked: showCorrections,
+ onCheckedChange: setShowCorrectionsForSession,
+ },
+ {
+ label: "tool calls",
+ checked: showInlineToolCalls,
+ onCheckedChange: setInlineToolCallsForSession,
+ },
+ {
+ label: "system prompt",
+ checked: showSystemPrompt,
+ onCheckedChange: setShowSystemPromptForSession,
+ },
+ ];
+
const sessionCommentCounts = api.comments.getCountByObjectId.useQuery(
{
projectId,
@@ -1022,6 +1076,27 @@ const LoadedSessionEventsPage: React.FC<{
? filterMatchedView
: null;
const viewLabel = matchedView?.name ?? null;
+ const isLlmCallPresetActive = SESSION_DETAIL_LLM_CALL_PRESETS.some(
+ (preset) => matchedView?.id === preset.id,
+ );
+
+ const applyLlmCallPreset = (preset: SessionDetailSystemPreset) => {
+ capture("saved_views:system_preset_selected", {
+ tableName: TableViewPresetTableName.SessionDetail,
+ presetId: preset.id,
+ });
+ viewControllers.handleSetViewId(preset.id);
+ viewControllers.applyViewState(
+ {
+ filters: preset.filters,
+ columnOrder: [],
+ columnVisibility: {},
+ orderBy: null,
+ searchQuery: "",
+ },
+ { trigger: "system_preset", viewId: preset.id },
+ );
+ };
// Recover the system-preset viewId the view manager strips from the URL on
// reload/shared-link (frontend presets aren't backend-fetchable). Idempotent
@@ -1125,6 +1200,72 @@ const LoadedSessionEventsPage: React.FC<{
),
actionButtonsRight: (
<>
+ <WebCalloutButton
+ projectId={projectId}
+ traceId={null}
+ observationId={null}
+ sessionId={sessionId}
+ />
+ {isModernSessionEnabled ? (
+ <>
+ <div className="hidden items-center gap-3 pr-2 min-[1900px]:flex">
+ <span className="text-muted-foreground text-xs">Show:</span>
+ {displayOptions.map(
+ ({ label, checked, onCheckedChange }) => (
+ <label
+ key={label}
+ className="flex items-center gap-1.5"
+ >
+ <Switch
+ checked={checked}
+ onCheckedChange={onCheckedChange}
+ size="sm"
+ />
+ <span className="text-muted-foreground text-xs">
+ {label}
+ </span>
+ </label>
+ ),
+ )}
+ </div>
+ <div className="flex items-center gap-1.5 pr-2 min-[1900px]:hidden">
+ <span className="text-muted-foreground text-xs">Show:</span>
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-8 gap-1 px-2"
+ >
+ Options
+ <ChevronDown className="h-3.5 w-3.5" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-52 p-2">
+ <div className="flex flex-col gap-1">
+ {displayOptions.map(
+ ({ label, checked, onCheckedChange }) => (
+ <label
+ key={label}
+ className="hover:bg-muted flex items-center justify-between gap-4 rounded-md px-2 py-1.5"
+ >
+ <span className="text-sm capitalize">
+ {label}
+ </span>
+ <Switch
+ checked={checked}
+ onCheckedChange={onCheckedChange}
+ size="sm"
+ />
+ </label>
+ ),
+ )}
+ </div>
+ </PopoverContent>
+ </Popover>
+ </div>
+ </>
+ ) : null}
{!router.query.peek && (
<DetailPageNav
key="nav"
@@ -1135,12 +1276,6 @@ const LoadedSessionEventsPage: React.FC<{
listKey="sessions"
/>
)}
- <WebCalloutButton
- projectId={projectId}
- traceId={null}
- observationId={null}
- sessionId={sessionId}
- />
<CommentDrawerButton
key="comment"
variant="outline"
@@ -1170,24 +1305,81 @@ const LoadedSessionEventsPage: React.FC<{
variant="outline"
/>
</div>
- <div className="flex items-center">
- <div className="mx-1">
+ {!isModernSessionEnabled ? (
+ <label className="flex items-center gap-1.5">
<Switch
checked={showCorrections}
onCheckedChange={setShowCorrectionsForSession}
size="sm"
/>
- </div>
- <span className="text-muted-foreground text-xs">
- Show corrections
- </span>
- </div>
+ <span className="text-muted-foreground text-xs">
+ Show corrections
+ </span>
+ </label>
+ ) : null}
</>
),
}}
>
- <div className="flex h-full flex-col overflow-auto">
+ <div
+ className={
+ isModernSessionEnabled
+ ? "flex h-full min-h-0 flex-col overflow-hidden"
+ : "flex h-full flex-col overflow-auto"
+ }
+ >
<div className="bg-background sticky top-0 z-40 flex flex-wrap items-center gap-2 border-b p-4">
+ {isModernSessionEnabled ? (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ aria-pressed={isLlmCallPresetActive}
+ className={
+ isLlmCallPresetActive ? "bg-primary/5" : undefined
+ }
+ >
+ LLM Calls per Trace
+ <ChevronDown className="ml-1 h-4 w-4" aria-hidden />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-72 p-1">
+ <div className="text-muted-foreground px-2 py-1.5 text-xs font-bold">
+ LLM Calls per Trace
+ </div>
+ {SESSION_DETAIL_LLM_CALL_PRESETS.map((preset) => {
+ const isActive = matchedView?.id === preset.id;
+ return (
+ <PopoverClose asChild key={preset.id}>
+ <button
+ type="button"
+ aria-current={isActive ? "true" : undefined}
+ className="hover:bg-accent flex w-full items-start justify-between gap-2 rounded-sm px-2 py-1.5 text-left text-sm"
+ onClick={() => applyLlmCallPreset(preset)}
+ >
+ <span className="flex flex-col">
+ <span className="font-bold">{preset.name}</span>
+ {preset.description ? (
+ <span className="text-muted-foreground text-xs">
+ {preset.description}
+ </span>
+ ) : null}
+ </span>
+ {isActive ? (
+ <CheckIcon
+ className="mt-0.5 h-4 w-4 shrink-0"
+ aria-hidden
+ />
+ ) : null}
+ </button>
+ </PopoverClose>
+ );
+ })}
+ </PopoverContent>
+ </Popover>
+ ) : null}
+
{/* Saved Views */}
<TableViewPresetsDrawer
viewConfig={{
@@ -1224,11 +1416,18 @@ const LoadedSessionEventsPage: React.FC<{
{/* Separator */}
<Separator orientation="vertical" className="h-6" />
- {/* Stats */}
- <Badge variant="outline">Total traces: {session.countTraces}</Badge>
- <Badge variant="outline">
- Total cost: {usdFormatter(session.totalCost ?? 0, 2)}
- </Badge>
+ {/* Stats stay in the toolbar for the existing card layout. Modern
+ Session shows trace count and cost in its minimap header. */}
+ {!isModernSessionEnabled ? (
+ <>
+ <Badge variant="outline">
+ Total traces: {session.countTraces}
+ </Badge>
+ <Badge variant="outline">
+ Total cost: {usdFormatter(session.totalCost ?? 0, 2)}
+ </Badge>
+ </>
+ ) : null}
{/* Users */}
{session.users?.length ? (
@@ -1238,44 +1437,60 @@ const LoadedSessionEventsPage: React.FC<{
{/* Scores */}
<SessionScores scores={session.scores} />
</div>
- <div ref={parentRef} className="flex-1 overflow-auto p-4">
- <div
- style={{
- height: `${virtualizer.getTotalSize()}px`,
- width: "100%",
- position: "relative",
- }}
- >
- {virtualItems.map((virtualItem) => {
- const trace = traces?.[virtualItem.index];
- if (!trace) return null;
-
- return (
- <SessionVirtualizedRow
- key={virtualItem.key}
- itemKey={String(virtualItem.key)}
- measurementKey={`${String(virtualItem.key)}:${showCorrections}:${visibleFilterMeasurementKey}`}
- source="events"
- virtualItem={virtualItem}
- virtualizer={virtualizer}
- >
- <LazySessionTraceEventsRow
- trace={trace}
- projectId={projectId}
- sessionId={sessionId}
- openPeek={openPeek}
- traceCommentCounts={asCommentCounts(
- traceCommentCounts.data,
- )}
- index={virtualItem.index}
- filterState={visibleFilterState}
- viewLabel={viewLabel}
- />
- </SessionVirtualizedRow>
- );
- })}
+ {!isModernSessionEnabled ? (
+ <div ref={parentRef} className="flex-1 overflow-auto p-4">
+ <div
+ style={{
+ height: `${virtualizer.getTotalSize()}px`,
+ width: "100%",
+ position: "relative",
+ }}
+ >
+ {virtualItems.map((virtualItem) => {
+ const trace = traces?.[virtualItem.index];
+ if (!trace) return null;
+
+ return (
+ <SessionVirtualizedRow
+ key={virtualItem.key}
+ itemKey={String(virtualItem.key)}
+ measurementKey={`${String(virtualItem.key)}:${showCorrections}:${visibleFilterMeasurementKey}`}
+ source="events"
+ virtualItem={virtualItem}
+ virtualizer={virtualizer}
+ >
+ <LazySessionTraceEventsRow
+ trace={trace}
+ projectId={projectId}
+ sessionId={sessionId}
+ openPeek={openPeek}
+ traceCommentCounts={asCommentCounts(
+ traceCommentCounts.data,
+ )}
+ index={virtualItem.index}
+ filterState={visibleFilterState}
+ viewLabel={viewLabel}
+ />
+ </SessionVirtualizedRow>
+ );
+ })}
+ </div>
</div>
- </div>
+ ) : (
+ <ModernSession
+ traces={traces ?? []}
+ projectId={projectId}
+ sessionId={sessionId}
+ openPeek={openPeek}
+ traceCommentCounts={asCommentCounts(traceCommentCounts.data)}
+ filterState={visibleFilterState}
+ filterMeasurementKey={visibleFilterMeasurementKey}
+ viewLabel={viewLabel}
+ totalCost={session.totalCost ?? 0}
+ showInlineToolCalls={showInlineToolCalls}
+ showSystemPrompt={showSystemPrompt}
+ />
+ )}
</div>
<TablePeekViewTraceDetail
itemType="TRACE"
diff --git a/web/src/components/session/session-detail-presets.ts b/web/src/components/session/session-detail-presets.ts
index 1db512b8dd..6e140bd586 100644
--- a/web/src/components/session/session-detail-presets.ts
+++ b/web/src/components/session/session-detail-presets.ts
@@ -53,7 +53,7 @@ export const SESSION_DETAIL_SYSTEM_PRESETS: SessionDetailSystemPreset[] = [
},
{
id: `${SYSTEM_PRESET_ID_PREFIX}first_generation__`,
- name: "First Generation in Trace",
+ name: "First LLM Call per Trace",
description: "Shows only the first generation in each trace",
filters: [
{
@@ -72,7 +72,7 @@ export const SESSION_DETAIL_SYSTEM_PRESETS: SessionDetailSystemPreset[] = [
},
{
id: `${SYSTEM_PRESET_ID_PREFIX}last_generation__`,
- name: "Last Generation in Trace",
+ name: "Last LLM Call per Trace",
description: "Shows only the last generation in each trace",
filters: [
{
@@ -91,6 +91,11 @@ export const SESSION_DETAIL_SYSTEM_PRESETS: SessionDetailSystemPreset[] = [
},
];
+export const SESSION_DETAIL_LLM_CALL_PRESETS =
+ SESSION_DETAIL_SYSTEM_PRESETS.filter((preset) =>
+ preset.filters.some((filter) => filter.type === "positionInTrace"),
+ );
+
/**
* The default view: "All observations with I/O". Shows the real session out of
* the box (chat looks like chat, an agent run shows its tool calls) without the
diff --git a/web/src/components/session/sessionDetailStore.clienttest.ts b/web/src/components/session/sessionDetailStore.clienttest.ts
index 4cb816997f..6cd775ada1 100644
--- a/web/src/components/session/sessionDetailStore.clienttest.ts
+++ b/web/src/components/session/sessionDetailStore.clienttest.ts
@@ -44,4 +44,52 @@ describe("createSessionDetailStore", () => {
expect(store.getState().showCorrections).toBe(true);
expect(store.getState().loadedTraceIds).toBe(loadedTraceIds);
});
+
+ it("keeps the inline-tool preference independent from loaded rows", () => {
+ const store = createSessionDetailStore({
+ initialSessionId: "session-a",
+ initialShowCorrections: false,
+ });
+
+ store.getState().actions.markTraceLoaded("trace-1");
+ const loadedTraceIds = store.getState().loadedTraceIds;
+
+ store.getState().actions.setShowInlineToolCalls(true);
+
+ expect(store.getState()).toMatchObject({
+ showInlineToolCalls: true,
+ });
+ expect(store.getState().loadedTraceIds).toBe(loadedTraceIds);
+ });
+
+ it("keeps system prompts independent from inline tool calls", () => {
+ const store = createSessionDetailStore({
+ initialSessionId: "session-a",
+ initialShowCorrections: false,
+ });
+
+ store.getState().actions.setShowSystemPrompt(true);
+
+ expect(store.getState()).toMatchObject({
+ showInlineToolCalls: false,
+ showSystemPrompt: true,
+ });
+ });
+
+ it("defaults optional conversation content to hidden when the session changes", () => {
+ const store = createSessionDetailStore({
+ initialSessionId: "session-a",
+ initialShowCorrections: false,
+ });
+
+ store.getState().actions.setShowInlineToolCalls(true);
+ store.getState().actions.setShowSystemPrompt(true);
+ store.getState().actions.resetForSession("session-b");
+
+ expect(store.getState()).toMatchObject({
+ sessionId: "session-b",
+ showInlineToolCalls: false,
+ showSystemPrompt: false,
+ });
+ });
});
diff --git a/web/src/components/session/sessionDetailStore.ts b/web/src/components/session/sessionDetailStore.ts
index 9b5ac753ba..0347d46644 100644
--- a/web/src/components/session/sessionDetailStore.ts
+++ b/web/src/components/session/sessionDetailStore.ts
@@ -5,10 +5,14 @@ export type LoadedTraceIds = Record<string, true>;
export interface SessionDetailStoreState {
loadedTraceIds: LoadedTraceIds;
showCorrections: boolean;
+ showInlineToolCalls: boolean;
+ showSystemPrompt: boolean;
sessionId: string;
actions: {
markTraceLoaded: (traceId: string) => void;
setShowCorrections: (showCorrections: boolean) => void;
+ setShowInlineToolCalls: (showInlineToolCalls: boolean) => void;
+ setShowSystemPrompt: (showSystemPrompt: boolean) => void;
resetForSession: (sessionId: string) => void;
};
}
@@ -25,6 +29,8 @@ export function createSessionDetailStore({
return createStore<SessionDetailStoreState>((set, get) => ({
loadedTraceIds: {},
showCorrections: initialShowCorrections,
+ showInlineToolCalls: false,
+ showSystemPrompt: false,
sessionId: initialSessionId,
actions: {
markTraceLoaded: (traceId: string) => {
@@ -41,10 +47,20 @@ export function createSessionDetailStore({
if (showCorrections === get().showCorrections) return;
set({ showCorrections });
},
+ setShowInlineToolCalls: (showInlineToolCalls: boolean) => {
+ if (showInlineToolCalls === get().showInlineToolCalls) return;
+ set({ showInlineToolCalls });
+ },
+ setShowSystemPrompt: (showSystemPrompt: boolean) => {
+ if (showSystemPrompt === get().showSystemPrompt) return;
+ set({ showSystemPrompt });
+ },
resetForSession: (sessionId: string) => {
if (sessionId === get().sessionId) return;
set({
loadedTraceIds: {},
+ showInlineToolCalls: false,
+ showSystemPrompt: false,
sessionId,
});
},
diff --git a/web/src/components/trace/components/IOPreview/IOPreview.tsx b/web/src/components/trace/components/IOPreview/IOPreview.tsx
index 52c1823225..004620b5a9 100644
--- a/web/src/components/trace/components/IOPreview/IOPreview.tsx
+++ b/web/src/components/trace/components/IOPreview/IOPreview.tsx
@@ -10,11 +10,13 @@ import { ViewModeToggle, type ViewMode } from "./components/ViewModeToggle";
import { IOPreviewJSON, type IOPreviewJSONProps } from "./IOPreviewJSON";
import { IOPreviewJSONSimple } from "./IOPreviewJSONSimple";
import { IOPreviewPretty } from "./IOPreviewPretty";
+import { type ChatMLParserResult } from "./hooks/useChatMLParser";
import { Button } from "@/src/components/ui/button";
import { ActionButton } from "@/src/components/ActionButton";
import { BookOpen, X } from "lucide-react";
export type { ViewMode };
+export type IOPreviewContentMode = "all" | "conversation";
const EMPTY_IO_ALERT_ID = "empty-io";
const STORAGE_KEY = "dismissed-trace-view-notifications";
@@ -57,6 +59,7 @@ export interface IOPreviewProps extends ExpansionStateProps {
parsedInput?: unknown;
parsedOutput?: unknown;
parsedMetadata?: unknown;
+ chatMLParserResult?: ChatMLParserResult;
observationName?: string;
isLoading?: boolean;
isParsing?: boolean;
@@ -65,6 +68,8 @@ export interface IOPreviewProps extends ExpansionStateProps {
hideOutput?: boolean;
hideInput?: boolean;
currentView?: ViewMode;
+ contentMode?: IOPreviewContentMode;
+ showSystemPrompt?: boolean;
setIsPrettyViewAvailable?: (value: boolean) => void;
// Inline comment props (JSON Beta view only)
enableInlineComments?: boolean;
@@ -104,6 +109,7 @@ export function IOPreview({
parsedInput,
parsedOutput,
parsedMetadata,
+ chatMLParserResult,
observationName,
isLoading = false,
isParsing = false,
@@ -112,6 +118,8 @@ export function IOPreview({
hideInput = false,
media,
currentView,
+ contentMode = "all",
+ showSystemPrompt,
inputExpansionState,
outputExpansionState,
metadataExpansionState,
@@ -175,6 +183,7 @@ export function IOPreview({
parsedInput,
parsedOutput,
parsedMetadata,
+ chatMLParserResult,
isLoading,
isParsing,
hideIfNull,
@@ -283,6 +292,8 @@ export function IOPreview({
{...sharedProps}
observationName={observationName}
showMetadata={showMetadata}
+ contentMode={contentMode}
+ showSystemPrompt={showSystemPrompt}
/>
)}
diff --git a/web/src/components/trace/components/IOPreview/IOPreviewPretty.tsx b/web/src/components/trace/components/IOPreview/IOPreviewPretty.tsx
index 2a14b5e089..b9816af0db 100644
--- a/web/src/components/trace/components/IOPreview/IOPreviewPretty.tsx
+++ b/web/src/components/trace/components/IOPreview/IOPreviewPretty.tsx
@@ -4,11 +4,18 @@ import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
import { type MetadataFilterActions } from "@/src/components/table/ValueCell";
import { MARKDOWN_RENDER_CHARACTER_LIMIT } from "@/src/utils/constants";
import { type MediaReturnType } from "@/src/features/media/validation";
-import { useChatMLParser } from "./hooks/useChatMLParser";
+import {
+ type ChatMLParserResult,
+ useChatMLParser,
+} from "./hooks/useChatMLParser";
import { ChatMessageList } from "./components/ChatMessageList";
import { SectionToolDefinitions } from "./components/SectionToolDefinitions";
-import { type ExpansionStateProps } from "./IOPreview";
+import {
+ type ExpansionStateProps,
+ type IOPreviewContentMode,
+} from "./IOPreview";
import { CorrectedOutputField } from "./components/CorrectedOutputField";
+import { isOnlyJsonMessage } from "./components/chat-message-utils";
interface JsonInputOutputViewProps {
parsedInput: unknown;
@@ -85,6 +92,7 @@ export interface IOPreviewPrettyProps extends ExpansionStateProps {
parsedInput?: unknown;
parsedOutput?: unknown;
parsedMetadata?: unknown;
+ chatMLParserResult?: ChatMLParserResult;
observationName?: string;
isLoading?: boolean;
isParsing?: boolean;
@@ -99,6 +107,8 @@ export interface IOPreviewPrettyProps extends ExpansionStateProps {
traceId: string;
environment?: string;
showCorrections?: boolean;
+ contentMode?: IOPreviewContentMode;
+ showSystemPrompt?: boolean;
}
/**
@@ -121,6 +131,7 @@ export function IOPreviewPretty({
parsedInput: preParsedInput,
parsedOutput: preParsedOutput,
parsedMetadata: preParsedMetadata,
+ chatMLParserResult,
observationName,
isLoading = false,
isParsing = false,
@@ -140,6 +151,8 @@ export function IOPreviewPretty({
traceId,
environment = "default",
showCorrections = true,
+ contentMode = "all",
+ showSystemPrompt,
}: IOPreviewPrettyProps) {
// Use pre-parsed data if available (from useParsedObservation hook),
// otherwise parse with size/depth limits to prevent UI freeze
@@ -186,6 +199,7 @@ export function IOPreviewPretty({
parsedInput,
parsedOutput,
parsedMetadata,
+ chatMLParserResult,
);
// Determine if markdown is safe to render (content size check)
@@ -250,17 +264,22 @@ export function IOPreviewPretty({
// Determine if metadata should be shown
const shouldShowMetadata = showMetadata && parsedMetadata !== undefined;
+ const showData = contentMode !== "conversation";
+ const shouldRenderMessages =
+ canDisplayAsChat && !allMessages.every(isOnlyJsonMessage);
return (
<div>
- <SectionToolDefinitions
- tools={allTools}
- toolCallCounts={toolCallCounts}
- toolCallsByName={toolCallsByName}
- toolNameToDefinitionNumber={toolNameToDefinitionNumber}
- />
+ {showData ? (
+ <SectionToolDefinitions
+ tools={allTools}
+ toolCallCounts={toolCallCounts}
+ toolCallsByName={toolCallsByName}
+ toolNameToDefinitionNumber={toolNameToDefinitionNumber}
+ />
+ ) : null}
- {canDisplayAsChat ? (
+ {shouldRenderMessages ? (
<div className="[&_.io-message-content]:px-2 [&_.io-message-header]:px-2">
<ChatMessageList
messages={allMessages}
@@ -270,6 +289,8 @@ export function IOPreviewPretty({
currentView="pretty"
messageToToolCallNumbers={messageToToolCallNumbers}
inputMessageCount={inputMessageCount}
+ contentMode={contentMode}
+ showSystemPrompt={showSystemPrompt}
/>
{showCorrections && (
<CorrectedOutputField
@@ -282,7 +303,7 @@ export function IOPreviewPretty({
/>
)}
</div>
- ) : (
+ ) : showData ? (
<>
<JsonInputOutputView {...jsonViewProps} />
<div className="[&_.io-message-content]:px-2 [&_.io-message-header]:px-2">
@@ -298,10 +319,10 @@ export function IOPreviewPretty({
)}
</div>
</>
- )}
+ ) : null}
{/* Metadata Section */}
- {shouldShowMetadata && (
+ {showData && shouldShowMetadata && (
<div className="[&_.io-message-content]:px-2 [&_.io-message-header]:px-2">
<PrettyJsonView
title="Metadata"
diff --git a/web/src/components/trace/components/IOPreview/components/ChatMessage.clienttest.tsx b/web/src/components/trace/components/IOPreview/components/ChatMessage.clienttest.tsx
index 1b9bd8fd8e..9eb71cd468 100644
--- a/web/src/components/trace/components/IOPreview/components/ChatMessage.clienttest.tsx
+++ b/web/src/components/trace/components/IOPreview/components/ChatMessage.clienttest.tsx
@@ -4,6 +4,7 @@ import { vi } from "vitest";
import { ChatMessage } from "./ChatMessage";
import { type ChatMlMessage } from "./chat-message-utils";
import { MarkdownContextProvider } from "@/src/features/theming/useMarkdownContext";
+import { type IOPreviewContentMode } from "../IOPreview";
function createMemoryStorage(): Storage {
const store = new Map<string, string>();
@@ -33,7 +34,13 @@ const longSystemPrompt = Array.from(
function renderChatMessage(
message: ChatMlMessage,
- { shouldRenderMarkdown = true }: { shouldRenderMarkdown?: boolean } = {},
+ {
+ shouldRenderMarkdown = true,
+ contentMode = "all",
+ }: {
+ shouldRenderMarkdown?: boolean;
+ contentMode?: IOPreviewContentMode;
+ } = {},
) {
return render(
<MarkdownContextProvider>
@@ -41,11 +48,40 @@ function renderChatMessage(
message={message}
shouldRenderMarkdown={shouldRenderMarkdown}
currentView="pretty"
+ contentMode={contentMode}
/>
</MarkdownContextProvider>,
);
}
+describe("ChatMessage content modes", () => {
+ const assistantWithToolCall = {
+ role: "assistant",
+ content: "I will check that for you.",
+ tool_calls: [
+ {
+ id: "call-1",
+ name: "search_traces",
+ arguments: '{"limit":10}',
+ },
+ ],
+ } as unknown as ChatMlMessage;
+
+ beforeEach(() => {
+ vi.stubGlobal("localStorage", createMemoryStorage());
+ vi.stubGlobal("sessionStorage", createMemoryStorage());
+ });
+
+ it("keeps assistant content but removes tool details in conversation mode", () => {
+ renderChatMessage(assistantWithToolCall, { contentMode: "conversation" });
+
+ expect(
+ screen.getAllByText("I will check that for you.").length,
+ ).toBeGreaterThan(0);
+ expect(screen.queryByText("search_traces")).not.toBeInTheDocument();
+ });
+});
+
// getByRole ignores elements hidden via display:none, so queries only see the
// active render path (markdown vs json), even though ChatMessage mounts both.
const expandButton = () =>
diff --git a/web/src/components/trace/components/IOPreview/components/ChatMessage.tsx b/web/src/components/trace/components/IOPreview/components/ChatMessage.tsx
index 8c6c3df37c..decf805580 100644
--- a/web/src/components/trace/components/IOPreview/components/ChatMessage.tsx
+++ b/web/src/components/trace/components/IOPreview/components/ChatMessage.tsx
@@ -22,6 +22,7 @@ import {
hasRedactedThinkingContent,
} from "./chat-message-utils";
import { ThinkingBlock, RedactedThinkingBlock } from "./ThinkingBlock";
+import { type IOPreviewContentMode } from "../IOPreview";
// View mode for pretty/json toggle
export type ViewMode = "pretty" | "json";
@@ -33,6 +34,7 @@ export interface ChatMessageProps {
currentView: ViewMode;
toolCallNumbers?: number[];
isOutputMessage?: boolean;
+ contentMode?: IOPreviewContentMode;
}
/**
@@ -50,6 +52,7 @@ export function ChatMessage({
currentView,
toolCallNumbers,
isOutputMessage,
+ contentMode = "all",
}: ChatMessageProps) {
const [showTableView, setShowTableView] = useState(false);
@@ -59,25 +62,27 @@ export function ChatMessage({
// Collapse from the raw role: the title is the message `name` when present,
// so name-bearing system prompts would otherwise never collapse.
const isSystemPrompt = message.role === "system";
+ const showData = contentMode !== "conversation";
// Toggle button for passthrough JSON
- const passthroughToggleButton = hasPassthroughJson(message) ? (
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={() => setShowTableView((v) => !v)}
- title={
- showTableView ? "Show formatted view" : "Show passthrough JSON data"
- }
- className="hover:bg-border -mr-2"
- >
- {showTableView ? (
- <ListChevronsDownUp className="text-primary h-3 w-3" />
- ) : (
- <ListChevronsUpDown className="h-3 w-3" />
- )}
- </Button>
- ) : undefined;
+ const passthroughToggleButton =
+ showData && hasPassthroughJson(message) ? (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() => setShowTableView((v) => !v)}
+ title={
+ showTableView ? "Show formatted view" : "Show passthrough JSON data"
+ }
+ className="hover:bg-border -mr-2"
+ >
+ {showTableView ? (
+ <ListChevronsDownUp className="text-primary h-3 w-3" />
+ ) : (
+ <ListChevronsUpDown className="h-3 w-3" />
+ )}
+ </Button>
+ ) : undefined;
// Placeholder message
if (isPlaceholderMessage(message)) {
@@ -194,7 +199,7 @@ export function ChatMessage({
afterHeader={thinkingBlocks}
isSystemPrompt={isSystemPrompt}
/>
- {toolCalls.length > 0 && (
+ {showData && toolCalls.length > 0 && (
<div className="mt-2">
<ToolCallInvocationsView
message={message}
@@ -214,7 +219,7 @@ export function ChatMessage({
afterHeader={thinkingBlocks}
isSystemPrompt={isSystemPrompt}
/>
- {toolCalls.length > 0 && (
+ {showData && toolCalls.length > 0 && (
<div className="mt-2">
<ToolCallInvocationsView
message={message}
diff --git a/web/src/components/trace/components/IOPreview/components/ChatMessageList.tsx b/web/src/components/trace/components/IOPreview/components/ChatMessageList.tsx
index f05695f2a9..1f81c7d512 100644
--- a/web/src/components/trace/components/IOPreview/components/ChatMessageList.tsx
+++ b/web/src/components/trace/components/IOPreview/components/ChatMessageList.tsx
@@ -7,8 +7,12 @@ import {
} from "@/src/components/ui/markdown-media.utils";
import { ChatMessage, type ViewMode } from "./ChatMessage";
import { SectionMedia } from "./SectionMedia";
-import { type ChatMlMessage, shouldRenderMessage } from "./chat-message-utils";
+import {
+ type ChatMlMessage,
+ shouldRenderMessageForContentMode,
+} from "./chat-message-utils";
import { type MediaReturnType } from "@/src/features/media/validation";
+import { type IOPreviewContentMode } from "../IOPreview";
const COLLAPSE_THRESHOLD = 3;
@@ -22,6 +26,8 @@ export interface ChatMessageListProps {
messageToToolCallNumbers: Map<number, number[]>;
collapseLongHistory?: boolean;
inputMessageCount?: number;
+ contentMode?: IOPreviewContentMode;
+ showSystemPrompt?: boolean;
}
/**
@@ -42,11 +48,22 @@ export function ChatMessageList({
messageToToolCallNumbers,
collapseLongHistory = true,
inputMessageCount,
+ contentMode = "all",
+ showSystemPrompt,
}: ChatMessageListProps) {
// Filter messages to only those with renderable content
const messagesToRender = useMemo(
- () => messages.filter(shouldRenderMessage),
- [messages],
+ () =>
+ messages
+ .map((message, originalIndex) => ({ message, originalIndex }))
+ .filter(({ message }) =>
+ shouldRenderMessageForContentMode(
+ message,
+ contentMode,
+ showSystemPrompt,
+ ),
+ ),
+ [contentMode, messages, showSystemPrompt],
);
// Initialize collapsed state based on message count
@@ -58,14 +75,12 @@ export function ChatMessageList({
const visibleMessages = useMemo(
() =>
- messagesToRender
- .map((message, originalIndex) => ({ message, originalIndex }))
- .filter(
- ({ originalIndex }) =>
- !isCollapsed ||
- originalIndex === 0 ||
- originalIndex > messagesToRender.length - COLLAPSE_THRESHOLD,
- ),
+ messagesToRender.filter(
+ (_, filteredIndex) =>
+ !isCollapsed ||
+ filteredIndex === 0 ||
+ filteredIndex > messagesToRender.length - COLLAPSE_THRESHOLD,
+ ),
[isCollapsed, messagesToRender],
);
@@ -113,26 +128,28 @@ export function ChatMessageList({
currentView={currentView}
toolCallNumbers={messageToToolCallNumbers.get(originalIndex)}
isOutputMessage={originalIndex >= (inputMessageCount ?? 0)}
+ contentMode={contentMode}
/>
{/* Show collapse/expand button after first message */}
- {isCollapsed !== null && originalIndex === 0 && (
- <Button
- variant="ghost"
- size="xs"
- onClick={() => setCollapsed((v) => !v)}
- className="underline"
- >
- {isCollapsed
- ? `Show ${messagesToRender.length - COLLAPSE_THRESHOLD} more ...`
- : "Hide history"}
- </Button>
- )}
+ {isCollapsed !== null &&
+ originalIndex === messagesToRender[0]?.originalIndex && (
+ <Button
+ variant="ghost"
+ size="xs"
+ onClick={() => setCollapsed((v) => !v)}
+ className="underline"
+ >
+ {isCollapsed
+ ? `Show ${messagesToRender.length - COLLAPSE_THRESHOLD} more ...`
+ : "Hide history"}
+ </Button>
+ )}
</Fragment>
))}
</div>
{/* Additional input section */}
- {additionalInput && (
+ {contentMode !== "conversation" && additionalInput && (
<PrettyJsonView
title="Additional Input"
json={additionalInput}
diff --git a/web/src/components/trace/components/IOPreview/components/chat-message-utils.clienttest.ts b/web/src/components/trace/components/IOPreview/components/chat-message-utils.clienttest.ts
index 43a0e135bf..167e026e69 100644
--- a/web/src/components/trace/components/IOPreview/components/chat-message-utils.clienttest.ts
+++ b/web/src/components/trace/components/IOPreview/components/chat-message-utils.clienttest.ts
@@ -6,7 +6,9 @@ import {
hasPassthroughJson,
isPlaceholderMessage,
isOnlyJsonMessage,
+ hasRenderableConversationMessages,
shouldRenderMessage,
+ shouldRenderMessageForContentMode,
parseToolCallsFromMessage,
} from "./chat-message-utils";
@@ -222,6 +224,19 @@ describe("chat-message-utils", () => {
});
});
+ describe("hasRenderableConversationMessages", () => {
+ it("rejects empty-content passthrough JSON without changing all-data rendering", () => {
+ const message = createMessage({
+ role: "assistant",
+ content: "",
+ json: { data: "test" },
+ });
+
+ expect(hasRenderableConversationMessages([message], false)).toBe(false);
+ expect(shouldRenderMessage(message)).toBe(true);
+ });
+ });
+
describe("shouldRenderMessage", () => {
it("returns true for message with content", () => {
expect(
@@ -313,4 +328,44 @@ describe("chat-message-utils", () => {
).toEqual(directToolCalls);
});
});
+
+ describe("shouldRenderMessageForContentMode", () => {
+ const systemMessage = createMessage({
+ role: "system",
+ content: "Follow the support policy.",
+ });
+ const toolMessage = createMessage({
+ role: "tool",
+ content: "Order lookup complete.",
+ });
+ it("controls system prompts independently from inline data", () => {
+ expect(
+ shouldRenderMessageForContentMode(systemMessage, "conversation", false),
+ ).toBe(false);
+ expect(
+ shouldRenderMessageForContentMode(systemMessage, "conversation", true),
+ ).toBe(true);
+ expect(
+ shouldRenderMessageForContentMode(systemMessage, "all", false),
+ ).toBe(false);
+ expect(
+ shouldRenderMessageForContentMode(systemMessage, "all", true),
+ ).toBe(true);
+ expect(
+ shouldRenderMessageForContentMode(toolMessage, "conversation", true),
+ ).toBe(false);
+ expect(shouldRenderMessageForContentMode(toolMessage, "all", false)).toBe(
+ true,
+ );
+ });
+
+ it("preserves the existing defaults outside Modern Session", () => {
+ expect(
+ shouldRenderMessageForContentMode(systemMessage, "conversation"),
+ ).toBe(false);
+ expect(shouldRenderMessageForContentMode(systemMessage, "all")).toBe(
+ true,
+ );
+ });
+ });
});
diff --git a/web/src/components/trace/components/IOPreview/components/chat-message-utils.ts b/web/src/components/trace/components/IOPreview/components/chat-message-utils.ts
index c9572443fd..84900592de 100644
--- a/web/src/components/trace/components/IOPreview/components/chat-message-utils.ts
+++ b/web/src/components/trace/components/IOPreview/components/chat-message-utils.ts
@@ -1,6 +1,7 @@
import type { z } from "zod";
import type { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";
import type { combineInputOutputMessages } from "@/src/utils/chatml";
+import type { IOPreviewContentMode } from "../IOPreview";
export type ChatMlMessage = z.infer<typeof ChatMlMessageSchema>;
@@ -67,6 +68,41 @@ export function shouldRenderMessage(message: ChatMlMessage): boolean {
);
}
+export function shouldRenderMessageForContentMode(
+ message: ChatMlMessage,
+ contentMode: IOPreviewContentMode,
+ showSystemPrompt?: boolean,
+): boolean {
+ const shouldShowSystemPrompt =
+ showSystemPrompt ?? contentMode !== "conversation";
+
+ if (message.role === "system" && !shouldShowSystemPrompt) return false;
+
+ if (contentMode === "all") return shouldRenderMessage(message);
+
+ return (
+ (message.role === "user" ||
+ message.role === "assistant" ||
+ message.role === "system") &&
+ (hasRenderableContent(message) ||
+ hasThinkingContent(message) ||
+ hasRedactedThinkingContent(message))
+ );
+}
+
+export function hasRenderableConversationMessages(
+ messages: ChatMlMessage[],
+ showSystemPrompt?: boolean,
+): boolean {
+ return messages.some((message) =>
+ shouldRenderMessageForContentMode(
+ message,
+ "conversation",
+ showSystemPrompt,
+ ),
+ );
+}
+
/**
* Parse tool calls from a ChatML message.
* Handles both standard tool_calls array and passthrough json.tool_calls.
diff --git a/web/src/components/trace/components/IOPreview/hooks/useChatMLParser.clienttest.ts b/web/src/components/trace/components/IOPreview/hooks/useChatMLParser.clienttest.ts
index 058c85679f..f05064c755 100644
--- a/web/src/components/trace/components/IOPreview/hooks/useChatMLParser.clienttest.ts
+++ b/web/src/components/trace/components/IOPreview/hooks/useChatMLParser.clienttest.ts
@@ -1,5 +1,5 @@
import { renderHook } from "@testing-library/react";
-import { useChatMLParser } from "./useChatMLParser";
+import { type ChatMLParserResult, useChatMLParser } from "./useChatMLParser";
describe("useChatMLParser", () => {
it("groups output-side tool call arguments by tool name", () => {
@@ -158,4 +158,33 @@ describe("useChatMLParser", () => {
},
]);
});
+
+ it("reuses an already computed parser result", () => {
+ const preparedResult: ChatMLParserResult = {
+ canDisplayAsChat: true,
+ allMessages: [],
+ additionalInput: undefined,
+ allTools: [],
+ toolCallCounts: new Map(),
+ toolCallsByName: new Map(),
+ messageToToolCallNumbers: new Map(),
+ toolNameToDefinitionNumber: new Map(),
+ inputMessageCount: 0,
+ };
+
+ const { result } = renderHook(() =>
+ useChatMLParser(
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ preparedResult,
+ ),
+ );
+
+ expect(result.current).toBe(preparedResult);
+ });
});
diff --git a/web/src/components/trace/components/IOPreview/hooks/useChatMLParser.ts b/web/src/components/trace/components/IOPreview/hooks/useChatMLParser.ts
index e460a448c4..b312a77e11 100644
--- a/web/src/components/trace/components/IOPreview/hooks/useChatMLParser.ts
+++ b/web/src/components/trace/components/IOPreview/hooks/useChatMLParser.ts
@@ -82,6 +82,104 @@ function getToolCallArguments(toolCall: unknown): unknown {
);
}
+/**
+ * Parse already-decoded I/O into the same ChatML representation used by the
+ * pretty preview. Kept pure so parent surfaces can decide whether a filtered
+ * result has any conversation representation without relying on observation
+ * types.
+ */
+function parseChatML(
+ parsedInput: unknown,
+ parsedOutput: unknown,
+ parsedMetadata: unknown,
+ observationName: string | undefined,
+): ChatMLParserResult {
+ const ctx = { metadata: parsedMetadata, observationName };
+ const inResult = normalizeInput(parsedInput, ctx);
+ const outResult = normalizeOutput(parsedOutput, ctx);
+ const outputClean = cleanLegacyOutput(parsedOutput, parsedOutput);
+ const messages = combineInputOutputMessages(inResult, outResult, outputClean);
+
+ const toolsMap = new Map<string, ToolDefinition>();
+ for (const message of messages) {
+ if (message.tools && Array.isArray(message.tools)) {
+ for (const tool of message.tools) {
+ if (!toolsMap.has(tool.name)) {
+ toolsMap.set(tool.name, tool);
+ }
+ }
+ }
+ }
+
+ const inputMessageCount = inResult.success ? inResult.data.length : 0;
+ let toolCallCounter = 0;
+ const messageToToolCallNumbers = new Map<number, number[]>();
+ const toolCallCounts = new Map<string, number>();
+ const toolCallsByName = new Map<string, ToolCallInvocation[]>();
+
+ for (let i = 0; i < messages.length; i++) {
+ const message = messages[i];
+ const isOutputMessage = i >= inputMessageCount;
+ const toolCallList = parseToolCallsFromMessage(message);
+
+ if (toolCallList.length > 0) {
+ const messageToolNumbers: number[] = [];
+
+ for (const toolCall of toolCallList) {
+ const calledToolName = getToolCallName(toolCall);
+
+ if (calledToolName && isOutputMessage) {
+ toolCallCounts.set(
+ calledToolName,
+ (toolCallCounts.get(calledToolName) || 0) + 1,
+ );
+ toolCallCounter++;
+ messageToolNumbers.push(toolCallCounter);
+
+ const toolCallsForName = toolCallsByName.get(calledToolName) ?? [];
+ toolCallsForName.push({
+ id: getToolCallStringField(toolCall, "id"),
+ name: calledToolName,
+ arguments: getToolCallArguments(toolCall),
+ invocationNumber: toolCallCounter,
+ });
+ toolCallsByName.set(calledToolName, toolCallsForName);
+ }
+ }
+
+ if (messageToolNumbers.length > 0) {
+ messageToToolCallNumbers.set(i, messageToolNumbers);
+ }
+ }
+ }
+
+ const sortedTools = Array.from(toolsMap.values()).sort((a, b) => {
+ const callCountA = toolCallCounts.get(a.name) || 0;
+ const callCountB = toolCallCounts.get(b.name) || 0;
+ if (callCountA > 0 && callCountB === 0) return -1;
+ if (callCountA === 0 && callCountB > 0) return 1;
+ return callCountB - callCountA;
+ });
+
+ const toolNameToDefinitionNumber = new Map<string, number>();
+ sortedTools.forEach((tool, index) => {
+ toolNameToDefinitionNumber.set(tool.name, index + 1);
+ });
+
+ return {
+ canDisplayAsChat:
+ (inResult.success || outResult.success) && messages.length > 0,
+ allMessages: messages as ChatMlMessage[],
+ additionalInput: extractAdditionalInput(parsedInput),
+ allTools: sortedTools,
+ toolCallCounts,
+ toolCallsByName,
+ messageToToolCallNumbers,
+ toolNameToDefinitionNumber,
+ inputMessageCount,
+ };
+}
+
/**
* Hook to parse input/output into ChatML format and extract tool information.
*
@@ -103,130 +201,38 @@ export function useChatMLParser(
preParsedInput?: unknown,
preParsedOutput?: unknown,
preParsedMetadata?: unknown,
+ preParsedResult?: ChatMLParserResult,
): ChatMLParserResult {
// Use pre-parsed data if available (from Web Worker), otherwise parse synchronously
// This eliminates ~100ms of duplicate parsing when data comes from useParsedObservation
- const parsedInput =
- preParsedInput !== undefined
+ const parsedInput = preParsedResult
+ ? undefined
+ : preParsedInput !== undefined
? preParsedInput
: deepParseJson(input, { maxSize: 300_000, maxDepth: 25 });
- const parsedOutput =
- preParsedOutput !== undefined
+ const parsedOutput = preParsedResult
+ ? undefined
+ : preParsedOutput !== undefined
? preParsedOutput
: deepParseJson(output, { maxSize: 300_000, maxDepth: 25 });
- const parsedMetadata =
- preParsedMetadata !== undefined
+ const parsedMetadata = preParsedResult
+ ? undefined
+ : preParsedMetadata !== undefined
? preParsedMetadata
: deepParseJson(metadata, { maxSize: 100_000, maxDepth: 25 });
- return useMemo(() => {
- // Normalize input
- const ctx = { metadata: parsedMetadata, observationName };
- const inResult = normalizeInput(parsedInput, ctx);
-
- // Normalize output
- const outResult = normalizeOutput(parsedOutput, ctx);
-
- // Clean legacy output
- const outputClean = cleanLegacyOutput(parsedOutput, parsedOutput);
-
- // Combine messages
- const messages = combineInputOutputMessages(
- inResult,
- outResult,
- outputClean,
- );
-
- // Extract all unique tools from messages (no numbering yet)
- const toolsMap = new Map<string, ToolDefinition>();
-
- for (const message of messages) {
- if (message.tools && Array.isArray(message.tools)) {
- for (const tool of message.tools) {
- if (!toolsMap.has(tool.name)) {
- toolsMap.set(tool.name, tool);
- }
- }
- }
- }
-
- // Count tool call invocations
- // Only number tool calls from OUTPUT messages (current invocation), not input (history)
- const inputMessageCount = inResult.success ? inResult.data.length : 0;
- let toolCallCounter = 0;
- const messageToToolCallNumbers = new Map<number, number[]>();
- const toolCallCounts = new Map<string, number>();
- const toolCallsByName = new Map<string, ToolCallInvocation[]>();
-
- for (let i = 0; i < messages.length; i++) {
- const message = messages[i];
- const isOutputMessage = i >= inputMessageCount;
-
- const toolCallList = parseToolCallsFromMessage(message);
-
- if (toolCallList.length > 0) {
- const messageToolNumbers: number[] = [];
-
- for (const toolCall of toolCallList) {
- const calledToolName = getToolCallName(toolCall);
-
- if (calledToolName) {
- // Count tool calls from OUTPUT messages only
- if (isOutputMessage) {
- toolCallCounts.set(
- calledToolName,
- (toolCallCounts.get(calledToolName) || 0) + 1,
- );
- toolCallCounter++;
- messageToolNumbers.push(toolCallCounter);
-
- const toolCallsForName =
- toolCallsByName.get(calledToolName) ?? [];
- toolCallsForName.push({
- id: getToolCallStringField(toolCall, "id"),
- name: calledToolName,
- arguments: getToolCallArguments(toolCall),
- invocationNumber: toolCallCounter,
- });
- toolCallsByName.set(calledToolName, toolCallsForName);
- }
- }
- }
-
- if (messageToolNumbers.length > 0) {
- messageToToolCallNumbers.set(i, messageToolNumbers);
- }
- }
- }
-
- // Sort tools by display order (called first, then by call count)
- const sortedTools = Array.from(toolsMap.values()).sort((a, b) => {
- const callCountA = toolCallCounts.get(a.name) || 0;
- const callCountB = toolCallCounts.get(b.name) || 0;
- if (callCountA > 0 && callCountB === 0) return -1;
- if (callCountA === 0 && callCountB > 0) return 1;
- return callCountB - callCountA;
- });
-
- // Assign definition numbers based on sorted display order
- const toolNameToDefinitionNumber = new Map<string, number>();
- sortedTools.forEach((tool, index) => {
- toolNameToDefinitionNumber.set(tool.name, index + 1);
- });
-
- return {
- canDisplayAsChat:
- (inResult.success || outResult.success) && messages.length > 0,
- allMessages: messages as ChatMlMessage[],
- additionalInput: extractAdditionalInput(parsedInput),
- allTools: sortedTools,
- toolCallCounts,
- toolCallsByName,
- messageToToolCallNumbers,
- toolNameToDefinitionNumber,
- inputMessageCount,
- };
- }, [parsedInput, parsedOutput, parsedMetadata, observationName]);
+ return useMemo(
+ () =>
+ preParsedResult ??
+ parseChatML(parsedInput, parsedOutput, parsedMetadata, observationName),
+ [
+ preParsedResult,
+ parsedInput,
+ parsedOutput,
+ parsedMetadata,
+ observationName,
+ ],
+ );
}
// Re-export for use in ChatMessage
diff --git a/web/src/features/feature-flags/README.md b/web/src/features/feature-flags/README.md
index cdc052c8a8..1ad697131d 100644
--- a/web/src/features/feature-flags/README.md
+++ b/web/src/features/feature-flags/README.md
@@ -13,3 +13,7 @@ When is a feature flag enabled?
1. flag is in user.feature_flags
2. LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES is set
3. user.admin is true
+
+User-controlled previews may pass `{ enableForAdmins: false }` so an
+administrator can opt in or out like any other user. The deployment-wide
+`LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES` override still forces flags on.
diff --git a/web/src/features/feature-flags/available-flags.ts b/web/src/features/feature-flags/available-flags.ts
index 30f7fca3c5..02a2ce0303 100644
--- a/web/src/features/feature-flags/available-flags.ts
+++ b/web/src/features/feature-flags/available-flags.ts
@@ -1,4 +1,5 @@
export const availableFlags = [
+ "modernSession",
// TODO(remove ~2026-06-19): "searchBar" is retired — the grammar search bar
// is now GA on the v4 events tables for everyone (see useSearchBarEnabled),
// no longer a per-user Feature Preview opt-in. Kept as dead plumbing for a
diff --git a/web/src/features/feature-flags/components/FeatureFlagToggle.tsx b/web/src/features/feature-flags/components/FeatureFlagToggle.tsx
index 6afce5aa8c..0f9e234ef2 100644
--- a/web/src/features/feature-flags/components/FeatureFlagToggle.tsx
+++ b/web/src/features/feature-flags/components/FeatureFlagToggle.tsx
@@ -16,7 +16,7 @@ const isWhitelistedForFeature = (
featureFlag: Flag,
): boolean => {
const flags = session.data?.user?.featureFlags;
- return flags !== undefined && flags[featureFlag];
+ return flags?.[featureFlag] === true;
};
export const FeatureFlagToggle = (props: {
diff --git a/web/src/features/feature-flags/hooks/useIsFeatureEnabled.ts b/web/src/features/feature-flags/hooks/useIsFeatureEnabled.ts
index e69362d2c9..6c7951251f 100644
--- a/web/src/features/feature-flags/hooks/useIsFeatureEnabled.ts
+++ b/web/src/features/feature-flags/hooks/useIsFeatureEnabled.ts
@@ -1,7 +1,10 @@
import { useSession } from "next-auth/react";
import type { Flag } from "../types";
-export default function useIsFeatureEnabled(feature: Flag): boolean {
+export default function useIsFeatureEnabled(
+ feature: Flag,
+ { enableForAdmins = true }: { enableForAdmins?: boolean } = {},
+): boolean {
const session = useSession();
const isAdmin = session.data?.user?.admin ?? false;
@@ -12,5 +15,9 @@ export default function useIsFeatureEnabled(feature: Flag): boolean {
const isFeatureEnabledOnUser =
session.data?.user?.featureFlags[feature] ?? false;
- return isExperimentalFeaturesEnabled || isAdmin || isFeatureEnabledOnUser;
+ return (
+ isExperimentalFeaturesEnabled ||
+ (enableForAdmins && isAdmin) ||
+ isFeatureEnabledOnUser
+ );
}
diff --git a/web/src/features/feature-flags/types.ts b/web/src/features/feature-flags/types.ts
index 9529f00e68..4416608325 100644
--- a/web/src/features/feature-flags/types.ts
+++ b/web/src/features/feature-flags/types.ts
@@ -2,5 +2,8 @@ import { type availableFlags } from "./available-flags";
export type Flag = (typeof availableFlags)[number];
export type Flags = {
- [key in (typeof availableFlags)[number]]: boolean;
+ [key in Exclude<Flag, "modernSession">]: boolean;
+} & {
+ // Optional while older sessions and test fixtures roll across the new flag.
+ modernSession?: boolean;
};
diff --git a/web/src/features/feature-previews/assets/modern-session-dark.svg b/web/src/features/feature-previews/assets/modern-session-dark.svg
new file mode 100644
index 0000000000..83bce45c42
--- /dev/null
+++ b/web/src/features/feature-previews/assets/modern-session-dark.svg
@@ -0,0 +1,39 @@
+<svg width="1200" height="700" viewBox="0 0 1200 700" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <rect width="1200" height="700" fill="#09090B"/>
+ <rect x="32" y="28" width="1136" height="644" rx="18" fill="#111827" stroke="#334155" stroke-width="2"/>
+ <rect x="32" y="28" width="1136" height="72" rx="18" fill="#0F172A"/>
+ <path d="M32 100H1168" stroke="#334155" stroke-width="2"/>
+ <rect x="62" y="52" width="148" height="22" rx="6" fill="#475569"/>
+ <rect x="930" y="48" width="208" height="30" rx="15" fill="#334155"/>
+ <path d="M350 100V672" stroke="#334155" stroke-width="2"/>
+ <rect x="54" y="124" width="274" height="118" rx="12" fill="#172554" stroke="#60A5FA" stroke-width="2"/>
+ <rect x="74" y="146" width="126" height="16" rx="5" fill="#E2E8F0"/>
+ <rect x="74" y="176" width="204" height="10" rx="5" fill="#94A3B8"/>
+ <rect x="74" y="198" width="150" height="10" rx="5" fill="#475569"/>
+ <rect x="74" y="218" width="164" height="12" rx="6" fill="#1E3A8A"/>
+ <rect x="54" y="256" width="274" height="104" rx="12" fill="#0F172A" stroke="#334155"/>
+ <rect x="74" y="278" width="138" height="16" rx="5" fill="#CBD5E1"/>
+ <rect x="74" y="308" width="196" height="10" rx="5" fill="#64748B"/>
+ <rect x="74" y="332" width="164" height="12" rx="6" fill="#334155"/>
+ <rect x="54" y="374" width="274" height="104" rx="12" fill="#0F172A" stroke="#334155"/>
+ <rect x="74" y="396" width="112" height="16" rx="5" fill="#CBD5E1"/>
+ <rect x="74" y="426" width="210" height="10" rx="5" fill="#64748B"/>
+ <rect x="74" y="450" width="164" height="12" rx="6" fill="#334155"/>
+ <rect x="378" y="118" width="762" height="52" rx="10" fill="#0F172A" stroke="#334155"/>
+ <rect x="398" y="136" width="130" height="16" rx="5" fill="#E2E8F0"/>
+ <rect x="548" y="139" width="184" height="10" rx="5" fill="#64748B"/>
+ <rect x="954" y="139" width="164" height="10" rx="5" fill="#64748B"/>
+ <rect x="402" y="194" width="530" height="60" rx="14" fill="#1E293B"/>
+ <rect x="426" y="217" width="350" height="14" rx="7" fill="#94A3B8"/>
+ <rect x="402" y="276" width="704" height="116" rx="14" fill="#052E2B"/>
+ <rect x="426" y="302" width="624" height="13" rx="6" fill="#CBD5E1"/>
+ <rect x="426" y="330" width="572" height="13" rx="6" fill="#94A3B8"/>
+ <rect x="426" y="358" width="466" height="13" rx="6" fill="#94A3B8"/>
+ <rect x="378" y="430" width="762" height="52" rx="10" fill="#0F172A" stroke="#334155"/>
+ <rect x="398" y="448" width="130" height="16" rx="5" fill="#E2E8F0"/>
+ <rect x="548" y="451" width="184" height="10" rx="5" fill="#64748B"/>
+ <rect x="402" y="506" width="486" height="60" rx="14" fill="#1E293B"/>
+ <rect x="426" y="529" width="316" height="14" rx="7" fill="#94A3B8"/>
+ <rect x="402" y="588" width="704" height="60" rx="14" fill="#052E2B"/>
+ <rect x="426" y="611" width="590" height="14" rx="7" fill="#94A3B8"/>
+</svg>
diff --git a/web/src/features/feature-previews/assets/modern-session-light.svg b/web/src/features/feature-previews/assets/modern-session-light.svg
new file mode 100644
index 0000000000..10b8d1f209
--- /dev/null
+++ b/web/src/features/feature-previews/assets/modern-session-light.svg
@@ -0,0 +1,39 @@
+<svg width="1200" height="700" viewBox="0 0 1200 700" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <rect width="1200" height="700" fill="#F8FAFC"/>
+ <rect x="32" y="28" width="1136" height="644" rx="18" fill="white" stroke="#E2E8F0" stroke-width="2"/>
+ <rect x="32" y="28" width="1136" height="72" rx="18" fill="#F8FAFC"/>
+ <path d="M32 100H1168" stroke="#E2E8F0" stroke-width="2"/>
+ <rect x="62" y="52" width="148" height="22" rx="6" fill="#CBD5E1"/>
+ <rect x="930" y="48" width="208" height="30" rx="15" fill="#E2E8F0"/>
+ <path d="M350 100V672" stroke="#E2E8F0" stroke-width="2"/>
+ <rect x="54" y="124" width="274" height="118" rx="12" fill="#EFF6FF" stroke="#60A5FA" stroke-width="2"/>
+ <rect x="74" y="146" width="126" height="16" rx="5" fill="#334155"/>
+ <rect x="74" y="176" width="204" height="10" rx="5" fill="#94A3B8"/>
+ <rect x="74" y="198" width="150" height="10" rx="5" fill="#CBD5E1"/>
+ <rect x="74" y="218" width="164" height="12" rx="6" fill="#DBEAFE"/>
+ <rect x="54" y="256" width="274" height="104" rx="12" fill="#F8FAFC" stroke="#E2E8F0"/>
+ <rect x="74" y="278" width="138" height="16" rx="5" fill="#475569"/>
+ <rect x="74" y="308" width="196" height="10" rx="5" fill="#94A3B8"/>
+ <rect x="74" y="332" width="164" height="12" rx="6" fill="#E2E8F0"/>
+ <rect x="54" y="374" width="274" height="104" rx="12" fill="#F8FAFC" stroke="#E2E8F0"/>
+ <rect x="74" y="396" width="112" height="16" rx="5" fill="#475569"/>
+ <rect x="74" y="426" width="210" height="10" rx="5" fill="#94A3B8"/>
+ <rect x="74" y="450" width="164" height="12" rx="6" fill="#E2E8F0"/>
+ <rect x="378" y="118" width="762" height="52" rx="10" fill="#F8FAFC" stroke="#E2E8F0"/>
+ <rect x="398" y="136" width="130" height="16" rx="5" fill="#334155"/>
+ <rect x="548" y="139" width="184" height="10" rx="5" fill="#94A3B8"/>
+ <rect x="954" y="139" width="164" height="10" rx="5" fill="#94A3B8"/>
+ <rect x="402" y="194" width="530" height="60" rx="14" fill="#F1F5F9"/>
+ <rect x="426" y="217" width="350" height="14" rx="7" fill="#64748B"/>
+ <rect x="402" y="276" width="704" height="116" rx="14" fill="#ECFDF5"/>
+ <rect x="426" y="302" width="624" height="13" rx="6" fill="#475569"/>
+ <rect x="426" y="330" width="572" height="13" rx="6" fill="#64748B"/>
+ <rect x="426" y="358" width="466" height="13" rx="6" fill="#64748B"/>
+ <rect x="378" y="430" width="762" height="52" rx="10" fill="#F8FAFC" stroke="#E2E8F0"/>
+ <rect x="398" y="448" width="130" height="16" rx="5" fill="#334155"/>
+ <rect x="548" y="451" width="184" height="10" rx="5" fill="#94A3B8"/>
+ <rect x="402" y="506" width="486" height="60" rx="14" fill="#F1F5F9"/>
+ <rect x="426" y="529" width="316" height="14" rx="7" fill="#64748B"/>
+ <rect x="402" y="588" width="704" height="60" rx="14" fill="#ECFDF5"/>
+ <rect x="426" y="611" width="590" height="14" rx="7" fill="#64748B"/>
+</svg>
diff --git a/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx b/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx
index 7c7732eba8..f7728e4eaf 100644
--- a/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx
+++ b/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx
@@ -1,3 +1,10 @@
+import { useSession } from "next-auth/react";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { api } from "@/src/utils/api";
+
import {
FeaturePreviewModal,
type PreviewFlag,
@@ -9,11 +16,57 @@ type ControlledFeaturePreviewModalProps = {
onOpenChange: (open: boolean) => void;
};
+const PREVIEW_LABEL: Record<PreviewFlag, string> = {
+ modernSession: "Compact Session View",
+ searchBar: "Filter Search Bar",
+};
+
export function ControlledFeaturePreviewModal({
open,
onOpenChange,
}: ControlledFeaturePreviewModalProps) {
+ const authSession = useSession();
+ const { isBetaEnabled } = useV4Beta();
+ const capture = usePostHogClientCapture();
+ const setFeaturePreviewEnabled =
+ api.userAccount.setFeaturePreviewEnabled.useMutation({
+ onSuccess: async (_data, variables) => {
+ await authSession.update();
+ capture("user_settings:feature_preview_toggled", {
+ feature: variables.flag,
+ isEnabled: variables.enabled,
+ });
+ showSuccessToast({
+ title: "Feature preview updated",
+ description: `${PREVIEW_LABEL[variables.flag]} preview has been ${
+ variables.enabled ? "enabled" : "disabled"
+ }.`,
+ });
+ },
+ onError: (error) => {
+ showErrorToast("Failed to update feature preview", error.message);
+ },
+ });
+
+ const onToggle = (flag: PreviewFlag) => (enabled: boolean) =>
+ setFeaturePreviewEnabled.mutate({ flag, enabled });
+
const state: Partial<Record<PreviewFlag, PreviewState>> = {
+ modernSession: {
+ enabled:
+ authSession.data?.user?.featureFlags.modernSession === true ||
+ authSession.data?.environment.enableExperimentalFeatures === true,
+ disabled:
+ !isBetaEnabled ||
+ authSession.data?.environment.enableExperimentalFeatures === true,
+ warningReason: !isBetaEnabled
+ ? "Compact Session View is only available on the events-backed session view. Turn on Fast (Preview) to enable it."
+ : authSession.data?.environment.enableExperimentalFeatures === true
+ ? "This preview is enabled by LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES, so a per-user opt-out does not disable it."
+ : undefined,
+ onToggle: onToggle("modernSession"),
+ isToggling: setFeaturePreviewEnabled.isPending,
+ },
// The "Filter Search Bar" preview is retired — the bar is now generally
// available on the v4 events tables for everyone (see useSearchBarEnabled),
// so it no longer renders a tile here. The `searchBar` flag plumbing
diff --git a/web/src/features/feature-previews/components/FeaturePreviewModal.stories.tsx b/web/src/features/feature-previews/components/FeaturePreviewModal.stories.tsx
index 3cb873dde6..fbf43e9ad2 100644
--- a/web/src/features/feature-previews/components/FeaturePreviewModal.stories.tsx
+++ b/web/src/features/feature-previews/components/FeaturePreviewModal.stories.tsx
@@ -56,7 +56,7 @@ const meta = preview.meta({
open: true,
onOpenChange: fn(),
state: {
- searchBar: { enabled: false, onToggle: fn(), isToggling: false },
+ modernSession: { enabled: false, onToggle: fn(), isToggling: false },
},
},
render: StatefulFeaturePreviewModal,
@@ -67,10 +67,10 @@ export const Default = meta.story({});
export const Warning = meta.story({
args: {
state: {
- searchBar: {
+ modernSession: {
enabled: false,
warningReason:
- "The search bar appears on the new (v4) Observations and Traces tables. Turn on Fast (Preview) in the sidebar to use it after enabling this preview.",
+ "This preview is enabled globally, so a per-user opt-out does not disable it.",
onToggle: fn(),
},
},
@@ -80,7 +80,7 @@ export const Warning = meta.story({
export const Loading = meta.story({
args: {
state: {
- searchBar: { enabled: false, onToggle: fn(), isToggling: false },
+ modernSession: { enabled: false, onToggle: fn(), isToggling: true },
},
},
});
diff --git a/web/src/features/feature-previews/components/FeaturePreviewModal.tsx b/web/src/features/feature-previews/components/FeaturePreviewModal.tsx
index 12a6e8b284..36cb1967af 100644
--- a/web/src/features/feature-previews/components/FeaturePreviewModal.tsx
+++ b/web/src/features/feature-previews/components/FeaturePreviewModal.tsx
@@ -1,5 +1,5 @@
import Image from "next/image";
-import { useEffect, useState } from "react";
+import { useState } from "react";
import {
Dialog,
@@ -15,14 +15,15 @@ import { cn } from "@/src/utils/tailwind";
import filterSearchBarDarkIllustration from "../assets/filter-search-bar-dark.svg";
import filterSearchBarLightIllustration from "../assets/filter-search-bar-light.svg";
+import modernSessionDarkIllustration from "../assets/modern-session-dark.svg";
+import modernSessionLightIllustration from "../assets/modern-session-light.svg";
/** Flags the Feature Preview modal can toggle. Keep in sync with the
* userAccount.setFeaturePreviewEnabled allowlist and available-flags.ts.
- * NOTE: the current flag is retired and no longer renders a tile — see
- * ControlledFeaturePreviewModal. It is kept in the type + registry below only
- * as dead code for a safe rollback.
- * TODO(remove ~2026-06-19): drop "searchBar" here once GA is confirmed. */
-export type PreviewFlag = "searchBar";
+ * `searchBar` is retired and no longer renders a tile — see
+ * ControlledFeaturePreviewModal. It remains as rollback plumbing.
+ * TODO(remove ~2026-06-19): drop "searchBar" once GA is confirmed. */
+export type PreviewFlag = "modernSession" | "searchBar";
type PreviewIllustration = {
light: React.ComponentProps<typeof Image>["src"];
@@ -44,6 +45,7 @@ type PreviewRegistryItem = {
* owns the session + the toggle mutation). The static content lives here. */
export type PreviewState = {
enabled: boolean;
+ disabled?: boolean;
warningReason?: string;
onToggle: (enabled: boolean) => void;
isToggling?: boolean;
@@ -52,6 +54,21 @@ export type PreviewState = {
// Static registry — one entry per preview. Order = sidebar order; each
// preview ships separate light/dark illustrations.
const PREVIEW_REGISTRY: PreviewRegistryItem[] = [
+ {
+ flag: "modernSession",
+ title: "Compact Session View",
+ sidebarLabel: "Compact Session View",
+ description:
+ "Navigate every trace in a session from one continuous conversation feed, with tools and structured data available on demand.",
+ details:
+ "Compact Session View replaces separate trace cards with a compact minimap and a virtualized feed. Jump between traces, keep the active trace in view, or temporarily show inline tool calls and system prompts.",
+ feedbackUrl: "https://github.com/orgs/langfuse/discussions",
+ illustration: {
+ light: modernSessionLightIllustration,
+ dark: modernSessionDarkIllustration,
+ alt: "Compact Session View showing a trace minimap beside a continuous session conversation feed.",
+ },
+ },
// TODO(remove ~2026-06-19): dead registry entry — "searchBar" is GA on the v4
// events tables and no longer surfaced in the dialog (no state entry in
// ControlledFeaturePreviewModal), so this is filtered out and never renders.
@@ -93,13 +110,7 @@ export function FeaturePreviewModal({
const [selectedFlag, setSelectedFlag] = useState<PreviewFlag | null>(
items[0]?.flag ?? null,
);
- // Keep the selection valid if the available previews change.
- useEffect(() => {
- if (items.length > 0 && !items.some((i) => i.flag === selectedFlag)) {
- setSelectedFlag(items[0]!.flag);
- }
- }, [items, selectedFlag]);
-
+ // A removed preview falls back without synchronizing derived props into state.
const selected = items.find((i) => i.flag === selectedFlag) ?? items[0];
const selectedState = selected ? state[selected.flag] : undefined;
@@ -143,7 +154,11 @@ export function FeaturePreviewModal({
{item.sidebarLabel}
</span>
<span className="text-muted-foreground mt-1 line-clamp-2 block text-xs">
- {state[item.flag]?.enabled ? "Enabled" : "Available"}
+ {state[item.flag]?.disabled
+ ? "Unavailable"
+ : state[item.flag]?.enabled
+ ? "Enabled"
+ : "Available"}
</span>
</span>
</button>
@@ -182,7 +197,10 @@ export function FeaturePreviewModal({
<div className="flex shrink-0 flex-col items-end gap-2">
<Switch
checked={selectedState.enabled}
- disabled={selectedState.isToggling === true}
+ disabled={
+ selectedState.disabled === true ||
+ selectedState.isToggling === true
+ }
onCheckedChange={selectedState.onToggle}
aria-label={`Toggle ${selected.title}`}
/>
diff --git a/web/src/features/filters/filter-integration.clienttest.ts b/web/src/features/filters/filter-integration.clienttest.ts
index 8e034e1873..d06e96e76c 100644
--- a/web/src/features/filters/filter-integration.clienttest.ts
+++ b/web/src/features/filters/filter-integration.clienttest.ts
@@ -825,7 +825,7 @@ describe("Saved view validation", () => {
];
// LFE-10520: the default view is "All observations with I/O", expressed as
// a real, renderable boolean filter (not a hidden flag). Selecting a
- // generation preset still applies its positionInTrace filters.
+ // LLM-call preset still applies its positionInTrace filters.
const defaultPreset = getSessionDetailPresetToApply({
selectedViewId: null,
hasFilters: false,
@@ -852,19 +852,19 @@ describe("Saved view validation", () => {
validateFilters(defaultPreset?.filters ?? [], sessionEventColumns),
).toEqual(defaultPreset?.filters ?? []);
- const firstGenerationPreset = SESSION_DETAIL_SYSTEM_PRESETS.find(
- (preset) => preset.name === "First Generation in Trace",
+ const firstLlmCallPreset = SESSION_DETAIL_SYSTEM_PRESETS.find(
+ (preset) => preset.name === "First LLM Call per Trace",
);
- const appliedFirstGeneration = getSessionDetailPresetToApply({
- selectedViewId: firstGenerationPreset?.id ?? null,
+ const appliedFirstLlmCall = getSessionDetailPresetToApply({
+ selectedViewId: firstLlmCallPreset?.id ?? null,
hasFilters: false,
});
const lastPreset = SESSION_DETAIL_SYSTEM_PRESETS.find(
- (preset) => preset.name === "Last Generation in Trace",
+ (preset) => preset.name === "Last LLM Call per Trace",
);
- expect(appliedFirstGeneration).toEqual(firstGenerationPreset);
- expect(firstGenerationPreset?.filters).toEqual([
+ expect(appliedFirstLlmCall).toEqual(firstLlmCallPreset);
+ expect(firstLlmCallPreset?.filters).toEqual([
{
column: "type",
type: "stringOptions",
@@ -879,11 +879,8 @@ describe("Saved view validation", () => {
},
]);
expect(
- validateFilters(
- firstGenerationPreset?.filters ?? [],
- sessionEventColumns,
- ),
- ).toEqual(firstGenerationPreset?.filters ?? []);
+ validateFilters(firstLlmCallPreset?.filters ?? [], sessionEventColumns),
+ ).toEqual(firstLlmCallPreset?.filters ?? []);
expect(lastPreset?.filters).toEqual([
{
column: "type",
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 654cca354f..cf5672cd2a 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -124,6 +124,8 @@ export const events = {
"copy_session_id_click",
"truncated_observation_open_trace_click",
"truncated_observation_download_click",
+ "inline_tools_toggled",
+ "system_prompt_toggled",
],
eval_config: [
"new_form_submit",
@@ -244,7 +246,7 @@ export const events = {
"tracing_agent_prompt_copy_clicked",
"tracing_manual_docs_link_clicked",
],
- user_settings: ["theme_changed"],
+ user_settings: ["theme_changed", "feature_preview_toggled"],
project_settings: [
"project_delete",
"rename_form_submit",
diff --git a/web/src/server/api/routers/userAccount.ts b/web/src/server/api/routers/userAccount.ts
index d69cb6a347..192ee4253f 100644
--- a/web/src/server/api/routers/userAccount.ts
+++ b/web/src/server/api/routers/userAccount.ts
@@ -101,11 +101,9 @@ export const userAccountRouter = createTRPCRouter({
z.object({
// Allowlist of user-toggleable Feature Preview flags (the Feature
// Preview modal). Keep in sync with the modal's preview registry.
- // TODO(remove ~2026-06-19): "searchBar" is retired — the bar is now GA
- // on the v4 events tables (see useSearchBarEnabled) and no longer has a
- // dialog tile. Kept in the allowlist as dead plumbing for a safe
- // rollback; drop once the GA rollout is confirmed stable.
- flag: z.enum(["searchBar"]),
+ // `modernSession` is the active preview. `searchBar` is retired — the
+ // bar is now GA on v4 events tables — but remains as rollback plumbing.
+ flag: z.enum(["modernSession", "searchBar"]),
enabled: z.boolean(),
}),
)