Skip to content

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

feat(trace): Move messages tab and reuse session timeline (#18953)

Ben Bachem30427b5ea023
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsx
index 362e6856c6..cdd067e5d8 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsx
@@ -10,11 +10,12 @@ import {
useSessionConversationTimelineController,
type SessionConversationTimelineScrollTarget,
} from "@/src/features/sessions/hooks/useSessionConversationTimelineController";
-import { type SessionConversationTimelineTrace } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace";
import { getSessionConversationEntries } from "../../fns/getSessionConversationEntries";
import { type Observation } from "@langfuse/shared";
-type TraceProps = ComponentProps<typeof SessionConversationTimelineTrace>;
+type TraceProps = ComponentProps<
+ typeof SessionConversationalView
+>["traces"][number];
type TranscriptState = Extract<TraceProps["state"], { type: "transcript" }>;
type WorkflowObservation = TranscriptObservation & {
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.tsx
index 9c8aa4b1c3..82d03908f1 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.tsx
@@ -15,6 +15,7 @@ import { getSessionToolStatus } from "@/src/features/sessions/components/Connect
import { getSessionTranscriptThreads } from "../../fns/getSessionTranscriptThreads";
import { getSessionConversationEntries } from "../../fns/getSessionConversationEntries";
import { computeIdleGapSeconds } from "@/src/features/sessions/sessionIdleGap";
+import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";
export function SessionConversationalView(
props: (
@@ -30,7 +31,9 @@ export function SessionConversationalView(
isSearchPending: boolean;
})
) & {
- traces: ComponentProps<typeof SessionConversationTimeline>["traces"];
+ traces: readonly (ComponentProps<
+ typeof SessionConversationTimeline
+ >["traces"][number] & { trace: EventSessionTrace })[];
controller: SessionConversationTimelineController;
},
) {
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.stories.tsx
index 8fa0756e29..7d41955be3 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.stories.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.stories.tsx
@@ -1,13 +1,15 @@
import preview from "@/.storybook/preview";
+import { useState, type ComponentProps } from "react";
import { expect, fn, userEvent, waitFor } from "storybook/test";
import { SessionConversationTimeline } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline";
import { useSessionConversationTimelineController } from "@/src/features/sessions/hooks/useSessionConversationTimelineController";
function SessionConversationTimelineStory({
dynamicContent,
+ navigation,
}: {
dynamicContent: boolean;
-}) {
+} & Pick<ComponentProps<typeof SessionConversationTimeline>, "navigation">) {
const traces = Array.from(
{ length: dynamicContent ? 40 : 3 },
(_, index) => ({
@@ -73,7 +75,11 @@ function SessionConversationTimelineStory({
const controller = useSessionConversationTimelineController(traces);
return (
<div className="h-[200px]">
- <SessionConversationTimeline traces={traces} controller={controller} />
+ <SessionConversationTimeline
+ traces={traces}
+ controller={controller}
+ navigation={navigation}
+ />
</div>
);
}
@@ -84,6 +90,111 @@ const meta = preview.meta({
});
export default meta;
+function SingleTraceLoadingStory() {
+ const [isLoading, setIsLoading] = useState(true);
+ const traces: ComponentProps<typeof SessionConversationTimeline>["traces"] = [
+ {
+ trace: { id: "trace-1", name: "Loading trace" },
+ turnNumber: 1,
+ variant: "single-trace",
+ state: isLoading ? { type: "loading" } : { type: "empty" },
+ onOpenTrace: fn(),
+ onOpenObservation: fn(),
+ scrollTarget: null,
+ },
+ ];
+ const controller = useSessionConversationTimelineController(traces);
+ return (
+ <div>
+ <button onClick={() => setIsLoading(false)}>Finish loading</button>
+ <div className="h-[600px]">
+ <SessionConversationTimeline
+ traces={traces}
+ controller={controller}
+ navigation={{
+ previousTrace: { href: "#previous", count: 3 },
+ nextTrace: { href: "#next", count: 1 },
+ }}
+ />
+ </div>
+ </div>
+ );
+}
+
+export const StableSingleTraceLoading = meta.story({
+ name: "(Test) Single Trace Navigation Stays Stable While Loading",
+ render: () => <SingleTraceLoadingStory />,
+ play: async ({ canvas }) => {
+ const previous = canvas.getByRole("link", {
+ name: "Previous trace in session (3)",
+ });
+ const next = canvas.getByRole("link", {
+ name: "Next trace in session (1)",
+ });
+ expect(
+ canvas.getByRole("status", { name: "Loading messages" }),
+ ).toBeVisible();
+ const previousTop = previous.getBoundingClientRect().top;
+ const nextTop = next.getBoundingClientRect().top;
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Finish loading" }),
+ );
+ expect(
+ canvas.queryByRole("status", { name: "Loading messages" }),
+ ).not.toBeInTheDocument();
+ expect(previous).toBeVisible();
+ expect(next).toBeVisible();
+ expect(previous.getBoundingClientRect().top).toBe(previousTop);
+ expect(next.getBoundingClientRect().top).toBe(nextTop);
+ },
+});
+
+export const TimelineNavigation = meta.story({
+ name: "(Test) Navigation Before And After Messages",
+ args: {
+ navigation: {
+ previousTrace: {
+ count: 3,
+ href: "/project/project-1/traces?peek=previous-trace&traceView=messages",
+ shallow: true,
+ },
+ nextTrace: {
+ count: 1,
+ href: "/project/project-1/traces?peek=next-trace&traceView=messages",
+ shallow: true,
+ },
+ },
+ },
+ play: async ({ canvas, args }) => {
+ const timeline = canvas.getByLabelText("Session conversation timeline");
+ const previous = await canvas.findByRole("link", {
+ name: "Previous trace in session (3)",
+ });
+ const firstTrace = await canvas.findByRole("button", {
+ name: /Turn 1.*trace-1/,
+ });
+ expect(previous.compareDocumentPosition(firstTrace)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ );
+ expect(previous).toHaveAttribute(
+ "href",
+ args.navigation?.previousTrace?.href,
+ );
+ timeline.scrollTop = timeline.scrollHeight;
+ timeline.dispatchEvent(new Event("scroll", { bubbles: true }));
+ const next = await canvas.findByRole("link", {
+ name: "Next trace in session (1)",
+ });
+ const lastTrace = await canvas.findByRole("button", {
+ name: /Turn 3.*trace-3/,
+ });
+ expect(lastTrace.compareDocumentPosition(next)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ );
+ expect(next).toHaveAttribute("href", args.navigation?.nextTrace?.href);
+ },
+});
+
export const ScrollableTimeline = meta.story({
name: "(Test) Scrollable Timeline",
play: async ({ canvas }) => {
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.tsx
index 9e52003a67..02d76c1511 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.tsx
@@ -1,4 +1,6 @@
import { type ComponentProps } from "react";
+import Link from "next/link";
+import { ArrowUp, ArrowDown } from "lucide-react";
import { SessionConversationTimelineTrace } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace";
import { type SessionConversationTimelineController } from "@/src/features/sessions/hooks/useSessionConversationTimelineController";
import styles from "./SessionConversationTimeline.module.css";
@@ -6,11 +8,30 @@ import styles from "./SessionConversationTimeline.module.css";
export function SessionConversationTimeline({
traces,
controller,
+ navigation,
}: {
traces: readonly ComponentProps<typeof SessionConversationTimelineTrace>[];
controller: SessionConversationTimelineController;
+ navigation?: {
+ previousTrace?: Pick<ComponentProps<typeof Link>, "href" | "shallow"> & {
+ count: number;
+ };
+ nextTrace?: Pick<ComponentProps<typeof Link>, "href" | "shallow"> & {
+ count: number;
+ };
+ };
}) {
const { feedRef, virtualItems, virtualizer } = controller;
+ const isSingleTraceView =
+ traces.length > 0 &&
+ traces.every(({ variant }) => variant === "single-trace");
+ const rows = isSingleTraceView
+ ? traces.map((trace, index) => ({
+ key: trace.itemId ?? trace.trace.id,
+ index,
+ start: 0,
+ }))
+ : virtualItems;
return (
<div
@@ -19,30 +40,69 @@ export function SessionConversationTimeline({
className={`${styles.timeline} h-full min-h-0 overflow-y-auto [overflow-anchor:none]`}
>
<div
- style={{
- height: `${virtualizer.getTotalSize()}px`,
- width: "100%",
- position: "relative",
- }}
+ className={isSingleTraceView ? "flex min-h-full flex-col" : undefined}
+ style={
+ isSingleTraceView
+ ? undefined
+ : {
+ height: `${virtualizer.getTotalSize()}px`,
+ width: "100%",
+ position: "relative",
+ }
+ }
>
- {virtualItems.map((virtualItem) => {
+ {rows.map((virtualItem) => {
const traceProps = traces[virtualItem.index];
if (!traceProps) return null;
return (
<div
key={virtualItem.key}
- ref={virtualizer.measureElement}
- data-index={virtualItem.index}
- data-session-virtualizer-row="modern"
- style={{
- position: "absolute",
- top: virtualItem.start,
- left: 0,
- width: "100%",
- }}
+ ref={isSingleTraceView ? undefined : virtualizer.measureElement}
+ data-index={isSingleTraceView ? undefined : virtualItem.index}
+ data-session-virtualizer-row={
+ isSingleTraceView ? undefined : "modern"
+ }
+ className={isSingleTraceView ? "flex flex-1 flex-col" : undefined}
+ style={
+ isSingleTraceView
+ ? undefined
+ : {
+ position: "absolute",
+ top: virtualItem.start,
+ left: 0,
+ width: "100%",
+ }
+ }
>
- <SessionConversationTimelineTrace {...traceProps} />
+ {virtualItem.index === 0 && navigation?.previousTrace && (
+ <div className="flex justify-center pb-4">
+ <Link
+ href={navigation.previousTrace.href}
+ shallow={navigation.previousTrace.shallow}
+ className="text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-ring flex w-full items-center justify-center gap-2 rounded-md border border-dashed px-4 py-3 text-sm transition-colors focus-visible:ring-2 focus-visible:outline-none"
+ >
+ <ArrowUp className="icon-base" />
+ Previous trace in session ({navigation.previousTrace.count})
+ </Link>
+ </div>
+ )}
+ <div className={isSingleTraceView ? "flex-1" : undefined}>
+ <SessionConversationTimelineTrace {...traceProps} />
+ </div>
+ {virtualItem.index === traces.length - 1 &&
+ navigation?.nextTrace && (
+ <div className="flex justify-center pt-4">
+ <Link
+ href={navigation.nextTrace.href}
+ shallow={navigation.nextTrace.shallow}
+ className="text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-ring flex w-full items-center justify-center gap-2 rounded-md border border-dashed px-4 py-3 text-sm transition-colors focus-visible:ring-2 focus-visible:outline-none"
+ >
+ <ArrowDown className="icon-base" />
+ Next trace in session ({navigation.nextTrace.count})
+ </Link>
+ </div>
+ )}
</div>
);
})}
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsx
index 9c258a6e7a..9f133f0a49 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsx
@@ -3,13 +3,14 @@ import preview from "@/.storybook/preview";
import { type ComponentProps } from "react";
import { expect, fn, userEvent, waitFor, within } from "storybook/test";
import { SessionConversationTimelineTrace } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace";
+import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";
type Props = ComponentProps<typeof SessionConversationTimelineTrace>;
type TranscriptState = Extract<Props["state"], { type: "transcript" }>;
type Thread = NonNullable<
TranscriptState["result"]["transcript"]
>["threads"][number];
-const trace: Props["trace"] = {
+const trace: EventSessionTrace = {
id: "trace-1",
name: "Weather assistant",
timestamp: new Date("2026-09-24T12:00:00Z"),
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx
index b4a51333c8..b294cae64a 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx
@@ -26,13 +26,18 @@ export function SessionConversationTimelineTrace({
itemId,
threadIndex,
displayNumber,
+ threadCount,
+ variant = "session",
+ includeNestedThreads = false,
}: {
+ includeNestedThreads?: boolean;
+ variant?: "session" | "single-trace";
itemId?: string;
threadIndex?: number;
threadNumber?: number;
displayNumber?: string;
threadCount?: number;
- trace: EventSessionTrace;
+ trace: Pick<EventSessionTrace, "id" | "name">;
turnNumber: number;
state: PreparedSessionConversationTimelineTraceState;
onOpenTrace: () => void;
@@ -44,72 +49,80 @@ export function SessionConversationTimelineTrace({
requestId: number;
} | null;
}) {
+ const showHeader = variant === "session" || (threadCount ?? 0) > 1;
const hiddenThreadCount =
state.type === "transcript"
- ? getSessionTranscriptThreads(state.result.transcript).hiddenThreadCount
+ ? getSessionTranscriptThreads(
+ state.result.transcript,
+ includeNestedThreads,
+ ).hiddenThreadCount
: 0;
return (
<div
- className="px-4 pb-14 sm:px-6 lg:px-10"
+ className={cn(
+ variant === "single-trace" ? "p-0" : "px-4 pb-14 sm:px-6 lg:px-10",
+ )}
data-session-trace-id={trace.id}
data-session-item-id={itemId}
>
- <div className="group/trace-header mb-6 flex items-center gap-4 pt-5">
- <button
- type="button"
- className="text-muted-foreground hover:text-foreground ph-no-capture flex min-w-0 items-center gap-2 font-mono text-xs transition-colors"
- onClick={onOpenTrace}
- title={`${trace.name ?? "Trace"} (${trace.id})`}
- >
- <span className="border-border bg-tertiary text-foreground flex h-4 min-w-4 shrink-0 items-center justify-center rounded-sm border px-0.5 font-mono text-[10px]">
- {displayNumber ?? turnNumber}
- </span>
- <span
- className="truncate"
- title={`${trace.name ?? "Trace"} · ${trace.id}`}
+ {showHeader && (
+ <div className="group/trace-header mb-6 flex items-center gap-4 pt-5">
+ <button
+ type="button"
+ className="text-muted-foreground hover:text-foreground ph-no-capture flex min-w-0 items-center gap-2 font-mono text-xs transition-colors"
+ onClick={onOpenTrace}
+ title={`${trace.name ?? "Trace"} (${trace.id})`}
>
- {trace.name ?? "Trace"} · {trace.id}
- </span>
- </button>
- <div className="border-border min-w-0 flex-1 border-t border-dashed" />
- <button
- type="button"
- className="text-muted-foreground hover:text-foreground hidden shrink-0 font-mono text-xs group-focus-within/trace-header:block group-hover/trace-header:block hover:underline"
- onClick={onOpenTrace}
- >
- Open trace
- </button>
- {hiddenThreadCount > 0 && (
- <Tooltip
- label={`${hiddenThreadCount} nested ${hiddenThreadCount === 1 ? "thread" : "threads"} hidden`}
+ <span className="border-border bg-tertiary text-foreground flex h-4 min-w-4 shrink-0 items-center justify-center rounded-sm border px-0.5 font-mono text-[10px]">
+ {displayNumber ?? turnNumber}
+ </span>
+ <span
+ className="truncate"
+ title={`${trace.name ?? "Trace"} · ${trace.id}`}
+ >
+ {trace.name ?? "Trace"} · {trace.id}
+ </span>
+ </button>
+ <div className="border-border min-w-0 flex-1 border-t border-dashed" />
+ <button
+ type="button"
+ className="text-muted-foreground hover:text-foreground hidden shrink-0 font-mono text-xs group-focus-within/trace-header:block group-hover/trace-header:block hover:underline"
+ onClick={onOpenTrace}
>
- {({ getTriggerProps }) => (
- <button
- {...getTriggerProps()}
- type="button"
- className="bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors"
- aria-label={`${hiddenThreadCount} nested ${hiddenThreadCount === 1 ? "thread" : "threads"} hidden`}
- >
- <GitBranch className="icon-base" aria-hidden="true" />
- </button>
- )}
- </Tooltip>
- )}
- {state.type === "transcript" && state.result.cutoff && (
- <Tooltip label="Some messages may be missing because the observation limit was reached.">
- {({ getTriggerProps }) => (
- <button
- {...getTriggerProps()}
- type="button"
- className="bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors"
- aria-label="Some messages may be missing"
- >
- <MessageSquareOff className="icon-base" aria-hidden="true" />
- </button>
- )}
- </Tooltip>
- )}
- </div>
+ Open trace
+ </button>
+ {variant === "session" && hiddenThreadCount > 0 && (
+ <Tooltip
+ label={`${hiddenThreadCount} nested ${hiddenThreadCount === 1 ? "thread" : "threads"} hidden`}
+ >
+ {({ getTriggerProps }) => (
+ <button
+ {...getTriggerProps()}
+ type="button"
+ className="bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors"
+ aria-label={`${hiddenThreadCount} nested ${hiddenThreadCount === 1 ? "thread" : "threads"} hidden`}
+ >
+ <GitBranch className="icon-base" aria-hidden="true" />
+ </button>
+ )}
+ </Tooltip>
+ )}
+ {state.type === "transcript" && state.result.cutoff && (
+ <Tooltip label="Some messages may be missing because the observation limit was reached.">
+ {({ getTriggerProps }) => (
+ <button
+ {...getTriggerProps()}
+ type="button"
+ className="bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors"
+ aria-label="Some messages may be missing"
+ >
+ <MessageSquareOff className="icon-base" aria-hidden="true" />
+ </button>
+ )}
+ </Tooltip>
+ )}
+ </div>
+ )}
{state.type === "loading" && (
<div
@@ -157,6 +170,8 @@ export function SessionConversationTimelineTrace({
)}
{state.type === "transcript" && (
<SessionTranscriptContent
+ includeNestedThreads={includeNestedThreads}
+ variant={variant}
{...state}
onOpenObservation={onOpenObservation}
scrollTarget={scrollTarget}
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/SessionTranscriptContent.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/SessionTranscriptContent.tsx
index 72dd1e5038..fab352c22c 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/SessionTranscriptContent.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/SessionTranscriptContent.tsx
@@ -25,21 +25,31 @@ export function SessionTranscriptContent({
onOpenObservation,
scrollTarget,
threadIndex: selectedThreadIndex,
+ variant,
+ includeNestedThreads = false,
}: {
+ includeNestedThreads?: boolean;
+ variant?: ComponentProps<typeof SessionTimelineContentMessage>["variant"];
threadIndex?: number;
result: Extract<SessionTraceTranscriptState, { state: "loaded" }>;
- onOpenObservation: (observationId: string) => void;
+ onOpenObservation?: (observationId: string) => void;
scrollTarget: {
observationId: string;
rowId?: string;
requestId: number;
} | null;
}) {
- const rows = getSessionTranscriptRows(result.transcript).filter(
+ const rows = getSessionTranscriptRows(
+ result.transcript,
+ includeNestedThreads,
+ ).filter(
({ threadIndex }) =>
selectedThreadIndex === undefined || threadIndex === selectedThreadIndex,
);
- const { visibleThreads } = getSessionTranscriptThreads(result.transcript);
+ const { visibleThreads } = getSessionTranscriptThreads(
+ result.transcript,
+ includeNestedThreads,
+ );
return (
<div className="ph-no-capture space-y-4">
{rows.length === 0 && (
@@ -59,6 +69,7 @@ export function SessionTranscriptContent({
</h3>
)}
<SessionTranscriptThread
+ variant={variant}
rows={rows.filter((row) => row.threadIndex === threadIndex)}
onOpenObservation={onOpenObservation}
scrollTarget={scrollTarget}
@@ -80,11 +91,13 @@ type DisplayMessage = NormalizedMessage & {
function SessionTranscriptThread({
rows,
+ variant,
onOpenObservation,
scrollTarget,
}: {
rows: ReturnType<typeof getSessionTranscriptRows>;
- onOpenObservation: (observationId: string) => void;
+ variant?: ComponentProps<typeof SessionTimelineContentMessage>["variant"];
+ onOpenObservation?: (observationId: string) => void;
scrollTarget: {
observationId: string;
rowId?: string;
@@ -131,6 +144,7 @@ function SessionTranscriptThread({
>
{group.type === "tools" ? (
<SessionTranscriptToolGroup
+ variant={variant}
summary={group.summary}
title={group.title}
rows={group.rows}
@@ -139,6 +153,7 @@ function SessionTranscriptThread({
/>
) : (
<SessionTranscriptRow
+ variant={variant}
item={group.row}
onOpenObservation={onOpenObservation}
scrollTarget={scrollTarget}
@@ -150,6 +165,7 @@ function SessionTranscriptThread({
function SessionTranscriptRow({
item,
+ variant,
onOpenObservation,
scrollTarget,
}: {
@@ -169,7 +185,7 @@ function SessionTranscriptRow({
const metadata = (isTool || isSystem) &&
(timing || row.message.observationId) && (
<div className="text-muted-foreground flex items-center gap-3 font-mono text-xs opacity-0 group-hover/collapsible-row:opacity-100 group-has-[:focus-visible]/collapsible-row:opacity-100 group-data-[expanded=true]/collapsible-row:opacity-100">
- {row.message.observationId && (
+ {row.message.observationId && onOpenObservation && (
<button
type="button"
className="hover:text-foreground hover:underline"
@@ -207,6 +223,7 @@ function SessionTranscriptRow({
<SessionTranscriptTool row={row} trailingContent={metadata} />
) : (
<SessionTranscriptMessage
+ variant={variant}
expandRequestId={scrollRequestId}
message={row.message}
trailingContent={isSystem ? metadata : null}
@@ -397,13 +414,15 @@ function SessionTranscriptTool({
function SessionTranscriptMessage({
message,
+ variant,
trailingContent,
onOpenObservation,
expandRequestId,
}: {
message: DisplayMessage;
+ variant?: ComponentProps<typeof SessionTimelineContentMessage>["variant"];
trailingContent: ReactNode;
- onOpenObservation: (observationId: string) => void;
+ onOpenObservation?: (observationId: string) => void;
expandRequestId?: number;
}) {
if (message.role === "system") {
@@ -417,13 +436,14 @@ function SessionTranscriptMessage({
}
return (
<SessionTimelineContentMessage
+ variant={variant}
expandRequestId={expandRequestId}
role={message.role}
parts={message.parts}
senderName={message.senderName}
timestamp={message.timing?.startTime ?? null}
onOpenObservation={
- message.observationId
+ message.observationId && onOpenObservation
? () => onOpenObservation(message.observationId!)
: undefined
}
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsx
index b5b12c1ad3..6d63cac2fe 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsx
@@ -20,7 +20,7 @@ const rolePresentation = {
label: "Assistant",
icon: Bot,
wrapper: "justify-start",
- container: "bg-muted/50 max-w-[min(85%,48rem)] rounded-2xl px-4 py-2.5",
+ container: "max-w-[min(85%,48rem)] rounded-2xl px-4 py-2.5",
},
tool: {
label: "Tool",
@@ -45,7 +45,9 @@ export function SessionTimelineContentMessage({
timestamp,
onOpenObservation,
expandRequestId,
+ variant = "session",
}: {
+ variant?: "session" | "single-trace";
role: Exclude<NormalizedMessage["role"], "system">;
parts: NormalizedMessage["parts"];
senderName: NormalizedMessage["senderName"];
@@ -139,6 +141,8 @@ export function SessionTimelineContentMessage({
className={cn(
"group/bubble min-w-0 overflow-hidden",
presentation.container,
+ role === "assistant" &&
+ (variant === "single-trace" ? "bg-muted" : "bg-muted/50"),
((isJsonOnly && isJsonExpanded) || hasToolParts) && "w-full",
)}
>
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionConversationEntries.ts b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionConversationEntries.ts
index eefa8c8008..874a1fc9eb 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionConversationEntries.ts
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionConversationEntries.ts
@@ -8,9 +8,10 @@ export function getSessionConversationEntries(
| RouterOutputs["events"]["transcriptByTraceId"]["transcript"]
| undefined;
}[],
+ includeNestedThreads = false,
) {
const visibility = traces.map(({ transcript }) =>
- getSessionTranscriptThreads(transcript ?? null),
+ getSessionTranscriptThreads(transcript ?? null, includeNestedThreads),
);
const useThreadNumbers = visibility.some(
({ visibleThreads }) => visibleThreads.length > 1,
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows.clienttest.ts b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows.clienttest.ts
index 64bcda075f..2d7aab2fa2 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows.clienttest.ts
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows.clienttest.ts
@@ -360,6 +360,45 @@ describe("getSessionTranscriptRows", () => {
0, 0, 0, 2, 2, 2,
]);
expect(JSON.stringify(rows)).not.toContain("Nested-only search match");
+
+ const expandedRows = getSessionTranscriptRows(nestedTranscript, true);
+ expect(expandedRows.map(({ threadIndex }) => threadIndex)).toEqual([
+ 0, 0, 0, 1, 2, 2, 2,
+ ]);
+ expect(JSON.stringify(expandedRows)).toContain("Nested-only search match");
+ expect(getSessionTranscriptThreads(nestedTranscript, true)).toMatchObject({
+ hiddenThreadCount: 0,
+ visibleThreads: [
+ { threadIndex: 0 },
+ { threadIndex: 1 },
+ { threadIndex: 2 },
+ ],
+ });
+ expect(
+ getSessionConversationEntries(
+ [{ trace: { id: "trace" }, transcript: nestedTranscript }],
+ true,
+ ),
+ ).toMatchObject([
+ {
+ itemId: "trace:0",
+ threadIndex: 0,
+ threadCount: 3,
+ displayNumber: "1.1",
+ },
+ {
+ itemId: "trace:1",
+ threadIndex: 1,
+ threadCount: 3,
+ displayNumber: "1.2",
+ },
+ {
+ itemId: "trace:2",
+ threadIndex: 2,
+ threadCount: 3,
+ displayNumber: "1.3",
+ },
+ ]);
});
it("reports no hidden threads for absent or empty transcripts", () => {
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows.ts b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows.ts
index a415e68952..a38d561e9e 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows.ts
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows.ts
@@ -4,56 +4,58 @@ import { getSessionTranscriptThreads } from "./getSessionTranscriptThreads";
export function getSessionTranscriptRows(
transcript: RouterOutputs["events"]["transcriptByTraceId"]["transcript"],
+ includeNestedThreads = false,
) {
- return getSessionTranscriptThreads(transcript).visibleThreads.flatMap(
- ({ thread, threadIndex }) => {
- const messages = thread.currentTurn.messages.map((message) => ({
- ...message,
- timing: { startTime: message.startTime, endTime: message.endTime },
- }));
- return groupTranscriptMessages(messages).flatMap((row, rowIndex) => {
- // TODO: Consider excluding opaque encrypted parts during transcript generation instead.
- const parts = row.message.parts.filter((part) => {
- if (part.type !== "custom") return true;
- if (part.kind === "encrypted_content") {
- return false;
- }
- if (part.kind !== "Microsoft.Extensions.AI.TextReasoningContent") {
- return true;
- }
- const value = part.value;
- if (
- value === null ||
- typeof value !== "object" ||
- Array.isArray(value)
- ) {
- return true;
- }
- const content = value.content;
- if (
- content === null ||
- typeof content !== "object" ||
- Array.isArray(content)
- ) {
- return true;
- }
- if (
- typeof content.protectedData === "string" &&
- content.protectedData.length > 0
- ) {
- return false;
- }
+ return getSessionTranscriptThreads(
+ transcript,
+ includeNestedThreads,
+ ).visibleThreads.flatMap(({ thread, threadIndex }) => {
+ const messages = thread.currentTurn.messages.map((message) => ({
+ ...message,
+ timing: { startTime: message.startTime, endTime: message.endTime },
+ }));
+ return groupTranscriptMessages(messages).flatMap((row, rowIndex) => {
+ // TODO: Consider excluding opaque encrypted parts during transcript generation instead.
+ const parts = row.message.parts.filter((part) => {
+ if (part.type !== "custom") return true;
+ if (part.kind === "encrypted_content") {
+ return false;
+ }
+ if (part.kind !== "Microsoft.Extensions.AI.TextReasoningContent") {
return true;
- });
- if (row.type === "message" && parts.length === 0) return [];
- return [
- {
- id: `${threadIndex}:${rowIndex}`,
- threadIndex,
- row: { ...row, message: { ...row.message, parts } },
- },
- ];
+ }
+ const value = part.value;
+ if (
+ value === null ||
+ typeof value !== "object" ||
+ Array.isArray(value)
+ ) {
+ return true;
+ }
+ const content = value.content;
+ if (
+ content === null ||
+ typeof content !== "object" ||
+ Array.isArray(content)
+ ) {
+ return true;
+ }
+ if (
+ typeof content.protectedData === "string" &&
+ content.protectedData.length > 0
+ ) {
+ return false;
+ }
+ return true;
});
- },
- );
+ if (row.type === "message" && parts.length === 0) return [];
+ return [
+ {
+ id: `${threadIndex}:${rowIndex}`,
+ threadIndex,
+ row: { ...row, message: { ...row.message, parts } },
+ },
+ ];
+ });
+ });
}
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptThreads.ts b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptThreads.ts
index 2913345832..17a5c11bd8 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptThreads.ts
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptThreads.ts
@@ -2,6 +2,7 @@ import { type RouterOutputs } from "@/src/utils/api";
export function getSessionTranscriptThreads(
transcript: RouterOutputs["events"]["transcriptByTraceId"]["transcript"],
+ includeNestedThreads = false,
) {
const threads = transcript?.threads ?? [];
const shallowestLevel = threads.reduce(
@@ -11,7 +12,9 @@ export function getSessionTranscriptThreads(
const visibleThreads = threads
.map((thread, threadIndex) => ({ thread, threadIndex }))
.filter(
- ({ thread }) => thread.currentTurn.nestingLevel === shallowestLevel,
+ ({ thread }) =>
+ includeNestedThreads ||
+ thread.currentTurn.nestingLevel === shallowestLevel,
);
return {
visibleThreads,
diff --git a/web/src/features/sessions/hooks/useSessionConversationTimelineController.ts b/web/src/features/sessions/hooks/useSessionConversationTimelineController.ts
index c9cf23d7bf..4dd2a6efa9 100644
--- a/web/src/features/sessions/hooks/useSessionConversationTimelineController.ts
+++ b/web/src/features/sessions/hooks/useSessionConversationTimelineController.ts
@@ -23,7 +23,7 @@ export type SessionConversationTimelineScrollTarget = {
};
export function useSessionConversationTimelineController(
- traces: readonly { trace: EventSessionTrace; itemId?: string }[],
+ traces: readonly { trace: Pick<EventSessionTrace, "id">; itemId?: string }[],
onVisibleTraceIdsChange?: (traceIds: string[]) => void,
) {
const items = traces.map(({ trace, itemId }) => ({
diff --git a/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx b/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
index 3e1e2558df..da4caad50c 100644
--- a/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
+++ b/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
@@ -71,7 +71,6 @@ import {
useInternalFeaturesEnabled,
useIsFeatureEnabled,
} from "@/src/features/feature-flags";
-import { TraceMessagesView } from "../TraceMessagesView/TraceMessagesView";
import { DetailAttributesTab } from "../DetailAttributesTab";
import { buildModelParameters } from "@/src/features/traces/fns/buildModelParameters";
import { buildObservationAttributes } from "@/src/features/traces/fns/buildObservationAttributes";
@@ -484,13 +483,6 @@ export function ConnectedObservationDetailView({
}
/>
- {selectedTab === "messages" && (
- <Tabs.Content value="messages" layout="fill">
- <div className="min-h-0 flex-1 overflow-auto px-4">
- <TraceMessagesView />
- </div>
- </Tabs.Content>
- )}
<Tabs.Content value="preview" layout="fill">
<ObservationPreview
currentView={currentView}
diff --git a/web/src/features/traces/components/Trace.tsx b/web/src/features/traces/components/Trace.tsx
index a7e0b66b64..b171d88978 100644
--- a/web/src/features/traces/components/Trace.tsx
+++ b/web/src/features/traces/components/Trace.tsx
@@ -39,6 +39,11 @@ import { useHasProjectAccess } from "@/src/features/rbac";
import { staleProps } from "@/src/features/traces/fns/staleProps";
import { cn } from "@/src/utils/tailwind";
import { SkeletonGroup } from "@/src/components/ui/skeleton";
+import { Tabs } from "@/src/components/design-system/Tabs/Tabs";
+import { useInternalFeaturesEnabled } from "@/src/features/feature-flags";
+import { useReadPath } from "@/src/features/events";
+import { StringParam, useQueryParam } from "use-query-params";
+import { TraceMessagesView } from "./TraceMessagesView/TraceMessagesView";
export type TraceProps = {
isLoading?: false;
@@ -227,6 +232,12 @@ function TraceContent({ desktopLayout }: { desktopLayout: DesktopLayout }) {
const isMobile = useIsMobile();
const { isGraphViewAvailable } = useTraceGraphData();
const { isPlaceholderData } = useTraceData();
+ const [traceView, setTraceView] = useQueryParam("traceView", StringParam);
+ const internalFeaturesEnabled = useInternalFeaturesEnabled();
+ const { isV4 } = useReadPath();
+ const showMessagesTab = isV4 && internalFeaturesEnabled;
+ const activeView =
+ showMessagesTab && traceView === "messages" ? "messages" : "trace";
const stale = staleProps(isPlaceholderData);
const panels = isMobile ? (
@@ -241,7 +252,31 @@ function TraceContent({ desktopLayout }: { desktopLayout: DesktopLayout }) {
className={cn(traceContentClassName, stale.className)}
>
<TraceHeader />
- <div className="min-h-0 flex-1">{panels}</div>
+ {showMessagesTab ? (
+ <Tabs
+ value={activeView}
+ onValueChange={(value) => {
+ if (value === "messages") setTraceView("messages", "pushIn");
+ if (value === "trace") setTraceView(undefined, "pushIn");
+ }}
+ layout="fill"
+ >
+ <Tabs.List variant="underline">
+ <Tabs.Trigger value="trace" label="Trace" />
+ <Tabs.Trigger value="messages" label="Messages" internal />
+ </Tabs.List>
+ <Tabs.Content value="trace" layout="fill">
+ {panels}
+ </Tabs.Content>
+ <Tabs.Content value="messages" layout="fill">
+ <div className="min-h-0 flex-1 p-4">
+ <TraceMessagesView />
+ </div>
+ </Tabs.Content>
+ </Tabs>
+ ) : (
+ <div className="min-h-0 flex-1">{panels}</div>
+ )}
</div>
);
}
diff --git a/web/src/features/traces/components/TraceDetailTabsBarList.tsx b/web/src/features/traces/components/TraceDetailTabsBarList.tsx
index ac63f5142b..b9f52d9c65 100644
--- a/web/src/features/traces/components/TraceDetailTabsBarList.tsx
+++ b/web/src/features/traces/components/TraceDetailTabsBarList.tsx
@@ -8,7 +8,6 @@ import type { DetailTab } from "../contexts/SelectionContext";
const labels: Record<DetailTab, string> = {
preview: "Preview",
- messages: "Messages",
attributes: "Attributes",
scores: "Scores",
log: "Log View",
@@ -68,7 +67,6 @@ function LoadedTraceDetailTabsBarList({
key={tab}
value={tab}
label={labels[tab]}
- internal={tab === "messages"}
tooltip={tab === "log" ? logViewDescription : undefined}
/>
))}
diff --git a/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx b/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
index 7186edb45d..8dfd967666 100644
--- a/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
+++ b/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
@@ -51,7 +51,6 @@ import { ScoresTable } from "@/src/features/scores";
import { getMostRecentCorrection } from "@/src/features/corrections";
import { useInternalFeaturesEnabled } from "@/src/features/feature-flags";
import { useReadPath } from "@/src/features/events";
-import { TraceMessagesView } from "../TraceMessagesView/TraceMessagesView";
import { TraceDetailTabsBarList } from "../TraceDetailTabsBarList";
import { DetailAttributesTab } from "../DetailAttributesTab";
import { getDetailTabs } from "../../fns/getDetailTabs";
@@ -411,14 +410,6 @@ function LoadedTraceDetailView({
/>
)}
- {selectedTab === "messages" && (
- <Tabs.Content value="messages" layout="fill">
- <div className="min-h-0 flex-1 overflow-auto px-4">
- <TraceMessagesView />
- </div>
- </Tabs.Content>
- )}
-
{/* Preview tab content */}
<Tabs.Content value="preview" layout="fill">
<div
diff --git a/web/src/features/traces/components/TraceLayoutDesktop.tsx b/web/src/features/traces/components/TraceLayoutDesktop.tsx
index 8c463aa6f9..4792a9cdfb 100644
--- a/web/src/features/traces/components/TraceLayoutDesktop.tsx
+++ b/web/src/features/traces/components/TraceLayoutDesktop.tsx
@@ -24,8 +24,6 @@ import { cn } from "@/src/utils/tailwind";
import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";
import { useSelection } from "@/src/features/traces/contexts/SelectionContext";
import { TraceReviewLayout } from "./TraceReviewLayout";
-import { useInternalFeaturesEnabled } from "@/src/features/feature-flags";
-import { useReadPath } from "@/src/features/events";
import { resolveEffectiveWidthFraction } from "@/src/components/table/peek/store/peekPanelStore";
import { usePeekTableState } from "@/src/components/table/peek/contexts/PeekTableStateContext";
@@ -266,7 +264,6 @@ function TraceNavigationDetailLayout({
pendingPanelExpand: pendingExpand,
setPendingPanelExpand: setPendingExpand,
openDetails,
- selectedTab,
} = useSelection();
const isNavigationPanelCollapsed =
navigationPanelCollapsed ??
@@ -487,15 +484,6 @@ function TraceNavigationDetailLayout({
openDetails();
};
- const internalFeaturesEnabled = useInternalFeaturesEnabled();
- const { isV4 } = useReadPath();
- const showMessages =
- selectedTab === "messages" && internalFeaturesEnabled && isV4;
- useEffect(() => {
- if (!showMessages || reviewOpen) return;
- panelRef.current?.collapse();
- }, [showMessages, reviewOpen, panelRef]);
-
// Apply the caller's first-use default. A restored layout always wins.
useEffect(() => {
if (
diff --git a/web/src/features/traces/components/TraceMessagesView/TraceMessagesView.tsx b/web/src/features/traces/components/TraceMessagesView/TraceMessagesView.tsx
index 58de38a771..91dc7167c1 100644
--- a/web/src/features/traces/components/TraceMessagesView/TraceMessagesView.tsx
+++ b/web/src/features/traces/components/TraceMessagesView/TraceMessagesView.tsx
@@ -1,224 +1,101 @@
-/**
- * TraceMessagesView - the trace as a conversation transcript
- *
- * Internal preview available in Internal view mode. Renders the transcript
- * assembled server-side from the trace's generations and tools with the same
- * message components as the formatted IO view: replayed conversation history
- * first, then the current turn with links to the observations that emitted it.
- */
-
-import { useMemo, useState } from "react";
+import { useState, type ComponentProps } from "react";
+import { StringParam, useQueryParam } from "use-query-params";
import { ErrorBoundary } from "@sentry/nextjs";
-import type { NormalizedMessage } from "@langfuse/shared/src/utils/normalized-io";
-import { api, type RouterOutputs } from "@/src/utils/api";
-import { Button } from "@/src/components/ui/button";
-import { useMarkdownRenderCharacterLimit } from "@/src/hooks/useMarkdownRenderCharacterLimit";
-import { type MediaReturnType } from "@/src/features/media";
-import { ChatMessageList } from "@/src/features/traces/components/ChatMessageList";
import { useSelection } from "@/src/features/traces/contexts/SelectionContext";
import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";
-import { toIOPreview } from "@/src/features/traces/parsers/toIOPreview";
-import { IO_SECTIONS_FLUSH_CLASS } from "@/src/features/traces/constants/ioSectionClasses";
-
-type Transcript = NonNullable<
- RouterOutputs["events"]["transcriptByTraceId"]["transcript"]
->;
-type Thread = Transcript["threads"][number];
-
-// Media is looked up per contributing observation; bound the request fan-out
-// of agentic turns with very many tool calls.
-const MAX_MEDIA_LOOKUPS_PER_TURN = 20;
+import { useTraceMessagesNavigation } from "./hooks/useTraceMessagesNavigation";
+import { useTraceMessagesTranscript } from "./hooks/useTraceMessagesTranscript";
+// TODO: Before TraceMessagesView leaves internal preview, rename the components
+// shared by session and trace views and move them to a common location.
+import { SessionConversationTimeline } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline";
+import { getSessionConversationEntries } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionConversationEntries";
+import { useSessionConversationTimelineController } from "@/src/features/sessions/hooks/useSessionConversationTimelineController";
+import { getSessionTranscriptThreads } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptThreads";
export function TraceMessagesView() {
- const { trace, observations } = useTraceData();
- const { data, isLoading, error } = api.events.transcriptByTraceId.useQuery({
- projectId: trace.projectId,
- traceId: trace.id,
- timestamp: trace.timestamp,
- });
- const observationNames = useMemo(
- () => new Map(observations.map((o) => [o.id, o.name ?? o.id])),
- [observations],
+ const { trace, isPlaceholderData } = useTraceData();
+ const [expandedTraceId, setExpandedTraceId] = useState<string | null>(null);
+ const { selectNode, setSelectedTab } = useSelection();
+ const [, setTraceView] = useQueryParam("traceView", StringParam);
+ const { messageTrace, navigation } = useTraceMessagesNavigation();
+ const { data, state } = useTraceMessagesTranscript(
+ {
+ projectId: trace.projectId,
+ traceId: messageTrace.id,
+ timestamp: messageTrace.timestamp,
+ },
+ isPlaceholderData,
);
-
- if (isLoading) {
- return <Notice>Assembling messages…</Notice>;
- }
- if (error) {
- return <Notice>{error.message}</Notice>;
- }
- if (!data?.transcript) {
- return (
- <div className="flex flex-col">
- {data?.cutoff && <CutoffNotice />}
- <Notice>
- No messages. Transcripts are assembled from generations and tool
- observations with chat-shaped input and output.
- </Notice>
- </div>
- );
- }
-
- const { threads } = data.transcript;
- return (
- <div className="flex h-full w-full flex-col gap-6 overflow-y-auto py-3">
- {data.cutoff && <CutoffNotice />}
- {threads.map((thread, index) => (
- <ErrorBoundary
- key={index}
- fallback={<Notice>Unprocessable content.</Notice>}
- >
- <ThreadBlock
- thread={thread}
- title={threads.length > 1 ? `Thread ${index + 1}` : undefined}
- observationNames={observationNames}
- projectId={trace.projectId}
- traceId={trace.id}
- />
- </ErrorBoundary>
- ))}
- </div>
+ const includeNestedThreads = expandedTraceId === messageTrace.id;
+ const { hiddenThreadCount } = getSessionTranscriptThreads(
+ data?.transcript ?? null,
+ includeNestedThreads,
);
-}
-
-function ThreadBlock({
- thread,
- title,
- observationNames,
- projectId,
- traceId,
-}: {
- thread: Thread;
- title?: string;
- observationNames: Map<string, string>;
- projectId: string;
- traceId: string;
-}) {
- const { selectNode } = useSelection();
- // History is context, not the point of the view; start folded.
- const [showHistory, setShowHistory] = useState(false);
- // Media of the emitting observations, so inline references resolve the way
- // they do in the formatted view. History has no emitter to ask.
- const mediaQueries = api.useQueries((t) =>
- thread.currentTurn.observations
- .slice(0, MAX_MEDIA_LOOKUPS_PER_TURN)
- .map(({ id }) =>
- t.media.getByTraceOrObservationId(
- { projectId, traceId, observationId: id },
- { refetchOnWindowFocus: false, staleTime: 50 * 60 * 1000 },
- ),
- ),
+ const entries = getSessionConversationEntries(
+ [{ trace: messageTrace, transcript: data?.transcript }],
+ includeNestedThreads,
);
- const media = mediaQueries.flatMap((query) => query.data ?? []);
-
- const selectObservation = (id: string) => {
- selectNode(id);
- };
+ const traces: ComponentProps<typeof SessionConversationTimeline>["traces"] =
+ entries.map((entry) => ({
+ ...entry,
+ trace: messageTrace,
+ turnNumber: 1,
+ variant: "single-trace",
+ includeNestedThreads,
+ state,
+ onOpenTrace: () => {
+ setTraceView(undefined, "pushIn");
+ selectNode(null);
+ },
+ onOpenObservation: (observationId) => {
+ setTraceView(undefined, "pushIn");
+ setSelectedTab("preview");
+ selectNode(observationId);
+ },
+ scrollTarget: null,
+ }));
+ const controller = useSessionConversationTimelineController(traces);
return (
- <section className="flex flex-col gap-3">
- {title && <h3 className="text-sm font-bold">{title}</h3>}
- {thread.conversationHistory.length > 0 && (
- <>
- <SectionLabel>
+ <ErrorBoundary
+ key={trace.id}
+ fallback={
+ <div className="text-muted-foreground p-3 text-sm">
+ Unprocessable content.
+ </div>
+ }
+ >
+ <div className="flex h-full min-h-0 w-full flex-col">
+ {state.type === "transcript" && hiddenThreadCount > 0 && (
+ <div
+ role="status"
+ className="text-muted-foreground flex shrink-0 items-center justify-between gap-3 rounded-md border p-3 text-sm"
+ >
+ <span>
+ {hiddenThreadCount} nested{" "}
+ {hiddenThreadCount === 1 ? "thread is" : "threads are"} hidden.
+ </span>
<button
type="button"
- className="hover:text-foreground"
- onClick={() => setShowHistory((shown) => !shown)}
+ className="text-foreground shrink-0 underline underline-offset-4"
+ onClick={() => setExpandedTraceId(messageTrace.id)}
>
- {showHistory ? "Hide" : "Show"} conversation history (
- {thread.conversationHistory.length})
+ Show nested threads
</button>
- </SectionLabel>
- {showHistory && (
- <div className="opacity-70">
- <MessageList messages={thread.conversationHistory} media={[]} />
- </div>
- )}
- <SectionLabel>Current turn</SectionLabel>
- </>
- )}
- <div className="flex flex-wrap gap-1">
- {thread.currentTurn.observations.map(({ id }) => (
- <Button
- key={id}
- variant="outline"
- size="sm"
- className="h-6 px-2 text-xs"
- title="Show observation"
- onClick={() => selectObservation(id)}
- >
- {observationNames.get(id) ?? id}
- </Button>
- ))}
+ </div>
+ )}
+ {data?.cutoff && (!data.transcript || entries.length <= 1) && (
+ <div className="text-muted-foreground p-3 text-sm">
+ This trace exceeds the observation cap. Later observations are not
+ part of the transcript.
+ </div>
+ )}
+ <SessionConversationTimeline
+ traces={traces}
+ controller={controller}
+ navigation={navigation}
+ />
</div>
- <MessageList messages={thread.currentTurn.messages} media={media} />
- </section>
- );
-}
-
-/** Formatted IO rendering of normalized messages, without re-parsing. */
-function MessageList({
- messages,
- media,
-}: {
- messages: NormalizedMessage[];
- media: MediaReturnType[];
-}) {
- const characterLimit = useMarkdownRenderCharacterLimit();
- const preview = useMemo(
- () =>
- toIOPreview({
- messages,
- toolDefinitions: [],
- span: { input: undefined, output: undefined, metadata: undefined },
- }),
- [messages],
- );
- // Same size gate as the formatted view.
- const shouldRenderMarkdown = useMemo(
- () => JSON.stringify(preview.allMessages).length <= characterLimit,
- [preview, characterLimit],
- );
-
- return (
- <div className={IO_SECTIONS_FLUSH_CLASS}>
- <ChatMessageList
- messages={preview.allMessages}
- shouldRenderMarkdown={shouldRenderMarkdown}
- media={media}
- currentView="pretty"
- messageToToolCallNumbers={preview.messageToToolCallNumbers}
- inputMessageCount={preview.inputMessageCount}
- collapseLongHistory={false}
- />
- </div>
- );
-}
-
-function SectionLabel({ children }: { children: React.ReactNode }) {
- return (
- <div className="text-muted-foreground flex items-center gap-2 text-xs tracking-wide uppercase">
- <span className="bg-border h-px flex-1" />
- {children}
- <span className="bg-border h-px flex-1" />
- </div>
- );
-}
-
-function CutoffNotice() {
- return (
- <Notice>
- This trace exceeds the observation cap. Later observations are not part of
- the transcript.
- </Notice>
- );
-}
-
-function Notice({ children }: { children: React.ReactNode }) {
- return (
- <div className="text-muted-foreground my-3 rounded-md border border-dashed p-3 text-sm">
- {children}
- </div>
+ </ErrorBoundary>
);
}
diff --git a/web/src/features/traces/components/TraceMessagesView/hooks/useTraceMessagesNavigation.ts b/web/src/features/traces/components/TraceMessagesView/hooks/useTraceMessagesNavigation.ts
new file mode 100644
index 0000000000..529d1b273c
--- /dev/null
+++ b/web/src/features/traces/components/TraceMessagesView/hooks/useTraceMessagesNavigation.ts
@@ -0,0 +1,97 @@
+import { useEffect } from "react";
+import { useRouter } from "next/router";
+import { api } from "@/src/utils/api";
+import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";
+import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";
+
+export function useTraceMessagesNavigation() {
+ const { trace, isPlaceholderData } = useTraceData();
+ const { isPeekMode, isAnnotationMode } = useViewPreferences();
+ const router = useRouter();
+ const utils = api.useUtils();
+ const { data: sessionTraces } = api.sessions.tracesFromEvents.useQuery(
+ { projectId: trace.projectId, sessionId: trace.sessionId ?? "" },
+ {
+ enabled: Boolean(trace.sessionId),
+ staleTime: (query) => {
+ const latestTrace = query.state.data?.at(-1);
+ if (!latestTrace) return 30 * 1_000;
+ const sessionInactive =
+ Date.now() - latestTrace.timestamp.getTime() >= 30 * 60 * 1_000;
+ return sessionInactive ? 10 * 60 * 1_000 : 30 * 1_000;
+ },
+ gcTime: 10 * 60 * 1_000,
+ refetchOnWindowFocus: false,
+ },
+ );
+ const requestedTraceId = isPeekMode
+ ? (router.query.traceId ?? router.query.peek)
+ : router.query.traceId;
+ const messageTrace = isPlaceholderData
+ ? (sessionTraces?.find(({ id }) => id === requestedTraceId) ?? trace)
+ : trace;
+ const traceIndex =
+ sessionTraces?.findIndex(({ id }) => id === messageTrace.id) ?? -1;
+ const previousTrace =
+ traceIndex > 0 ? sessionTraces?.[traceIndex - 1] : undefined;
+ const nextTrace =
+ traceIndex >= 0 ? sessionTraces?.[traceIndex + 1] : undefined;
+ useEffect(() => {
+ if (isPlaceholderData) return;
+ for (const neighbor of [previousTrace, nextTrace]) {
+ if (!neighbor) continue;
+ utils.events.transcriptByTraceId.prefetch(
+ {
+ projectId: trace.projectId,
+ traceId: neighbor.id,
+ timestamp: neighbor.timestamp,
+ },
+ { staleTime: 60 * 1_000 },
+ );
+ }
+ }, [isPlaceholderData, previousTrace, nextTrace, trace.projectId, utils]);
+ const [previousTraceLink, nextTraceLink] = [previousTrace, nextTrace].map(
+ (target, directionIndex) => {
+ if (isAnnotationMode || !target) return undefined;
+ const count =
+ directionIndex === 0
+ ? traceIndex
+ : (sessionTraces?.length ?? 0) - traceIndex - 1;
+ if (isPeekMode) {
+ const query = { ...router.query };
+ delete query.observation;
+ return {
+ count,
+ href: {
+ pathname: router.pathname,
+ query: {
+ ...query,
+ traceId: target.id,
+ timestamp: target.timestamp.toISOString(),
+ traceView: "messages",
+ },
+ },
+ shallow: true,
+ };
+ }
+ return {
+ count,
+ href: {
+ pathname: `/project/${trace.projectId}/traces/${target.id}`,
+ query: {
+ timestamp: target.timestamp.toISOString(),
+ traceView: "messages",
+ },
+ },
+ };
+ },
+ );
+
+ return {
+ messageTrace,
+ navigation: {
+ previousTrace: previousTraceLink,
+ nextTrace: nextTraceLink,
+ },
+ };
+}
diff --git a/web/src/features/traces/components/TraceMessagesView/hooks/useTraceMessagesTranscript.ts b/web/src/features/traces/components/TraceMessagesView/hooks/useTraceMessagesTranscript.ts
new file mode 100644
index 0000000000..d42beb55af
--- /dev/null
+++ b/web/src/features/traces/components/TraceMessagesView/hooks/useTraceMessagesTranscript.ts
@@ -0,0 +1,23 @@
+import { api, type RouterInputs } from "@/src/utils/api";
+
+export function useTraceMessagesTranscript(
+ input: RouterInputs["events"]["transcriptByTraceId"],
+ isPlaceholderData: boolean,
+) {
+ const { data, isLoading, error } = api.events.transcriptByTraceId.useQuery(
+ input,
+ { staleTime: 60 * 1_000 },
+ );
+
+ if (isLoading || isPlaceholderData)
+ return { data, state: { type: "loading" as const } };
+ if (error) return { data, state: { type: "error" as const } };
+ if (!data?.transcript) return { data, state: { type: "empty" as const } };
+ return {
+ data,
+ state: {
+ type: "transcript" as const,
+ result: { state: "loaded" as const, ...data },
+ },
+ };
+}
diff --git a/web/src/features/traces/constants/detailTabs.ts b/web/src/features/traces/constants/detailTabs.ts
index 5cfcbe9e10..87d048c67e 100644
--- a/web/src/features/traces/constants/detailTabs.ts
+++ b/web/src/features/traces/constants/detailTabs.ts
@@ -1,9 +1,3 @@
-export const DETAIL_TABS = [
- "preview",
- "messages",
- "attributes",
- "scores",
- "log",
-] as const;
+export const DETAIL_TABS = ["preview", "attributes", "scores", "log"] as const;
export type DetailTab = (typeof DETAIL_TABS)[number];
diff --git a/web/src/features/traces/fns/getDetailTabs.ts b/web/src/features/traces/fns/getDetailTabs.ts
index 275a266f14..c43a475bbf 100644
--- a/web/src/features/traces/fns/getDetailTabs.ts
+++ b/web/src/features/traces/fns/getDetailTabs.ts
@@ -3,7 +3,6 @@ import { DETAIL_TABS, type DetailTab } from "../constants/detailTabs";
export function getDetailTabs({
target,
isV4,
- internalFeaturesEnabled,
isAnnotationMode,
hasObservations,
canViewScores,
@@ -17,7 +16,6 @@ export function getDetailTabs({
}) {
const visibility: Record<DetailTab, boolean> = {
preview: true,
- messages: isV4 && internalFeaturesEnabled,
attributes: true,
scores: canViewScores && !isAnnotationMode,
log: (target === "trace" || isV4) && hasObservations && !isAnnotationMode,