🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(sessions): Redesigned timeline (#17016)
Ben Bachem31acefbba189
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex c640db7469..9594c55b61 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -1,5 +1,8 @@import { prisma } from "../../db";-import type { ClickHouseClientConfigOptions } from "@clickhouse/client";+import {+ TupleParam,+ type ClickHouseClientConfigOptions,+} from "@clickhouse/client";import type {EventsObservation,MetadataDomain,@@ -137,6 +140,7 @@ import { parseMetadataCHRecordToDomain } from "../utils/metadata_conversion";export type EventBatchIOStringOutput = {id: string;+ traceId: string;input: string | null;output: string | null;metadata: MetadataDomain;@@ -2556,6 +2560,8 @@ export const getObservationsBatchIOFromEventsTable = async <* the payload. Ignored for truncated reads (events_core caps far tighter).*/ioCharLimit?: number;+ /** Restricts every requested observation to an already-authorized session. */+ sessionId?: string;includeExperimentFields?: TIncludeExperiment;/** Opt-in: tool-call arrays can be large; only eval consumers need them. */includeToolCallFields?: TIncludeToolCalls;@@ -2574,9 +2580,13 @@ export const getObservationsBatchIOFromEventsTable = async <? Math.max(1, Math.trunc(opts.ioCharLimit)): undefined;- // Extract IDs and trace IDs for filtering+ // Keep the individual filters for primary-key pruning and the tuple filter+ // for exact trace/observation matching.const observationIds = opts.observations.map((o) => o.id);- const traceIds = [...new Set(opts.observations.map((o) => o.traceId))];+ const traceIds = Array.from(new Set(opts.observations.map((o) => o.traceId)));+ const observationTuples = opts.observations.map(+ (observation) => new TupleParam([observation.traceId, observation.id]),+ );// Use provided timestamp range with buffer for efficient filteringconst minTimestamp = new Date(opts.minStartTime.getTime() - 1000); // -1 second buffer@@ -2612,12 +2622,24 @@ export const getObservationsBatchIOFromEventsTable = async <? `e.tool_calls as tool_calls,e.tool_call_names as tool_call_names,- `+ `: "";+ const sessionTraceFilter =+ opts.sessionId !== undefined+ ? `AND e.trace_id IN (+ SELECT trace_id+ FROM events_core+ WHERE project_id = {projectId: String}+ AND trace_id IN {traceIds: Array(String)}+ GROUP BY trace_id+ HAVING argMaxIf(session_id, event_ts, session_id <> '') = {sessionId: String}+ )`+ : "";const query = `- SELECT- e.span_id as id,+ SELECT+ e.span_id as id,+ e.trace_id as trace_id,${inputSelect},${outputSelect},${experimentFieldsSelect}@@ -2625,14 +2647,17 @@ export const getObservationsBatchIOFromEventsTable = async <mapFromArrays(arrayReverse(e.metadata_names), arrayReverse(${metadataValues})) as metadataFROM ${tableName} eWHERE e.project_id = {projectId: String}- AND e.span_id IN {observationIds: Array(String)}- AND e.trace_id IN {traceIds: Array(String)}+ AND e.span_id IN {observationIds: Array(String)}+ AND e.trace_id IN {traceIds: Array(String)}+ AND (e.trace_id, e.span_id) IN {observationTuples: Array(Tuple(String, String))}+ ${sessionTraceFilter}AND e.start_time >= {minTimestamp: DateTime64(3)}AND e.start_time <= {maxTimestamp: DateTime64(3)}`;const results = await queryClickhouse<{id: string;+ trace_id: string;input: string | null;output: string | null;metadata: Record<string, string>;@@ -2646,6 +2671,8 @@ export const getObservationsBatchIOFromEventsTable = async <projectId: opts.projectId,observationIds,traceIds,+ observationTuples,+ sessionId: opts.sessionId,minTimestamp: convertDateToClickhouseDateTime(minTimestamp),maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),},@@ -2655,6 +2682,7 @@ export const getObservationsBatchIOFromEventsTable = async <return results.map((r) => ({id: r.id,+ traceId: r.trace_id,input: applyBatchIOStringRendering(r.input),output: applyBatchIOStringRendering(r.output),metadata:diff --git a/web/src/__tests__/server/admin-access-webhook-middleware.servertest.ts b/web/src/__tests__/server/admin-access-webhook-middleware.servertest.tsindex bbd62032d0..6ca8f1250e 100644--- a/web/src/__tests__/server/admin-access-webhook-middleware.servertest.ts+++ b/web/src/__tests__/server/admin-access-webhook-middleware.servertest.ts@@ -348,4 +348,15 @@ describe("admin access webhook in tRPC authorization middleware", () => {org: null,});});++ it("rejects an empty session id before checking access", async () => {+ const { caller, mockPrisma } = createTestCaller({+ session: createAdminSession([]),+ });++ await expect(+ caller.session({ sessionId: "", projectId: "project-id" }),+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ expect(mockPrisma.traceSession.findFirst).not.toHaveBeenCalled();+ });});diff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.tsindex 9018ff6991..9a9b89bafe 100644--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts@@ -4162,6 +4162,168 @@ describe("Clickhouse Events Repository Test", () => {expect(io3?.metadata?.key3).toBe("value3");});+ it("matches trace and observation ids within the authorized session", async () => {+ const observationId = randomUUID();+ const outsideObservationId = randomUUID();+ const firstTraceId = randomUUID();+ const secondTraceId = randomUUID();+ const outsideTraceId = randomUUID();+ const sessionId = randomUUID();+ const nowMicro = Date.now() * 1000;+ const timestamp = new Date(nowMicro / 1000);++ await createEventsCh([+ createEvent({+ id: randomUUID(),+ span_id: observationId,+ project_id: projectId,+ trace_id: firstTraceId,+ session_id: sessionId,+ type: "GENERATION",+ input: "first trace",+ start_time: nowMicro,+ }),+ createEvent({+ id: randomUUID(),+ span_id: observationId,+ project_id: projectId,+ trace_id: secondTraceId,+ session_id: sessionId,+ type: "GENERATION",+ input: "second trace",+ start_time: nowMicro + 1000,+ }),+ createEvent({+ id: randomUUID(),+ span_id: outsideObservationId,+ project_id: projectId,+ trace_id: outsideTraceId,+ session_id: randomUUID(),+ type: "GENERATION",+ input: "outside session",+ start_time: nowMicro + 2000,+ }),+ ]);++ const result = await getObservationsBatchIOFromEventsTable({+ projectId,+ sessionId,+ observations: [+ { id: observationId, traceId: firstTraceId },+ { id: observationId, traceId: secondTraceId },+ { id: outsideObservationId, traceId: outsideTraceId },+ ],+ minStartTime: timestamp,+ maxStartTime: timestamp,+ });++ expect(result).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: observationId,+ traceId: firstTraceId,+ input: "first trace",+ }),+ expect.objectContaining({+ id: observationId,+ traceId: secondTraceId,+ input: "second trace",+ }),+ ]),+ );+ expect(result).toHaveLength(2);+ });++ it("authorizes observations using the trace's latest session", async () => {+ const uniqueProjectId = randomUUID();+ const previousSessionId = randomUUID();+ const currentSessionId = randomUUID();+ const observationId = randomUUID();+ const traceId = randomUUID();+ const nowMicro = Date.now() * 1000;+ const timestamp = new Date(nowMicro / 1000);++ await createEventsCh([+ createEvent({+ id: randomUUID(),+ span_id: observationId,+ project_id: uniqueProjectId,+ trace_id: traceId,+ session_id: previousSessionId,+ type: "GENERATION",+ input: "observation input",+ start_time: nowMicro,+ event_ts: nowMicro,+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: traceId,+ session_id: currentSessionId,+ type: "SPAN",+ start_time: nowMicro + 1_000,+ event_ts: nowMicro + 1_000,+ }),+ ]);++ const params = {+ projectId: uniqueProjectId,+ observations: [{ id: observationId, traceId }],+ minStartTime: timestamp,+ maxStartTime: timestamp,+ };++ await expect(+ getObservationsBatchIOFromEventsTable({+ ...params,+ sessionId: previousSessionId,+ }),+ ).resolves.toEqual([]);+ await expect(+ getObservationsBatchIOFromEventsTable({+ ...params,+ sessionId: currentSessionId,+ }),+ ).resolves.toEqual([+ expect.objectContaining({+ id: observationId,+ traceId,+ input: "observation input",+ }),+ ]);+ });++ it("keeps the session filter when the session id is empty", async () => {+ const observationId = randomUUID();+ const traceId = randomUUID();+ const nowMicro = Date.now() * 1000;+ const timestamp = new Date(nowMicro / 1000);++ await createEventsCh([+ createEvent({+ id: randomUUID(),+ span_id: observationId,+ project_id: projectId,+ trace_id: traceId,+ session_id: randomUUID(),+ type: "GENERATION",+ input: "outside empty session",+ start_time: nowMicro,+ }),+ ]);++ const result = await getObservationsBatchIOFromEventsTable({+ projectId,+ sessionId: "",+ observations: [{ id: observationId, traceId }],+ minStartTime: timestamp,+ maxStartTime: timestamp,+ });++ expect(result).toEqual([]);+ });+it("should handle empty observation array", async () => {// minStartTime/maxStartTime are intentionally omitted: the function// early-returns on an empty observations array before touching them.diff --git a/web/src/__tests__/server/sessions-trpc-events-only.servertest.ts b/web/src/__tests__/server/sessions-trpc-events-only.servertest.tsindex d283f53a17..ff92556db9 100644--- a/web/src/__tests__/server/sessions-trpc-events-only.servertest.ts+++ b/web/src/__tests__/server/sessions-trpc-events-only.servertest.ts@@ -218,4 +218,14 @@ maybe("sessions trpc (events_only write mode)", () => {expect(read.public).toBe(true);expect(read.bookmarked).toBe(false);});++ it("rejects publishing an empty session id", async () => {+ await expect(+ caller.sessions.publish({+ projectId,+ sessionId: "",+ public: true,+ }),+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ });});diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.tsindex a64153ab3a..49161f690b 100644--- a/web/src/features/events/server/eventsRouter.ts+++ b/web/src/features/events/server/eventsRouter.ts@@ -3,6 +3,7 @@ import {createTRPCRouter,protectedProjectProcedure,protectedGetEventsTraceProcedure,+ protectedGetSessionProcedure,} from "@/src/server/api/trpc";import {type OrderByState,@@ -115,6 +116,9 @@ const BatchIOInput = zodSchema.object({// Opts into trace-level auth (public traces) in protectedGetEventsTraceProceduretraceId: zodSchema.string().optional(),});+const SessionBatchIOInput = BatchIOInput.omit({ traceId: true }).extend({+ sessionId: zodSchema.string().min(1),+});type BatchIOInput = z.infer<typeof BatchIOInput>;@@ -293,6 +297,31 @@ export const eventsRouter = createTRPCRouter({includeToolCallFields: input.includeToolCalls,});+ return batchIO.map(toDomainWithStringifiedMetadata);+ },+ );+ }),+ sessionBatchIO: protectedGetSessionProcedure+ .input(SessionBatchIOInput)+ .query(async ({ input }) => {+ return instrumentAsync(+ { name: "get-event-session-batch-io-trpc" },+ async (span) => {+ span.setAttribute("project_id", input.projectId);+ span.setAttribute("session_id", input.sessionId);+ span.setAttribute("observation_count", input.observations.length);++ const batchIO = await getEventBatchIO({+ projectId: input.projectId,+ sessionId: input.sessionId,+ observations: input.observations,+ minStartTime: input.minStartTime,+ maxStartTime: input.maxStartTime,+ truncated: input.truncated,+ ioCharLimit: input.ioCharLimit,+ includeToolCallFields: input.includeToolCalls,+ });+return batchIO.map(toDomainWithStringifiedMetadata);},);diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.tsindex 45397c4bdf..abdc37813e 100644--- a/web/src/features/events/server/eventsService.ts+++ b/web/src/features/events/server/eventsService.ts@@ -927,6 +927,7 @@ interface GetEventBatchIOParams<maxStartTime: Date;truncated?: boolean;ioCharLimit?: number;+ sessionId?: string;includeExperimentFields?: TIncludeExperiment;/** Opt-in: tool-call arrays can be large; only eval consumers need them. */includeToolCallFields?: TIncludeToolCalls;@@ -948,6 +949,7 @@ export async function getEventBatchIO<maxStartTime: params.maxStartTime,truncated: params.truncated,ioCharLimit: params.ioCharLimit,+ sessionId: params.sessionId,includeExperimentFields: params.includeExperimentFields,includeToolCallFields: params.includeToolCallFields,});diff --git a/web/src/features/feature-flags/available-flags.ts b/web/src/features/feature-flags/available-flags.tsindex e3be529e78..fd8bc61f0d 100644--- a/web/src/features/feature-flags/available-flags.ts+++ b/web/src/features/feature-flags/available-flags.ts@@ -48,4 +48,7 @@ export const availableFlags = ["v4BetaToggleVisible","observationEvals","experimentsV4Enabled",+ // Internal flag (deliberately NOT in featurePreviewFlags): gates the+ // redesigned compact session timeline for admins/flagged users only.+ "sessionTimeline",] as const;diff --git a/web/src/features/feature-flags/types.ts b/web/src/features/feature-flags/types.tsindex 0f1da62fd3..5aea25f1f1 100644--- a/web/src/features/feature-flags/types.ts+++ b/web/src/features/feature-flags/types.ts@@ -2,9 +2,13 @@ import { type availableFlags } from "./available-flags";export type Flag = (typeof availableFlags)[number];export type Flags = {- [key in Exclude<Flag, "modernSession" | "normalizedIoPreview">]: boolean;+ [key in Exclude<+ Flag,+ "modernSession" | "normalizedIoPreview" | "sessionTimeline"+ >]: boolean;} & {// Optional while older sessions and test fixtures roll across new flags.modernSession?: boolean;normalizedIoPreview?: boolean;+ sessionTimeline?: boolean;};diff --git a/web/src/features/sessions/ConnectedModernSessionBodyLegacy.tsx b/web/src/features/sessions/ConnectedModernSessionBodyLegacy.tsxnew file mode 100644index 0000000000..f4f15a9af4--- /dev/null+++ b/web/src/features/sessions/ConnectedModernSessionBodyLegacy.tsx@@ -0,0 +1,469 @@+import React, { useEffect, useRef, useState } from "react";+import { useVirtualizer } from "@tanstack/react-virtual";+import { type FilterState } from "@langfuse/shared";++import { LazySessionTraceEventsRow } from "@/src/features/sessions/LazySessionTraceEventsRow";+import { SessionVirtualizedRow } from "@/src/features/sessions/SessionVirtualizedRow";+import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";+import { computeIdleGapSeconds } from "@/src/features/sessions/sessionIdleGap";+import { useElementSize } from "@/src/hooks/useElementSize";+import { useDebounce } from "@/src/hooks/useDebounce";+import { useVirtualizedScrollSpy } from "@/src/hooks/useVirtualizedScrollSpy";+import {+ ModernSessionSidebar,+ type ModernSessionSidebarFilterControls,+ type ModernSessionSidebarTrace,+} from "@/src/features/sessions/ModernSessionSidebar";+import { api } from "@/src/utils/api";++const MODERN_SESSION_OVERSCAN = 5;+const SIDEBAR_TRACE_CHUNK_SIZE = 20;+const SIDEBAR_OBSERVATION_PAGE_SIZE = 100;+const EMPTY_TRACES: EventSessionTrace[] = [];++type ConnectedModernSessionBodyLegacyProps = {+ tracesState:+ | { type: "loading" }+ | { type: "loaded"; traces: EventSessionTrace[] };+ projectId: string;+ sessionId: string;+ sessionMinTimestamp: Date;+ sessionMaxTimestamp: Date;+ openPeek: (id: string, row: EventSessionTrace) => void;+ traceCommentCounts: Map<string, number> | undefined;+ filterState: FilterState;+ filterMeasurementKey: string;+ viewLabel: string | null;+ showInlineToolCalls: boolean;+ showSystemPrompt: boolean;+ sidebarFilterControls: ModernSessionSidebarFilterControls;+ onFilterObservationByName: (+ name: string,+ operator: "any of" | "none of",+ ) => void;+};++export function ConnectedModernSessionBodyLegacy({+ tracesState,+ projectId,+ sessionId,+ sessionMinTimestamp,+ sessionMaxTimestamp,+ openPeek,+ traceCommentCounts,+ filterState,+ filterMeasurementKey,+ viewLabel,+ showInlineToolCalls,+ showSystemPrompt,+ sidebarFilterControls,+ onFilterObservationByName,+}: ConnectedModernSessionBodyLegacyProps) {+ const traces =+ tracesState.type === "loaded" ? tracesState.traces : EMPTY_TRACES;+ const [search, setSearch] = useState("");+ const [searchQuery, setSearchQuery] = useState("");+ const debouncedSetSearchQuery = useDebounce(setSearchQuery, 500, false);+ const isSearchPending = search.trim() !== searchQuery;+ const [collapsedTraceIds, setCollapsedTraceIds] = useState<Set<string>>(+ new Set(),+ );+ const [visibleTraceIds, setVisibleTraceIds] = useState<string[]>([]);+ const [pageCounts, setPageCounts] = useState<Record<string, number>>({});+ const expandedTraceIds = new Set(+ traces+ .filter((trace) => !collapsedTraceIds.has(trace.id))+ .map((trace) => trace.id),+ );++ const baseFilters: FilterState = [+ ...filterState,+ {+ column: "sessionId",+ type: "string",+ operator: "=",+ value: sessionId,+ },+ {+ column: "startTime",+ type: "datetime",+ operator: ">=",+ value: sessionMinTimestamp,+ },+ {+ column: "startTime",+ type: "datetime",+ operator: "<=",+ value: sessionMaxTimestamp,+ },+ ];+ const filtersRequireIO = filterState.some(+ (filter) =>+ (filter.column === "hasInput" || filter.column === "hasOutput") &&+ filter.type === "boolean" &&+ filter.operator === "=" &&+ filter.value,+ );++ const traceIndexById = new Map(+ traces.map((trace, index) => [trace.id, index] as const),+ );+ const activeChunkIndices = new Set<number>();+ if (!searchQuery) {+ for (const traceId of visibleTraceIds) {+ if (!expandedTraceIds.has(traceId)) continue;+ const traceIndex = traceIndexById.get(traceId);+ if (traceIndex === undefined) continue;+ activeChunkIndices.add(Math.floor(traceIndex / SIDEBAR_TRACE_CHUNK_SIZE));+ }+ }++ const queryDescriptors: Array<{+ key: string;+ page: number;+ traceIds: string[] | undefined;+ }> = [];+ if (searchQuery) {+ const key = `search:${filterMeasurementKey}:${searchQuery}`;+ const pageCount = pageCounts[key] ?? 1;+ for (let page = 1; page <= pageCount; page++) {+ queryDescriptors.push({ key, page, traceIds: undefined });+ }+ } else {+ for (const chunkIndex of activeChunkIndices) {+ const key = `browse:${filterMeasurementKey}:${chunkIndex}`;+ const pageCount = pageCounts[key] ?? 1;+ const startIndex = chunkIndex * SIDEBAR_TRACE_CHUNK_SIZE;+ const traceIds = traces+ .slice(startIndex, startIndex + SIDEBAR_TRACE_CHUNK_SIZE)+ .map((trace) => trace.id);+ for (let page = 1; page <= pageCount; page++) {+ queryDescriptors.push({ key, page, traceIds });+ }+ }+ }++ const observationQueries = api.useQueries((t) =>+ queryDescriptors.map((descriptor) =>+ t.events.all(+ {+ projectId,+ filter: descriptor.traceIds+ ? [+ ...baseFilters,+ {+ column: "traceId",+ type: "stringOptions",+ operator: "any of",+ value: descriptor.traceIds,+ },+ ]+ : baseFilters,+ searchQuery: searchQuery || null,+ searchType: searchQuery ? ["id"] : [],+ page: descriptor.page,+ limit: SIDEBAR_OBSERVATION_PAGE_SIZE,+ orderBy: { column: "startTime", order: "ASC" },+ },+ {+ staleTime: 60 * 1000,+ refetchOnWindowFocus: false,+ },+ ),+ ),+ );++ const observationsByTraceId = new Map<+ string,+ NonNullable<ModernSessionSidebarTrace["observations"]>+ >();+ const observationIdsByTraceId = new Map<string, Set<string>>();+ const traceIdsWithMatchingTraceLevelIO = new Set<string>();+ for (const query of observationQueries) {+ for (const observation of query.data?.observations ?? []) {+ if (!observation.traceId) {+ continue;+ }+ if (observation.id === `t-${observation.traceId}`) {+ traceIdsWithMatchingTraceLevelIO.add(observation.traceId);+ continue;+ }+ const observationIds = observationIdsByTraceId.get(observation.traceId);+ if (observationIds?.has(observation.id)) {+ continue;+ }+ if (observationIds) observationIds.add(observation.id);+ else {+ observationIdsByTraceId.set(+ observation.traceId,+ new Set([observation.id]),+ );+ }+ const observations = observationsByTraceId.get(observation.traceId);+ const row = {+ id: observation.id,+ name: observation.name,+ type: observation.type,+ latency: observation.latency,+ };+ if (observations) observations.push(row);+ else observationsByTraceId.set(observation.traceId, [row]);+ }+ }++ const sidebarTraces: ModernSessionSidebarTrace[] = [];+ for (const [index, trace] of traces.entries()) {+ const chunkIndex = Math.floor(index / SIDEBAR_TRACE_CHUNK_SIZE);+ const chunkKey = `browse:${filterMeasurementKey}:${chunkIndex}`;+ const relevantQueryIndices = queryDescriptors.flatMap(+ (descriptor, queryIndex) =>+ descriptor.key ===+ (searchQuery+ ? `search:${filterMeasurementKey}:${searchQuery}`+ : chunkKey)+ ? [queryIndex]+ : [],+ );+ const hasLoadedObservations = observationsByTraceId.has(trace.id);+ const isPending =+ relevantQueryIndices.length === 0 ||+ relevantQueryIndices.every(+ (queryIndex) => observationQueries[queryIndex]?.isPending,+ );+ const isError = relevantQueryIndices.some(+ (queryIndex) => observationQueries[queryIndex]?.isError,+ );+ const lastRelevantQuery =+ observationQueries[relevantQueryIndices.at(-1) ?? -1];+ const mayHaveMoreObservations = Boolean(+ lastRelevantQuery?.isPending || lastRelevantQuery?.data?.hasMore,+ );+ const observations =+ isPending && !hasLoadedObservations+ ? undefined+ : isError+ ? null+ : mayHaveMoreObservations && !hasLoadedObservations+ ? undefined+ : (observationsByTraceId.get(trace.id) ?? []);++ if (+ searchQuery &&+ !observationsByTraceId.has(trace.id) &&+ !traceIdsWithMatchingTraceLevelIO.has(trace.id)+ ) {+ continue;+ }++ sidebarTraces.push({+ trace,+ turnNumber: index + 1,+ idleGapSeconds:+ index === 0 ? null : computeIdleGapSeconds(traces[index - 1]!, trace),+ observations,+ hasMatchingTraceLevelIO:+ filtersRequireIO && traceIdsWithMatchingTraceLevelIO.has(trace.id),+ });+ }++ const lastQueryByKey = new Map<string, number>();+ queryDescriptors.forEach((descriptor, queryIndex) => {+ lastQueryByKey.set(descriptor.key, queryIndex);+ });+ const hasMoreObservations = Array.from(lastQueryByKey.values()).some(+ (queryIndex) => observationQueries[queryIndex]?.data?.hasMore,+ );+ const isLoadingMoreObservations = Array.from(lastQueryByKey.values()).some(+ (queryIndex) => observationQueries[queryIndex]?.isFetching,+ );+ const observationLoadError = observationQueries.some(+ (query) => query.isError,+ );++ const loadMoreObservations = () => {+ setPageCounts((current) => {+ let next = current;+ for (const [key, queryIndex] of lastQueryByKey) {+ const query = observationQueries[queryIndex];+ const descriptor = queryDescriptors[queryIndex];+ if (!query?.data?.hasMore || query.isFetching || !descriptor) {+ continue;+ }+ if (next === current) next = { ...current };+ next[key] = Math.max(current[key] ?? 1, descriptor.page + 1);+ }+ return next;+ });+ };++ const handleVisibleTraceIdsChange = (nextTraceIds: string[]) => {+ setVisibleTraceIds((current) => {+ if (+ current.length === nextTraceIds.length &&+ current.every((traceId, index) => traceId === nextTraceIds[index])+ ) {+ return current;+ }+ return nextTraceIds;+ });+ };++ const handleSearchChange = (nextSearch: string) => {+ setSearch(nextSearch);+ debouncedSetSearchQuery(nextSearch.trim());+ };++ const toggleTraceExpanded = (traceId: string) => {+ setCollapsedTraceIds((current) => {+ const next = new Set(current);+ if (next.has(traceId)) next.delete(traceId);+ else next.add(traceId);+ return next;+ });+ };+ const [feedRef, feedSize] = useElementSize<HTMLDivElement>();+ const virtualizer = useVirtualizer({+ count: traces.length,+ getScrollElement: () => feedRef.current,+ estimateSize: () => 520,+ overscan: MODERN_SESSION_OVERSCAN,+ getItemKey: (index) => traces[index]?.id ?? index,+ });+ const {+ activeItemId: activeTraceId,+ virtualItems,+ selectItem: selectTrace,+ } = useVirtualizedScrollSpy({+ items: traces,+ virtualizer,+ scrollElementRef: feedRef,+ viewportHeight: feedSize?.height ?? 0,+ endTransitionRatio: 0.2,+ });+ const observationScrollCleanupRef = useRef<(() => void) | null>(null);+ useEffect(() => () => observationScrollCleanupRef.current?.(), []);+ const handleSelect = (index: number, observationId?: string) => {+ observationScrollCleanupRef.current?.();+ observationScrollCleanupRef.current = null;+ selectTrace(index);+ if (!observationId) return;++ const feed = feedRef.current;+ if (!feed) return;++ const scrollToObservation = () => {+ const observation = Array.from(+ feed.querySelectorAll<HTMLElement>("[data-session-observation-id]"),+ ).find(+ (element) => element.dataset.sessionObservationId === observationId,+ );+ if (!observation) return false;++ const top =+ feed.scrollTop ++ observation.getBoundingClientRect().top -+ feed.getBoundingClientRect().top -+ Math.max(0, (feed.clientHeight - observation.clientHeight) / 2);+ feed.scrollTo({ top, behavior: "smooth" });+ return true;+ };++ if (scrollToObservation()) return;++ let timeout: number;+ const cleanup = () => {+ observer.disconnect();+ window.clearTimeout(timeout);+ };+ const observer = new MutationObserver(() => {+ if (!scrollToObservation()) return;+ cleanup();+ if (observationScrollCleanupRef.current === cleanup) {+ observationScrollCleanupRef.current = null;+ }+ });+ observer.observe(feed, { childList: true, subtree: true });+ timeout = window.setTimeout(() => {+ cleanup();+ if (observationScrollCleanupRef.current === cleanup) {+ observationScrollCleanupRef.current = null;+ }+ }, 5_000);+ observationScrollCleanupRef.current = cleanup;+ };++ return (+ <div className="bg-background relative grid min-h-0 flex-1 grid-rows-[minmax(10rem,13rem)_minmax(0,1fr)] gap-x-4 overflow-hidden lg:grid-cols-[clamp(200px,24vw,296px)_minmax(0,1fr)] lg:grid-rows-1">+ {tracesState.type === "loading" ? (+ <ModernSessionSidebar state="loading" />+ ) : (+ <ModernSessionSidebar+ state="loaded"+ traces={isSearchPending ? [] : sidebarTraces}+ activeTraceId={activeTraceId}+ filterControls={sidebarFilterControls}+ search={search}+ onSearchChange={handleSearchChange}+ expandedTraceIds={expandedTraceIds}+ onToggleTraceExpanded={toggleTraceExpanded}+ onFilterObservationByName={onFilterObservationByName}+ onSelect={handleSelect}+ onVisibleTraceIdsChange={handleVisibleTraceIdsChange}+ hasMoreObservations={hasMoreObservations}+ isLoadingMoreObservations={+ isSearchPending || isLoadingMoreObservations+ }+ observationLoadError={observationLoadError}+ onLoadMoreObservations={loadMoreObservations}+ onViewportUnderfilled={+ searchQuery && !isSearchPending ? loadMoreObservations : undefined+ }+ />+ )}+ <div className="bg-card dark:bg-background relative min-h-0 min-w-[320px]">+ <div+ ref={feedRef}+ className="h-full min-h-0 overflow-y-auto scroll-smooth"+ >+ <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}+ />+ </SessionVirtualizedRow>+ );+ })}+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/web/src/features/sessions/ConnectedModernSessionBodyTimeline.tsx b/web/src/features/sessions/ConnectedModernSessionBodyTimeline.tsxnew file mode 100644index 0000000000..41af049970--- /dev/null+++ b/web/src/features/sessions/ConnectedModernSessionBodyTimeline.tsx@@ -0,0 +1,451 @@+import { useRef, useState } from "react";+import { type FilterState } from "@langfuse/shared";++import {+ ConnectedSessionConversationTimeline,+ type ConnectedSessionConversationTimelineItem,+} from "@/src/features/sessions/SessionConversationTimeline/ConnectedSessionConversationTimeline";+import {+ type SessionConversationTimelineScrollTarget,+ useSessionConversationTimelineController,+} from "@/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline";+import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";+import { computeIdleGapSeconds } from "@/src/features/sessions/sessionIdleGap";+import { useDebounce } from "@/src/hooks/useDebounce";+import {+ ModernSessionSidebar,+ type ModernSessionSidebarFilterControls,+ type ModernSessionSidebarTrace,+} from "@/src/features/sessions/ModernSessionSidebar";+import { api, type RouterOutputs } from "@/src/utils/api";++const SIDEBAR_TRACE_CHUNK_SIZE = 20;+const SIDEBAR_OBSERVATION_PAGE_SIZE = 100;+const EMPTY_TRACES: EventSessionTrace[] = [];++type OpenPeek = (id: string, row: EventSessionTrace) => void;++type ConnectedModernSessionBodyTimelineProps = {+ tracesState:+ | { type: "loading" }+ | { type: "loaded"; traces: EventSessionTrace[] };+ projectId: string;+ sessionId: string;+ sessionMinTimestamp: Date;+ sessionMaxTimestamp: Date;+ openPeek: OpenPeek;+ filterState: FilterState;+ filterMeasurementKey: string;+ viewLabel: string | null;+ sidebarFilterControls: ModernSessionSidebarFilterControls;+ onFilterObservationByName: (+ name: string,+ operator: "any of" | "none of",+ ) => void;+};++export function ConnectedModernSessionBodyTimeline({+ tracesState,+ projectId,+ sessionId,+ sessionMinTimestamp,+ sessionMaxTimestamp,+ openPeek,+ filterState,+ filterMeasurementKey,+ viewLabel,+ sidebarFilterControls,+ onFilterObservationByName,+}: ConnectedModernSessionBodyTimelineProps) {+ const traces =+ tracesState.type === "loaded" ? tracesState.traces : EMPTY_TRACES;+ const [search, setSearch] = useState("");+ const [searchQuery, setSearchQuery] = useState("");+ const debouncedSetSearchQuery = useDebounce(setSearchQuery, 500, false);+ const isSearchPending = search.trim() !== searchQuery;+ const [collapsedTraceIds, setCollapsedTraceIds] = useState<Set<string>>(+ new Set(),+ );+ const [visibleTraceIds, setVisibleTraceIds] = useState<string[]>([]);+ const [scrollTarget, setScrollTarget] =+ useState<SessionConversationTimelineScrollTarget | null>(null);+ const scrollRequestIdRef = useRef(0);+ const [loadedTracePrefix, setLoadedTracePrefix] = useState({+ sessionId,+ chunkIndex: -1,+ });+ const loadedThroughChunkIndex =+ loadedTracePrefix.sessionId === sessionId+ ? loadedTracePrefix.chunkIndex+ : -1;+ const [pageCounts, setPageCounts] = useState<Record<string, number>>({});+ const expandedTraceIds = new Set(+ traces+ .filter((trace) => !collapsedTraceIds.has(trace.id))+ .map((trace) => trace.id),+ );++ const baseFilters: FilterState = [+ ...filterState,+ {+ column: "sessionId",+ type: "string",+ operator: "=",+ value: sessionId,+ },+ {+ column: "startTime",+ type: "datetime",+ operator: ">=",+ value: sessionMinTimestamp,+ },+ {+ column: "startTime",+ type: "datetime",+ operator: "<=",+ value: sessionMaxTimestamp,+ },+ ];+ const filtersRequireIO = filterState.some(+ (filter) =>+ (filter.column === "hasInput" || filter.column === "hasOutput") &&+ filter.type === "boolean" &&+ filter.operator === "=" &&+ filter.value,+ );++ const traceIndexById = new Map(+ traces.map((trace, index) => [trace.id, index] as const),+ );+ const activeChunkIndices = new Set<number>();+ if (!searchQuery) {+ let highestChunkIndex = Math.min(+ loadedThroughChunkIndex,+ Math.ceil(traces.length / SIDEBAR_TRACE_CHUNK_SIZE) - 1,+ );+ for (const traceId of visibleTraceIds) {+ const traceIndex = traceIndexById.get(traceId);+ if (traceIndex === undefined) continue;+ highestChunkIndex = Math.max(+ highestChunkIndex,+ Math.floor(traceIndex / SIDEBAR_TRACE_CHUNK_SIZE),+ );+ }+ for (let chunkIndex = 0; chunkIndex <= highestChunkIndex; chunkIndex++) {+ activeChunkIndices.add(chunkIndex);+ }+ }++ const queryDescriptors: Array<{+ key: string;+ page: number;+ traceIds: string[] | undefined;+ }> = [];+ if (searchQuery) {+ const key = `search:${filterMeasurementKey}:${searchQuery}`;+ const pageCount = pageCounts[key] ?? 1;+ for (let page = 1; page <= pageCount; page++) {+ queryDescriptors.push({ key, page, traceIds: undefined });+ }+ } else {+ for (const chunkIndex of activeChunkIndices) {+ const key = `browse:${filterMeasurementKey}:${chunkIndex}`;+ const pageCount = pageCounts[key] ?? 1;+ const startIndex = chunkIndex * SIDEBAR_TRACE_CHUNK_SIZE;+ const traceIds = traces+ .slice(startIndex, startIndex + SIDEBAR_TRACE_CHUNK_SIZE)+ .map((trace) => trace.id);+ for (let page = 1; page <= pageCount; page++) {+ queryDescriptors.push({ key, page, traceIds });+ }+ }+ }++ const observationQueries = api.useQueries((t) =>+ queryDescriptors.map((descriptor) =>+ t.events.all(+ {+ projectId,+ filter: descriptor.traceIds+ ? [+ ...baseFilters,+ {+ column: "traceId",+ type: "stringOptions",+ operator: "any of",+ value: descriptor.traceIds,+ },+ ]+ : baseFilters,+ searchQuery: searchQuery || null,+ searchType: searchQuery ? ["id"] : [],+ page: descriptor.page,+ limit: SIDEBAR_OBSERVATION_PAGE_SIZE,+ orderBy: { column: "startTime", order: "ASC" },+ },+ {+ staleTime: 60 * 1000,+ refetchOnWindowFocus: false,+ },+ ),+ ),+ );++ const observationsByTraceId = new Map<+ string,+ NonNullable<ModernSessionSidebarTrace["observations"]>+ >();+ const timelineObservationsByTraceId = new Map<+ string,+ RouterOutputs["events"]["all"]["observations"]+ >();+ const observationIdsByTraceId = new Map<string, Set<string>>();+ const traceIdsWithMatchingTraceLevelIO = new Set<string>();+ for (const query of observationQueries) {+ for (const observation of query.data?.observations ?? []) {+ if (!observation.traceId) {+ continue;+ }+ if (observation.id === `t-${observation.traceId}`) {+ traceIdsWithMatchingTraceLevelIO.add(observation.traceId);+ continue;+ }+ const observationIds = observationIdsByTraceId.get(observation.traceId);+ if (observationIds?.has(observation.id)) {+ continue;+ }+ if (observationIds) observationIds.add(observation.id);+ else {+ observationIdsByTraceId.set(+ observation.traceId,+ new Set([observation.id]),+ );+ }+ const observations = observationsByTraceId.get(observation.traceId);+ const timelineObservations = timelineObservationsByTraceId.get(+ observation.traceId,+ );+ const row = {+ id: observation.id,+ name: observation.name,+ type: observation.type,+ latency: observation.latency,+ };+ if (observations) observations.push(row);+ else observationsByTraceId.set(observation.traceId, [row]);+ if (timelineObservations) timelineObservations.push(observation);+ else {+ timelineObservationsByTraceId.set(observation.traceId, [observation]);+ }+ }+ }++ const sidebarTraces: ModernSessionSidebarTrace[] = [];+ for (const [index, trace] of traces.entries()) {+ const chunkIndex = Math.floor(index / SIDEBAR_TRACE_CHUNK_SIZE);+ const chunkKey = `browse:${filterMeasurementKey}:${chunkIndex}`;+ const relevantQueryIndices = queryDescriptors.flatMap(+ (descriptor, queryIndex) =>+ descriptor.key ===+ (searchQuery+ ? `search:${filterMeasurementKey}:${searchQuery}`+ : chunkKey)+ ? [queryIndex]+ : [],+ );+ const hasLoadedObservations = observationsByTraceId.has(trace.id);+ const isPending =+ relevantQueryIndices.length === 0 ||+ relevantQueryIndices.every(+ (queryIndex) => observationQueries[queryIndex]?.isPending,+ );+ const isError = relevantQueryIndices.some(+ (queryIndex) => observationQueries[queryIndex]?.isError,+ );+ const lastRelevantQuery =+ observationQueries[relevantQueryIndices.at(-1) ?? -1];+ const mayHaveMoreObservations = Boolean(+ lastRelevantQuery?.isPending || lastRelevantQuery?.data?.hasMore,+ );+ const observations =+ isPending && !hasLoadedObservations+ ? undefined+ : isError+ ? null+ : mayHaveMoreObservations && !hasLoadedObservations+ ? undefined+ : (observationsByTraceId.get(trace.id) ?? []);++ if (+ searchQuery &&+ !observationsByTraceId.has(trace.id) &&+ !traceIdsWithMatchingTraceLevelIO.has(trace.id)+ ) {+ continue;+ }++ sidebarTraces.push({+ trace,+ turnNumber: index + 1,+ idleGapSeconds:+ index === 0 ? null : computeIdleGapSeconds(traces[index - 1]!, trace),+ observations,+ hasMatchingTraceLevelIO:+ filtersRequireIO && traceIdsWithMatchingTraceLevelIO.has(trace.id),+ });+ }++ const lastQueryByKey = new Map<string, number>();+ queryDescriptors.forEach((descriptor, queryIndex) => {+ lastQueryByKey.set(descriptor.key, queryIndex);+ });+ const hasMoreObservations = Array.from(lastQueryByKey.values()).some(+ (queryIndex) => observationQueries[queryIndex]?.data?.hasMore,+ );+ const isLoadingMoreObservations = Array.from(lastQueryByKey.values()).some(+ (queryIndex) => observationQueries[queryIndex]?.isFetching,+ );+ const observationLoadError = observationQueries.some(+ (query) => query.isError,+ );++ const loadMoreObservations = () => {+ setPageCounts((current) => {+ let next = current;+ for (const [key, queryIndex] of lastQueryByKey) {+ const query = observationQueries[queryIndex];+ const descriptor = queryDescriptors[queryIndex];+ if (!query?.data?.hasMore || query.isFetching || !descriptor) {+ continue;+ }+ if (next === current) next = { ...current };+ next[key] = Math.max(current[key] ?? 1, descriptor.page + 1);+ }+ return next;+ });+ };++ const handleVisibleTraceIdsChange = (nextTraceIds: string[]) => {+ const highestVisibleTraceIndex = nextTraceIds.reduce(+ (highestIndex, traceId) =>+ Math.max(highestIndex, traceIndexById.get(traceId) ?? -1),+ -1,+ );+ if (!searchQuery && highestVisibleTraceIndex >= 0) {+ setLoadedTracePrefix((current) => ({+ sessionId,+ chunkIndex: Math.max(+ current.sessionId === sessionId ? current.chunkIndex : -1,+ Math.floor(highestVisibleTraceIndex / SIDEBAR_TRACE_CHUNK_SIZE),+ ),+ }));+ }+ setVisibleTraceIds((current) => {+ if (+ current.length === nextTraceIds.length &&+ current.every((traceId, index) => traceId === nextTraceIds[index])+ ) {+ return current;+ }+ return nextTraceIds;+ });+ };++ const handleSearchChange = (nextSearch: string) => {+ setSearch(nextSearch);+ debouncedSetSearchQuery(nextSearch.trim());+ };+ const sidebarTraceById = new Map(+ sidebarTraces.map((sidebarTrace) => [sidebarTrace.trace.id, sidebarTrace]),+ );++ const toggleTraceExpanded = (traceId: string) => {+ setCollapsedTraceIds((current) => {+ const next = new Set(current);+ if (next.has(traceId)) next.delete(traceId);+ else next.add(traceId);+ return next;+ });+ };+ const timelineTraces: ConnectedSessionConversationTimelineItem[] = traces.map(+ (trace, index) => {+ const sidebarTrace = sidebarTraceById.get(trace.id);+ const observations =+ sidebarTrace?.observations === null+ ? null+ : sidebarTrace?.observations === undefined+ ? undefined+ : (timelineObservationsByTraceId.get(trace.id) ?? []);++ return {+ trace,+ turnNumber: index + 1,+ observations,+ };+ },+ );+ const timelineController =+ useSessionConversationTimelineController(timelineTraces);+ const handleSelect = (index: number, observationId?: string) => {+ const traceId = timelineTraces[index]?.trace.id;+ if (observationId && traceId) {+ scrollRequestIdRef.current += 1;+ setScrollTarget({+ traceId,+ observationId,+ requestId: scrollRequestIdRef.current,+ });+ }+ timelineController.onSelect(index, observationId);+ };++ return (+ <div className="bg-background relative grid min-h-0 flex-1 grid-rows-[minmax(10rem,13rem)_minmax(0,1fr)] gap-x-4 overflow-hidden lg:grid-cols-[clamp(200px,24vw,296px)_minmax(0,1fr)] lg:grid-rows-1">+ {tracesState.type === "loading" ? (+ <ModernSessionSidebar state="loading" />+ ) : (+ <ModernSessionSidebar+ state="loaded"+ traces={isSearchPending ? [] : sidebarTraces}+ activeTraceId={timelineController.activeTraceId ?? undefined}+ filterControls={sidebarFilterControls}+ search={search}+ onSearchChange={handleSearchChange}+ expandedTraceIds={expandedTraceIds}+ onToggleTraceExpanded={toggleTraceExpanded}+ onFilterObservationByName={onFilterObservationByName}+ onSelect={handleSelect}+ onVisibleTraceIdsChange={handleVisibleTraceIdsChange}+ hasMoreObservations={hasMoreObservations}+ isLoadingMoreObservations={+ isSearchPending || isLoadingMoreObservations+ }+ observationLoadError={observationLoadError}+ onLoadMoreObservations={loadMoreObservations}+ onViewportUnderfilled={+ searchQuery && !isSearchPending ? loadMoreObservations : undefined+ }+ />+ )}+ <div className="bg-card dark:bg-background relative min-h-0 min-w-[320px]">+ <ConnectedSessionConversationTimeline+ traces={timelineTraces}+ projectId={projectId}+ sessionId={sessionId}+ filterState={filterState}+ filterMeasurementKey={filterMeasurementKey}+ viewLabel={viewLabel}+ openPeek={openPeek}+ controller={timelineController}+ scrollTarget={scrollTarget}+ onFilterObservationByName={onFilterObservationByName}+ onLoadMoreObservations={+ hasMoreObservations && !isLoadingMoreObservations+ ? loadMoreObservations+ : undefined+ }+ />+ </div>+ </div>+ );+}diff --git a/web/src/features/sessions/ModernSession.clienttest.tsx b/web/src/features/sessions/ModernSession.clienttest.tsxnew file mode 100644index 0000000000..f23ef13430--- /dev/null+++ b/web/src/features/sessions/ModernSession.clienttest.tsx@@ -0,0 +1,132 @@+import { render, screen } from "@testing-library/react";+import { type ComponentProps, type ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { ModernSession } from "@/src/features/sessions/ModernSession";++const { useIsAuthenticatedAndProjectMember } = vi.hoisted(() => ({+ useIsAuthenticatedAndProjectMember: vi.fn(() => true),+}));++vi.mock("@/src/features/auth/hooks", () => ({+ useIsAuthenticatedAndProjectMember,+}));++vi.mock("@/src/features/sessions/ConnectedModernSessionBodyLegacy", () => ({+ ConnectedModernSessionBodyLegacy: () => <div>Legacy body</div>,+}));++vi.mock("@/src/features/sessions/ConnectedModernSessionBodyTimeline", () => ({+ ConnectedModernSessionBodyTimeline: () => <div>Timeline body</div>,+}));++vi.mock("@/src/features/sessions/ModernSessionHeader", () => ({+ ModernSessionHeader: () => <div>Modern session header</div>,+}));++vi.mock("@/src/features/sessions/ModernSessionFilterControls", () => ({+ ModernSessionFilterControls: ({+ children,+ }: {+ children: (controls: never) => ReactNode;+ }) => children({} as never),+}));++vi.mock("@/src/features/sessions/SessionMetadataJsonPathControl", () => ({+ SessionMetadataJsonPathControl: ({+ children,+ }: {+ children: (state: {+ paths: readonly string[];+ source: { state: "idle" };+ onEditorOpenChange: (open: boolean) => void;+ onSave: (path: string) => void;+ onRemove: (path: string) => void;+ }) => ReactNode;+ }) =>+ children({+ paths: [],+ source: { state: "idle" },+ onEditorOpenChange: vi.fn(),+ onSave: vi.fn(),+ onRemove: vi.fn(),+ }),+}));++const defaultProps = {+ isTimelineEnabled: false,+ session: {+ countTraces: 0,+ inputUsage: 0,+ outputUsage: 0,+ totalTokens: 0,+ totalCost: 0,+ environment: undefined,+ users: [],+ scores: [],+ minTimestamp: new Date("2026-01-01T00:00:00.000Z"),+ maxTimestamp: new Date("2026-01-01T00:00:01.000Z"),+ },+ tracesState: { type: "loaded", traces: [] } as const,+ projectId: "project-id",+ sessionId: "session-id",+ openPeek: vi.fn(),+ traceCommentCounts: undefined,+ filterState: [],+ filterMeasurementKey: "filters",+ viewLabel: null,+ showInlineToolCalls: false,+ showSystemPrompt: false,+ filterControlsProps: {+ projectId: "project-id",+ filterState: [],+ filterColumns: [],+ filterColumnsWithCustomSelect: [],+ onChange: vi.fn(),+ viewControllers: {+ selectedViewId: null,+ appliedViewId: null,+ handleSetViewId: vi.fn(),+ applyViewState: vi.fn(),+ },+ currentViewState: {+ orderBy: null,+ filters: [],+ columnOrder: [],+ columnVisibility: {},+ searchQuery: "",+ },+ },+ onFilterObservationByName: vi.fn(),+} satisfies ComponentProps<typeof ModernSession>;++describe("ModernSession", () => {+ beforeEach(() => {+ useIsAuthenticatedAndProjectMember.mockReturnValue(true);+ });++ it("renders the shared header and legacy connected body by default", () => {+ render(<ModernSession {...defaultProps} />);++ expect(screen.getByText("Modern session header")).toBeInTheDocument();+ expect(screen.getByText("Legacy body")).toBeInTheDocument();+ expect(screen.queryByText("Timeline body")).not.toBeInTheDocument();+ });++ it("renders only the timeline connected body when enabled", () => {+ render(<ModernSession {...defaultProps} isTimelineEnabled />);++ expect(screen.getByText("Modern session header")).toBeInTheDocument();+ expect(screen.getByText("Timeline body")).toBeInTheDocument();+ expect(screen.queryByText("Legacy body")).not.toBeInTheDocument();+ });++ it("renders the legacy body for public access when the timeline is enabled", () => {+ useIsAuthenticatedAndProjectMember.mockReturnValue(false);++ render(<ModernSession {...defaultProps} isTimelineEnabled />);++ expect(screen.getByText("Legacy body")).toBeInTheDocument();+ expect(screen.queryByText("Timeline body")).not.toBeInTheDocument();+ });+});diff --git a/web/src/features/sessions/ModernSession.tsx b/web/src/features/sessions/ModernSession.tsxindex b35e28fe47..998cc9c240 100644--- a/web/src/features/sessions/ModernSession.tsx+++ b/web/src/features/sessions/ModernSession.tsx@@ -1,44 +1,48 @@-import React, { useEffect, useRef, useState } from "react";-import { useVirtualizer } from "@tanstack/react-virtual";+import { type ComponentProps } from "react";import { type FilterState } from "@langfuse/shared";-import { LazySessionTraceEventsRow } from "@/src/features/sessions/LazySessionTraceEventsRow";-import { SessionVirtualizedRow } from "@/src/features/sessions/SessionVirtualizedRow";-import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";-import { computeIdleGapSeconds } from "@/src/features/sessions/sessionIdleGap";-import { useElementSize } from "@/src/hooks/useElementSize";-import { useDebounce } from "@/src/hooks/useDebounce";-import { useVirtualizedScrollSpy } from "@/src/hooks/useVirtualizedScrollSpy";+import { ConnectedModernSessionBodyLegacy } from "@/src/features/sessions/ConnectedModernSessionBodyLegacy";+import { ConnectedModernSessionBodyTimeline } from "@/src/features/sessions/ConnectedModernSessionBodyTimeline";+import { ModernSessionFilterControls } from "@/src/features/sessions/ModernSessionFilterControls";+import { ModernSessionHeader } from "@/src/features/sessions/ModernSessionHeader";+import { SessionMetadataJsonPathControl } from "@/src/features/sessions/SessionMetadataJsonPathControl";+import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";import {- ModernSessionSidebar,- type ModernSessionSidebarFilterControls,- type ModernSessionSidebarTrace,-} from "@/src/features/sessions/ModernSessionSidebar";-import { api } from "@/src/utils/api";--const MODERN_SESSION_OVERSCAN = 5;-const SIDEBAR_TRACE_CHUNK_SIZE = 20;-const SIDEBAR_OBSERVATION_PAGE_SIZE = 100;-const EMPTY_TRACES: EventSessionTrace[] = [];--type OpenPeek = (id: string, row: EventSessionTrace) => void;+ type EventSession,+ type EventSessionTrace,+} from "@/src/features/sessions/sessionDetailPageTypes";type ModernSessionProps = {+ isTimelineEnabled: boolean;+ session: Pick<+ EventSession,+ | "countTraces"+ | "inputUsage"+ | "outputUsage"+ | "totalTokens"+ | "totalCost"+ | "environment"+ | "users"+ | "scores"+ | "minTimestamp"+ | "maxTimestamp"+ >;tracesState:| { type: "loading" }| { type: "loaded"; traces: EventSessionTrace[] };projectId: string;sessionId: string;- sessionMinTimestamp: Date;- sessionMaxTimestamp: Date;- openPeek: OpenPeek;+ openPeek: (id: string, row: EventSessionTrace) => void;traceCommentCounts: Map<string, number> | undefined;filterState: FilterState;filterMeasurementKey: string;viewLabel: string | null;showInlineToolCalls: boolean;showSystemPrompt: boolean;- sidebarFilterControls: ModernSessionSidebarFilterControls;+ filterControlsProps: Omit<+ ComponentProps<typeof ModernSessionFilterControls>,+ "children"+ >;onFilterObservationByName: (name: string,operator: "any of" | "none of",@@ -46,11 +50,11 @@ type ModernSessionProps = {};export function ModernSession({+ isTimelineEnabled,+ session,tracesState,projectId,sessionId,- sessionMinTimestamp,- sessionMaxTimestamp,openPeek,traceCommentCounts,filterState,@@ -58,418 +62,72 @@ export function ModernSession({viewLabel,showInlineToolCalls,showSystemPrompt,- sidebarFilterControls,+ filterControlsProps,onFilterObservationByName,}: ModernSessionProps) {- const traces =- tracesState.type === "loaded" ? tracesState.traces : EMPTY_TRACES;- const [search, setSearch] = useState("");- const [searchQuery, setSearchQuery] = useState("");- const debouncedSetSearchQuery = useDebounce(setSearchQuery, 500, false);- const isSearchPending = search.trim() !== searchQuery;- const [collapsedTraceIds, setCollapsedTraceIds] = useState<Set<string>>(- new Set(),- );- const [visibleTraceIds, setVisibleTraceIds] = useState<string[]>([]);- const [pageCounts, setPageCounts] = useState<Record<string, number>>({});- const expandedTraceIds = new Set(- traces- .filter((trace) => !collapsedTraceIds.has(trace.id))- .map((trace) => trace.id),- );-- const baseFilters: FilterState = [- ...filterState,- {- column: "sessionId",- type: "string",- operator: "=",- value: sessionId,- },- {- column: "startTime",- type: "datetime",- operator: ">=",- value: sessionMinTimestamp,- },- {- column: "startTime",- type: "datetime",- operator: "<=",- value: sessionMaxTimestamp,- },- ];- const filtersRequireIO = filterState.some(- (filter) =>- (filter.column === "hasInput" || filter.column === "hasOutput") &&- filter.type === "boolean" &&- filter.operator === "=" &&- filter.value,- );-- const traceIndexById = new Map(- traces.map((trace, index) => [trace.id, index] as const),- );- const activeChunkIndices = new Set<number>();- if (!searchQuery) {- for (const traceId of visibleTraceIds) {- if (!expandedTraceIds.has(traceId)) continue;- const traceIndex = traceIndexById.get(traceId);- if (traceIndex === undefined) continue;- activeChunkIndices.add(Math.floor(traceIndex / SIDEBAR_TRACE_CHUNK_SIZE));- }- }-- const queryDescriptors: Array<{- key: string;- page: number;- traceIds: string[] | undefined;- }> = [];- if (searchQuery) {- const key = `search:${filterMeasurementKey}:${searchQuery}`;- const pageCount = pageCounts[key] ?? 1;- for (let page = 1; page <= pageCount; page++) {- queryDescriptors.push({ key, page, traceIds: undefined });- }- } else {- for (const chunkIndex of activeChunkIndices) {- const key = `browse:${filterMeasurementKey}:${chunkIndex}`;- const pageCount = pageCounts[key] ?? 1;- const startIndex = chunkIndex * SIDEBAR_TRACE_CHUNK_SIZE;- const traceIds = traces- .slice(startIndex, startIndex + SIDEBAR_TRACE_CHUNK_SIZE)- .map((trace) => trace.id);- for (let page = 1; page <= pageCount; page++) {- queryDescriptors.push({ key, page, traceIds });- }- }- }-- const observationQueries = api.useQueries((t) =>- queryDescriptors.map((descriptor) =>- t.events.all(- {- projectId,- filter: descriptor.traceIds- ? [- ...baseFilters,- {- column: "traceId",- type: "stringOptions",- operator: "any of",- value: descriptor.traceIds,- },- ]- : baseFilters,- searchQuery: searchQuery || null,- searchType: searchQuery ? ["id"] : [],- page: descriptor.page,- limit: SIDEBAR_OBSERVATION_PAGE_SIZE,- orderBy: { column: "startTime", order: "ASC" },- },- {- staleTime: 60 * 1000,- refetchOnWindowFocus: false,- },- ),- ),- );-- const observationsByTraceId = new Map<- string,- NonNullable<ModernSessionSidebarTrace["observations"]>- >();- const observationIdsByTraceId = new Map<string, Set<string>>();- const traceIdsWithMatchingTraceLevelIO = new Set<string>();- for (const query of observationQueries) {- for (const observation of query.data?.observations ?? []) {- if (!observation.traceId) {- continue;- }- if (observation.id === `t-${observation.traceId}`) {- traceIdsWithMatchingTraceLevelIO.add(observation.traceId);- continue;- }- const observationIds = observationIdsByTraceId.get(observation.traceId);- if (observationIds?.has(observation.id)) {- continue;- }- if (observationIds) observationIds.add(observation.id);- else {- observationIdsByTraceId.set(- observation.traceId,- new Set([observation.id]),- );- }- const observations = observationsByTraceId.get(observation.traceId);- const row = {- id: observation.id,- name: observation.name,- type: observation.type,- latency: observation.latency,- };- if (observations) observations.push(row);- else observationsByTraceId.set(observation.traceId, [row]);- }- }-- const sidebarTraces: ModernSessionSidebarTrace[] = [];- for (const [index, trace] of traces.entries()) {- const chunkIndex = Math.floor(index / SIDEBAR_TRACE_CHUNK_SIZE);- const chunkKey = `browse:${filterMeasurementKey}:${chunkIndex}`;- const relevantQueryIndices = queryDescriptors.flatMap(- (descriptor, queryIndex) =>- descriptor.key ===- (searchQuery- ? `search:${filterMeasurementKey}:${searchQuery}`- : chunkKey)- ? [queryIndex]- : [],- );- const hasLoadedObservations = observationsByTraceId.has(trace.id);- const isPending =- relevantQueryIndices.length === 0 ||- relevantQueryIndices.every(- (queryIndex) => observationQueries[queryIndex]?.isPending,- );- const isError = relevantQueryIndices.some(- (queryIndex) => observationQueries[queryIndex]?.isError,- );- const lastRelevantQuery =- observationQueries[relevantQueryIndices.at(-1) ?? -1];- const mayHaveMoreObservations = Boolean(- lastRelevantQuery?.isPending || lastRelevantQuery?.data?.hasMore,- );- const observations =- isPending && !hasLoadedObservations- ? undefined- : isError- ? null- : mayHaveMoreObservations && !hasLoadedObservations- ? undefined- : (observationsByTraceId.get(trace.id) ?? []);-- if (- searchQuery &&- !observationsByTraceId.has(trace.id) &&- !traceIdsWithMatchingTraceLevelIO.has(trace.id)- ) {- continue;- }-- sidebarTraces.push({- trace,- turnNumber: index + 1,- idleGapSeconds:- index === 0 ? null : computeIdleGapSeconds(traces[index - 1]!, trace),- observations,- hasMatchingTraceLevelIO:- filtersRequireIO && traceIdsWithMatchingTraceLevelIO.has(trace.id),- });- }-- const lastQueryByKey = new Map<string, number>();- queryDescriptors.forEach((descriptor, queryIndex) => {- lastQueryByKey.set(descriptor.key, queryIndex);- });- const hasMoreObservations = Array.from(lastQueryByKey.values()).some(- (queryIndex) => observationQueries[queryIndex]?.data?.hasMore,- );- const isLoadingMoreObservations = Array.from(lastQueryByKey.values()).some(- (queryIndex) => observationQueries[queryIndex]?.isFetching,- );- const observationLoadError = observationQueries.some(- (query) => query.isError,- );-- const loadMoreObservations = () => {- setPageCounts((current) => {- let next = current;- for (const [key, queryIndex] of lastQueryByKey) {- const query = observationQueries[queryIndex];- const descriptor = queryDescriptors[queryIndex];- if (!query?.data?.hasMore || query.isFetching || !descriptor) {- continue;- }- if (next === current) next = { ...current };- next[key] = Math.max(current[key] ?? 1, descriptor.page + 1);- }- return next;- });- };-- const handleVisibleTraceIdsChange = (nextTraceIds: string[]) => {- setVisibleTraceIds((current) => {- if (- current.length === nextTraceIds.length &&- current.every((traceId, index) => traceId === nextTraceIds[index])- ) {- return current;- }- return nextTraceIds;- });- };-- const handleSearchChange = (nextSearch: string) => {- setSearch(nextSearch);- debouncedSetSearchQuery(nextSearch.trim());- };-- const toggleTraceExpanded = (traceId: string) => {- setCollapsedTraceIds((current) => {- const next = new Set(current);- if (next.has(traceId)) next.delete(traceId);- else next.add(traceId);- return next;- });- };- const [feedRef, feedSize] = useElementSize<HTMLDivElement>();- const virtualizer = useVirtualizer({- count: traces.length,- getScrollElement: () => feedRef.current,- estimateSize: () => 520,- overscan: MODERN_SESSION_OVERSCAN,- getItemKey: (index) => traces[index]?.id ?? index,- });- const {- activeItemId: activeTraceId,- virtualItems,- selectItem: selectTrace,- } = useVirtualizedScrollSpy({- items: traces,- virtualizer,- scrollElementRef: feedRef,- viewportHeight: feedSize?.height ?? 0,- endTransitionRatio: 0.2,- });- const observationScrollCleanupRef = useRef<(() => void) | null>(null);- useEffect(() => () => observationScrollCleanupRef.current?.(), []);- const handleSelect = (index: number, observationId?: string) => {- observationScrollCleanupRef.current?.();- observationScrollCleanupRef.current = null;- selectTrace(index);- if (!observationId) return;-- const feed = feedRef.current;- if (!feed) return;-- const scrollToObservation = () => {- const observation = Array.from(- feed.querySelectorAll<HTMLElement>("[data-session-observation-id]"),- ).find(- (element) => element.dataset.sessionObservationId === observationId,- );- if (!observation) return false;-- const top =- feed.scrollTop +- observation.getBoundingClientRect().top -- feed.getBoundingClientRect().top -- Math.max(0, (feed.clientHeight - observation.clientHeight) / 2);- feed.scrollTo({ top, behavior: "smooth" });- return true;- };-- if (scrollToObservation()) return;-- let timeout: number;- const cleanup = () => {- observer.disconnect();- window.clearTimeout(timeout);- };- const observer = new MutationObserver(() => {- if (!scrollToObservation()) return;- cleanup();- if (observationScrollCleanupRef.current === cleanup) {- observationScrollCleanupRef.current = null;- }- });- observer.observe(feed, { childList: true, subtree: true });- timeout = window.setTimeout(() => {- cleanup();- if (observationScrollCleanupRef.current === cleanup) {- observationScrollCleanupRef.current = null;- }- }, 5_000);- observationScrollCleanupRef.current = cleanup;+ const isProjectMember = useIsAuthenticatedAndProjectMember(projectId);+ // Public session authorization must support timeline event queries before removing the sessionTimeline flag.+ const shouldRenderTimeline = isTimelineEnabled && isProjectMember;+ const headerTraces =+ tracesState.type === "loaded"+ ? ({ state: "loaded", data: tracesState.traces } as const)+ : ({ state: "loading" } as const);+ const sharedBodyProps = {+ tracesState,+ projectId,+ sessionId,+ sessionMinTimestamp: session.minTimestamp,+ sessionMaxTimestamp: session.maxTimestamp,+ openPeek,+ filterState,+ filterMeasurementKey,+ viewLabel,+ onFilterObservationByName,};return (- <div className="bg-background relative grid min-h-0 flex-1 grid-rows-[minmax(10rem,13rem)_minmax(0,1fr)] gap-x-4 overflow-hidden lg:grid-cols-[clamp(200px,24vw,296px)_minmax(0,1fr)] lg:grid-rows-1">- {tracesState.type === "loading" ? (- <ModernSessionSidebar state="loading" />- ) : (- <ModernSessionSidebar- state="loaded"- traces={isSearchPending ? [] : sidebarTraces}- activeTraceId={activeTraceId}- filterControls={sidebarFilterControls}- search={search}- onSearchChange={handleSearchChange}- expandedTraceIds={expandedTraceIds}- onToggleTraceExpanded={toggleTraceExpanded}- onFilterObservationByName={onFilterObservationByName}- onSelect={handleSelect}- onVisibleTraceIdsChange={handleVisibleTraceIdsChange}- hasMoreObservations={hasMoreObservations}- isLoadingMoreObservations={- isSearchPending || isLoadingMoreObservations- }- observationLoadError={observationLoadError}- onLoadMoreObservations={loadMoreObservations}- onViewportUnderfilled={- searchQuery && !isSearchPending ? loadMoreObservations : undefined- }- />- )}- <div className="bg-card dark:bg-background relative min-h-0 min-w-[320px]">- <div- ref={feedRef}- className="h-full min-h-0 overflow-y-auto scroll-smooth"- >- <div- style={{- height: `${virtualizer.getTotalSize()}px`,- width: "100%",- position: "relative",- }}- >- {virtualItems.map((virtualItem) => {- const trace = traces[virtualItem.index];- if (!trace) return null;-- const content = (- <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}- />- );-- return (- <SessionVirtualizedRow- key={virtualItem.key}- itemKey={String(virtualItem.key)}- measurementKey={`${String(virtualItem.key)}:${showInlineToolCalls}:${showSystemPrompt}:${filterMeasurementKey}`}- source="modern"- virtualItem={virtualItem}- virtualizer={virtualizer}- >- {content}- </SessionVirtualizedRow>- );- })}- </div>- </div>- </div>- </div>+ <>+ <SessionMetadataJsonPathControl+ key={`${projectId}:${sessionId}`}+ projectId={projectId}+ sessionId={sessionId}+ traces={headerTraces}+ filterState={filterState}+ >+ {(metadataJsonPaths) => (+ <ModernSessionHeader+ projectId={projectId}+ countTraces={session.countTraces}+ traces={headerTraces}+ tokensIn={session.inputUsage}+ tokensOut={session.outputUsage}+ totalTokens={session.totalTokens}+ totalCost={session.totalCost ?? 0}+ environment={session.environment ?? null}+ users={session.users ?? []}+ metadataJsonPaths={metadataJsonPaths}+ scores={session.scores}+ />+ )}+ </SessionMetadataJsonPathControl>+ <ModernSessionFilterControls {...filterControlsProps}>+ {(sidebarFilterControls) =>+ shouldRenderTimeline ? (+ <ConnectedModernSessionBodyTimeline+ {...sharedBodyProps}+ sidebarFilterControls={sidebarFilterControls}+ />+ ) : (+ <ConnectedModernSessionBodyLegacy+ {...sharedBodyProps}+ traceCommentCounts={traceCommentCounts}+ showInlineToolCalls={showInlineToolCalls}+ showSystemPrompt={showSystemPrompt}+ sidebarFilterControls={sidebarFilterControls}+ />+ )+ }+ </ModernSessionFilterControls>+ </>);}diff --git a/web/src/features/sessions/ModernSessionHeaderActionsController.clienttest.tsx b/web/src/features/sessions/ModernSessionHeaderActionsController.clienttest.tsxindex 699d3bc70a..1ad8e5cde2 100644--- a/web/src/features/sessions/ModernSessionHeaderActionsController.clienttest.tsx+++ b/web/src/features/sessions/ModernSessionHeaderActionsController.clienttest.tsx@@ -78,9 +78,7 @@ vi.mock("@/src/utils/api", () => ({}));describe("ModernSessionHeaderActionsController", () => {- it("keeps all display settings reachable from the actions menu", () => {- const onShowCorrectionsChange = vi.fn();- const onShowInlineToolCallsChange = vi.fn();+ it("keeps the timeline display setting reachable from the actions menu", () => {const onShowSystemPromptChange = vi.fn();render(@@ -88,11 +86,7 @@ describe("ModernSessionHeaderActionsController", () => {projectId="project-id"sessionId="session-id"isPublic={false}- showCorrections={false}- showInlineToolCalls={false}showSystemPrompt={false}- onShowCorrectionsChange={onShowCorrectionsChange}- onShowInlineToolCallsChange={onShowInlineToolCallsChange}onShowSystemPromptChange={onShowSystemPromptChange}><DropdownMenuTrigger asChild>@@ -103,17 +97,35 @@ describe("ModernSessionHeaderActionsController", () => {expect(screen.getByText("Display")).toBeInTheDocument();fireEvent.click(- screen.getByRole("menuitemcheckbox", { name: "Show corrections" }),+ screen.getByRole("menuitemcheckbox", { name: "Show system prompt" }),);- fireEvent.click(- screen.getByRole("menuitemcheckbox", { name: "Show tool calls" }),++ expect(onShowSystemPromptChange).toHaveBeenCalledWith(true);+ });++ it("shows the legacy tool-call setting only when provided", () => {+ const onShowInlineToolCallsChange = vi.fn();++ render(+ <ModernSessionHeaderActionsController+ projectId="project-id"+ sessionId="session-id"+ isPublic={false}+ showInlineToolCalls={false}+ showSystemPrompt={false}+ onShowInlineToolCallsChange={onShowInlineToolCallsChange}+ onShowSystemPromptChange={vi.fn()}+ >+ <DropdownMenuTrigger asChild>+ <button type="button">Actions</button>+ </DropdownMenuTrigger>+ </ModernSessionHeaderActionsController>,);+fireEvent.click(- screen.getByRole("menuitemcheckbox", { name: "Show system prompt" }),+ screen.getByRole("menuitemcheckbox", { name: "Show tool calls" }),);- expect(onShowCorrectionsChange).toHaveBeenCalledWith(true);expect(onShowInlineToolCallsChange).toHaveBeenCalledWith(true);- expect(onShowSystemPromptChange).toHaveBeenCalledWith(true);});});diff --git a/web/src/features/sessions/ModernSessionHeaderActionsController.tsx b/web/src/features/sessions/ModernSessionHeaderActionsController.tsxindex 38cc8308fb..3e8b260092 100644--- a/web/src/features/sessions/ModernSessionHeaderActionsController.tsx+++ b/web/src/features/sessions/ModernSessionHeaderActionsController.tsx@@ -31,12 +31,12 @@ export function ModernSessionHeaderActionsController({projectId: string;sessionId: string;isPublic: boolean;- showCorrections: boolean;- showInlineToolCalls: boolean;- showSystemPrompt: boolean;- onShowCorrectionsChange: (isEnabled: boolean) => void;- onShowInlineToolCallsChange: (isEnabled: boolean) => void;- onShowSystemPromptChange: (isEnabled: boolean) => void;+ showCorrections?: boolean;+ showInlineToolCalls?: boolean;+ showSystemPrompt?: boolean;+ onShowCorrectionsChange?: (isEnabled: boolean) => void;+ onShowInlineToolCallsChange?: (isEnabled: boolean) => void;+ onShowSystemPromptChange?: (isEnabled: boolean) => void;children: ReactNode;}) {const capture = usePostHogClientCapture();@@ -49,6 +49,10 @@ export function ModernSessionHeaderActionsController({const publishMutation = api.sessions.publish.useMutation({onSuccess: () => utils.sessions.invalidate(),});+ const hasDisplaySettings =+ (showCorrections !== undefined && onShowCorrectionsChange) ||+ (showInlineToolCalls !== undefined && onShowInlineToolCallsChange) ||+ (showSystemPrompt !== undefined && onShowSystemPromptChange);return (<DropdownMenu>@@ -77,39 +81,50 @@ export function ModernSessionHeaderActionsController({<CopyIcon className="mr-2 h-3.5 w-3.5" />Copy session ID</DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuSub>- <DropdownMenuSubTrigger>Display</DropdownMenuSubTrigger>- <DropdownMenuSubContent>- <DropdownMenuCheckboxItem- checked={showCorrections}- onClick={(event) => {- event.preventDefault();- onShowCorrectionsChange(!showCorrections);- }}- >- Show corrections- </DropdownMenuCheckboxItem>- <DropdownMenuCheckboxItem- checked={showInlineToolCalls}- onClick={(event) => {- event.preventDefault();- onShowInlineToolCallsChange(!showInlineToolCalls);- }}- >- Show tool calls- </DropdownMenuCheckboxItem>- <DropdownMenuCheckboxItem- checked={showSystemPrompt}- onClick={(event) => {- event.preventDefault();- onShowSystemPromptChange(!showSystemPrompt);- }}- >- Show system prompt- </DropdownMenuCheckboxItem>- </DropdownMenuSubContent>- </DropdownMenuSub>+ {hasDisplaySettings ? (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>Display</DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ {showCorrections !== undefined && onShowCorrectionsChange ? (+ <DropdownMenuCheckboxItem+ checked={showCorrections}+ onClick={(event) => {+ event.preventDefault();+ onShowCorrectionsChange(!showCorrections);+ }}+ >+ Show corrections+ </DropdownMenuCheckboxItem>+ ) : null}+ {showInlineToolCalls !== undefined &&+ onShowInlineToolCallsChange ? (+ <DropdownMenuCheckboxItem+ checked={showInlineToolCalls}+ onClick={(event) => {+ event.preventDefault();+ onShowInlineToolCallsChange(!showInlineToolCalls);+ }}+ >+ Show tool calls+ </DropdownMenuCheckboxItem>+ ) : null}+ {showSystemPrompt !== undefined && onShowSystemPromptChange ? (+ <DropdownMenuCheckboxItem+ checked={showSystemPrompt}+ onClick={(event) => {+ event.preventDefault();+ onShowSystemPromptChange(!showSystemPrompt);+ }}+ >+ Show system prompt+ </DropdownMenuCheckboxItem>+ ) : null}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ </>+ ) : null}</DropdownMenuContent></DropdownMenu>);diff --git a/web/src/features/sessions/ModernSessionSidebar.tsx b/web/src/features/sessions/ModernSessionSidebar.tsxindex 2cf59ef83e..5140210163 100644--- a/web/src/features/sessions/ModernSessionSidebar.tsx+++ b/web/src/features/sessions/ModernSessionSidebar.tsx@@ -101,7 +101,7 @@ function ObservationListRows({}) {if (state.type === "loading") {return (- <div className="-mx-1 flex flex-col gap-1 px-1 py-2">+ <div className="flex flex-col gap-1 px-1 py-2"><div className="bg-muted h-3 w-3/4 animate-pulse rounded-sm" /><div className="bg-muted h-3 w-1/2 animate-pulse rounded-sm" /></div>@@ -110,7 +110,7 @@ function ObservationListRows({if (state.type === "empty") {return (- <p className="text-muted-foreground -mx-1 px-1 py-2 text-xs">+ <p className="text-muted-foreground px-1 py-2 text-xs">{state.hasFilters? "No matching child observations": "No child observations"}@@ -120,7 +120,7 @@ function ObservationListRows({if (state.type === "trace-io-only") {return (- <div className="border-border bg-border/40 text-foreground -mx-1 mt-2 rounded-sm border px-2 py-1.5 text-xs">+ <div className="border-border bg-border/40 text-foreground rounded-sm border px-2 py-1.5 text-xs">Trace-level I/O only</div>);@@ -128,7 +128,7 @@ function ObservationListRows({if (state.type === "error") {return (- <p className="text-muted-foreground -mx-1 px-1 py-2 text-xs">+ <p className="text-muted-foreground px-1 py-2 text-xs">Failed to load observations</p>);@@ -139,7 +139,7 @@ function ObservationListRows({}return (- <div className="mt-2 flex flex-col">+ <div className="flex flex-col">{state.rows.map((observation) => (<divkey={observation.id}@@ -233,6 +233,13 @@ const TurnCard = React.memo(sidebarTrace;const isTraceLevelIOOnly =hasMatchingTraceLevelIO && observations?.length === 0;+ let observationListClassName = "-mx-1";+ if (observations?.length) {+ observationListClassName = "mt-2";+ }+ if (isTraceLevelIOOnly) {+ observationListClassName = "-mx-1 mt-2";+ }return (<div@@ -283,27 +290,29 @@ const TurnCard = React.memo(</button></div>{!isCollapsed ? (- observations === undefined ? (- <ObservationListRows state={{ type: "loading" }} />- ) : observations === null ? (- <ObservationListRows state={{ type: "error" }} />- ) : observations.length === 0 ? (- <ObservationListRows- state={- isTraceLevelIOOnly- ? { type: "trace-io-only" }- : { type: "empty", hasFilters }- }- />- ) : (- <ObservationListRows- state={{ type: "loaded", rows: observations }}- onSelectObservation={(observationId) =>- onSelect(selectIndex, observationId)- }- onFilterObservationByName={onFilterObservationByName}- />- )+ <div className={observationListClassName}>+ {observations === undefined ? (+ <ObservationListRows state={{ type: "loading" }} />+ ) : observations === null ? (+ <ObservationListRows state={{ type: "error" }} />+ ) : observations.length === 0 ? (+ <ObservationListRows+ state={+ isTraceLevelIOOnly+ ? { type: "trace-io-only" }+ : { type: "empty", hasFilters }+ }+ />+ ) : (+ <ObservationListRows+ state={{ type: "loaded", rows: observations }}+ onSelectObservation={(observationId) =>+ onSelect(selectIndex, observationId)+ }+ onFilterObservationByName={onFilterObservationByName}+ />+ )}+ </div>) : null}</div>);diff --git a/web/src/features/sessions/SessionConversationTimeline/ConnectedSessionConversationTimeline.tsx b/web/src/features/sessions/SessionConversationTimeline/ConnectedSessionConversationTimeline.tsxnew file mode 100644index 0000000000..66db178bfa--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/ConnectedSessionConversationTimeline.tsx@@ -0,0 +1,212 @@+import { useCallback, useMemo } from "react";+import { type FilterState } from "@langfuse/shared";++import {+ SessionConversationTimeline,+ type SessionConversationTimelineController,+ type SessionConversationTimelineScrollTarget,+} from "@/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline";+import { type SessionObservation } from "@/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace";+import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";+import { api, sendAsPostOption, type RouterOutputs } from "@/src/utils/api";++const BATCH_IO_SIZE = 500;++type EventObservation = RouterOutputs["events"]["all"]["observations"][number];+type SessionBatchIOQueryResult = {+ data: RouterOutputs["events"]["sessionBatchIO"] | undefined;+ isError: boolean;+ isPending: boolean;+};++const getObservationKey = (traceId: string, observationId: string) =>+ `${traceId}\0${observationId}`;++export type ConnectedSessionConversationTimelineItem = {+ trace: EventSessionTrace;+ turnNumber: number;+ observations: EventObservation[] | null | undefined;+};++export function ConnectedSessionConversationTimeline({+ traces,+ projectId,+ sessionId,+ filterState,+ filterMeasurementKey,+ viewLabel,+ openPeek,+ controller,+ scrollTarget,+ onFilterObservationByName,+ onLoadMoreObservations,+}: {+ traces: readonly ConnectedSessionConversationTimelineItem[];+ projectId: string;+ sessionId: string;+ filterState: FilterState;+ filterMeasurementKey: string;+ viewLabel: string | null;+ openPeek: (+ id: string,+ row: EventSessionTrace & { observationId?: string },+ ) => void;+ controller: SessionConversationTimelineController;+ scrollTarget: SessionConversationTimelineScrollTarget | null;+ onFilterObservationByName: (+ name: string,+ operator: "any of" | "none of",+ ) => void;+ onLoadMoreObservations?: () => void;+}) {+ const observationRefs = useMemo(+ () =>+ traces.flatMap(+ ({ trace, observations }) =>+ observations?.map((observation) => ({+ observation,+ traceId: trace.id,+ })) ?? [],+ ),+ [traces],+ );+ const batches = useMemo(() => {+ const nextBatches: (typeof observationRefs)[] = [];+ for (+ let index = 0;+ index < observationRefs.length;+ index += BATCH_IO_SIZE+ ) {+ nextBatches.push(observationRefs.slice(index, index + BATCH_IO_SIZE));+ }+ return nextBatches;+ }, [observationRefs]);++ const combineIOQueries = useCallback(+ (results: readonly SessionBatchIOQueryResult[]) =>+ results.map(({ data, isError, isPending }) => ({+ data,+ isError,+ isPending,+ })),+ [],+ );++ const ioQueries = api.useQueries(+ (t) =>+ batches.map((batch) => {+ const timestamps = batch.map(({ observation }) =>+ observation.startTime.getTime(),+ );+ return t.events.sessionBatchIO(+ {+ projectId,+ sessionId,+ observations: batch.map(({ observation, traceId }) => ({+ id: observation.id,+ traceId,+ })),+ minStartTime: new Date(Math.min(...timestamps)),+ maxStartTime: new Date(Math.max(...timestamps)),+ truncated: false,+ ioCharLimit: 10_000,+ },+ {+ ...sendAsPostOption,+ staleTime: 60 * 1000,+ refetchOnWindowFocus: false,+ },+ );+ }),+ { combine: combineIOQueries },+ );++ const hydratedObservationGroups = useMemo(() => {+ const ioByObservationKey = new Map<+ string,+ RouterOutputs["events"]["sessionBatchIO"][number]+ >();+ const queryIndexByObservationKey = new Map<string, number>();+ batches.forEach((batch, queryIndex) => {+ batch.forEach(({ observation, traceId }) => {+ const observationKey = getObservationKey(traceId, observation.id);+ queryIndexByObservationKey.set(observationKey, queryIndex);+ });+ for (const io of ioQueries[queryIndex]?.data ?? []) {+ ioByObservationKey.set(getObservationKey(io.traceId, io.id), io);+ }+ });++ return traces.map(({ trace, observations }) => {+ if (observations === undefined || observations === null)+ return observations;++ const queryIndices = new Set(+ observations.flatMap((observation) => {+ const queryIndex = queryIndexByObservationKey.get(+ getObservationKey(trace.id, observation.id),+ );+ return queryIndex === undefined ? [] : [queryIndex];+ }),+ );+ if (+ Array.from(queryIndices).some(+ (queryIndex) => ioQueries[queryIndex]?.isError,+ )+ ) {+ return null;+ }+ if (+ Array.from(queryIndices).some(+ (queryIndex) => ioQueries[queryIndex]?.isPending,+ )+ ) {+ return undefined;+ }++ return observations.map((observation) => {+ const io = ioByObservationKey.get(+ getObservationKey(trace.id, observation.id),+ );+ return {+ ...observation,+ input: io?.input ?? null,+ output: io?.output ?? null,+ metadata: io?.metadata ?? null,+ } satisfies SessionObservation;+ });+ });+ }, [batches, ioQueries, traces]);+ const timelineTraces = useMemo(+ () =>+ traces.map((timelineTrace, traceIndex) => ({+ ...timelineTrace,+ observations: hydratedObservationGroups[traceIndex],+ })),+ [hydratedObservationGroups, traces],+ );+ const emptyMessage =+ filterState.length === 0+ ? "This trace has no observations."+ : viewLabel+ ? `No observation matches the “${viewLabel}” view in this trace.`+ : "No observation matches the current filters in this trace.";++ return (+ <SessionConversationTimeline+ traces={timelineTraces}+ filterMeasurementKey={filterMeasurementKey}+ emptyMessage={emptyMessage}+ onOpenTrace={(trace) => openPeek(trace.id, trace)}+ onOpenObservation={(trace, observationId) =>+ openPeek(trace.id, { ...trace, observationId })+ }+ controller={controller}+ scrollTarget={scrollTarget}+ observationActions={{+ onFilterByName: onFilterObservationByName,+ }}+ onLoadMoreObservations={onLoadMoreObservations}+ />+ );+}diff --git a/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.stories.tsx b/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.stories.tsxnew file mode 100644index 0000000000..30e57eef8b--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.stories.tsx@@ -0,0 +1,2722 @@+import preview from "@/.storybook/preview";+import { expect, fn, userEvent, waitFor, within } from "storybook/test";+import { type ComponentProps } from "react";++import {+ SessionConversationTimeline,+ useSessionConversationTimelineController,+} from "@/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline";++type TimelineProps = Omit<+ ComponentProps<typeof SessionConversationTimeline>,+ "controller"+>;+type Observation = NonNullable<+ TimelineProps["traces"][number]["observations"]+>[number];++function SessionConversationTimelineStory(props: TimelineProps) {+ const controller = useSessionConversationTimelineController(props.traces);++ return (+ <div className="bg-card dark:bg-background h-screen min-w-[320px]">+ <SessionConversationTimeline {...props} controller={controller} />+ </div>+ );+}++const trace = {+ id: "trace-order-support-8f3a2",+ name: "Resolve delivery address request",+ timestamp: new Date("2026-01-01T12:14:03.000Z"),+ environment: "production",+ userId: "customer-48291",+ observationCount: 5,+ latencyMs: 4260,+ scores: [],+} satisfies TimelineProps["traces"][number]["trace"];++const observations = [+ {+ id: "generation-1",+ name: "Plan support response",+ type: "GENERATION",+ startTime: new Date("2026-01-01T12:14:03.000Z"),+ input: JSON.stringify([+ {+ role: "system",+ content:+ "You are Acme's customer support agent. Verify order details before making changes. Never promise an address update after an order has shipped.",+ },+ {+ role: "user",+ content:+ "Hi, I just noticed order #LF-20481 is going to my old address. Can you send it to 12 Market Street, San Francisco, CA 94105 instead?",+ },+ ]),+ output: JSON.stringify({+ role: "assistant",+ content: "I'll check whether the order can still be updated.",+ tool_calls: [+ {+ id: "call-order-lookup",+ type: "function",+ function: {+ name: "get_order",+ arguments: '{"orderId":"LF-20481"}',+ },+ },+ ],+ }),+ metadata: { model: "gpt-4.1", region: "us-west-2" },+ latency: 0.81,+ inputTruncated: false,+ outputTruncated: false,+ metadataTruncated: false,+ },+ {+ id: "tool-order-lookup",+ name: "Get order",+ type: "TOOL",+ startTime: new Date("2026-01-01T12:14:03.810Z"),+ input: JSON.stringify({ orderId: "LF-20481" }),+ output: JSON.stringify({+ orderId: "LF-20481",+ status: "processing",+ carrier: "UPS",+ estimatedDelivery: "2026-01-04",+ shippingAddress: {+ line1: "800 Pine Street",+ city: "Seattle",+ state: "WA",+ postalCode: "98101",+ },+ }),+ metadata: { cache: "miss", toolCallId: "call-order-lookup" },+ latency: 0.34,+ inputTruncated: false,+ outputTruncated: false,+ metadataTruncated: false,+ },+ {+ id: "generation-2",+ name: "Decide next action",+ type: "GENERATION",+ startTime: new Date("2026-01-01T12:14:04.150Z"),+ input: JSON.stringify({+ role: "tool",+ tool_call_id: "call-order-lookup",+ content: JSON.stringify({+ orderId: "LF-20481",+ status: "processing",+ addressCanBeChanged: true,+ }),+ }),+ output: JSON.stringify({+ role: "assistant",+ content: [+ {+ type: "reasoning",+ text: "The order is still processing and permits address changes, so it is safe to update it.",+ },+ {+ type: "text",+ text: "The order is still processing, so I can update the delivery address.",+ },+ ],+ tool_calls: [+ {+ id: "call-address-update",+ type: "function",+ function: {+ name: "update_shipping_address",+ arguments: JSON.stringify({+ orderId: "LF-20481",+ address: {+ line1: "12 Market Street",+ city: "San Francisco",+ state: "CA",+ postalCode: "94105",+ country: "US",+ },+ }),+ },+ },+ ],+ }),+ metadata: { model: "gpt-4.1", finishReason: "tool_calls" },+ latency: 0.93,+ inputTruncated: false,+ outputTruncated: false,+ metadataTruncated: false,+ },+ {+ id: "tool-address-update",+ name: "Update shipping address",+ type: "TOOL",+ startTime: new Date("2026-01-01T12:14:05.080Z"),+ input: JSON.stringify({+ orderId: "LF-20481",+ address: "12 Market Street, San Francisco, CA 94105",+ }),+ output: JSON.stringify({+ success: true,+ confirmationId: "addr_7b19c2",+ updatedAt: "2026-01-01T12:14:05.410Z",+ }),+ metadata: {+ service: "order-management",+ toolCallId: "call-address-update",+ },+ latency: 0.33,+ inputTruncated: false,+ outputTruncated: false,+ metadataTruncated: false,+ },+ {+ id: "generation-3",+ name: "Compose final response",+ type: "GENERATION",+ startTime: new Date("2026-01-01T12:14:05.410Z"),+ input: JSON.stringify({+ role: "tool",+ tool_call_id: "call-address-update",+ content: JSON.stringify({ success: true, confirmationId: "addr_7b19c2" }),+ }),+ output: JSON.stringify({+ role: "assistant",+ content:+ "Your shipping address has been updated to **12 Market Street, San Francisco, CA 94105**.\n\nOrder **#LF-20481** is still expected by **January 4**. You'll receive tracking details by email once it ships.",+ }),+ metadata: { model: "gpt-4.1", finishReason: "stop" },+ latency: 0.85,+ inputTruncated: false,+ outputTruncated: false,+ metadataTruncated: false,+ },+] as unknown as Observation[];++const agentPrompt =+ "Build a fictional recipe planner dashboard with a compact density option. Inspect the codebase, update the existing component and tests, then verify the change.";+const researchTraceId = "trace-demo-research-turn";+const implementationTraceId = "trace-demo-implementation-turn";+const fixtureStart = new Date("2026-01-02T09:30:00.000Z").getTime();++const telemetryMetadata = {+ agent: "demo-coding-agent",+ "attributes.langfuse.environment": "storybook",+ "attributes.langfuse.internal.is_app_root": false,+ "attributes.langfuse.plugin.version": "0.0.0-demo",+ "attributes.langfuse.user.id": "demo-user",+ "attributes.session.id": "session-demo-recipe-planner",+ "resourceAttributes.service.name": "fictional-editor",+ "resourceAttributes.telemetry.sdk.language": "typescript",+ "resourceAttributes.telemetry.sdk.name": "demo-sdk",+ "resourceAttributes.telemetry.sdk.version": "0.0.0-demo",+ "scope.name": "demo-coding-agent",+ "scope.version": "0.0.0-demo",+};++function codingAgentObservation({+ traceId,+ id,+ parentObservationId,+ type,+ name,+ offsetMs,+ latency,+ input,+ output,+ metadata,+}: {+ traceId: string;+ id: string;+ parentObservationId: string | null;+ type: "AGENT" | "EVENT" | "GENERATION" | "TOOL";+ name: string;+ offsetMs: number;+ latency: number | null;+ input: string | null;+ output: string | null;+ metadata?: Record<string, unknown>;+}) {+ return {+ id,+ traceId,+ parentObservationId,+ name,+ type,+ startTime: new Date(fixtureStart + offsetMs),+ input,+ output,+ metadata: {+ ...telemetryMetadata,+ "attributes.langfuse.observation.type": type.toLowerCase(),+ ...(type === "GENERATION"+ ? {+ finish: "stop",+ messageID: `message-${id}`,+ mode: "build",+ modelID: "demo-model-1",+ providerID: "demo-provider",+ }+ : {}),+ ...(type === "AGENT"+ ? { modelID: "demo-model-1", providerID: "demo-provider" }+ : {}),+ ...(type === "TOOL" ? { callID: `call-${id}`, tool: name } : {}),+ ...metadata,+ },+ latency,+ model: type === "GENERATION" ? "demo-model-1" : null,+ inputTruncated: false,+ outputTruncated: false,+ metadataTruncated: false,+ } as unknown as Observation;+}++const userMessage = JSON.stringify([+ { role: "user", content: [{ type: "text", text: agentPrompt }] },+]);+const assistantMessage = (content: string) =>+ JSON.stringify([{ role: "assistant", content }]);+const toolResult = (toolCallId: string, content: string) => ({+ role: "tool",+ tool_call_id: toolCallId,+ content,+});+const assistantToolCalls = (+ content: string | null,+ calls: Array<{ id: string; name: string; arguments: object }>,+) =>+ JSON.stringify([+ {+ role: "assistant",+ content,+ tool_calls: calls.map((call) => ({+ id: call.id,+ type: "function",+ function: {+ name: call.name,+ arguments: JSON.stringify(call.arguments),+ },+ })),+ },+ ]);++const researchTurnId = "research-agent-turn";+const researchCodingAgentObservations = [+ codingAgentObservation({+ traceId: researchTraceId,+ id: researchTurnId,+ parentObservationId: "session-root-demo",+ type: "AGENT",+ name: "opencode.turn",+ offsetMs: 0,+ latency: 87.347,+ input: userMessage,+ output: assistantMessage(+ "I mapped the dashboard, its state ownership, and the closest interaction tests. The implementation can stay local to the existing component.",+ ),+ }),+ codingAgentObservation({+ traceId: researchTraceId,+ id: "research-user-message",+ parentObservationId: researchTurnId,+ type: "EVENT",+ name: "opencode.message.user",+ offsetMs: 1,+ latency: 0,+ input: userMessage,+ output: null,+ }),+ codingAgentObservation({+ traceId: researchTraceId,+ id: "research-generation-1",+ parentObservationId: researchTurnId,+ type: "GENERATION",+ name: "opencode.generation",+ offsetMs: 6,+ latency: 13.224,+ input: userMessage,+ output: assistantMessage(+ "I will load the frontend and Storybook guidance, index the fictional repository, and locate the dashboard entry points.",+ ),+ }),+ ...[+ [+ "research-tool-1",+ "skill",+ 13_230,+ 0.064,+ { name: "typescript" },+ { loaded: true },+ ],+ [+ "research-tool-2",+ "skill",+ 13_232,+ 0.061,+ { name: "storybook" },+ { loaded: true },+ ],+ [+ "research-tool-3",+ "skill",+ 13_234,+ 0.051,+ { name: "frontend-guidelines" },+ { loaded: true },+ ],+ [+ "research-tool-4",+ "grepika_add_workspace",+ 13_236,+ 4.592,+ { path: "~/demo/recipe-planner" },+ { indexedFiles: 214 },+ ],+ [+ "research-tool-5",+ "tilth_tilth_search",+ 13_238,+ 0.096,+ { query: "RecipeDashboard" },+ { matches: 6 },+ ],+ [+ "research-tool-6",+ "tilth_tilth_files",+ 13_240,+ 0.389,+ { patterns: ["src/features/recipes/**/*"] },+ { files: 12 },+ ],+ ].map(([id, name, offsetMs, latency, input, output]) =>+ codingAgentObservation({+ traceId: researchTraceId,+ id: id as string,+ parentObservationId: "research-generation-1",+ type: "TOOL",+ name: name as string,+ offsetMs: offsetMs as number,+ latency: latency as number,+ input: JSON.stringify(input),+ output: JSON.stringify(output),+ }),+ ),+ codingAgentObservation({+ traceId: researchTraceId,+ id: "research-generation-2",+ parentObservationId: researchTurnId,+ type: "GENERATION",+ name: "opencode.generation",+ offsetMs: 17_828,+ latency: 43.193,+ input: JSON.stringify([+ { role: "assistant", content: "I will inspect the matching files." },+ toolResult("call-research-tool-1", "TypeScript guidance loaded."),+ toolResult("call-research-tool-2", "Storybook guidance loaded."),+ toolResult("call-research-tool-3", "Frontend guidance loaded."),+ toolResult("call-research-tool-4", "The demo workspace is indexed."),+ toolResult("call-research-tool-5", "Found the dashboard and tests."),+ toolResult("call-research-tool-6", "Found twelve recipe feature files."),+ ]),+ output: assistantToolCalls(null, [+ {+ id: "call-read-component",+ name: "tilth_tilth_read",+ arguments: { path: "src/features/recipes/RecipeDashboard.tsx" },+ },+ {+ id: "call-read-test",+ name: "tilth_tilth_read",+ arguments: { path: "src/features/recipes/RecipeDashboard.test.tsx" },+ },+ {+ id: "call-package",+ name: "bash",+ arguments: { command: "pnpm --filter demo-app test --help" },+ },+ {+ id: "call-search-state",+ name: "tilth_tilth_search",+ arguments: { query: "sessionStorage" },+ },+ {+ id: "call-list-stories",+ name: "tilth_tilth_files",+ arguments: { patterns: ["src/**/*.stories.tsx"] },+ },+ ]),+ }),+ ...[+ [+ "research-tool-7",+ "tilth_tilth_read",+ 61_021,+ 0.01,+ { path: "src/features/recipes/RecipeDashboard.tsx" },+ {+ lines: 186,+ summary: "Dashboard component with toolbar and task cards.",+ },+ ],+ [+ "research-tool-8",+ "tilth_tilth_read",+ 61_023,+ 0.003,+ { path: "src/features/recipes/RecipeDashboard.test.tsx" },+ { lines: 122, summary: "Existing rendering and filtering tests." },+ ],+ [+ "research-tool-9",+ "bash",+ 61_025,+ 33.987,+ { command: "pnpm --filter demo-app test --help" },+ "Usage: test [filters]\nAll command examples are fictional.",+ ],+ [+ "research-tool-10",+ "tilth_tilth_search",+ 61_027,+ 6.862,+ { query: "sessionStorage" },+ { matches: 4 },+ ],+ [+ "research-tool-11",+ "tilth_tilth_files",+ 61_029,+ 7.109,+ { patterns: ["src/**/*.stories.tsx"] },+ { files: 19 },+ ],+ ].map(([id, name, offsetMs, latency, input, output]) =>+ codingAgentObservation({+ traceId: researchTraceId,+ id: id as string,+ parentObservationId: "research-generation-2",+ type: "TOOL",+ name: name as string,+ offsetMs: offsetMs as number,+ latency: latency as number,+ input: JSON.stringify(input),+ output: typeof output === "string" ? output : JSON.stringify(output),+ }),+ ),+ codingAgentObservation({+ traceId: researchTraceId,+ id: "research-generation-3",+ parentObservationId: researchTurnId,+ type: "GENERATION",+ name: "opencode.generation",+ offsetMs: 61_031,+ latency: 9.66,+ input:+ "The dashboard uses local state and has an established toolbar checkbox pattern.",+ output: assistantToolCalls(null, [+ { id: "call-index", name: "grepika_index", arguments: { force: false } },+ {+ id: "call-read-storage",+ name: "tilth_tilth_read",+ arguments: { path: "src/hooks/useSessionPreference.ts" },+ },+ {+ id: "call-find-tests",+ name: "tilth_tilth_files",+ arguments: { patterns: ["src/features/recipes/*.test.tsx"] },+ },+ {+ id: "call-find-config",+ name: "tilth_tilth_files",+ arguments: { patterns: ["**/vitest.config.*"] },+ },+ {+ id: "call-search-checkbox",+ name: "tilth_tilth_search",+ arguments: { query: "Hide archived" },+ },+ ]),+ }),+ ...[+ [+ "research-tool-12",+ "grepika_index",+ 70_691,+ 0.227,+ { force: false },+ { indexedFiles: 214 },+ ],+ [+ "research-tool-13",+ "tilth_tilth_read",+ 70_693,+ 0.005,+ { path: "src/hooks/useSessionPreference.ts" },+ { lines: 48 },+ ],+ [+ "research-tool-14",+ "tilth_tilth_files",+ 70_695,+ 0.002,+ { patterns: ["src/features/recipes/*.test.tsx"] },+ { files: 2 },+ ],+ [+ "research-tool-15",+ "tilth_tilth_files",+ 70_697,+ 0.006,+ { patterns: ["**/vitest.config.*"] },+ { files: 1 },+ ],+ [+ "research-tool-16",+ "tilth_tilth_search",+ 70_699,+ 0.136,+ { query: "Hide archived" },+ { matches: 1 },+ ],+ ].map(([id, name, offsetMs, latency, input, output]) =>+ codingAgentObservation({+ traceId: researchTraceId,+ id: id as string,+ parentObservationId: "research-generation-3",+ type: "TOOL",+ name: name as string,+ offsetMs: offsetMs as number,+ latency: latency as number,+ input: JSON.stringify(input),+ output: JSON.stringify(output),+ }),+ ),+ codingAgentObservation({+ traceId: researchTraceId,+ id: "research-generation-4",+ parentObservationId: researchTurnId,+ type: "GENERATION",+ name: "opencode.generation",+ offsetMs: 70_701,+ latency: 13.95,+ input: JSON.stringify([+ { role: "assistant", content: null },+ toolResult("call-index", "Index refreshed."),+ toolResult(+ "call-read-storage",+ "A session preference hook already exists.",+ ),+ toolResult("call-find-tests", "Two nearby test files found."),+ toolResult("call-find-config", "One Vitest config found."),+ toolResult(+ "call-search-checkbox",+ "Found an analogous toolbar checkbox.",+ ),+ ]),+ output: assistantToolCalls(+ "I have the implementation pattern and will confirm its callers before editing.",+ [+ {+ id: "call-final-search",+ name: "tilth_tilth_search",+ arguments: { query: "useSessionPreference" },+ },+ {+ id: "call-final-files",+ name: "tilth_tilth_files",+ arguments: { patterns: ["src/features/recipes/*"] },+ },+ {+ id: "call-related",+ name: "grepika_search",+ arguments: { query: "recipe filtering toolbar" },+ },+ ],+ ),+ }),+ ...[+ [+ "research-tool-17",+ "tilth_tilth_search",+ 84_651,+ 0.136,+ { query: "useSessionPreference" },+ { matches: 7 },+ ],+ [+ "research-tool-18",+ "tilth_tilth_files",+ 84_653,+ 0.344,+ { patterns: ["src/features/recipes/*"] },+ { files: 9 },+ ],+ [+ "research-tool-19",+ "grepika_search",+ 84_655,+ 0.006,+ { query: "recipe filtering toolbar" },+ { matches: 3 },+ ],+ ].map(([id, name, offsetMs, latency, input, output]) =>+ codingAgentObservation({+ traceId: researchTraceId,+ id: id as string,+ parentObservationId: "research-generation-4",+ type: "TOOL",+ name: name as string,+ offsetMs: offsetMs as number,+ latency: latency as number,+ input: JSON.stringify(input),+ output: JSON.stringify(output),+ }),+ ),+ codingAgentObservation({+ traceId: researchTraceId,+ id: "research-generation-5",+ parentObservationId: researchTurnId,+ type: "GENERATION",+ name: "opencode.generation",+ offsetMs: 84_657,+ latency: 7.294,+ input: JSON.stringify([+ {+ role: "assistant",+ content: "I will confirm the final integration points.",+ },+ toolResult(+ "call-final-search",+ "The hook is already used by seven components.",+ ),+ toolResult("call-final-files", "The dashboard and test are colocated."),+ toolResult("call-related", "The toolbar owns all recipe filters."),+ ]),+ output: assistantMessage(+ "Research complete. I will add the compact-density checkbox to the existing toolbar, persist it with the session preference hook, and extend the colocated interaction test.",+ ),+ }),+];++const implementationTurnId = "implementation-agent-turn";+const implementationCodingAgentObservations = [+ codingAgentObservation({+ traceId: implementationTraceId,+ id: implementationTurnId,+ parentObservationId: "session-root-demo",+ type: "AGENT",+ name: "opencode.turn",+ offsetMs: 120_000,+ latency: 167.662,+ input: userMessage,+ output: assistantMessage(+ "Implemented the compact recipe cards, added coverage, and verified tests and lint.",+ ),+ }),+ codingAgentObservation({+ traceId: implementationTraceId,+ id: "implementation-user-message",+ parentObservationId: implementationTurnId,+ type: "EVENT",+ name: "opencode.message.user",+ offsetMs: 120_001,+ latency: 0,+ input: userMessage,+ output: null,+ }),+ codingAgentObservation({+ traceId: implementationTraceId,+ id: "implementation-generation-1",+ parentObservationId: implementationTurnId,+ type: "GENERATION",+ name: "opencode.generation",+ offsetMs: 120_006,+ latency: 20.463,+ input: userMessage,+ output: assistantToolCalls(+ "I will make the smallest component and test change.",+ [+ {+ id: "call-patch-1",+ name: "apply_patch",+ arguments: {+ file: "src/features/recipes/RecipeDashboard.tsx",+ change: "Add compact density preference.",+ },+ },+ ],+ ),+ }),+ codingAgentObservation({+ traceId: implementationTraceId,+ id: "implementation-tool-1",+ parentObservationId: "implementation-generation-1",+ type: "TOOL",+ name: "apply_patch",+ offsetMs: 140_469,+ latency: 0.023,+ input: JSON.stringify({+ patch: "Synthetic dashboard patch with no source code.",+ }),+ output: JSON.stringify({ success: true, filesChanged: 1 }),+ }),+ codingAgentObservation({+ traceId: implementationTraceId,+ id: "implementation-generation-2",+ parentObservationId: implementationTurnId,+ type: "GENERATION",+ name: "opencode.generation",+ offsetMs: 140_492,+ latency: 5.241,+ input: JSON.stringify([+ { role: "assistant", content: "The component change is applied." },+ toolResult("call-patch-1", "Updated one fictional file."),+ ]),+ output: assistantToolCalls(null, [+ {+ id: "call-diff",+ name: "tilth_tilth_diff",+ arguments: { scope: "src/features/recipes/RecipeDashboard.tsx" },+ },+ {+ id: "call-search-tests",+ name: "tilth_tilth_search",+ arguments: { query: "RecipeDashboard tests" },+ },+ {+ id: "call-read-tests",+ name: "tilth_tilth_read",+ arguments: { path: "src/features/recipes/RecipeDashboard.test.tsx" },+ },+ ]),+ }),+ ...[+ [+ "implementation-tool-2",+ "tilth_tilth_diff",+ 145_733,+ 0.083,+ { scope: "src/features/recipes/RecipeDashboard.tsx" },+ { additions: 18, deletions: 2 },+ ],+ [+ "implementation-tool-3",+ "tilth_tilth_search",+ 145_735,+ 0.197,+ { query: "RecipeDashboard tests" },+ { matches: 4 },+ ],+ [+ "implementation-tool-4",+ "tilth_tilth_read",+ 145_737,+ 0.196,+ { path: "src/features/recipes/RecipeDashboard.test.tsx" },+ { lines: 122 },+ ],+ ].map(([id, name, offsetMs, latency, input, output]) =>+ codingAgentObservation({+ traceId: implementationTraceId,+ id: id as string,+ parentObservationId: "implementation-generation-2",+ type: "TOOL",+ name: name as string,+ offsetMs: offsetMs as number,+ latency: latency as number,+ input: JSON.stringify(input),+ output: JSON.stringify(output),+ }),+ ),+ codingAgentObservation({+ traceId: implementationTraceId,+ id: "implementation-generation-3",+ parentObservationId: implementationTurnId,+ type: "GENERATION",+ name: "opencode.generation",+ offsetMs: 145_739,+ latency: 10.318,+ input: JSON.stringify([+ { role: "assistant", content: null },+ toolResult("call-diff", "The component diff is scoped."),+ toolResult("call-search-tests", "Found the colocated tests."),+ toolResult("call-read-tests", "The test uses user-visible queries."),+ ]),+ output: assistantToolCalls(null, [+ {+ id: "call-patch-tests",+ name: "apply_patch",+ arguments: {+ file: "src/features/recipes/RecipeDashboard.test.tsx",+ change: "Cover compact density persistence.",+ },+ },+ ]),+ }),+ codingAgentObservation({+ traceId: implementationTraceId,+ id: "implementation-tool-5",+ parentObservationId: "implementation-generation-3",+ type: "TOOL",+ name: "apply_patch",+ offsetMs: 156_057,+ latency: 0.004,+ input: JSON.stringify({ patch: "Synthetic interaction test patch." }),+ output: JSON.stringify({ success: true, filesChanged: 1 }),+ }),+ codingAgentObservation({+ traceId: implementationTraceId,+ id: "implementation-generation-4",+ parentObservationId: implementationTurnId,+ type: "GENERATION",+ name: "opencode.generation",+ offsetMs: 156_061,+ latency: 61.287,+ input: JSON.stringify([+ { role: "assistant", content: null },+ toolResult("call-patch-tests", "Updated one fictional test file."),+ ]),+ output: assistantToolCalls(+ "The implementation and test are ready. I will run both targeted checks in parallel.",+ [+ {+ id: "call-test",+ name: "bash",+ arguments: {+ command: "pnpm --filter demo-app test RecipeDashboard.test.tsx",+ },+ },+ {+ id: "call-lint",+ name: "bash",+ arguments: {+ command: "pnpm --filter demo-app lint RecipeDashboard.tsx",+ },+ },+ ],+ ),+ }),+ codingAgentObservation({+ traceId: implementationTraceId,+ id: "implementation-tool-6",+ parentObservationId: "implementation-generation-4",+ type: "TOOL",+ name: "bash",+ offsetMs: 217_348,+ latency: 14.852,+ input: JSON.stringify({+ command: "pnpm --filter demo-app test RecipeDashboard.test.tsx",+ }),+ output: JSON.stringify({ testFiles: 1, testsPassed: 6, testsFailed: 0 }),+ }),+ codingAgentObservation({+ traceId: implementationTraceId,+ id: "implementation-tool-7",+ parentObservationId: "implementation-generation-4",+ type: "TOOL",+ name: "bash",+ offsetMs: 217_350,+ latency: 51.812,+ input: JSON.stringify({+ command: "pnpm --filter demo-app lint RecipeDashboard.tsx",+ }),+ output: "Lint completed successfully with no warnings.",+ }),+ codingAgentObservation({+ traceId: implementationTraceId,+ id: "implementation-generation-5",+ parentObservationId: implementationTurnId,+ type: "GENERATION",+ name: "opencode.generation",+ offsetMs: 217_352,+ latency: 23.685,+ input:+ "Targeted tests and lint passed. Inspect the final diff and repository status.",+ output: assistantToolCalls(null, [+ {+ id: "call-status",+ name: "bash",+ arguments: { command: "git status --short" },+ },+ {+ id: "call-format",+ name: "bash",+ arguments: {+ command:+ "pnpm prettier --check src/features/recipes/RecipeDashboard.tsx",+ },+ },+ {+ id: "call-diff-stat",+ name: "bash",+ arguments: { command: "git diff --stat" },+ },+ ]),+ }),+ ...[+ [+ "implementation-tool-8",+ 241_037,+ 0.139,+ { command: "git status --short" },+ { modified: ["RecipeDashboard.tsx", "RecipeDashboard.test.tsx"] },+ ],+ [+ "implementation-tool-9",+ 241_039,+ 14.279,+ {+ command:+ "pnpm prettier --check src/features/recipes/RecipeDashboard.tsx",+ },+ { checked: 1, formatted: true },+ ],+ [+ "implementation-tool-10",+ 241_041,+ 0.599,+ { command: "git diff --stat" },+ { filesChanged: 2, insertions: 37, deletions: 4 },+ ],+ ].map(([id, offsetMs, latency, input, output]) =>+ codingAgentObservation({+ traceId: implementationTraceId,+ id: id as string,+ parentObservationId: "implementation-generation-5",+ type: "TOOL",+ name: "bash",+ offsetMs: offsetMs as number,+ latency: latency as number,+ input: JSON.stringify(input),+ output: JSON.stringify(output),+ }),+ ),+ codingAgentObservation({+ traceId: implementationTraceId,+ id: "implementation-generation-6",+ parentObservationId: implementationTurnId,+ type: "GENERATION",+ name: "opencode.generation",+ offsetMs: 241_043,+ latency: 35.864,+ input: JSON.stringify([+ { role: "assistant", content: null },+ toolResult("call-status", "Only the two intended files changed."),+ toolResult("call-format", "Formatting passed."),+ toolResult("call-diff-stat", "The diff is compact."),+ ]),+ output: assistantToolCalls(+ "I will run the final focused Storybook check.",+ [+ {+ id: "call-storybook",+ name: "bash",+ arguments: {+ command:+ "pnpm --filter demo-app test-storybook RecipeDashboard.stories.tsx",+ },+ },+ ],+ ),+ }),+ codingAgentObservation({+ traceId: implementationTraceId,+ id: "implementation-tool-11",+ parentObservationId: "implementation-generation-6",+ type: "TOOL",+ name: "bash",+ offsetMs: 276_907,+ latency: 28.994,+ input: JSON.stringify({+ command:+ "pnpm --filter demo-app test-storybook RecipeDashboard.stories.tsx",+ }),+ output: JSON.stringify({ storyFiles: 1, testsPassed: 8, testsFailed: 0 }),+ }),+ codingAgentObservation({+ traceId: implementationTraceId,+ id: "implementation-generation-7",+ parentObservationId: implementationTurnId,+ type: "GENERATION",+ name: "opencode.generation",+ offsetMs: 276_909,+ latency: 10.775,+ input: JSON.stringify([+ {+ role: "assistant",+ content: "I will run the final focused Storybook check.",+ },+ toolResult("call-storybook", "Eight Storybook tests passed."),+ ]),+ output: assistantMessage(+ "Implemented a compact density option for the fictional recipe dashboard, persisted it for the browser tab, and added interaction coverage. Targeted tests, Storybook, formatting, and lint all pass.",+ ),+ }),+];++const inAppAgentTraceId = "trace-demo-error-analysis";+const inAppAgentTurnId = "error-analysis-agent-turn";+const inAppAgentPrompt =+ "Analyze failed traces for a fictional travel assistant. Sample representative failures, group recurring causes into a taxonomy, recommend what to fix first, and suggest how to track the top issue.";+const inAppAgentMetadata = {+ cloud_region: "DEMO",+ conversation_id: "conversation-demo-error-analysis",+ execution_runtime: "worker",+ langfuse_ai_feature: "in-app-agent",+ langfuse_project_id: "project-demo-travel-assistant",+ langfuse_user_email: "redacted",+ langfuse_user_id: "user-demo-analyst",+ langfuse_user_is_admin: false,+ prompt_name: "demo-in-app-agent-system-prompt",+ prompt_version: 1,+ run_id: "run-demo-error-analysis",+};++const inAppAgentActions: Array<{+ offsetMs: number;+ latency: number;+ summary: string;+ tools: Array<{+ name: string;+ latency: number;+ input: Record<string, unknown>;+ output: unknown;+ outputAsText?: boolean;+ }>;+}> = [+ {+ offsetMs: 300_000,+ latency: 6.37,+ summary: "I will load the error-analysis workflow before inspecting data.",+ tools: [+ {+ name: "skill",+ latency: 0.001,+ input: { name: "error-analysis" },+ output:+ "Use representative samples, separate symptoms from root causes, and quantify each recurring category.",+ outputAsText: true,+ },+ ],+ },+ {+ offsetMs: 307_000,+ latency: 5.345,+ summary:+ "I will confirm the analysis guidance and retrieve a bounded sample of failed observations.",+ tools: [+ {+ name: "langfuseDocs_getLangfuseDocsPage",+ latency: 0.29,+ input: { pathOrUrl: "/docs/observability/errors", silent: false },+ output: {+ type: "tool-result",+ toolName: "langfuseDocs_getLangfuseDocsPage",+ content: "Synthetic guidance for investigating failed traces.",+ },+ },+ {+ name: "langfuse_listObservations",+ latency: 0.233,+ input: {+ fields: ["id", "name", "level", "statusMessage"],+ fromStartTime: "2026-01-01T00:00:00Z",+ toStartTime: "2026-01-08T00:00:00Z",+ level: "ERROR",+ limit: 25,+ silent: false,+ },+ output: {+ type: "tool-result",+ toolName: "langfuse_listObservations",+ output: { count: 25, cursor: "cursor-demo-page-2" },+ },+ },+ ],+ },+ {+ offsetMs: 313_000,+ latency: 2.759,+ summary:+ "I will summarize the first sample locally without exposing payloads.",+ tools: [+ {+ name: "bash",+ latency: 1.541,+ input: { command: "jq 'group_by(.name)' synthetic-errors.json" },+ output: {+ startedAt: "2026-01-08T09:00:13Z",+ completedAt: "2026-01-08T09:00:14Z",+ exitCode: 0,+ stdout: "booking-assistant: 11\nroute-planner: 8\nfare-checker: 6",+ stderr: "",+ },+ },+ ],+ },+ {+ offsetMs: 317_000,+ latency: 5.457,+ summary: "I will inspect status-message frequencies in the sample.",+ tools: [+ {+ name: "bash",+ latency: 0.195,+ input: {+ command: "jq 'group_by(.statusMessage)' synthetic-errors.json",+ },+ output: {+ startedAt: "2026-01-08T09:00:17Z",+ completedAt: "2026-01-08T09:00:17Z",+ exitCode: 0,+ stdout: "timeout: 9\ninvalid itinerary: 7\nmissing fare: 5\nother: 4",+ stderr: "",+ },+ },+ ],+ },+ {+ offsetMs: 323_000,+ latency: 5.896,+ summary: "I will fetch examples from the largest failure category.",+ tools: [+ {+ name: "langfuse_listObservations",+ latency: 0.219,+ input: {+ fields: ["id", "traceId", "input", "output", "statusMessage"],+ filter: [+ { column: "statusMessage", operator: "contains", value: "timeout" },+ ],+ fromStartTime: "2026-01-01T00:00:00Z",+ toStartTime: "2026-01-08T00:00:00Z",+ level: "ERROR",+ limit: 10,+ silent: false,+ },+ output: {+ type: "tool-result",+ toolName: "langfuse_listObservations",+ output: { count: 10, sample: "synthetic timeout observations" },+ },+ },+ ],+ },+ {+ offsetMs: 329_000,+ latency: 2.974,+ summary: "I will compare error signatures across those examples.",+ tools: [+ {+ name: "bash",+ latency: 0.207,+ input: {+ command: "jq '.[] | [.name, .statusMessage]' synthetic-timeouts.json",+ },+ output: {+ startedAt: "2026-01-08T09:00:29Z",+ completedAt: "2026-01-08T09:00:29Z",+ exitCode: 0,+ stdout:+ "upstream timeout: 6\nretry exhausted: 3\nclient cancelled: 1",+ stderr: "",+ },+ },+ ],+ },+ {+ offsetMs: 332_000,+ latency: 8.043,+ summary:+ "I will discover the available model values before filtering further.",+ tools: [+ {+ name: "langfuse_getObservationFilterValues",+ latency: 0.284,+ input: {+ column: "model",+ fromStartTime: "2026-01-01T00:00:00Z",+ toStartTime: "2026-01-08T00:00:00Z",+ limit: 20,+ silent: false,+ },+ output: {+ type: "tool-result",+ toolName: "langfuse_getObservationFilterValues",+ output: ["demo-chat-large", "demo-chat-fast", "demo-embed-small"],+ },+ },+ ],+ },+ {+ offsetMs: 341_000,+ latency: 3.716,+ summary: "I will quantify failures by model and operation.",+ tools: [+ {+ name: "bash",+ latency: 0.2,+ input: {+ command: "jq 'group_by([.model,.name])' synthetic-errors.json",+ },+ output: {+ startedAt: "2026-01-08T09:00:41Z",+ completedAt: "2026-01-08T09:00:41Z",+ exitCode: 0,+ stdout:+ "demo-chat-fast / route-planner: 8\ndemo-chat-large / booking-assistant: 11",+ stderr: "",+ },+ },+ ],+ },+ {+ offsetMs: 344_000,+ latency: 15.801,+ summary: "I will inspect invalid-itinerary failures as the second cluster.",+ tools: [+ {+ name: "langfuse_listObservations",+ latency: 0.202,+ input: {+ fields: ["id", "traceId", "input", "output", "metadata"],+ filter: [+ {+ column: "statusMessage",+ operator: "contains",+ value: "invalid itinerary",+ },+ ],+ fromStartTime: "2026-01-01T00:00:00Z",+ toStartTime: "2026-01-08T00:00:00Z",+ level: "ERROR",+ limit: 10,+ silent: false,+ },+ output: {+ type: "tool-result",+ toolName: "langfuse_listObservations",+ output: {+ count: 7,+ sample: "synthetic itinerary validation failures",+ },+ },+ },+ ],+ },+ {+ offsetMs: 361_000,+ latency: 5.819,+ summary: "I will extract the common validation causes.",+ tools: [+ {+ name: "bash",+ latency: 0.183,+ input: {+ command:+ "jq '.[] | .metadata.validationReason' synthetic-itineraries.json",+ },+ output: {+ startedAt: "2026-01-08T09:01:01Z",+ completedAt: "2026-01-08T09:01:01Z",+ exitCode: 0,+ stdout:+ "impossible connection: 4\nmissing airport: 2\ndate ordering: 1",+ stderr: "",+ },+ },+ ],+ },+ {+ offsetMs: 367_000,+ latency: 14.948,+ summary: "I will inspect missing-fare failures as the third cluster.",+ tools: [+ {+ name: "langfuse_listObservations",+ latency: 0.675,+ input: {+ fields: ["id", "traceId", "input", "output", "metadata"],+ filter: [+ {+ column: "statusMessage",+ operator: "contains",+ value: "missing fare",+ },+ ],+ fromStartTime: "2026-01-01T00:00:00Z",+ toStartTime: "2026-01-08T00:00:00Z",+ limit: 10,+ silent: false,+ },+ output: {+ type: "tool-result",+ toolName: "langfuse_listObservations",+ output: { count: 5, sample: "synthetic pricing lookup failures" },+ },+ },+ ],+ },+ {+ offsetMs: 382_000,+ latency: 7.054,+ summary: "I will compare provider and cache behavior for missing fares.",+ tools: [+ {+ name: "bash",+ latency: 0.199,+ input: {+ command:+ "jq 'group_by([.metadata.provider,.metadata.cache])' synthetic-fares.json",+ },+ output: {+ startedAt: "2026-01-08T09:01:22Z",+ completedAt: "2026-01-08T09:01:22Z",+ exitCode: 0,+ stdout: "provider unavailable / cache miss: 4\nmalformed response: 1",+ stderr: "",+ },+ },+ ],+ },+ {+ offsetMs: 390_000,+ latency: 9.036,+ summary: "I will calculate an initial taxonomy and prevalence table.",+ tools: [+ {+ name: "bash",+ latency: 0.199,+ input: { command: "node scripts/summarize-synthetic-errors.mjs" },+ output: {+ startedAt: "2026-01-08T09:01:30Z",+ completedAt: "2026-01-08T09:01:30Z",+ exitCode: 0,+ stdout:+ "upstream reliability 36%\nvalidation 28%\ndata availability 20%\nother 16%",+ stderr: "",+ },+ },+ ],+ },+ {+ offsetMs: 399_000,+ latency: 12.964,+ summary:+ "I will page through additional failures to check whether the taxonomy holds.",+ tools: [+ {+ name: "langfuse_listObservations",+ latency: 0.192,+ input: {+ cursor: "cursor-demo-page-2",+ environment: "production-demo",+ fields: ["id", "name", "level", "statusMessage"],+ fromStartTime: "2026-01-01T00:00:00Z",+ toStartTime: "2026-01-08T00:00:00Z",+ level: "ERROR",+ limit: 25,+ silent: false,+ },+ output: {+ type: "tool-result",+ toolName: "langfuse_listObservations",+ output: { count: 25, cursor: null },+ },+ },+ ],+ },+ {+ offsetMs: 412_000,+ latency: 5.249,+ summary: "I will merge both pages and recompute category shares.",+ tools: [+ {+ name: "bash",+ latency: 0.197,+ input: { command: "node scripts/merge-synthetic-samples.mjs" },+ output: {+ startedAt: "2026-01-08T09:01:52Z",+ completedAt: "2026-01-08T09:01:52Z",+ exitCode: 0,+ stdout: "50 observations classified; 46 matched the draft taxonomy",+ stderr: "",+ },+ },+ ],+ },+ {+ offsetMs: 417_000,+ latency: 9.648,+ summary:+ "I will identify representative trace IDs for each major category.",+ tools: [+ {+ name: "bash",+ latency: 0.43,+ input: { command: "node scripts/select-synthetic-representatives.mjs" },+ output: {+ startedAt: "2026-01-08T09:01:57Z",+ completedAt: "2026-01-08T09:01:57Z",+ exitCode: 0,+ stdout:+ "trace-demo-timeout\ntrace-demo-validation\ntrace-demo-fare\ntrace-demo-other",+ stderr: "",+ },+ },+ ],+ },+ {+ offsetMs: 428_000,+ latency: 18.765,+ summary: "I will inspect four representative traces in parallel.",+ tools: [+ {+ name: "langfuse_listObservations",+ latency: 1.207,+ input: {+ fields: ["*"],+ limit: 100,+ silent: false,+ traceId: "trace-demo-timeout",+ },+ output: {+ type: "tool-result",+ toolName: "langfuse_listObservations",+ output: { observations: 14, category: "upstream timeout" },+ },+ },+ {+ name: "langfuse_listObservations",+ latency: 0.138,+ input: {+ fields: ["*"],+ limit: 100,+ silent: false,+ traceId: "trace-demo-validation",+ },+ output: {+ type: "tool-result",+ toolName: "langfuse_listObservations",+ output: { observations: 9, category: "itinerary validation" },+ },+ },+ {+ name: "langfuse_listObservations",+ latency: 0.139,+ input: {+ fields: ["*"],+ limit: 100,+ silent: false,+ traceId: "trace-demo-fare",+ },+ output: {+ type: "tool-result",+ toolName: "langfuse_listObservations",+ output: { observations: 11, category: "fare unavailable" },+ },+ },+ {+ name: "langfuse_listObservations",+ latency: 0.12,+ input: {+ fields: ["*"],+ limit: 100,+ silent: false,+ traceId: "trace-demo-other",+ },+ output: {+ type: "tool-result",+ toolName: "langfuse_listObservations",+ output: { observations: 7, category: "uncategorized" },+ },+ },+ ],+ },+ {+ offsetMs: 448_000,+ latency: 7.902,+ summary: "I will compare the causal chains in those representative traces.",+ tools: [+ {+ name: "bash",+ latency: 1.924,+ input: { command: "node scripts/compare-synthetic-traces.mjs" },+ output: {+ startedAt: "2026-01-08T09:02:28Z",+ completedAt: "2026-01-08T09:02:30Z",+ exitCode: 0,+ stdout:+ "timeouts originate at the inventory provider; validation failures originate before model invocation; missing fares follow cache misses",+ stderr: "",+ },+ },+ ],+ },+ {+ offsetMs: 459_000,+ latency: 21.138,+ summary:+ "I will calculate impact and confidence for the recommended priority order.",+ tools: [+ {+ name: "bash",+ latency: 1.783,+ input: { command: "node scripts/rank-synthetic-fixes.mjs" },+ output: {+ startedAt: "2026-01-08T09:02:39Z",+ completedAt: "2026-01-08T09:02:41Z",+ exitCode: 0,+ stdout:+ "1 provider timeout handling\n2 itinerary pre-validation\n3 fare cache fallback\n4 improve unknown-error metadata",+ stderr: "",+ },+ },+ ],+ },+ {+ offsetMs: 482_000,+ latency: 22.149,+ summary:+ "The dominant failure mode is upstream inventory timeout, followed by invalid itinerary construction and missing fare data. Fix timeout retries and circuit breaking first, then add deterministic itinerary validation before model invocation. Track the top category with a categorical evaluator or an annotation queue.",+ tools: [],+ },+];++const inAppAgentSystemMessages = [+ {+ role: "system",+ content:+ "You are a demo observability analyst. Use only fictional project data.",+ },+ {+ role: "system",+ content:+ "Inspect representative failures before proposing a taxonomy or remediation.",+ },+ {+ role: "system",+ content: "Never expose identifiers or payloads from real users.",+ providerOptions: { demo: { cacheControl: "temporary" } },+ },+];++const inAppAgentObservations = [+ ...inAppAgentActions.flatMap((action, actionIndex) => {+ const generationId = `error-analysis-generation-${actionIndex + 1}`;+ const previousMessages = inAppAgentActions+ .slice(0, actionIndex)+ .flatMap((previousAction, previousActionIndex) => [+ {+ role: "assistant",+ content: null,+ tool_calls: previousAction.tools.map((tool, toolIndex) => ({+ toolCallId: `error-analysis-call-${previousActionIndex + 1}-${toolIndex + 1}`,+ toolName: tool.name,+ args: tool.input,+ })),+ },+ {+ role: "tool",+ content: JSON.stringify(+ previousAction.tools.map((tool, toolIndex) => ({+ toolCallId: `error-analysis-call-${previousActionIndex + 1}-${toolIndex + 1}`,+ toolName: tool.name,+ output: tool.output,+ })),+ ),+ },+ ]);+ const runtimeContextOffsetMs =+ actionIndex < 6+ ? inAppAgentActions[0]!.offsetMs+ : actionIndex < 13+ ? inAppAgentActions[6]!.offsetMs+ : actionIndex < 18+ ? inAppAgentActions[13]!.offsetMs+ : inAppAgentActions[18]!.offsetMs;+ const generationInput = JSON.stringify({+ messages: [+ ...inAppAgentSystemMessages,+ {+ role: "user",+ content: [+ {+ type: "text",+ text: inAppAgentPrompt,+ providerOptions: { demo: { cacheControl: "temporary" } },+ },+ ],+ providerOptions: { demo: { cacheControl: "temporary" } },+ },+ ...previousMessages,+ ...(actionIndex === inAppAgentActions.length - 1+ ? [+ {+ role: "user",+ content: [+ {+ type: "text",+ text: "Summarize the taxonomy, recommend the first fix, and suggest a durable way to track it.",+ },+ ],+ providerOptions: {+ demo: { cacheControl: "temporary" },+ },+ },+ ]+ : []),+ {+ role: "user",+ content: [+ {+ type: "text",+ text: `<screen_context>+Current page: /project/project-demo-travel-assistant/traces+Active filter: level is ERROR+ Saved view: booking-assistant, route-planner, fare-checker+ </screen_context>+ <current_time>${new Date(fixtureStart + runtimeContextOffsetMs).toISOString()}</current_time>`,+ },+ ],+ },+ ],+ providerOptions: { demo: { region: "local" } },+ toolChoice: { type: "auto" },+ tools: [+ { name: "langfuse_listObservations" },+ { name: "langfuse_getObservationFilterValues" },+ { name: "langfuseDocs_getLangfuseDocsPage" },+ { name: "bash" },+ ],+ });+ const generationOutput = JSON.stringify(+ action.tools.length > 0+ ? {+ tool_calls: action.tools.map((tool, toolIndex) => ({+ args: tool.input,+ toolCallId: `error-analysis-call-${actionIndex + 1}-${toolIndex + 1}`,+ toolName: tool.name,+ })),+ }+ : { text: action.summary },+ );++ return [+ codingAgentObservation({+ traceId: inAppAgentTraceId,+ id: generationId,+ parentObservationId: inAppAgentTurnId,+ type: "GENERATION",+ name: "invoke-model",+ offsetMs: action.offsetMs,+ latency: action.latency,+ input: generationInput,+ output: generationOutput,+ metadata: { ...inAppAgentMetadata, finish_reason: "stop" },+ }),+ ...action.tools.map((tool, toolIndex) => {+ const toolCallId = `error-analysis-call-${actionIndex + 1}-${toolIndex + 1}`;+ return codingAgentObservation({+ traceId: inAppAgentTraceId,+ id: `error-analysis-tool-${actionIndex + 1}-${toolIndex + 1}`,+ parentObservationId: inAppAgentTurnId,+ type: "TOOL",+ name: tool.name,+ offsetMs: action.offsetMs + Math.round(action.latency * 1_000),+ latency: tool.latency,+ input: JSON.stringify(tool.input),+ output: tool.outputAsText+ ? String(tool.output)+ : JSON.stringify({+ type: "tool-result",+ toolCallId,+ toolName: tool.name,+ output: tool.output,+ }),+ metadata: {+ ...inAppAgentMetadata,+ parentMessageId: `message-demo-${actionIndex + 1}`,+ toolCallApprovalSource: "automatic",+ toolCallId,+ },+ });+ }),+ ];+ }),+];++const inAppAgentTrace = {+ id: inAppAgentTraceId,+ name: "Analyze fictional travel-assistant failures",+ timestamp: new Date(fixtureStart + 300_000),+ environment: "storybook",+ userId: "user-demo-analyst",+ observationCount: inAppAgentObservations.length,+ latencyMs: 205_058,+ scores: [],+} satisfies TimelineProps["traces"][number]["trace"];++const researchCodingAgentTrace = {+ id: researchTraceId,+ name: "Research recipe dashboard density setting",+ timestamp: new Date(fixtureStart),+ environment: "storybook",+ userId: "demo-user",+ observationCount: researchCodingAgentObservations.length,+ latencyMs: 87_347,+ scores: [],+} satisfies TimelineProps["traces"][number]["trace"];++const implementationCodingAgentTrace = {+ id: implementationTraceId,+ name: "Implement recipe dashboard density setting",+ timestamp: new Date(fixtureStart + 120_000),+ environment: "storybook",+ userId: "demo-user",+ observationCount: implementationCodingAgentObservations.length,+ latencyMs: 167_662,+ scores: [],+} satisfies TimelineProps["traces"][number]["trace"];++const observationActions = {+ onFilterByName: fn(),+} satisfies NonNullable<TimelineProps["observationActions"]>;++const loadedArgs = {+ traces: [{ trace, turnNumber: 1, observations }],+ filterMeasurementKey: "default",+ emptyMessage: "This trace has no observations.",+ onOpenTrace: fn(),+ onOpenObservation: fn(),+ observationActions,+} satisfies TimelineProps;++type ToolShape = {+ callId: string;+ name: string;+ input: Record<string, unknown>;+};++const toolShapePrompt =+ "Help me determine whether customer CUS-48291 can cancel their annual plan and receive a refund.";+const toolShapeGenerationMessage =+ "I'll review the customer account and refund policy.";++const toolShapeArgs = ({+ generationTool,+ observationTool,+ nestObservationTool,+}: {+ generationTool: ToolShape | null;+ observationTool: (ToolShape & { output: Record<string, unknown> }) | null;+ nestObservationTool: boolean;+}) => {+ const generationId = "tool-shape-generation";+ const shapeObservations = [+ codingAgentObservation({+ traceId: trace.id,+ id: generationId,+ parentObservationId: null,+ type: "GENERATION",+ name: "Tool shape generation",+ offsetMs: 0,+ latency: 1,+ input: JSON.stringify([{ role: "user", content: toolShapePrompt }]),+ output: generationTool+ ? assistantToolCalls(toolShapeGenerationMessage, [+ {+ id: generationTool.callId,+ name: generationTool.name,+ arguments: generationTool.input,+ },+ ])+ : assistantMessage(toolShapeGenerationMessage),+ }),+ ...(observationTool+ ? [+ codingAgentObservation({+ traceId: trace.id,+ id: "tool-shape-observation",+ parentObservationId: nestObservationTool ? generationId : null,+ type: "TOOL",+ name: observationTool.name,+ offsetMs: 1,+ latency: 1,+ input: JSON.stringify(observationTool.input),+ output: JSON.stringify(observationTool.output),+ metadata: { callID: observationTool.callId },+ }),+ ]+ : []),+ ];++ return {+ ...loadedArgs,+ traces: [+ {+ trace: {+ ...trace,+ observationCount: shapeObservations.length,+ },+ turnNumber: 1,+ observations: shapeObservations,+ },+ ],+ } satisfies TimelineProps;+};++const nestedObservation = ({+ id,+ parentObservationId,+ type,+ input,+ output,+ offset,+}: {+ id: string;+ parentObservationId: string | null;+ type: "AGENT" | "GENERATION" | "TOOL";+ input: unknown;+ output: unknown;+ offset: number;+}) =>+ ({+ id,+ traceId: trace.id,+ parentObservationId,+ type,+ name: id,+ startTime: new Date(offset),+ latency: 1,+ input,+ output,+ metadata: null,+ inputTruncated: false,+ outputTruncated: false,+ metadataTruncated: false,+ }) as Observation;++const nestedObservations = [+ nestedObservation({+ id: "opencode.turn",+ parentObservationId: null,+ type: "AGENT",+ input: [{ role: "user", content: "Build the dashboard" }],+ output: "Finished the dashboard",+ offset: 0,+ }),+ nestedObservation({+ id: "generation-1",+ parentObservationId: "opencode.turn",+ type: "GENERATION",+ input: [{ role: "user", content: "Build the dashboard" }],+ output: "Calling three tools",+ offset: 1,+ }),+ ...[1, 2, 3].map((toolNumber) =>+ nestedObservation({+ id: `tool-${toolNumber}`,+ parentObservationId: "generation-1",+ type: "TOOL",+ input: { toolNumber },+ output: { success: true },+ offset: 1 + toolNumber,+ }),+ ),+ nestedObservation({+ id: "generation-2",+ parentObservationId: "opencode.turn",+ type: "GENERATION",+ input: "Continue",+ output: "Calling two tools",+ offset: 5,+ }),+ ...[4, 5].map((toolNumber) =>+ nestedObservation({+ id: `tool-${toolNumber}`,+ parentObservationId: "generation-2",+ type: "TOOL",+ input: { toolNumber },+ output: { success: true },+ offset: 1 + toolNumber,+ }),+ ),+ nestedObservation({+ id: "leaf-generation",+ parentObservationId: null,+ type: "GENERATION",+ input: "Standalone prompt",+ output: "Standalone answer",+ offset: 8,+ }),+];++const meta = preview.meta({+ component: SessionConversationTimelineStory,+ parameters: { layout: "fullscreen", a11y: { test: "error" } },+});++export default meta;++export const SupportAgentWorkflow = meta.story({+ args: loadedArgs,+});++export const CodingAgentWorkflow = meta.story({+ args: {+ ...loadedArgs,+ traces: [+ {+ trace: researchCodingAgentTrace,+ turnNumber: 2,+ observations: researchCodingAgentObservations,+ },+ {+ trace: implementationCodingAgentTrace,+ turnNumber: 3,+ observations: implementationCodingAgentObservations,+ },+ ],+ },+});++export const LangfuseAssistantWorkflow = meta.story({+ args: {+ ...loadedArgs,+ traces: [+ {+ trace: inAppAgentTrace,+ turnNumber: 4,+ observations: inAppAgentObservations,+ },+ ],+ },+});++export const Loading = meta.story({+ args: {+ ...loadedArgs,+ traces: [{ trace, turnNumber: 1, observations: undefined }],+ },+});++export const Error = meta.story({+ args: {+ ...loadedArgs,+ traces: [{ trace, turnNumber: 1, observations: null }],+ },+});++export const Empty = meta.story({+ args: {+ ...loadedArgs,+ traces: [{ trace, turnNumber: 1, observations: [] }],+ },+});++export const FilteredEmpty = meta.story({+ args: {+ ...loadedArgs,+ traces: [{ trace, turnNumber: 1, observations: [] }],+ emptyMessage:+ "No observation matches the “Generations” view in this trace.",+ },+});++export const RenderLoadedConversation = meta.story({+ name: "(Test) Renders Loaded Conversation",+ args: SupportAgentWorkflow.input.args,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const traceButton = canvas.getByRole("button", {+ name: /1.*trace.*trace-order-support-8f3a2/i,+ });+ await expect(traceButton).toBeInTheDocument();+ await expect(within(traceButton).getByText("1")).toHaveClass("bg-tertiary");+ await expect(canvas.queryByText("+10 min idle")).not.toBeInTheDocument();++ const observationButton = canvas.getByRole("button", {+ name: "Plan support response",+ });+ await expect(+ within(observationButton).getByText("Plan support response"),+ ).toHaveClass("font-normal");+ await expect(+ canvas.getByText(/Hi, I just noticed order #LF-20481/),+ ).toBeInTheDocument();+ await expect(+ canvas.getByText("I'll check whether the order can still be updated."),+ ).toBeInTheDocument();+ const generation = canvasElement.querySelector(+ '[data-session-observation-id="generation-1"]',+ );+ await expect(generation).not.toBeNull();+ await expect(+ within(generation as HTMLElement).queryByRole("button", {+ name: "get_order",+ }),+ ).not.toBeInTheDocument();+ await expect(+ within(+ generation?.closest("[data-session-observation-depth]") as HTMLElement,+ ).queryByRole("button", { name: "Show 1 tool" }),+ ).not.toBeInTheDocument();+ await expect(+ canvas.queryByRole("button", { name: "get_order" }),+ ).not.toBeInTheDocument();+ await expect(+ canvas.getByRole("button", { name: "Get order" }),+ ).toBeInTheDocument();+ await expect(+ canvas.queryByRole("button", { name: "update_shipping_address" }),+ ).not.toBeInTheDocument();+ await expect(+ canvas.getByRole("button", { name: "Update shipping address" }),+ ).toBeInTheDocument();+ await expect(+ canvas.getByRole("button", { name: "Expand Get order" }),+ ).toBeInTheDocument();+ expect(+ canvas.getByRole("button", { name: "Reasoning" }).closest("article"),+ ).toBeNull();+ },+});++export const TruncatedObservation = meta.story({+ name: "(Test) Renders Truncated Observation",+ args: {+ ...loadedArgs,+ traces: [+ {+ trace,+ turnNumber: 1,+ observations: [+ {+ ...observations[0]!,+ input: "First 4,000 characters of the input…",+ output: "First 4,000 characters of the output…",+ inputTruncated: true,+ outputTruncated: true,+ },+ ],+ },+ ],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(+ canvas+ .getByText("First 4,000 characters of the input…")+ .closest("article")?.parentElement,+ ).toHaveClass("justify-end");+ await expect(+ canvas+ .getByText("First 4,000 characters of the output…")+ .closest("article")?.parentElement,+ ).toHaveClass("justify-start");+ await expect(+ canvas.getByRole("img", { name: "Content truncated" }),+ ).toBeInTheDocument();+ await expect(+ canvas.queryByText(+ "This observation is too large to parse in the session timeline.",+ ),+ ).not.toBeInTheDocument();+ await expect(+ canvas.queryByRole("button", { name: "Open in trace view" }),+ ).not.toBeInTheDocument();+ await expect(canvasElement.querySelector("pre")).toBeNull();+ },+});++export const UseObservationFilters = meta.story({+ name: "(Test) Uses Observation Filters",+ args: {+ ...loadedArgs,+ observationActions: {+ onFilterByName: fn(),+ },+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const page = within(canvasElement.ownerDocument.body);+ const actionsButton = canvas.getByRole("button", {+ name: "Actions for Plan support response",+ });++ await userEvent.click(actionsButton);+ await expect(+ page.getByRole("menuitem", {+ name: "Only show observations with the same name",+ }),+ ).toBeInTheDocument();+ await expect(+ page.getByRole("menuitem", {+ name: "Exclude observations with the same name",+ }),+ ).toBeInTheDocument();+ await expect(+ page.queryByRole("menuitem", { name: "Annotate" }),+ ).not.toBeInTheDocument();+ await expect(+ page.queryByRole("menuitem", { name: "Add comment" }),+ ).not.toBeInTheDocument();+ await expect(+ page.queryByRole("menuitem", { name: "Add to dataset" }),+ ).not.toBeInTheDocument();++ await userEvent.click(+ page.getByRole("menuitem", {+ name: "Only show observations with the same name",+ }),+ );+ await expect(args.observationActions?.onFilterByName).toHaveBeenCalledWith(+ "Plan support response",+ "any of",+ );+ await waitFor(() =>+ expect(+ canvasElement.ownerDocument.getElementById("__next"),+ ).not.toHaveAttribute("aria-hidden", "true"),+ );+ },+});++export const MetadataOmitted = meta.story({+ name: "(Test) Renders Omitted Metadata",+ args: {+ ...loadedArgs,+ traces: [+ {+ trace,+ turnNumber: 1,+ observations: [{ ...observations[0]!, metadataTruncated: true }],+ },+ ],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(+ canvas.getByRole("img", {+ name: "Metadata omitted because it is too large",+ }),+ ).toBeInTheDocument();+ await expect(+ canvas.queryByText(/Messages are parsed from input and output only/i),+ ).not.toBeInTheDocument();+ await expect(+ canvas.getByText(/Hi, I just noticed order #LF-20481/),+ ).toBeInTheDocument();+ },+});++export const RenderFalsyTruncatedValues = meta.story({+ name: "(Test) Renders Falsy Truncated Values",+ args: {+ ...loadedArgs,+ traces: [+ {+ trace,+ turnNumber: 1,+ observations: [+ {+ ...observations[0]!,+ input: "0",+ output: "false",+ outputTruncated: true,+ },+ ],+ },+ ],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(canvas.getByText("0")).toBeInTheDocument();+ await expect(canvas.getByText("false")).toBeInTheDocument();+ },+});++export const OpenObservation = meta.story({+ name: "(Test) Opens Observation",+ args: { ...loadedArgs, onOpenObservation: fn() },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(+ canvas.getByRole("button", { name: "Plan support response" }),+ );+ await expect(args.onOpenObservation).toHaveBeenCalledWith(+ trace,+ "generation-1",+ );+ },+});++export const ExpandToolObservation = meta.story({+ name: "(Test) Expands Tool Observation Without Moving Header",+ args: loadedArgs,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const header = canvas.getByRole("button", { name: "Get order" });+ const initialTop = header.getBoundingClientRect().top;+ const expandButton = canvas.getByRole("button", {+ name: "Expand Get order",+ });+ await expect(expandButton.previousElementSibling).toBe(header);+ await expect(canvasElement.querySelectorAll("pre")).toHaveLength(0);++ await userEvent.click(expandButton);+ await expect(header.getBoundingClientRect().top).toBe(initialTop);+ const toolPreviews = canvasElement.querySelectorAll("pre");+ await expect(toolPreviews).toHaveLength(2);+ await expect(toolPreviews[0]).toHaveTextContent('{"orderId":"LF-20481"}');+ await expect(toolPreviews[1]).toHaveTextContent('"status":"processing"');++ await userEvent.click(+ canvas.getByRole("button", { name: "Collapse Get order" }),+ );+ await expect(header.getBoundingClientRect().top).toBe(initialTop);+ await expect(canvasElement.querySelectorAll("pre")).toHaveLength(0);+ },+});++export const ExpandRolledUpTool = meta.story({+ name: "(Test) Expands Rolled-up Tool With Rail",+ args: {+ ...loadedArgs,+ traces: [+ {+ trace: { ...trace, observationCount: 1 },+ turnNumber: 1,+ observations: [observations[0]!],+ },+ ],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const generation = canvasElement+ .querySelector('[data-session-observation-id="generation-1"]')+ ?.closest("[data-session-observation-depth]");+ await userEvent.click(+ within(generation as HTMLElement).getByRole("button", {+ name: "Show 1 tool",+ }),+ );+ const expandButton = canvas.getByRole("button", {+ name: "Expand get_order",+ });+ const toolRow = expandButton.closest("[data-session-observation-depth]");+ const toolIcon = expandButton.previousElementSibling?.querySelector("svg");+ const unavailableActionsIcon = within(toolRow as HTMLElement).getByRole(+ "img",+ {+ name: "Actions available on parent observation",+ },+ );++ await expect(toolRow).toHaveAttribute(+ "data-session-observation-depth",+ "1",+ );+ await expect(toolRow).toHaveStyle({ paddingLeft: "24px" });+ await expect(+ toolRow?.querySelector('[data-session-observation-rail-depth="0"]'),+ ).toBeInTheDocument();+ await expect(+ toolRow?.querySelector('[data-session-observation-rail-depth="1"]'),+ ).not.toBeInTheDocument();+ await expect(toolIcon).not.toBeNull();+ await userEvent.hover(unavailableActionsIcon);+ await expect(+ await within(canvasElement.ownerDocument.body).findByRole("tooltip"),+ ).toHaveTextContent("Actions are available on the parent observation");+ await userEvent.unhover(unavailableActionsIcon);++ await userEvent.click(expandButton);++ await expect(+ toolRow?.querySelector('[data-session-observation-rail-depth="1"]'),+ ).toBeInTheDocument();+ await expect(+ toolRow?.querySelector("[data-session-observation-rail-end]"),+ ).toBeInTheDocument();+ },+});++export const MergeSystemPrompts = meta.story({+ name: "(Test) Merges System Prompts",+ args: LangfuseAssistantWorkflow.input.args,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const firstGeneration = canvasElement.querySelector(+ '[data-session-observation-id="error-analysis-generation-1"]',+ );+ await expect(firstGeneration).not.toBeNull();++ const observation = within(firstGeneration as HTMLElement);+ await expect(+ observation.getAllByRole("button", { name: "System prompt" }),+ ).toHaveLength(1);++ await userEvent.click(+ observation.getByRole("button", { name: "System prompt" }),+ );+ await expect(+ observation.getByText(+ "You are a demo observability analyst. Use only fictional project data.",+ ),+ ).toBeInTheDocument();+ await expect(+ observation.getByText(+ "Inspect representative failures before proposing a taxonomy or remediation.",+ ),+ ).toBeInTheDocument();+ await expect(+ observation.getByText(+ "Never expose identifiers or payloads from real users.",+ ),+ ).toBeInTheDocument();+ await expect(+ observation.queryByRole("button", { name: "skill" }),+ ).not.toBeInTheDocument();+ await expect(canvas.getAllByRole("button", { name: "skill" })).toHaveLength(+ 1,+ );+ await expect(canvas.getAllByText(inAppAgentPrompt)).toHaveLength(1);+ await expect(+ canvas.getByText(+ "Summarize the taxonomy, recommend the first fix, and suggest a durable way to track it.",+ ),+ ).toBeInTheDocument();+ },+});++export const ExpandNestedObservations = meta.story({+ name: "(Test) Expands Nested Observations",+ args: {+ ...loadedArgs,+ traces: [{ trace, turnNumber: 1, observations: nestedObservations }],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(canvas.getByText("Build the dashboard")).toBeInTheDocument();+ await expect(+ canvas.getByText("Finished the dashboard"),+ ).toBeInTheDocument();+ const leafObservation = canvas+ .getByText("Standalone answer")+ .closest("[data-session-observation-depth]");+ await expect(+ leafObservation?.querySelector(+ '[data-session-observation-rail-depth="0"]',+ ),+ ).toBeInTheDocument();+ await expect(+ leafObservation?.querySelector("[data-session-observation-rail-end]"),+ ).toBeInTheDocument();+ await expect(canvas.queryByText("generation-1")).not.toBeInTheDocument();+ await expect(canvas.queryByText("tool-1")).not.toBeInTheDocument();++ const rootToggle = canvas.getByRole("button", {+ name: "Show 2 generations and 5 tools",+ });+ const rootStart = rootToggle.closest("[data-session-observation-depth]");+ await expect(+ rootStart?.querySelector('[data-session-observation-rail-depth="0"]'),+ ).toHaveClass("top-[22px]");+ const closingRailEnd = canvas+ .getByText("Finished the dashboard")+ .closest("[data-session-observation-depth]")+ ?.querySelector("[data-session-observation-rail-end]");+ await expect(closingRailEnd).toBeInTheDocument();+ await expect(closingRailEnd).toHaveClass("rounded-full");+ await expect(+ rootToggle.querySelector(".lucide-chevrons-up-down"),+ ).not.toBeNull();+ const initialRootToggleTop = rootToggle.getBoundingClientRect().top;++ // Expanding a parent reveals its direct children, but nested groups remain collapsed.+ await userEvent.click(rootToggle);++ // Expanding the rail must not move the toggle the user just clicked.+ await expect(rootToggle.getBoundingClientRect().top).toBe(+ initialRootToggleTop,+ );+ await expect(canvas.getByText("generation-1")).toBeInTheDocument();+ await expect(canvas.getByText("generation-2")).toBeInTheDocument();+ await expect(canvas.queryByText("tool-1")).not.toBeInTheDocument();+ await expect(rootToggle.parentElement).toHaveClass("h-0");+ await expect(+ rootToggle.querySelector(".lucide-chevrons-down-up"),+ ).not.toBeNull();+ const nestedGeneration = canvasElement+ .querySelector('[data-session-observation-id="generation-1"]')+ ?.closest("[data-session-observation-depth]");+ await expect(nestedGeneration).toHaveAttribute(+ "data-session-observation-depth",+ "1",+ );+ await expect(nestedGeneration).toHaveStyle({ paddingLeft: "24px" });+ await expect(+ nestedGeneration?.querySelectorAll(+ "[data-session-observation-rail-depth]",+ ),+ ).toHaveLength(2);+ const nestedObservationIcon = nestedGeneration?.querySelector(+ '[data-session-observation-id="generation-1"] button svg',+ );+ await expect(nestedObservationIcon).not.toBeNull();+ const rootToggleRect = rootToggle.getBoundingClientRect();+ const nestedObservationIconRect = (+ nestedObservationIcon as SVGElement+ ).getBoundingClientRect();+ // The rail toggle stays vertically centered with the child observation icon beside it.+ await expect(rootToggleRect.top + rootToggleRect.height / 2).toBe(+ nestedObservationIconRect.top + nestedObservationIconRect.height / 2,+ );+ const nestedToggle = canvas.getByRole("button", { name: "Show 3 tools" });+ const initialNestedToggleTop = nestedToggle.getBoundingClientRect().top;++ // Nested observations expand independently from their ancestors.+ await userEvent.click(nestedToggle);++ // Expanding a nested rail must keep its toggle anchored too.+ await expect(nestedToggle.getBoundingClientRect().top).toBe(+ initialNestedToggleTop,+ );+ await expect(canvas.getByText("tool-1")).toBeInTheDocument();+ const nestedTool = canvasElement+ .querySelector('[data-session-observation-id="tool-1"]')+ ?.closest("[data-session-observation-depth]");+ await expect(nestedTool).toHaveAttribute(+ "data-session-observation-depth",+ "2",+ );+ await expect(nestedTool).toHaveStyle({ paddingLeft: "48px" });+ await expect(+ nestedTool?.querySelectorAll("[data-session-observation-rail-depth]"),+ ).toHaveLength(2);+ await expect(+ nestedTool?.querySelector('[data-session-observation-rail-depth="2"]'),+ ).not.toBeInTheDocument();++ await userEvent.click(+ canvas.getByRole("button", { name: "Expand tool-1" }),+ );+ await expect(+ nestedTool?.querySelector('[data-session-observation-rail-depth="2"]'),+ ).toHaveClass("top-[22px]");+ await expect(+ nestedTool?.querySelector("[data-session-observation-rail-end]"),+ ).toBeInTheDocument();++ await userEvent.click(+ canvas.getByRole("button", { name: "Collapse tool-1" }),+ );+ await expect(+ nestedTool?.querySelector('[data-session-observation-rail-depth="2"]'),+ ).not.toBeInTheDocument();+ await expect(+ nestedTool?.querySelector("[data-session-observation-rail-end]"),+ ).not.toBeInTheDocument();+ await expect(nestedToggle).toHaveStyle({ left: "7.5px" });+ await expect(nestedToggle).toHaveClass("top-5");++ await userEvent.click(nestedToggle);++ // Collapsing the nested rail must not move the toggle either.+ await expect(nestedToggle.getBoundingClientRect().top).toBe(+ initialNestedToggleTop,+ );+ await expect(canvas.queryByText("tool-1")).not.toBeInTheDocument();+ await expect(+ canvas.getByRole("button", { name: "Show 3 tools" }),+ ).toBeInTheDocument();+ },+});++export const ExpandEmptyTopLevelObservation = meta.story({+ name: "(Test) Expands Empty Top-Level Observation",+ args: {+ ...loadedArgs,+ traces: [+ {+ trace,+ turnNumber: 1,+ observations: nestedObservations.map((observation) =>+ observation.id === "opencode.turn"+ ? { ...observation, input: null, output: null }+ : observation,+ ),+ },+ ],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(canvas.getByText("generation-1")).toBeInTheDocument();+ await expect(+ canvas.getByRole("button", {+ name: "Hide 2 generations and 5 tools",+ }),+ ).toBeInTheDocument();+ },+});++export const ToolObservationDataOnly = meta.story({+ name: "(Test) Tool Observation Data Only",+ args: toolShapeArgs({+ generationTool: null,+ nestObservationTool: true,+ observationTool: {+ callId: "call-subscription-details",+ name: "get_subscription_details",+ input: { customerId: "CUS-48291" },+ output: {+ plan: "annual_pro",+ refundable: true,+ refundWindowEndsAt: "2026-01-15",+ },+ },+ }),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(canvas.getByRole("button", { name: "Show 1 tool" }));+ await expect(+ canvas.getAllByRole("button", { name: "get_subscription_details" }),+ ).toHaveLength(1);+ await expect(+ canvasElement.querySelector(+ '[data-session-observation-id="tool-shape-observation"]',+ ),+ ).toBeInTheDocument();+ },+});++export const GenerationToolDataOnly = meta.story({+ name: "(Test) Generation Tool Data Only",+ args: toolShapeArgs({+ generationTool: {+ callId: "call-subscription-details",+ name: "get_subscription_details",+ input: { customerId: "CUS-48291" },+ },+ nestObservationTool: false,+ observationTool: null,+ }),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(canvas.getByRole("button", { name: "Show 1 tool" }));+ await expect(+ canvas.getAllByRole("button", { name: "get_subscription_details" }),+ ).toHaveLength(1);+ await expect(+ canvasElement.querySelector(+ '[data-session-observation-id="tool-shape-generation-tool-call-call-subscription-details"]',+ ),+ ).toBeInTheDocument();+ },+});++export const DeduplicateMatchingToolData = meta.story({+ name: "(Test) Deduplicates Matching Tool Data",+ args: toolShapeArgs({+ generationTool: {+ callId: "call-subscription-details",+ name: "get_subscription_details",+ input: { customerId: "CUS-48291" },+ },+ nestObservationTool: true,+ observationTool: {+ callId: "call-subscription-details",+ name: "get_subscription_details",+ input: { customerId: "CUS-48291" },+ output: {+ plan: "annual_pro",+ refundable: true,+ refundWindowEndsAt: "2026-01-15",+ },+ },+ }),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(canvas.getByRole("button", { name: "Show 1 tool" }));+ await expect(+ canvas.getAllByRole("button", { name: "get_subscription_details" }),+ ).toHaveLength(1);+ await expect(+ canvasElement.querySelector(+ '[data-session-observation-id="tool-shape-observation"]',+ ),+ ).toBeInTheDocument();+ await expect(+ canvasElement.querySelector(+ '[data-session-observation-id="tool-shape-generation-tool-call-call-subscription-details"]',+ ),+ ).not.toBeInTheDocument();+ },+});++export const KeepDifferentToolData = meta.story({+ name: "(Test) Keeps Different Tool Data",+ args: toolShapeArgs({+ generationTool: {+ callId: "call-cancellation-policy",+ name: "search_documentation",+ input: { query: "annual plan cancellation policy", limit: 3 },+ },+ nestObservationTool: true,+ observationTool: {+ callId: "call-customer-profile",+ name: "get_customer_profile",+ input: { customerId: "CUS-48291" },+ output: {+ plan: "annual_pro",+ renewalDate: "2026-06-15",+ accountStatus: "active",+ },+ },+ }),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(canvas.getByRole("button", { name: "Show 2 tools" }));+ await expect(+ canvas.getAllByRole("button", { name: "search_documentation" }),+ ).toHaveLength(1);+ await expect(+ canvas.getAllByRole("button", { name: "get_customer_profile" }),+ ).toHaveLength(1);+ await expect(+ canvasElement.querySelector(+ '[data-session-observation-id="tool-shape-generation-tool-call-call-cancellation-policy"]',+ ),+ ).toBeInTheDocument();+ await expect(+ canvasElement.querySelector(+ '[data-session-observation-id="tool-shape-observation"]',+ ),+ ).toBeInTheDocument();+ },+});++export const LoadMoreObservations = meta.story({+ name: "(Test) Loads More Observations",+ args: {+ ...loadedArgs,+ onLoadMoreObservations: fn(),+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const timeline = canvas.getByLabelText("Session conversation timeline");++ timeline.scrollTop = timeline.scrollHeight;+ timeline.dispatchEvent(new Event("scroll", { bubbles: true }));++ await expect(args.onLoadMoreObservations).toHaveBeenCalledOnce();+ },+});diff --git a/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.tsx b/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.tsxnew file mode 100644index 0000000000..c9dc15fe72--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.tsx@@ -0,0 +1,316 @@+import { useEffect, useMemo, useRef, type UIEvent } from "react";+import { useVirtualizer } from "@tanstack/react-virtual";++import {+ prepareSessionTimelineObservations,+ type PreparedSessionTimelineItem,+} from "@/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations";+import {+ SessionConversationTimelineTrace,+ type PreparedSessionConversationTimelineTraceState,+ type SessionObservation,+ type SessionObservationActions,+} from "@/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace";+import { SessionVirtualizedRow } from "@/src/features/sessions/SessionVirtualizedRow";+import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";+import { useElementSize } from "@/src/hooks/useElementSize";+import { useVirtualizedScrollSpy } from "@/src/hooks/useVirtualizedScrollSpy";++const SESSION_TIMELINE_OVERSCAN = 5;+const observationIdentityByReference = new WeakMap<object, number>();+let nextObservationIdentity = 0;++const getObservationIdentity = (observation: SessionObservation) => {+ const existingIdentity = observationIdentityByReference.get(observation);+ if (existingIdentity !== undefined) return existingIdentity;++ const identity = nextObservationIdentity++;+ observationIdentityByReference.set(observation, identity);+ return identity;+};++export type SessionConversationTimelineItem = {+ trace: EventSessionTrace;+ turnNumber: number;+ observations: readonly SessionObservation[] | null | undefined;+};++export type SessionConversationTimelineObservationActions =+ SessionObservationActions;++export type SessionConversationTimelineScrollTarget = {+ traceId: string;+ observationId: string;+ requestId: number;+};++export function useSessionConversationTimelineController(+ traces: readonly Pick<SessionConversationTimelineItem, "trace">[],+) {+ const items = traces.map(({ trace }) => trace);+ const [feedRef, feedSize] = useElementSize<HTMLDivElement>();+ const virtualizer = useVirtualizer({+ count: traces.length,+ getScrollElement: () => feedRef.current,+ estimateSize: () => 520,+ overscan: SESSION_TIMELINE_OVERSCAN,+ getItemKey: (index) => traces[index]?.trace.id ?? index,+ });+ const {+ activeItemId,+ virtualItems,+ selectItem: selectTrace,+ } = useVirtualizedScrollSpy({+ items,+ virtualizer,+ scrollElementRef: feedRef,+ viewportHeight: feedSize?.height ?? 0,+ endTransitionRatio: 0.2,+ });+ const observationScrollCleanupRef = useRef<(() => void) | null>(null);++ useEffect(() => () => observationScrollCleanupRef.current?.(), []);++ const onSelect = (index: number, observationId?: string) => {+ observationScrollCleanupRef.current?.();+ observationScrollCleanupRef.current = null;+ selectTrace(index);+ if (!observationId) return;++ const feed = feedRef.current;+ const traceId = traces[index]?.trace.id;+ if (!feed || !traceId) return;++ const scrollToObservation = () => {+ const observation = Array.from(+ feed.querySelectorAll<HTMLElement>("[data-session-observation-id]"),+ ).find(+ (element) =>+ element.dataset.sessionObservationId === observationId &&+ element.closest<HTMLElement>("[data-session-trace-id]")?.dataset+ .sessionTraceId === traceId,+ );+ if (!observation) return false;++ const top =+ feed.scrollTop ++ observation.getBoundingClientRect().top -+ feed.getBoundingClientRect().top -+ Math.max(0, (feed.clientHeight - observation.clientHeight) / 2);+ feed.scrollTo({ top, behavior: "smooth" });+ return true;+ };++ if (scrollToObservation()) return;++ let timeout: number;+ const cleanup = () => {+ observer.disconnect();+ window.clearTimeout(timeout);+ };+ const observer = new MutationObserver(() => {+ if (!scrollToObservation()) return;+ cleanup();+ if (observationScrollCleanupRef.current === cleanup) {+ observationScrollCleanupRef.current = null;+ }+ });+ observer.observe(feed, { childList: true, subtree: true });+ timeout = window.setTimeout(() => {+ cleanup();+ if (observationScrollCleanupRef.current === cleanup) {+ observationScrollCleanupRef.current = null;+ }+ }, 5_000);+ observationScrollCleanupRef.current = cleanup;+ };++ return {+ activeTraceId: activeItemId ?? null,+ feedRef,+ onSelect,+ virtualItems,+ virtualizer,+ };+}++export type SessionConversationTimelineController = ReturnType<+ typeof useSessionConversationTimelineController+>;++export function SessionConversationTimeline({+ traces,+ filterMeasurementKey,+ emptyMessage,+ onOpenTrace,+ onOpenObservation,+ controller,+ observationActions,+ scrollTarget,+ onLoadMoreObservations,+}: {+ traces: readonly SessionConversationTimelineItem[];+ filterMeasurementKey: string;+ emptyMessage: string;+ onOpenTrace: (trace: EventSessionTrace) => void;+ onOpenObservation: (trace: EventSessionTrace, observationId: string) => void;+ controller: SessionConversationTimelineController;+ observationActions?: SessionConversationTimelineObservationActions;+ scrollTarget?: SessionConversationTimelineScrollTarget | null;+ onLoadMoreObservations?: () => void;+}) {+ const observationFingerprint = traces+ .flatMap(({ observations }) => observations ?? [])+ .map(getObservationIdentity)+ .join(",");+ const { states } = useMemo(() => {+ const preparedObservations = prepareSessionTimelineObservations(+ traces.flatMap(({ observations }) => observations ?? []),+ );+ const traceIndexByObservation = new Map<SessionObservation, number>();+ traces.forEach(({ observations }, traceIndex) => {+ observations?.forEach((observation) => {+ traceIndexByObservation.set(observation, traceIndex);+ });+ });+ const preparedObservationGroups: Array<+ PreparedSessionTimelineItem<SessionObservation>[] | null | undefined+ > = traces.map(({ observations }) =>+ observations === undefined || observations === null ? observations : [],+ );+ preparedObservations.forEach((preparedObservation) => {+ const traceIndex = traceIndexByObservation.get(+ preparedObservation.observation,+ );+ if (traceIndex === undefined) return;++ preparedObservationGroups[traceIndex]?.push(preparedObservation);+ });++ return {+ observationFingerprint,+ states: traces.map(+ (+ { observations },+ traceIndex,+ ): PreparedSessionConversationTimelineTraceState => {+ if (observations === undefined) return { type: "loading" };+ if (observations === null) return { type: "error" };+ if (observations.length === 0) {+ return { type: "empty", message: emptyMessage };+ }++ return {+ type: "loaded",+ observations: preparedObservationGroups[traceIndex] ?? [],+ };+ },+ ),+ };+ }, [emptyMessage, observationFingerprint, traces]);++ return (+ <SessionConversationTimelineFeed+ traces={traces}+ states={states}+ filterMeasurementKey={filterMeasurementKey}+ onOpenTrace={onOpenTrace}+ onOpenObservation={onOpenObservation}+ controller={controller}+ observationActions={observationActions}+ scrollTarget={scrollTarget ?? null}+ onLoadMoreObservations={onLoadMoreObservations}+ />+ );+}++function SessionConversationTimelineFeed({+ traces,+ states,+ filterMeasurementKey,+ onOpenTrace,+ onOpenObservation,+ controller,+ observationActions,+ scrollTarget,+ onLoadMoreObservations,+}: {+ traces: readonly SessionConversationTimelineItem[];+ states: readonly PreparedSessionConversationTimelineTraceState[];+ filterMeasurementKey: string;+ onOpenTrace: (trace: EventSessionTrace) => void;+ onOpenObservation: (trace: EventSessionTrace, observationId: string) => void;+ controller: SessionConversationTimelineController;+ observationActions?: SessionConversationTimelineObservationActions;+ scrollTarget: SessionConversationTimelineScrollTarget | null;+ onLoadMoreObservations?: () => void;+}) {+ const { feedRef, virtualItems, virtualizer } = controller;+ const handleScroll = (event: UIEvent<HTMLDivElement>) => {+ if (!onLoadMoreObservations) return;++ const { clientHeight, scrollTop } = event.currentTarget;+ const viewportBottom = scrollTop + clientHeight;+ const visibleTrace = virtualItems.findLast(+ (virtualItem) => virtualItem.start < viewportBottom,+ );+ const loadMoreThreshold = visibleTrace+ ? Math.min(240, visibleTrace.size / 4)+ : 0;+ if (+ visibleTrace &&+ viewportBottom >= visibleTrace.end - loadMoreThreshold+ ) {+ onLoadMoreObservations();+ }+ };++ return (+ <div+ ref={feedRef}+ aria-label="Session conversation timeline"+ className="h-full min-h-0 overflow-y-auto scroll-smooth"+ onScroll={handleScroll}+ >+ <div+ style={{+ height: `${virtualizer.getTotalSize()}px`,+ width: "100%",+ position: "relative",+ }}+ >+ {virtualItems.map((virtualItem) => {+ const timelineTrace = traces[virtualItem.index];+ const state = states[virtualItem.index];+ if (!timelineTrace || !state) return null;+ const { trace, turnNumber } = timelineTrace;++ return (+ <SessionVirtualizedRow+ key={virtualItem.key}+ itemKey={String(virtualItem.key)}+ measurementKey={`${String(virtualItem.key)}:${filterMeasurementKey}`}+ source="modern"+ virtualItem={virtualItem}+ virtualizer={virtualizer}+ >+ <SessionConversationTimelineTrace+ trace={trace}+ turnNumber={turnNumber}+ state={state}+ onOpenTrace={() => onOpenTrace(trace)}+ onOpenObservation={(observationId) =>+ onOpenObservation(trace, observationId)+ }+ observationActions={observationActions}+ scrollTarget={+ scrollTarget?.traceId === trace.id ? scrollTarget : null+ }+ />+ </SessionVirtualizedRow>+ );+ })}+ </div>+ </div>+ );+}diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.clienttest.tsx b/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.clienttest.tsxnew file mode 100644index 0000000000..b6d488c436--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.clienttest.tsx@@ -0,0 +1,92 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { type ComponentProps } from "react";+import { describe, expect, it, vi } from "vitest";++import { SessionConversationTimelineTrace } from "@/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace";+import { prepareSessionTimelineObservations } from "@/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations";++type TraceProps = ComponentProps<typeof SessionConversationTimelineTrace>;+type Observation = Extract<+ TraceProps["state"],+ { type: "loaded" }+>["observations"][number]["observation"];++const observation = (+ id: string,+ parentObservationId: string | null,+ type: string,+ startTime: Date,+) =>+ ({+ id,+ traceId: "trace-1",+ parentObservationId,+ name: id,+ type,+ startTime,+ input: type === "TOOL" ? "input" : [],+ output: type === "TOOL" ? "output" : [],+ metadata: null,+ latency: null,+ inputTruncated: false,+ outputTruncated: false,+ metadataTruncated: false,+ }) as Observation;++const observations = prepareSessionTimelineObservations([+ observation("parent", null, "AGENT", new Date(0)),+ observation("child", "parent", "AGENT", new Date(1)),+ observation("grandchild", "child", "TOOL", new Date(2)),+]);++const trace = {+ id: "trace-1",+ name: "Trace",+ timestamp: new Date(0),+ environment: "production",+ userId: null,+ observationCount: 3,+ latencyMs: 1,+ scores: [],+} satisfies TraceProps["trace"];++describe("SessionConversationTimelineTrace", () => {+ it("expands every parent when an observation scroll is requested", async () => {+ const props = {+ trace,+ turnNumber: 1,+ state: { type: "loaded", observations } as const,+ onOpenTrace: vi.fn(),+ onOpenObservation: vi.fn(),+ scrollTarget: null,+ } satisfies TraceProps;+ const { rerender } = render(+ <SessionConversationTimelineTrace {...props} />,+ );++ expect(screen.queryByText("grandchild")).not.toBeInTheDocument();++ rerender(+ <SessionConversationTimelineTrace+ {...props}+ scrollTarget={{ observationId: "grandchild", requestId: 1 }}+ />,+ );++ expect(screen.getByText("grandchild")).toBeInTheDocument();+ const parentToggle = screen.getByRole("button", {+ name: "Hide 1 tool",+ });+ fireEvent.click(parentToggle);+ expect(screen.queryByText("grandchild")).not.toBeInTheDocument();++ rerender(+ <SessionConversationTimelineTrace+ {...props}+ scrollTarget={{ observationId: "grandchild", requestId: 2 }}+ />,+ );++ expect(screen.getByText("grandchild")).toBeInTheDocument();+ });+});diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx b/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsxnew file mode 100644index 0000000000..88cfc68801--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx@@ -0,0 +1,892 @@+import { useState } from "react";+import {+ ChevronDown,+ ChevronsDownUp,+ ChevronsUpDown,+ FileWarning,+ MessageSquareOff,+ MoreHorizontal,+} from "lucide-react";+import { renderFilterIcon } from "@/src/components/ItemBadge";+import {+ type ParsedSessionTimelineObservation,+ type PreparedSessionTimelineItem,+ type PreparedSessionTimelineMessages,+} from "@/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations";+import { SessionTimelineContentMessage } from "@/src/features/sessions/SessionConversationTimeline/components/SessionTimelineContentMessage/SessionTimelineContentMessage";+import { SessionTimelineSystemMessage } from "@/src/features/sessions/SessionConversationTimeline/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage";+import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";+import { Button } from "@/src/components/ui/button";+import { Skeleton } from "@/src/components/ui/skeleton";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";+import { type RouterOutputs } from "@/src/utils/api";+import { formatIntervalSeconds } from "@/src/utils/dates";+import { cn } from "@/src/utils/tailwind";++type EventObservation = RouterOutputs["events"]["all"]["observations"][number];+type EventObservationIO = RouterOutputs["events"]["batchIO"][number];+export type SessionObservation = Omit<+ EventObservation,+ "input" | "output" | "metadata"+> &+ Pick<EventObservationIO, "input" | "output" | "metadata"> & {+ inputTruncated?: boolean;+ outputTruncated?: boolean;+ metadataTruncated?: boolean;+ };++type SessionConversationTimelineTraceState =+ | { type: "loading" }+ | { type: "error" }+ | { type: "empty"; message: string }+ | {+ type: "loaded";+ observations: readonly SessionObservation[];+ };++export type PreparedSessionConversationTimelineTraceState =+ | Exclude<SessionConversationTimelineTraceState, { type: "loaded" }>+ | {+ type: "loaded";+ observations: readonly PreparedSessionTimelineItem<SessionObservation>[];+ };++export type SessionObservationActions = {+ onFilterByName: (name: string, operator: "any of" | "none of") => void;+};++const toPreviewText = (value: unknown) =>+ typeof value === "string"+ ? value+ : (JSON.stringify(value, undefined, 2) ?? String(value));++const hasPreviewValue = (value: unknown) =>+ value !== null && value !== undefined && value !== "";++function SessionObservationActionsMenuContent({+ observation,+ actions,+}: {+ observation: SessionObservation;+ actions: SessionObservationActions;+}) {+ return (+ <DropdownMenuContent align="end" sideOffset={0}>+ {observation.name ? (+ <DropdownMenuItem+ onSelect={() =>+ actions.onFilterByName(observation.name as string, "any of")+ }+ >+ Only show observations with the same name+ </DropdownMenuItem>+ ) : null}+ {observation.name ? (+ <DropdownMenuItem+ onSelect={() =>+ actions.onFilterByName(observation.name as string, "none of")+ }+ >+ Exclude observations with the same name+ </DropdownMenuItem>+ ) : null}+ </DropdownMenuContent>+ );+}++function SessionTimelineRailEnd() {+ return (+ <>+ <span+ className="bg-background pointer-events-none absolute top-1/2 -bottom-2 left-[-15px] w-px"+ aria-hidden="true"+ />+ <span+ data-session-observation-rail-end+ className="bg-border pointer-events-none absolute top-1/2 left-[-18px] h-1.5 w-1.5 -translate-y-1/2 rounded-full"+ aria-hidden="true"+ />+ </>+ );+}++const NESTED_OBSERVATION_TYPE_ORDER = ["GENERATION", "TOOL"];++const formatNestedObservationCounts = (+ counts: Readonly<Record<string, number>>,+) => {+ const labels = Object.entries(counts)+ .filter(([, count]) => count > 0)+ .sort(([left], [right]) => {+ const leftIndex = NESTED_OBSERVATION_TYPE_ORDER.indexOf(left);+ const rightIndex = NESTED_OBSERVATION_TYPE_ORDER.indexOf(right);+ if (leftIndex !== -1 && rightIndex !== -1) return leftIndex - rightIndex;+ if (leftIndex !== -1) return -1;+ if (rightIndex !== -1) return 1;+ return left.localeCompare(right);+ })+ .map(+ ([type, count]) =>+ `${count} ${type.toLowerCase()}${count === 1 ? "" : "s"}`,+ );++ if (labels.length < 2) return labels[0] ?? "nested observations";+ if (labels.length === 2) return `${labels[0]} and ${labels[1]}`;+ return `${labels.slice(0, -1).join(", ")}, and ${labels.at(-1)}`;+};++function TruncatedObservation({+ observation,+ phase,+}: {+ observation: SessionObservation;+ phase: "complete" | "start" | "end";+}) {+ return (+ <div className="flex flex-col gap-5">+ {phase !== "end" && hasPreviewValue(observation.input) ? (+ <div className="relative">+ <SessionTimelineContentMessage+ role="user"+ parts={[{ type: "text", text: toPreviewText(observation.input) }]}+ senderName={undefined}+ />+ {phase === "complete" && !hasPreviewValue(observation.output) ? (+ <SessionTimelineRailEnd />+ ) : null}+ </div>+ ) : null}+ {phase !== "start" && hasPreviewValue(observation.output) ? (+ <div className="relative">+ <SessionTimelineContentMessage+ role="assistant"+ parts={[{ type: "text", text: toPreviewText(observation.output) }]}+ senderName={undefined}+ />+ <SessionTimelineRailEnd />+ </div>+ ) : null}+ </div>+ );+}++function SessionTimelineToolRow({+ id,+ name,+ startTime,+ latency,+ input,+ output,+ inputTruncated,+ outputTruncated,+ isExpanded,+ onExpandedChange,+ onOpenInTraceView,+ observation,+ actions,+}: {+ id: string;+ name: string;+ startTime: Date;+ latency: number | null;+ input: unknown;+ output: unknown;+ inputTruncated?: boolean;+ outputTruncated?: boolean;+ isExpanded: boolean;+ onExpandedChange: (isExpanded: boolean) => void;+ onOpenInTraceView: () => void;+ observation?: SessionObservation;+ actions?: SessionObservationActions;+}) {+ return (+ <section+ data-session-observation-id={id}+ className={cn("flex scroll-mt-16 flex-col py-1", isExpanded && "gap-2")}+ >+ <div className="flex w-full min-w-0 items-center gap-0.5">+ <button+ type="button"+ onClick={onOpenInTraceView}+ className="group 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"+ >+ <span className="bg-background relative z-[1] flex shrink-0 rounded-full">+ {renderFilterIcon("TOOL")}+ </span>+ <span+ className="min-w-0 truncate text-xs font-normal group-hover:underline"+ title={name}+ >+ {name}+ </span>+ </button>+ <button+ type="button"+ className="text-muted-foreground hover:text-foreground shrink-0 rounded-sm p-0.5 transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none"+ aria-expanded={isExpanded}+ aria-label={`${isExpanded ? "Collapse" : "Expand"} ${name}`}+ onClick={() => onExpandedChange(!isExpanded)}+ >+ <ChevronDown+ className={cn(+ "h-3.5 w-3.5 transition-transform",+ !isExpanded && "-rotate-90",+ )}+ aria-hidden="true"+ />+ </button>+ <span className="ml-auto flex shrink-0 items-center gap-2">+ {latency !== null ? (+ <span className="text-muted-foreground font-mono text-[11px]">+ {formatIntervalSeconds(latency)}+ </span>+ ) : null}+ <time className="text-muted-foreground font-mono text-[10px]">+ {startTime.toLocaleTimeString()}+ </time>+ {observation?.name && actions ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ className="text-muted-foreground hover:text-foreground shrink-0"+ aria-label={`Actions for ${observation.name ?? observation.id}`}+ >+ <MoreHorizontal className="h-3.5 w-3.5" aria-hidden="true" />+ </Button>+ </DropdownMenuTrigger>+ <SessionObservationActionsMenuContent+ observation={observation}+ actions={actions}+ />+ </DropdownMenu>+ ) : !observation ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <span+ className="text-muted-foreground/50 flex h-6 w-6 shrink-0 items-center justify-center"+ role="img"+ aria-label="Actions available on parent observation"+ >+ <MoreHorizontal className="h-3.5 w-3.5" aria-hidden="true" />+ </span>+ </TooltipTrigger>+ <TooltipContent side="top">+ Actions are available on the parent observation+ </TooltipContent>+ </Tooltip>+ ) : null}+ </span>+ </div>+ {isExpanded ? (+ <div className="flex min-w-0 flex-col gap-3 pl-[22px]">+ {hasPreviewValue(input) ? (+ <div className="relative flex min-w-0 flex-col gap-1">+ <span className="text-muted-foreground font-mono text-[10px] font-bold uppercase">+ Input{inputTruncated ? " (truncated)" : ""}+ </span>+ <pre className="bg-muted/30 max-h-48 overflow-auto rounded-md border p-3 font-mono text-xs break-all whitespace-pre-wrap">+ {toPreviewText(input)}+ </pre>+ {!hasPreviewValue(output) ? <SessionTimelineRailEnd /> : null}+ </div>+ ) : null}+ {hasPreviewValue(output) ? (+ <div className="relative flex min-w-0 flex-col gap-1">+ <span className="text-muted-foreground font-mono text-[10px] font-bold uppercase">+ Output{outputTruncated ? " (truncated)" : ""}+ </span>+ <pre className="bg-muted/30 max-h-48 overflow-auto rounded-md border p-3 font-mono text-xs break-all whitespace-pre-wrap">+ {toPreviewText(output)}+ </pre>+ <SessionTimelineRailEnd />+ </div>+ ) : null}+ {!hasPreviewValue(input) && !hasPreviewValue(output) ? (+ <div className="relative">+ <span className="text-muted-foreground text-xs">+ No input or output+ </span>+ <SessionTimelineRailEnd />+ </div>+ ) : null}+ </div>+ ) : null}+ </section>+ );+}++function SessionTimelineConversationObservation({+ observation,+ parsed,+ processedMessages,+ phase,+ onOpenInTraceView,+ actions,+}: {+ observation: SessionObservation;+ parsed: ParsedSessionTimelineObservation | null;+ processedMessages: PreparedSessionTimelineMessages;+ phase: "complete" | "start" | "end";+ onOpenInTraceView: () => void;+ actions?: SessionObservationActions;+}) {+ const isTruncated = observation.inputTruncated || observation.outputTruncated;+ const visibleMessages = processedMessages.messages;+ const hasTimelineContent =+ parsed?.type === "loaded" &&+ parsed.messages.some((message) =>+ message.parts.some((part) => part.type !== "tool-result"),+ );+ const hasNoConversationalContent =+ !isTruncated &&+ parsed?.type === "loaded" &&+ visibleMessages.length === 0 &&+ (parsed.messages.length === 0 || hasTimelineContent);+ const hasObservationBody =+ isTruncated || parsed?.type === "error" || visibleMessages.length > 0;+ const showHeader = phase !== "end";+ const showNonMessageBody = phase !== "end";++ return (+ <section+ data-session-observation-id={showHeader ? observation.id : undefined}+ className={cn(+ "flex scroll-mt-16 flex-col",+ hasObservationBody ? "gap-4 py-2" : "py-1",+ )}+ >+ {showHeader ? (+ <div className="flex w-full min-w-0 items-center gap-0.5">+ <button+ type="button"+ onClick={onOpenInTraceView}+ className="group 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"+ >+ <span className="bg-background relative z-[1] flex shrink-0 rounded-full">+ {renderFilterIcon(observation.type ?? "EVENT")}+ </span>+ <span+ className="min-w-0 truncate text-xs font-normal group-hover:underline"+ title={observation.name ?? observation.id}+ >+ {observation.name ?? observation.id}+ </span>+ </button>+ <span className="ml-auto flex shrink-0 items-center gap-2">+ {isTruncated ? (+ <span+ className="bg-muted text-muted-foreground shrink-0 rounded-md p-1"+ role="img"+ aria-label="Content truncated"+ title="Content truncated"+ >+ <FileWarning className="h-3 w-3" aria-hidden="true" />+ </span>+ ) : null}+ {hasNoConversationalContent ? (+ <span+ className="bg-muted text-muted-foreground shrink-0 rounded-md p-1"+ role="img"+ aria-label="No conversational content"+ title="No conversational content"+ >+ <MessageSquareOff className="h-3 w-3" aria-hidden="true" />+ </span>+ ) : null}+ {observation.metadataTruncated ? (+ <span+ className="bg-muted text-muted-foreground shrink-0 rounded-md p-1"+ role="img"+ aria-label="Metadata omitted because it is too large"+ title="Metadata omitted because it is too large"+ >+ <FileWarning className="h-3 w-3" aria-hidden="true" />+ </span>+ ) : null}+ {observation.latency !== null && observation.type !== "EVENT" ? (+ <span className="text-muted-foreground font-mono text-[11px]">+ {formatIntervalSeconds(observation.latency)}+ </span>+ ) : null}+ <time className="text-muted-foreground font-mono text-[10px]">+ {observation.startTime.toLocaleTimeString()}+ </time>+ {actions ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ className="text-muted-foreground hover:text-foreground shrink-0"+ aria-label={`Actions for ${observation.name ?? observation.id}`}+ >+ <MoreHorizontal+ className="h-3.5 w-3.5"+ aria-hidden="true"+ />+ </Button>+ </DropdownMenuTrigger>+ <SessionObservationActionsMenuContent+ observation={observation}+ actions={actions}+ />+ </DropdownMenu>+ ) : null}+ </span>+ </div>+ ) : null}+ <div className="flex min-w-0 flex-col gap-5 pl-[22px]">+ {isTruncated ? (+ <TruncatedObservation observation={observation} phase={phase} />+ ) : showNonMessageBody && parsed?.type === "error" ? (+ <div className="border-destructive/40 bg-destructive/5 flex items-center justify-between gap-3 rounded-lg border p-3">+ <span className="text-destructive text-xs">+ This observation could not be parsed.+ </span>+ <Button variant="outline" size="sm" onClick={onOpenInTraceView}>+ Open trace+ </Button>+ </div>+ ) : visibleMessages.length > 0 ? (+ visibleMessages.map((message, index) => {+ const messageContent =+ message.role === "system" ? (+ <SessionTimelineSystemMessage+ parts={message.parts}+ senderName={message.senderName}+ />+ ) : (+ <SessionTimelineContentMessage+ role={message.role}+ parts={message.parts}+ senderName={message.senderName}+ />+ );++ return (+ <div+ key={`${message.id ?? `${message.source}-${message.role}`}-${index}`}+ className="relative"+ >+ {messageContent}+ {phase !== "start" && index === visibleMessages.length - 1 ? (+ <SessionTimelineRailEnd />+ ) : null}+ </div>+ );+ })+ ) : null}+ </div>+ </section>+ );+}++function SessionTimelineObservation({+ observation,+ parsed,+ processedMessages,+ phase,+ isToolExpanded,+ onToolExpandedChange,+ onOpenInTraceView,+ actions,+}: {+ observation: SessionObservation;+ parsed: ParsedSessionTimelineObservation | null;+ processedMessages: PreparedSessionTimelineMessages;+ phase: "complete" | "start" | "end";+ isToolExpanded: boolean;+ onToolExpandedChange: (isExpanded: boolean) => void;+ onOpenInTraceView: () => void;+ actions?: SessionObservationActions;+}) {+ if (observation.type === "TOOL") {+ return (+ <SessionTimelineToolRow+ id={observation.id}+ name={observation.name ?? observation.id}+ startTime={observation.startTime}+ latency={observation.latency}+ input={observation.input}+ output={observation.output}+ inputTruncated={observation.inputTruncated}+ outputTruncated={observation.outputTruncated}+ isExpanded={isToolExpanded}+ onExpandedChange={onToolExpandedChange}+ onOpenInTraceView={onOpenInTraceView}+ observation={observation}+ actions={actions}+ />+ );+ }++ return (+ <SessionTimelineConversationObservation+ observation={observation}+ parsed={parsed}+ processedMessages={processedMessages}+ phase={phase}+ onOpenInTraceView={onOpenInTraceView}+ actions={actions}+ />+ );+}++function LoadedSessionConversationTimeline({+ observations,+ onOpenObservation,+ observationActions,+ scrollTarget,+}: {+ observations: readonly PreparedSessionTimelineItem<SessionObservation>[];+ onOpenObservation: (observationId: string) => void;+ observationActions?: SessionObservationActions;+ scrollTarget: { observationId: string; requestId: number } | null;+}) {+ const [collapseState, setCollapseState] = useState(() => ({+ scrollRequestId: null as number | null,+ observationIds: new Set(+ observations.flatMap(({ observation, phase, ancestorObservationIds }) => {+ if (phase !== "start") return [];+ if (ancestorObservationIds.length > 0) return [observation.id];+ if (+ hasPreviewValue(observation.input) ||+ hasPreviewValue(observation.output)+ ) {+ return [observation.id];+ }+ return [];+ }),+ ),+ }));+ const [expandedToolObservationIds, setExpandedToolObservationIds] = useState(+ () => new Set<string>(),+ );+ let collapsedObservationIds = collapseState.observationIds;+ if (+ scrollTarget &&+ scrollTarget.requestId !== collapseState.scrollRequestId+ ) {+ const target = observations.find(+ ({ observation }) => observation.id === scrollTarget.observationId,+ );+ const observationIds = new Set(collapseState.observationIds);+ target?.ancestorObservationIds.forEach((id) => observationIds.delete(id));+ collapsedObservationIds = observationIds;+ setCollapseState({+ scrollRequestId: scrollTarget.requestId,+ observationIds,+ });+ }++ return (+ <TooltipProvider>+ <div className="flex flex-col gap-1">+ {observations.map((item) => {+ const {+ observation,+ parsed,+ processedMessages,+ phase,+ ancestorObservationIds,+ nestedObservationCounts,+ } = item;+ if (+ ancestorObservationIds.some((ancestorId) =>+ collapsedObservationIds.has(ancestorId),+ )+ ) {+ return null;+ }++ const isToolStart =+ item.type === "observation" &&+ observation.type === "TOOL" &&+ phase === "start";+ const isEmptyEnd =+ item.type === "observation" &&+ phase === "end" &&+ processedMessages.messages.length === 0 &&+ !(+ observation.outputTruncated && hasPreviewValue(observation.output)+ );+ const hasNestedObservations =+ Object.keys(nestedObservationCounts).length > 0;+ const isCollapsed = collapsedObservationIds.has(observation.id);+ const itemId = item.type === "tool" ? item.id : observation.id;+ const isToolExpanded = expandedToolObservationIds.has(itemId);+ const hasChatBubbles =+ item.type === "observation" &&+ observation.type !== "TOOL" &&+ (observation.inputTruncated || observation.outputTruncated+ ? (phase !== "end" && hasPreviewValue(observation.input)) ||+ (phase !== "start" && hasPreviewValue(observation.output))+ : processedMessages.messages.length > 0);++ const depth = ancestorObservationIds.length;++ return (+ <div+ key={+ item.type === "tool" ? item.id : `${observation.id}-${phase}`+ }+ data-session-observation-depth={depth}+ className="relative"+ style={{ paddingLeft: `${depth * 24}px` }}+ >+ {ancestorObservationIds.map((ancestorId, ancestorDepth) => (+ <span+ key={ancestorId}+ data-session-observation-rail-depth={ancestorDepth}+ className="bg-border pointer-events-none absolute -top-1 -bottom-1 w-px"+ style={{ left: `${ancestorDepth * 24 + 7}px` }}+ aria-hidden="true"+ />+ ))}+ {(phase === "start" && !isToolStart) ||+ (phase === "complete" && (hasChatBubbles || isToolExpanded)) ? (+ <span+ data-session-observation-rail-depth={depth}+ className={cn(+ "bg-border pointer-events-none absolute top-[22px] w-px",+ phase === "start" ? "-bottom-1" : "bottom-0",+ )}+ style={{ left: `${depth * 24 + 7}px` }}+ aria-hidden="true"+ />+ ) : null}+ {phase === "end" ? (+ <span+ data-session-observation-rail-depth={depth}+ className="bg-border pointer-events-none absolute -top-1 bottom-0 w-px"+ style={{ left: `${depth * 24 + 7}px` }}+ aria-hidden="true"+ />+ ) : null}+ {item.type === "tool" ? (+ <SessionTimelineToolRow+ id={item.id}+ name={item.toolCall.toolName}+ startTime={observation.startTime}+ latency={null}+ input={item.toolCall.input}+ output={undefined}+ isExpanded={isToolExpanded}+ onExpandedChange={(isExpanded) =>+ setExpandedToolObservationIds((current) => {+ const next = new Set(current);+ if (isExpanded) next.add(itemId);+ else next.delete(itemId);+ return next;+ })+ }+ onOpenInTraceView={() => onOpenObservation(observation.id)}+ />+ ) : !isToolStart && !isEmptyEnd ? (+ <SessionTimelineObservation+ observation={observation}+ parsed={parsed}+ processedMessages={processedMessages}+ phase={phase}+ isToolExpanded={isToolExpanded}+ onToolExpandedChange={(isExpanded) =>+ setExpandedToolObservationIds((current) => {+ const next = new Set(current);+ if (isExpanded) next.add(itemId);+ else next.delete(itemId);+ return next;+ })+ }+ onOpenInTraceView={() => onOpenObservation(observation.id)}+ actions={observationActions}+ />+ ) : null}+ {phase === "start" && hasNestedObservations ? (+ <div className={cn("relative", isCollapsed ? "h-7" : "h-0")}>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ className="bg-background text-muted-foreground hover:text-foreground absolute top-5 z-[1] -translate-x-1/2 -translate-y-1/2 rounded-full"+ style={{ left: "7.5px" }}+ aria-expanded={!isCollapsed}+ aria-label={`${isCollapsed ? "Show" : "Hide"} ${formatNestedObservationCounts(nestedObservationCounts)}`}+ onClick={() =>+ setCollapseState((current) => {+ const observationIds = new Set(+ current.observationIds,+ );+ if (isCollapsed) {+ observationIds.delete(observation.id);+ } else observationIds.add(observation.id);+ return { ...current, observationIds };+ })+ }+ >+ {isCollapsed ? (+ <ChevronsUpDown+ className="h-3 w-3"+ aria-hidden="true"+ />+ ) : (+ <ChevronsDownUp+ className="h-3 w-3"+ aria-hidden="true"+ />+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent side="right">+ {isCollapsed ? "Show" : "Hide"}{" "}+ {formatNestedObservationCounts(nestedObservationCounts)}+ </TooltipContent>+ </Tooltip>+ </div>+ ) : null}+ </div>+ );+ })}+ </div>+ </TooltipProvider>+ );+}++export function SessionConversationTimelineTrace({+ trace,+ turnNumber,+ state,+ onOpenTrace,+ onOpenObservation,+ observationActions,+ scrollTarget,+}: {+ trace: EventSessionTrace;+ turnNumber: number;+ state: PreparedSessionConversationTimelineTraceState;+ onOpenTrace: () => void;+ onOpenObservation: (observationId: string) => void;+ observationActions?: SessionObservationActions;+ scrollTarget: { observationId: string; requestId: number } | null;+}) {+ return (+ <div+ className="px-4 pb-14 sm:px-6 lg:px-10"+ data-session-trace-id={trace.id}+ >+ <div className="mb-6 flex items-center gap-4 pt-5">+ <button+ type="button"+ className="text-muted-foreground hover:text-foreground ph-no-capture flex shrink-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 w-4 shrink-0 items-center justify-center rounded-sm border font-mono text-[10px]">+ {turnNumber}+ </span>+ <span>trace · {trace.id}</span>+ </button>+ <div className="border-border min-w-0 flex-1 border-t border-dashed" />+ </div>++ {state.type === "loading" ? (+ <div+ role="status"+ aria-label="Loading conversation"+ className="flex flex-col gap-1"+ >+ {[+ {+ nameWidth: "w-36",+ messages: [+ { alignment: "end", height: "h-16", width: "w-3/5" },+ { alignment: "start", height: "h-24", width: "w-4/5" },+ ],+ },+ { nameWidth: "w-24", messages: [] },+ {+ nameWidth: "w-44",+ messages: [+ { alignment: "start", height: "h-20", width: "w-2/3" },+ ],+ },+ ].map((observation, observationIndex) => (+ <div+ key={observationIndex}+ className={cn(+ "flex flex-col py-2",+ observation.messages.length > 0 && "gap-4",+ )}+ >+ <div className="flex w-full min-w-0 items-center gap-2">+ <Skeleton className="h-4 w-4 shrink-0 rounded-sm" />+ <Skeleton className={cn("h-3", observation.nameWidth)} />+ <span className="ml-auto flex shrink-0 items-center gap-2">+ <Skeleton className="h-3 w-9" />+ <Skeleton className="h-3 w-16" />+ </span>+ </div>+ {observation.messages.length > 0 ? (+ <div className="flex flex-col gap-5">+ {observation.messages.map((message, messageIndex) => (+ <div+ key={messageIndex}+ className={cn(+ "flex w-full",+ message.alignment === "end"+ ? "justify-end"+ : "justify-start",+ )}+ >+ <Skeleton+ className={cn(+ "max-w-[min(85%,48rem)] rounded-2xl",+ message.height,+ message.width,+ )}+ />+ </div>+ ))}+ </div>+ ) : null}+ </div>+ ))}+ </div>+ ) : state.type === "error" ? (+ <div className="border-destructive/40 bg-destructive/5 text-foreground rounded-lg border p-4 text-xs">+ Failed to load observations.+ </div>+ ) : state.type === "empty" ? (+ <div className="text-muted-foreground rounded-lg border border-dashed p-4 text-xs">+ {state.message}+ </div>+ ) : (+ <LoadedSessionConversationTimeline+ key={state.observations+ .map(({ observation, phase }) => `${observation.id}:${phase}`)+ .join("\0")}+ observations={state.observations}+ onOpenObservation={onOpenObservation}+ observationActions={observationActions}+ scrollTarget={scrollTarget}+ />+ )}+ </div>+ );+}diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineCollapsiblePart/SessionTimelineCollapsiblePart.tsx b/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineCollapsiblePart/SessionTimelineCollapsiblePart.tsxnew file mode 100644index 0000000000..38c53c6908--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineCollapsiblePart/SessionTimelineCollapsiblePart.tsx@@ -0,0 +1,84 @@+import React, { useState } from "react";+import { Check, ChevronDown, X } from "lucide-react";++import { cn } from "@/src/utils/tailwind";++export function SessionTimelineCollapsiblePart({+ label,+ icon: Icon,+ status,+ variant,+ alignment,+ children,+}: {+ label: string;+ icon?: React.ComponentType<{ className?: string }>;+ status?: "success" | "error";+ variant: "plain" | "card";+ alignment: "start" | "center" | "row";+ children: React.ReactNode;+}) {+ const [isExpanded, setIsExpanded] = useState(false);++ return (+ <div+ className={cn(+ "overflow-hidden",+ (alignment === "center" || alignment === "row") && "w-full",+ variant === "card" &&+ "border-border bg-background/80 w-fit max-w-full rounded-md border px-2",+ )}+ >+ <div className={cn(alignment === "row" && "flex items-center gap-4")}>+ <button+ type="button"+ className={cn(+ "flex max-w-full items-center gap-1.5 py-1 text-left font-mono text-xs transition-colors hover:opacity-80",+ alignment === "row" ? "text-muted-foreground" : "text-foreground",+ alignment === "center" && "mx-auto",+ alignment === "start" ? "font-bold" : "font-normal",+ )}+ aria-expanded={isExpanded}+ onClick={() => setIsExpanded((current) => !current)}+ >+ {Icon ? <Icon className="h-3 w-3 shrink-0" /> : null}+ <span className="truncate" title={label}>+ {label}+ </span>+ {status === "success" ? (+ <Check className="h-3 w-3 shrink-0" aria-label="Succeeded" />+ ) : status === "error" ? (+ <X+ className="text-destructive h-3 w-3 shrink-0"+ aria-label="Failed"+ />+ ) : null}+ <ChevronDown+ className={cn(+ "h-3 w-3 shrink-0 transition-transform",+ !isExpanded && "-rotate-90",+ )}+ aria-hidden="true"+ />+ </button>+ {alignment === "row" ? (+ <div className="border-border min-w-0 flex-1 border-t border-dashed" />+ ) : null}+ </div>+ {isExpanded ? (+ <div+ className={cn(+ "py-2",+ alignment === "center"+ ? "mx-auto w-fit max-w-full"+ : alignment === "start"+ ? "border-border ml-1.5 border-l pl-4"+ : "w-full",+ )}+ >+ {children}+ </div>+ ) : null}+ </div>+ );+}diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsx b/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsxnew file mode 100644index 0000000000..28b8874153--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsx@@ -0,0 +1,208 @@+import preview from "@/.storybook/preview";+import { expect, userEvent, within } from "storybook/test";++import { SessionTimelineContentMessage } from "@/src/features/sessions/SessionConversationTimeline/components/SessionTimelineContentMessage/SessionTimelineContentMessage";++const meta = preview.meta({+ component: SessionTimelineContentMessage,+ args: { senderName: undefined },+ parameters: { layout: "padded", a11y: { test: "error" } },+});++export default meta;++export const Assistant = meta.story({+ args: {+ role: "assistant",+ parts: [+ {+ type: "text",+ text: "The normalized parser preserves **markdown**, structured data, and provider-independent message roles.",+ },+ ],+ },+});++export const NamedUser = meta.story({+ args: {+ role: "user",+ senderName: "Customer",+ parts: [+ {+ type: "text",+ text: "Find the latest documentation and summarize the relevant section.",+ },+ ],+ },+});++export const Tool = meta.story({+ args: {+ role: "tool",+ parts: [{ type: "text", text: "Tool response" }],+ },+});++export const StructuredData = meta.story({+ args: {+ role: "tool",+ parts: [+ { type: "data", name: "confidence", value: 0.9 },+ { type: "custom", kind: "citation", value: 7 },+ ],+ },+});++export const Reasoning = meta.story({+ args: {+ role: "assistant",+ parts: [+ {+ type: "reasoning",+ content: {+ kind: "text",+ text: "I should compare the observation payloads before answering.",+ },+ },+ { type: "text", text: "Here is the result." },+ ],+ },+});++export const ReasoningData = meta.story({+ args: {+ role: "assistant",+ parts: [+ {+ type: "reasoning",+ content: {+ kind: "data",+ value: { checks: ["source available", "answer supported"] },+ },+ },+ { type: "text", text: "The answer is supported by the source." },+ ],+ },+});++export const RedactedReasoning = meta.story({+ args: {+ role: "assistant",+ parts: [+ {+ type: "reasoning",+ content: { kind: "redacted", data: "redacted-provider-payload" },+ },+ { type: "text", text: "Here is the result." },+ ],+ },+});++export const EncryptedReasoning = meta.story({+ args: {+ role: "assistant",+ parts: [+ {+ type: "reasoning",+ content: { kind: "encrypted", data: "encrypted-provider-payload" },+ },+ { type: "text", text: "Here is the result." },+ ],+ },+});++export const EmbeddedImages = meta.story({+ args: {+ role: "user",+ parts: [+ {+ type: "text",+ text: "Here are a landscape image and a square image.",+ },+ {+ type: "file",+ filename: "product-overview.jpg",+ mediaType: "image/jpeg",+ content: { kind: "url", url: "/assets/v4-beta-intro.jpg" },+ },+ {+ type: "file",+ filename: "app-icon.png",+ mediaType: "image/png",+ content: { kind: "url", url: "/icon256.png" },+ },+ ],+ },+});++export const FileAttachment = meta.story({+ name: "(Test) File Attachment Layout",+ args: {+ role: "user",+ parts: [+ { type: "text", text: "Here is the report from the inspection." },+ {+ type: "file",+ filename: "inspection-report.pdf",+ mediaType: "application/pdf",+ content: {+ kind: "url",+ url: "https://example.com/inspection-report.pdf",+ },+ },+ ],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const attachment = canvas+ .getByText("inspection-report.pdf")+ .closest(".bg-background");++ await expect(attachment).toHaveClass("w-fit", "max-w-full");+ await expect(attachment?.parentElement?.parentElement).toHaveClass(+ "bg-muted",+ );+ },+});++export const RenderSupportedParts = meta.story({+ name: "(Test) Renders Supported Parts",+ parameters: { a11y: { test: "off" } },+ args: {+ role: "tool",+ parts: [+ { type: "reasoning", content: { kind: "text", text: "Think" } },+ { type: "data", value: { confidence: 0.9 } },+ { type: "custom", kind: "citation", value: { id: "doc-1" } },+ ],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(canvas.getByText("Reasoning")).toBeInTheDocument();+ await expect(canvas.queryByText("Think")).not.toBeInTheDocument();++ await userEvent.click(canvas.getByRole("button", { name: "Reasoning" }));+ await expect(canvas.getByText("Think")).toBeVisible();+ await expect(canvasElement).toHaveTextContent("confidence");+ await expect(canvasElement).toHaveTextContent("citation");+ },+});++export const RejectUnsafeFileUrl = meta.story({+ name: "(Test) Rejects Unsafe File URL",+ parameters: { a11y: { test: "off" } },+ args: {+ role: "assistant",+ parts: [+ {+ type: "file",+ content: { kind: "url", url: "javascript:alert(1)" },+ },+ ],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(canvas.queryByRole("link")).not.toBeInTheDocument();+ await expect(canvasElement).toHaveTextContent("javascript:alert(1)");+ },+});diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsx b/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsxnew file mode 100644index 0000000000..764e3188b0--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsx@@ -0,0 +1,131 @@+import React from "react";+import { Bot, UserRound, Wrench } from "lucide-react";+import { type ReasoningPart } from "@langfuse/shared/src/utils/normalized-io";++import { type SessionTimelineConversationMessage } from "@/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages";+import { SessionTimelinePart } from "@/src/features/sessions/SessionConversationTimeline/components/SessionTimelinePart/SessionTimelinePart";+import { cn } from "@/src/utils/tailwind";++const rolePresentation = {+ user: {+ label: "User",+ icon: UserRound,+ wrapper: "justify-end",+ container: "bg-muted max-w-[min(85%,48rem)] rounded-2xl px-4 py-2.5",+ },+ assistant: {+ label: "Assistant",+ icon: Bot,+ wrapper: "justify-start",+ container: "bg-muted/50 max-w-[min(85%,48rem)] rounded-2xl px-4 py-2.5",+ },+ tool: {+ label: "Tool",+ icon: Wrench,+ wrapper: "justify-start",+ container: "w-full",+ },+} satisfies Record<+ Exclude<SessionTimelineConversationMessage["role"], "system">,+ {+ label: string;+ icon: React.ComponentType<{ className?: string }>;+ wrapper: string;+ container: string;+ }+>;++export function SessionTimelineContentMessage({+ role,+ parts,+ senderName,+}: {+ role: Exclude<SessionTimelineConversationMessage["role"], "system">;+ parts: SessionTimelineConversationMessage["parts"];+ senderName: SessionTimelineConversationMessage["senderName"];+}) {+ const presentation = rolePresentation[role];+ const Icon = presentation.icon;+ const showSender = Boolean(senderName && senderName !== presentation.label);+ type MessagePart = SessionTimelineConversationMessage["parts"][number];+ type ContentPart = Exclude<MessagePart, ReasoningPart>;+ const groups: Array<+ | { type: "reasoning"; parts: ReasoningPart[] }+ | { type: "content"; parts: ContentPart[] }+ > = [];++ for (const part of parts) {+ const previousGroup = groups.at(-1);+ if (part.type === "reasoning") {+ if (previousGroup?.type === "reasoning") {+ previousGroup.parts.push(part);+ } else {+ groups.push({ type: "reasoning", parts: [part] });+ }+ continue;+ }++ if (previousGroup?.type === "content") {+ previousGroup.parts.push(part);+ } else {+ groups.push({ type: "content", parts: [part] });+ }+ }++ const firstContentGroupIndex = groups.findIndex(+ (group) => group.type === "content",+ );++ return (+ <div className="ph-no-capture flex w-full flex-col gap-2">+ {groups.map((group, groupIndex) => {+ if (group.type === "reasoning") {+ return (+ <div+ key={`reasoning-${groupIndex}`}+ className="flex w-full flex-col gap-1"+ >+ {group.parts.map((part, partIndex) => (+ <SessionTimelinePart+ key={`${part.content.kind}-${partIndex}`}+ part={part}+ />+ ))}+ </div>+ );+ }++ return (+ <div+ key={`content-${groupIndex}`}+ className={cn("flex w-full", presentation.wrapper)}+ >+ <article+ className={cn("min-w-0 overflow-hidden", presentation.container)}+ >+ {showSender && groupIndex === firstContentGroupIndex ? (+ <div className="text-foreground mb-1 flex min-w-0 items-center gap-1.5 font-mono text-[11px]">+ <Icon className="h-3 w-3 shrink-0" />+ <span+ className="text-foreground truncate"+ title={senderName ?? presentation.label}+ >+ {senderName ?? presentation.label}+ </span>+ </div>+ ) : null}+ <div className="flex flex-col gap-2 text-sm leading-6">+ {group.parts.map((part, partIndex) => (+ <SessionTimelinePart+ key={`${part.type}-${partIndex}`}+ part={part}+ />+ ))}+ </div>+ </article>+ </div>+ );+ })}+ </div>+ );+}diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelinePart/SessionTimelinePart.tsx b/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelinePart/SessionTimelinePart.tsxnew file mode 100644index 0000000000..3f56b9fb50--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelinePart/SessionTimelinePart.tsx@@ -0,0 +1,147 @@+import { FileIcon } from "lucide-react";+import { assertUnreachable } from "@langfuse/shared";+import {+ type FilePart,+ type ReasoningPart,+} from "@langfuse/shared/src/utils/normalized-io";++import { type SessionTimelineConversationMessage } from "@/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages";+import { SessionTimelineCollapsiblePart } from "@/src/features/sessions/SessionConversationTimeline/components/SessionTimelineCollapsiblePart/SessionTimelineCollapsiblePart";+import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";+import { MarkdownView } from "@/src/components/ui/MarkdownViewer";+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { getSafeImageUrl, getSafeLinkUrl } from "@/src/components/ui/safe-url";++function SessionTimelineReasoning({ part }: { part: ReasoningPart }) {+ const content = part.content;++ if (content.kind === "text") {+ return (+ <SessionTimelineCollapsiblePart+ label="Reasoning"+ variant="plain"+ alignment="row"+ >+ <MarkdownView markdown={content.text} className="px-0 py-0" />+ </SessionTimelineCollapsiblePart>+ );+ }++ if (content.kind === "data") {+ return (+ <SessionTimelineCollapsiblePart+ label="Reasoning data"+ variant="plain"+ alignment="row"+ >+ <PrettyJsonView json={content.value} currentView="pretty" />+ </SessionTimelineCollapsiblePart>+ );+ }++ return (+ <SessionTimelineCollapsiblePart+ label={+ content.kind === "redacted"+ ? "Redacted reasoning"+ : "Encrypted reasoning"+ }+ variant="plain"+ alignment="row"+ >+ <pre className="text-muted-foreground overflow-hidden font-mono text-xs break-all whitespace-pre-wrap">+ {content.data}+ </pre>+ </SessionTimelineCollapsiblePart>+ );+}++function SessionTimelineFile({ part }: { part: FilePart }) {+ const source = part.providerMetadata?.source;+ const safeUrl =+ part.content.kind === "url" ? getSafeLinkUrl(part.content.url) : null;+ const safeImageUrl =+ part.content.kind === "url" && part.mediaType?.startsWith("image/")+ ? getSafeImageUrl(part.content.url)+ : null;+ const reference =+ part.content.kind === "reference" &&+ part.mediaType &&+ typeof source === "string"+ ? `@@@langfuseMedia:type=${part.mediaType}|id=${part.content.id}|source=${source}@@@`+ : undefined;++ return (+ <div className="border-border/70 bg-background flex w-fit max-w-full flex-col gap-2 rounded-md border p-3">+ <div className="text-muted-foreground flex items-center gap-2 text-xs font-bold">+ <FileIcon className="h-3.5 w-3.5" />+ {part.filename ?? part.mediaType ?? "File"}+ </div>+ {reference ? (+ <LangfuseMediaView mediaReferenceString={reference} variant="preview" />+ ) : safeImageUrl ? (+ <a href={safeImageUrl} target="_blank" rel="noreferrer">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={safeImageUrl}+ alt={part.filename ?? "Embedded image"}+ className="max-h-64 max-w-full rounded-md object-contain"+ />+ </a>+ ) : safeUrl ? (+ <a+ href={safeUrl}+ target="_blank"+ rel="noreferrer"+ className="text-primary min-w-0 truncate text-xs underline underline-offset-2"+ title={part.content.kind === "url" ? part.content.url : undefined}+ >+ {safeUrl}+ </a>+ ) : (+ <PrettyJsonView json={part} currentView="pretty" />+ )}+ </div>+ );+}++export function SessionTimelinePart({+ part,+}: {+ part: SessionTimelineConversationMessage["parts"][number];+}) {+ if (part.type === "text") {+ return (+ <div className="flex flex-col gap-1">+ {part.refusal ? (+ <span className="text-dark-red text-[11px] font-bold">Refusal</span>+ ) : null}+ <MarkdownView markdown={part.text} className="px-0 py-0" />+ </div>+ );+ }++ if (part.type === "reasoning") {+ return <SessionTimelineReasoning part={part} />;+ }++ if (part.type === "file") {+ return <SessionTimelineFile part={part} />;+ }++ if (part.type === "data") {+ return <PrettyJsonView json={part.value} currentView="pretty" />;+ }++ if (part.type === "custom") {+ return (+ <PrettyJsonView+ title={part.kind}+ json={part.value}+ currentView="pretty"+ />+ );+ }++ return assertUnreachable(part);+}diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.stories.tsx b/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.stories.tsxnew file mode 100644index 0000000000..15f2b35013--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.stories.tsx@@ -0,0 +1,47 @@+import preview from "@/.storybook/preview";+import { expect, userEvent, within } from "storybook/test";++import { SessionTimelineSystemMessage } from "@/src/features/sessions/SessionConversationTimeline/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage";++const systemPromptParts = [+ {+ type: "text" as const,+ text: "Answer using the product documentation and cite relevant sources.",+ },+];++const meta = preview.meta({+ component: SessionTimelineSystemMessage,+ args: { senderName: undefined },+ parameters: {+ layout: "padded",+ a11y: {+ test: "error",+ config: {+ rules: [{ id: "color-contrast", enabled: false }],+ },+ },+ },+});++export default meta;++export const SystemPrompt = meta.story({+ args: { parts: systemPromptParts },+});++export const ExpandSystemPrompt = meta.story({+ name: "(Test) Expands System Prompt",+ args: { parts: systemPromptParts },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const content = systemPromptParts[0].text;+ const trigger = canvas.getByRole("button", { name: "System prompt" });++ await expect(trigger).toHaveAttribute("aria-expanded", "false");+ await expect(canvas.queryByText(content)).not.toBeInTheDocument();+ await userEvent.click(trigger);+ await expect(trigger).toHaveAttribute("aria-expanded", "true");+ await expect(canvas.getByText(content)).toBeVisible();+ },+});diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.tsx b/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.tsxnew file mode 100644index 0000000000..d03f4641b1--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.tsx@@ -0,0 +1,27 @@+import { type SessionTimelineConversationMessage } from "@/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages";+import { SessionTimelineCollapsiblePart } from "@/src/features/sessions/SessionConversationTimeline/components/SessionTimelineCollapsiblePart/SessionTimelineCollapsiblePart";+import { SessionTimelinePart } from "@/src/features/sessions/SessionConversationTimeline/components/SessionTimelinePart/SessionTimelinePart";++export function SessionTimelineSystemMessage({+ parts,+ senderName,+}: {+ parts: SessionTimelineConversationMessage["parts"];+ senderName: SessionTimelineConversationMessage["senderName"];+}) {+ return (+ <div className="ph-no-capture flex w-full">+ <SessionTimelineCollapsiblePart+ label={senderName ?? "System prompt"}+ variant="plain"+ alignment="row"+ >+ <div className="text-muted-foreground flex flex-col gap-2 text-sm leading-6">+ {parts.map((part, index) => (+ <SessionTimelinePart key={`${part.type}-${index}`} part={part} />+ ))}+ </div>+ </SessionTimelineCollapsiblePart>+ </div>+ );+}diff --git a/web/src/features/sessions/SessionConversationTimeline/fns/deduplicateTimelineInput.ts b/web/src/features/sessions/SessionConversationTimeline/fns/deduplicateTimelineInput.tsnew file mode 100644index 0000000000..2e0a947187--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/fns/deduplicateTimelineInput.ts@@ -0,0 +1,32 @@+import { type NormalizedMessage } from "@langfuse/shared/src/utils/normalized-io";++import { getConversationEntries } from "@/src/features/sessions/SessionConversationTimeline/fns/getConversationEntries";+import { getHistoricalInputIndices } from "@/src/features/sessions/SessionConversationTimeline/fns/getHistoricalInputIndices";+import { type SessionTimelineConversationMessage } from "@/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages";++export function deduplicateTimelineInput(+ messages: SessionTimelineConversationMessage[],+ ancestorMessages: readonly NormalizedMessage[],+) {+ const currentInput = getConversationEntries(messages, "input");+ const ancestorInput = getConversationEntries(ancestorMessages, "input");+ const historicalInputIndices = getHistoricalInputIndices(+ ancestorInput,+ currentInput,+ );+ const historicalParts = new Set(+ currentInput+ .filter((_entry, index) => historicalInputIndices.has(index))+ .map((entry) => `${entry.messageIndex}:${entry.partIndex}`),+ );++ return messages.flatMap((message, messageIndex) => {+ if (message.source === "output") return [message];++ const parts = message.parts.filter(+ (_part, partIndex) =>+ !historicalParts.has(`${messageIndex}:${partIndex}`),+ );+ return parts.length > 0 ? [{ ...message, parts }] : [];+ });+}diff --git a/web/src/features/sessions/SessionConversationTimeline/fns/getConversationEntries.ts b/web/src/features/sessions/SessionConversationTimeline/fns/getConversationEntries.tsnew file mode 100644index 0000000000..11bb56b4ef--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/fns/getConversationEntries.ts@@ -0,0 +1,35 @@+import { type NormalizedMessage } from "@langfuse/shared/src/utils/normalized-io";++export type ConversationEntry = {+ key: string;+ messageIndex: number;+ partIndex: number;+};++export function getConversationEntries(+ messages: readonly NormalizedMessage[],+ source?: NormalizedMessage["source"],+) {+ const entries: ConversationEntry[] = [];++ messages.forEach((message, messageIndex) => {+ if (source && message.source !== source) return;++ message.parts.forEach((part, partIndex) => {+ if (part.type === "tool-call" || part.type === "tool-result") return;++ const { providerMetadata: _providerMetadata, ...semanticPart } = part;+ entries.push({+ key: JSON.stringify([+ message.role,+ message.senderName ?? null,+ semanticPart,+ ]),+ messageIndex,+ partIndex,+ });+ });+ });++ return entries;+}diff --git a/web/src/features/sessions/SessionConversationTimeline/fns/getHistoricalInputIndices.ts b/web/src/features/sessions/SessionConversationTimeline/fns/getHistoricalInputIndices.tsnew file mode 100644index 0000000000..b11ec330d0--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/fns/getHistoricalInputIndices.ts@@ -0,0 +1,25 @@+import { type ConversationEntry } from "@/src/features/sessions/SessionConversationTimeline/fns/getConversationEntries";++export function getHistoricalInputIndices(+ previousContext: ConversationEntry[],+ currentInput: ConversationEntry[],+) {+ const remainingOccurrencesByKey = new Map<string, number>();+ for (const previousEntry of previousContext) {+ remainingOccurrencesByKey.set(+ previousEntry.key,+ (remainingOccurrencesByKey.get(previousEntry.key) ?? 0) + 1,+ );+ }++ const historicalInputIndices = new Set<number>();+ currentInput.forEach((entry, index) => {+ const remainingOccurrences = remainingOccurrencesByKey.get(entry.key) ?? 0;+ if (remainingOccurrences === 0) return;++ historicalInputIndices.add(index);+ remainingOccurrencesByKey.set(entry.key, remainingOccurrences - 1);+ });++ return historicalInputIndices;+}diff --git a/web/src/features/sessions/SessionConversationTimeline/fns/getSemanticallyMatchedChildToolCalls.ts b/web/src/features/sessions/SessionConversationTimeline/fns/getSemanticallyMatchedChildToolCalls.tsnew file mode 100644index 0000000000..68867a529b--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/fns/getSemanticallyMatchedChildToolCalls.ts@@ -0,0 +1,80 @@+import { type ToolCallPart } from "@langfuse/shared/src/utils/normalized-io";++import {+ getToolObservationCallId,+ type ToolObservation,+} from "@/src/features/sessions/SessionConversationTimeline/fns/getToolObservationCallId";++const canonicalizeToolInput = (value: unknown): unknown => {+ let parsedValue = value;+ if (typeof value === "string") {+ try {+ parsedValue = JSON.parse(value) as unknown;+ } catch {+ return value;+ }+ }++ if (Array.isArray(parsedValue)) {+ return parsedValue.map(canonicalizeToolInput);+ }+ if (typeof parsedValue !== "object" || parsedValue === null) {+ return parsedValue;+ }++ return Object.fromEntries(+ Object.entries(parsedValue)+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([key, nestedValue]) => [key, canonicalizeToolInput(nestedValue)]),+ );+};++const getToolSemanticKey = (name: string | null | undefined, input: unknown) =>+ name ? JSON.stringify([name, canonicalizeToolInput(input)]) : null;++export function getSemanticallyMatchedChildToolCalls({+ rolledUpToolCalls,+ allToolCalls,+ childToolObservations,+}: {+ rolledUpToolCalls: readonly ToolCallPart[];+ allToolCalls: readonly ToolCallPart[];+ childToolObservations: readonly ToolObservation[];+}) {+ const emittedToolCallIds = new Set(+ allToolCalls.flatMap((toolCall) =>+ toolCall.toolCallId ? [toolCall.toolCallId] : [],+ ),+ );+ const unmatchedChildrenBySemanticKey = new Map<string, ToolObservation[]>();+ for (const observation of childToolObservations) {+ if (observation.type !== "TOOL") continue;+ const observationCallId = getToolObservationCallId(observation);+ if (observationCallId && emittedToolCallIds.has(observationCallId))+ continue;++ const semanticKey = getToolSemanticKey(observation.name, observation.input);+ if (!semanticKey) continue;+ const matchingChildren = unmatchedChildrenBySemanticKey.get(semanticKey);+ if (matchingChildren) matchingChildren.push(observation);+ else unmatchedChildrenBySemanticKey.set(semanticKey, [observation]);+ }++ const unmatchedCallsBySemanticKey = new Map<string, ToolCallPart[]>();+ for (const toolCall of rolledUpToolCalls) {+ const semanticKey = getToolSemanticKey(toolCall.toolName, toolCall.input);+ if (!semanticKey) continue;+ const matchingCalls = unmatchedCallsBySemanticKey.get(semanticKey);+ if (matchingCalls) matchingCalls.push(toolCall);+ else unmatchedCallsBySemanticKey.set(semanticKey, [toolCall]);+ }++ const matchedCalls = new Set<ToolCallPart>();+ for (const [semanticKey, calls] of unmatchedCallsBySemanticKey) {+ if (calls.length !== 1) continue;+ if (unmatchedChildrenBySemanticKey.get(semanticKey)?.length !== 1) continue;+ const matchingCall = calls[0];+ if (matchingCall) matchedCalls.add(matchingCall);+ }+ return matchedCalls;+}diff --git a/web/src/features/sessions/SessionConversationTimeline/fns/getStandaloneToolCallIds.clienttest.ts b/web/src/features/sessions/SessionConversationTimeline/fns/getStandaloneToolCallIds.clienttest.tsnew file mode 100644index 0000000000..255ffda18f--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/fns/getStandaloneToolCallIds.clienttest.ts@@ -0,0 +1,39 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";++import { getStandaloneToolCallIds } from "@/src/features/sessions/SessionConversationTimeline/fns/getStandaloneToolCallIds";++describe("getStandaloneToolCallIds", () => {+ it("reads supported ids from non-truncated tool metadata", () => {+ expect(+ getStandaloneToolCallIds([+ {+ type: "TOOL",+ metadata: { toolCallId: "tool-call-id" },+ metadataTruncated: false,+ },+ {+ type: "TOOL",+ metadata: JSON.stringify({ callID: "call-id" }),+ metadataTruncated: false,+ },+ {+ type: "GENERATION",+ metadata: { toolCallId: "generation-id" },+ metadataTruncated: false,+ },+ {+ type: "TOOL",+ metadata: { toolCallId: "truncated-id" },+ metadataTruncated: true,+ },+ {+ type: "TOOL",+ metadata: "invalid JSON",+ metadataTruncated: false,+ },+ ]),+ ).toEqual(new Set(["tool-call-id", "call-id"]));+ });+});diff --git a/web/src/features/sessions/SessionConversationTimeline/fns/getStandaloneToolCallIds.ts b/web/src/features/sessions/SessionConversationTimeline/fns/getStandaloneToolCallIds.tsnew file mode 100644index 0000000000..b638b59a84--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/fns/getStandaloneToolCallIds.ts@@ -0,0 +1,18 @@+import {+ getToolObservationCallId,+ type ToolObservation,+} from "@/src/features/sessions/SessionConversationTimeline/fns/getToolObservationCallId";++export function getStandaloneToolCallIds(+ observations: readonly ToolObservation[],+) {+ const toolCallIds = new Set<string>();++ for (const observation of observations) {+ if (observation.type !== "TOOL") continue;+ const toolCallId = getToolObservationCallId(observation);+ if (toolCallId) toolCallIds.add(toolCallId);+ }++ return toolCallIds;+}diff --git a/web/src/features/sessions/SessionConversationTimeline/fns/getToolObservationCallId.ts b/web/src/features/sessions/SessionConversationTimeline/fns/getToolObservationCallId.tsnew file mode 100644index 0000000000..ab8e3629ff--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/fns/getToolObservationCallId.ts@@ -0,0 +1,33 @@+export type ToolObservation = {+ type?: string | null;+ name?: string | null;+ input?: unknown;+ metadata: unknown;+ metadataTruncated?: boolean;+};++export function getToolObservationCallId(observation: ToolObservation) {+ if (observation.metadataTruncated) return null;++ let metadataValue: unknown = observation.metadata;+ if (typeof metadataValue === "string") {+ try {+ metadataValue = JSON.parse(metadataValue) as unknown;+ } catch {+ return null;+ }+ }+ if (+ typeof metadataValue !== "object" ||+ metadataValue === null ||+ Array.isArray(metadataValue)+ ) {+ return null;+ }++ const metadata = metadataValue as Record<string, unknown>;+ const toolCallId = metadata.toolCallId ?? metadata.callID;+ return typeof toolCallId === "string" && toolCallId.length > 0+ ? toolCallId+ : null;+}diff --git a/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.clienttest.ts b/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.clienttest.tsnew file mode 100644index 0000000000..98409003cf--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.clienttest.ts@@ -0,0 +1,431 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";++import { prepareSessionTimelineObservations } from "@/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations";++const observation = (+ id: string,+ input: unknown,+ output: unknown,+ type = "GENERATION",+ startTime = new Date(0),+ traceId = "trace-1",+ parentObservationId: string | null = null,+ metadata: unknown = null,+ name = id,+) => ({+ id,+ name,+ traceId,+ parentObservationId,+ type,+ startTime,+ input,+ output,+ metadata,+ inputTruncated: false,+ outputTruncated: false,+ metadataTruncated: false,+});++describe("prepareSessionTimelineObservations", () => {+ it("reconciles cumulative generation history across session traces", () => {+ const prepared = prepareSessionTimelineObservations([+ observation(+ "generation-1",+ [+ { role: "system", content: "Instructions" },+ { role: "user", content: "User 1" },+ ],+ "Assistant 1",+ ),+ observation(+ "generation-2",+ [+ { role: "system", content: "Instructions" },+ { role: "user", content: "User 1" },+ { role: "assistant", content: "Assistant 1" },+ { role: "user", content: "User 2" },+ ],+ "Assistant 2",+ ),+ ]);++ expect(prepared[1]?.processedMessages.messages).toMatchObject([+ {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "User 2" }],+ },+ {+ role: "assistant",+ source: "output",+ parts: [{ type: "text", text: "Assistant 2" }],+ },+ ]);+ });++ it("preserves skipped and failed observations in their original positions", () => {+ const invalidInput = Object.defineProperty({}, "messages", {+ get() {+ throw new Error("Cannot parse input");+ },+ });+ const observations = [+ observation("generation-1", [], null),+ observation("tool", null, null, "TOOL"),+ observation("invalid", invalidInput, null),+ ];++ const prepared = prepareSessionTimelineObservations(observations);++ expect(prepared).toHaveLength(observations.length);+ expect(prepared.map(({ observation: item }) => item.id)).toEqual([+ "generation-1",+ "tool",+ "invalid",+ ]);+ expect(prepared[1]?.parsed).toBeNull();+ expect(prepared[1]?.processedMessages).toEqual({+ messages: [],+ });+ expect(prepared[2]?.parsed).toEqual({ type: "error" });+ expect(prepared[2]?.processedMessages).toEqual({+ messages: [],+ });+ });++ it("reconciles overlapping traces by observation timestamp", () => {+ const prepared = prepareSessionTimelineObservations([+ observation(+ "generation-1",+ [{ role: "user", content: "User 1" }],+ "Assistant 1",+ "GENERATION",+ new Date(0),+ ),+ observation(+ "generation-3",+ [+ { role: "user", content: "User 1" },+ { role: "assistant", content: "Assistant 1" },+ { role: "user", content: "User 2" },+ { role: "assistant", content: "Assistant 2" },+ { role: "user", content: "User 3" },+ ],+ "Assistant 3",+ "GENERATION",+ new Date(20),+ ),+ observation(+ "generation-2",+ [+ { role: "user", content: "User 1" },+ { role: "assistant", content: "Assistant 1" },+ { role: "user", content: "User 2" },+ ],+ "Assistant 2",+ "GENERATION",+ new Date(10),+ ),+ ]);++ expect(prepared[1]?.processedMessages.messages).toMatchObject([+ { role: "user", parts: [{ type: "text", text: "User 3" }] },+ { role: "assistant", parts: [{ type: "text", text: "Assistant 3" }] },+ ]);+ expect(prepared[2]?.processedMessages.messages).toMatchObject([+ { role: "user", parts: [{ type: "text", text: "User 2" }] },+ { role: "assistant", parts: [{ type: "text", text: "Assistant 2" }] },+ ]);+ });++ it("renders a parent output after its nested observations", () => {+ const prepared = prepareSessionTimelineObservations([+ observation(+ "parent",+ [{ role: "user", content: "Start" }],+ [{ role: "assistant", content: "Finished" }],+ "GENERATION",+ new Date(0),+ ),+ observation(+ "child",+ "Tool input",+ "Tool output",+ "TOOL",+ new Date(1),+ "trace-1",+ "parent",+ ),+ ]);++ expect(+ prepared.map(({ observation: item, phase }) => [item.id, phase]),+ ).toEqual([+ ["parent", "start"],+ ["child", "complete"],+ ["parent", "end"],+ ]);+ expect(prepared[0]?.processedMessages.messages).toMatchObject([+ { source: "input", parts: [{ type: "text", text: "Start" }] },+ ]);+ expect(prepared[2]?.processedMessages.messages).toMatchObject([+ { source: "output", parts: [{ type: "text", text: "Finished" }] },+ ]);+ });++ it("renders input inherited by nested observations only once", () => {+ const inheritedInput = [{ role: "user", content: "Build the dashboard" }];+ const prepared = prepareSessionTimelineObservations([+ observation("agent", inheritedInput, "Agent finished", "AGENT"),+ observation(+ "user-event",+ inheritedInput,+ null,+ "EVENT",+ new Date(1),+ "trace-1",+ "agent",+ ),+ observation(+ "generation",+ [...inheritedInput, { role: "user", content: "Use compact density" }],+ "Generation finished",+ "GENERATION",+ new Date(2),+ "trace-1",+ "agent",+ ),+ ]);++ const visibleText = prepared.flatMap(({ processedMessages }) =>+ processedMessages.messages.flatMap((message) =>+ message.parts.flatMap((part) =>+ part.type === "text" ? [part.text] : [],+ ),+ ),+ );+ expect(visibleText).toEqual([+ "Build the dashboard",+ "Use compact density",+ "Generation finished",+ "Agent finished",+ ]);+ });++ it("emits rolled-up tool calls as nested items before generation output", () => {+ const prepared = prepareSessionTimelineObservations([+ observation("generation", "Question", [+ {+ role: "assistant",+ content: "I will search.",+ tool_calls: [+ {+ id: "call-search",+ type: "function",+ function: {+ name: "search",+ arguments: JSON.stringify({ query: "dashboard" }),+ },+ },+ ],+ },+ ]),+ ]);++ expect(prepared.map((item) => item.type)).toEqual([+ "observation",+ "tool",+ "observation",+ ]);+ expect(prepared[0]).toMatchObject({+ type: "observation",+ phase: "start",+ ancestorObservationIds: [],+ nestedObservationCounts: { TOOL: 1 },+ processedMessages: {+ messages: [{ source: "input" }],+ },+ });+ expect(prepared[1]).toMatchObject({+ type: "tool",+ observation: { id: "generation" },+ phase: "complete",+ ancestorObservationIds: ["generation"],+ toolCall: {+ toolCallId: "call-search",+ toolName: "search",+ input: { query: "dashboard" },+ },+ });+ expect(prepared[2]).toMatchObject({+ type: "observation",+ phase: "end",+ ancestorObservationIds: [],+ nestedObservationCounts: { TOOL: 1 },+ processedMessages: {+ messages: [{ source: "output" }],+ },+ });+ });++ it("deduplicates a direct child tool by its unique name and input", () => {+ const prepared = prepareSessionTimelineObservations([+ observation("generation", null, [+ {+ role: "assistant",+ content: null,+ tool_calls: [+ {+ id: "generation-call-id",+ type: "function",+ function: {+ name: "search",+ arguments: JSON.stringify({+ query: "dashboard",+ limit: 5,+ }),+ },+ },+ ],+ },+ ]),+ observation(+ "tool-observation",+ JSON.stringify({ limit: 5, query: "dashboard" }),+ "Found dashboard",+ "TOOL",+ new Date(1),+ "trace-1",+ "generation",+ { callID: "different-call-id" },+ "search",+ ),+ ]);++ expect(+ prepared.filter(+ (item) => item.type === "tool" && item.observation.id === "generation",+ ),+ ).toEqual([]);+ });++ it("keeps a rolled-up tool call when semantic child matching is ambiguous", () => {+ const toolCall = {+ role: "assistant",+ content: null,+ tool_calls: [+ {+ id: "generation-call-id",+ type: "function",+ function: {+ name: "search",+ arguments: JSON.stringify({ query: "dashboard" }),+ },+ },+ ],+ };+ const prepared = prepareSessionTimelineObservations([+ observation("generation", null, [toolCall]),+ ...["first-tool", "second-tool"].map((id, index) =>+ observation(+ id,+ JSON.stringify({ query: "dashboard" }),+ "Found dashboard",+ "TOOL",+ new Date(index + 1),+ "trace-1",+ "generation",+ { callID: `${id}-call-id` },+ "search",+ ),+ ),+ ]);++ expect(+ prepared.filter(+ (item) => item.type === "tool" && item.observation.id === "generation",+ ),+ ).toHaveLength(1);+ });++ it("flattens multiple nesting levels while preserving sibling chronology", () => {+ const prepared = prepareSessionTimelineObservations([+ observation("root", "root input", "root output"),+ observation(+ "second-child",+ null,+ null,+ "EVENT",+ new Date(3),+ "trace-1",+ "root",+ ),+ observation(+ "first-child",+ "child input",+ "child output",+ "GENERATION",+ new Date(1),+ "trace-1",+ "root",+ ),+ observation(+ "grandchild",+ null,+ null,+ "TOOL",+ new Date(2),+ "trace-1",+ "first-child",+ ),+ ]);++ expect(+ prepared.map(({ observation: item, phase }) => `${item.id}:${phase}`),+ ).toEqual([+ "root:start",+ "first-child:start",+ "grandchild:complete",+ "first-child:end",+ "second-child:complete",+ "root:end",+ ]);+ expect(prepared[0]).toMatchObject({+ ancestorObservationIds: [],+ nestedObservationCounts: {+ GENERATION: 1,+ EVENT: 1,+ TOOL: 1,+ },+ });+ expect(prepared[1]).toMatchObject({+ ancestorObservationIds: ["root"],+ nestedObservationCounts: { TOOL: 1 },+ });+ expect(prepared[2]).toMatchObject({+ ancestorObservationIds: ["root", "first-child"],+ nestedObservationCounts: {},+ });+ });++ it("renders observations with filtered or missing parents as roots", () => {+ const prepared = prepareSessionTimelineObservations([+ observation(+ "orphan",+ null,+ null,+ "EVENT",+ new Date(0),+ "trace-1",+ "filtered-parent",+ ),+ ]);++ expect(prepared).toMatchObject([+ { observation: { id: "orphan" }, phase: "complete" },+ ]);+ });+});diff --git a/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.ts b/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.tsnew file mode 100644index 0000000000..e193b34e04--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.ts@@ -0,0 +1,361 @@+import {+ normalizeSpanIO,+ type NormalizedMessage,+ type ToolCallPart,+} from "@langfuse/shared/src/utils/normalized-io";++import { deduplicateTimelineInput } from "@/src/features/sessions/SessionConversationTimeline/fns/deduplicateTimelineInput";+import { getSemanticallyMatchedChildToolCalls } from "@/src/features/sessions/SessionConversationTimeline/fns/getSemanticallyMatchedChildToolCalls";+import { getStandaloneToolCallIds } from "@/src/features/sessions/SessionConversationTimeline/fns/getStandaloneToolCallIds";+import { processTimelineMessages } from "@/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages";++export type SessionTimelineObservation = {+ id: string;+ traceId: string | null;+ parentObservationId?: string | null;+ name?: string | null;+ type: string | null;+ startTime: Date;+ input: unknown;+ output: unknown;+ metadata: unknown;+ inputTruncated?: boolean;+ outputTruncated?: boolean;+ metadataTruncated?: boolean;+};++export type ParsedSessionTimelineObservation =+ | {+ type: "loaded";+ messages: ReturnType<typeof normalizeSpanIO>["messages"];+ }+ | { type: "error" };++type ProcessedSessionTimelineMessages = ReturnType<+ typeof processTimelineMessages+>[number];+export type PreparedSessionTimelineMessages = Pick<+ ProcessedSessionTimelineMessages,+ "messages"+>;++type PreparedSessionTimelineItemBase<+ Observation extends SessionTimelineObservation,+> = {+ observation: Observation;+ parsed: ParsedSessionTimelineObservation | null;+ processedMessages: PreparedSessionTimelineMessages;+ phase: "complete" | "start" | "end";+ ancestorObservationIds: readonly string[];+ nestedObservationCounts: Readonly<Record<string, number>>;+};++export type PreparedSessionTimelineItem<+ Observation extends SessionTimelineObservation,+> =+ | (PreparedSessionTimelineItemBase<Observation> & {+ type: "observation";+ })+ | (PreparedSessionTimelineItemBase<Observation> & {+ type: "tool";+ id: string;+ toolCall: ToolCallPart;+ });++const EMPTY_TOOL_CALL_IDS: ReadonlySet<string> = new Set();++export function prepareSessionTimelineObservations<+ Observation extends SessionTimelineObservation,+>(observations: readonly Observation[]) {+ const chronologicalObservations = observations+ .map((observation, originalIndex) => ({ observation, originalIndex }))+ .sort(+ (left, right) =>+ left.observation.startTime.getTime() -+ right.observation.startTime.getTime() ||+ left.originalIndex - right.originalIndex,+ );+ const parsedObservations = chronologicalObservations.map(+ ({ observation }) => {+ if (+ observation.type === "TOOL" ||+ observation.inputTruncated ||+ observation.outputTruncated+ ) {+ return { parsed: null, messages: null };+ }++ try {+ const messages = normalizeSpanIO({+ input: observation.input,+ output: observation.output,+ metadata: observation.metadataTruncated+ ? undefined+ : observation.metadata,+ }).messages;++ return {+ parsed: { type: "loaded", messages } as const,+ messages,+ };+ } catch {+ return {+ parsed: { type: "error" } as const,+ messages: null,+ };+ }+ },+ );+ const observationsByTraceId = new Map<string | null, Observation[]>();+ for (const observation of observations) {+ const traceObservations = observationsByTraceId.get(observation.traceId);+ if (traceObservations) traceObservations.push(observation);+ else observationsByTraceId.set(observation.traceId, [observation]);+ }+ const standaloneToolCallIdsByTraceId = new Map(+ Array.from(observationsByTraceId, ([traceId, traceObservations]) => [+ traceId,+ getStandaloneToolCallIds(traceObservations),+ ]),+ );++ const processedMessageGroups = processTimelineMessages({+ messageGroups: parsedObservations.map(({ messages }) => messages),+ reconcileHistory: chronologicalObservations.map(+ ({ observation }) => observation.type === "GENERATION",+ ),+ standaloneToolCallIdsByGroup: chronologicalObservations.map(+ ({ observation }) =>+ standaloneToolCallIdsByTraceId.get(observation.traceId) ??+ EMPTY_TOOL_CALL_IDS,+ ),+ });++ const preparedObservations = chronologicalObservations+ .map(({ observation, originalIndex }, index) => ({+ originalIndex,+ prepared: {+ observation,+ parsed: parsedObservations[index]?.parsed ?? null,+ processedMessages: processedMessageGroups[index] ?? {+ messages: [],+ rolledUpToolCalls: [],+ },+ },+ }))+ .sort((left, right) => left.originalIndex - right.originalIndex)+ .map(({ prepared }) => prepared);+ const observationKey = (observation: Observation) =>+ `${observation.traceId ?? ""}\0${observation.id}`;+ const preparedByKey = new Map(+ preparedObservations.map((prepared) => [+ observationKey(prepared.observation),+ prepared,+ ]),+ );+ const childrenByParentKey = new Map<string, typeof preparedObservations>();++ for (const prepared of preparedObservations) {+ const { observation } = prepared;+ if (!observation.parentObservationId) continue;++ const parentKey = `${observation.traceId ?? ""}\0${observation.parentObservationId}`;+ if (+ parentKey === observationKey(observation) ||+ !preparedByKey.has(parentKey)+ ) {+ continue;+ }++ const children = childrenByParentKey.get(parentKey);+ if (children) {+ children.push(prepared);+ children.sort(+ (left, right) =>+ left.observation.startTime.getTime() -+ right.observation.startTime.getTime(),+ );+ } else childrenByParentKey.set(parentKey, [prepared]);+ }++ for (const prepared of preparedObservations) {+ const childToolObservations = (+ childrenByParentKey.get(observationKey(prepared.observation)) ?? []+ ).map(({ observation }) => observation);+ if (childToolObservations.length === 0) continue;++ const allToolCalls =+ prepared.parsed?.type === "loaded"+ ? prepared.parsed.messages.flatMap((message) =>+ message.source === "output"+ ? message.parts.filter(+ (part): part is ToolCallPart => part.type === "tool-call",+ )+ : [],+ )+ : [];+ const matchedCalls = getSemanticallyMatchedChildToolCalls({+ rolledUpToolCalls: prepared.processedMessages.rolledUpToolCalls,+ allToolCalls,+ childToolObservations,+ });+ prepared.processedMessages.rolledUpToolCalls =+ prepared.processedMessages.rolledUpToolCalls.filter(+ (toolCall) => !matchedCalls.has(toolCall),+ );+ }++ const result: PreparedSessionTimelineItem<Observation>[] = [];+ const emitted = new Set<string>();+ const active = new Set<string>();+ const nestedObservationCountsByKey = new Map<+ string,+ Readonly<Record<string, number>>+ >();+ const getNestedObservationCounts = (+ key: string,+ activeKeys: ReadonlySet<string>,+ ) => {+ const cached = nestedObservationCountsByKey.get(key);+ if (cached) return cached;++ const nextActiveKeys = new Set(activeKeys).add(key);+ const counts: Record<string, number> = {};+ const rolledUpToolCallCount =+ preparedByKey.get(key)?.processedMessages.rolledUpToolCalls.length ?? 0;+ if (rolledUpToolCallCount > 0) counts.TOOL = rolledUpToolCallCount;++ for (const child of childrenByParentKey.get(key) ?? []) {+ const childKey = observationKey(child.observation);+ if (nextActiveKeys.has(childKey)) continue;++ const type = child.observation.type ?? "EVENT";+ counts[type] = (counts[type] ?? 0) + 1;+ for (const [nestedType, count] of Object.entries(+ getNestedObservationCounts(childKey, nextActiveKeys),+ )) {+ counts[nestedType] = (counts[nestedType] ?? 0) + count;+ }+ }+ nestedObservationCountsByKey.set(key, counts);+ return counts;+ };+ const appendTimelineItems = ({+ prepared,+ phase,+ messages,+ rolledUpToolCalls,+ ancestorObservationIds,+ nestedObservationCounts,+ }: {+ prepared: (typeof preparedObservations)[number];+ phase: "complete" | "start" | "end";+ messages: ProcessedSessionTimelineMessages["messages"];+ rolledUpToolCalls: readonly ToolCallPart[];+ ancestorObservationIds: readonly string[];+ nestedObservationCounts: Readonly<Record<string, number>>;+ }) => {+ result.push({+ type: "observation",+ observation: prepared.observation,+ parsed: prepared.parsed,+ processedMessages: { messages },+ phase,+ ancestorObservationIds,+ nestedObservationCounts,+ });+ rolledUpToolCalls.forEach((toolCall, index) => {+ result.push({+ type: "tool",+ id: `${prepared.observation.id}-tool-call-${toolCall.toolCallId ?? index}`,+ observation: prepared.observation,+ toolCall,+ parsed: null,+ processedMessages: { messages: [] },+ phase: "complete",+ ancestorObservationIds: ancestorObservationIds.concat(+ prepared.observation.id,+ ),+ nestedObservationCounts: {},+ });+ });+ };+ const emit = (+ prepared: (typeof preparedObservations)[number],+ ancestorMessages: readonly NormalizedMessage[],+ ancestorObservationIds: readonly string[],+ ) => {+ const key = observationKey(prepared.observation);+ if (emitted.has(key) || active.has(key)) return;++ const children = childrenByParentKey.get(key) ?? [];+ const messages = deduplicateTimelineInput(+ prepared.processedMessages.messages,+ ancestorMessages,+ );+ const contextualPrepared = {+ ...prepared,+ processedMessages: { ...prepared.processedMessages, messages },+ ancestorObservationIds,+ nestedObservationCounts: getNestedObservationCounts(key, new Set()),+ };+ const rolledUpToolCalls =+ contextualPrepared.processedMessages.rolledUpToolCalls;+ if (children.length === 0 && rolledUpToolCalls.length === 0) {+ emitted.add(key);+ appendTimelineItems({+ prepared,+ phase: "complete",+ messages: contextualPrepared.processedMessages.messages,+ rolledUpToolCalls: [],+ ancestorObservationIds,+ nestedObservationCounts: contextualPrepared.nestedObservationCounts,+ });+ return;+ }++ active.add(key);+ appendTimelineItems({+ prepared,+ phase: "start",+ messages: messages.filter((message) => message.source === "input"),+ rolledUpToolCalls,+ ancestorObservationIds,+ nestedObservationCounts: contextualPrepared.nestedObservationCounts,+ });+ const ownInputMessages =+ prepared.parsed?.type === "loaded"+ ? prepared.parsed.messages.filter(+ (message) => message.source === "input",+ )+ : messages.filter((message) => message.source === "input");+ const descendantContext = ancestorMessages.concat(ownInputMessages);+ const descendantObservationIds = ancestorObservationIds.concat(+ prepared.observation.id,+ );+ for (const child of children) {+ emit(child, descendantContext, descendantObservationIds);+ }+ appendTimelineItems({+ prepared,+ phase: "end",+ messages: messages.filter((message) => message.source === "output"),+ rolledUpToolCalls: [],+ ancestorObservationIds,+ nestedObservationCounts: contextualPrepared.nestedObservationCounts,+ });+ active.delete(key);+ emitted.add(key);+ };++ for (const prepared of preparedObservations) {+ const parentKey = prepared.observation.parentObservationId+ ? `${prepared.observation.traceId ?? ""}\0${prepared.observation.parentObservationId}`+ : null;+ if (parentKey && preparedByKey.has(parentKey)) continue;+ emit(prepared, [], []);+ }+ for (const prepared of preparedObservations) emit(prepared, [], []);++ return result;+}diff --git a/web/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages.clienttest.ts b/web/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages.clienttest.tsnew file mode 100644index 0000000000..d060b6086d--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages.clienttest.ts@@ -0,0 +1,359 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import { type NormalizedMessage } from "@langfuse/shared/src/utils/normalized-io";++import { processTimelineMessages } from "@/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages";++const messages = [+ {+ role: "system",+ source: "input",+ parts: [{ type: "text", text: "First instruction" }],+ },+ {+ role: "system",+ source: "input",+ parts: [{ type: "text", text: "Second instruction" }],+ },+ {+ role: "assistant",+ source: "input",+ parts: [+ {+ type: "tool-call",+ toolCallId: "historical-call",+ toolName: "historical_tool",+ input: { query: "old" },+ },+ ],+ },+ {+ role: "assistant",+ source: "output",+ parts: [+ { type: "text", text: "Calling tools" },+ {+ type: "tool-call",+ toolCallId: "standalone-call",+ toolName: "existing_tool",+ input: { query: "existing" },+ },+ {+ type: "tool-call",+ toolCallId: null,+ toolName: "rolled_up_tool",+ input: { query: "new" },+ },+ ],+ },+ {+ role: "tool",+ source: "input",+ parts: [+ {+ type: "tool-result",+ toolCallId: "historical-call",+ toolName: "historical_tool",+ output: { result: "old" },+ },+ ],+ },+] satisfies NormalizedMessage[];++describe("processTimelineMessages", () => {+ it("keeps tool parts out of messages and emits unmatched output calls", () => {+ const [result] = processTimelineMessages({+ messageGroups: [messages],+ reconcileHistory: [true],+ standaloneToolCallIdsByGroup: [new Set(["standalone-call"])],+ });++ expect(result?.messages).toEqual([+ {+ role: "system",+ source: "input",+ parts: [+ { type: "text", text: "First instruction" },+ { type: "text", text: "Second instruction" },+ ],+ },+ {+ role: "assistant",+ source: "output",+ parts: [{ type: "text", text: "Calling tools" }],+ },+ ]);+ expect(result?.rolledUpToolCalls).toEqual([+ {+ type: "tool-call",+ toolCallId: null,+ toolName: "rolled_up_tool",+ input: { query: "new" },+ },+ ]);+ });++ it("does not deduplicate calls without an id", () => {+ const [result] = processTimelineMessages({+ messageGroups: [messages],+ reconcileHistory: [true],+ standaloneToolCallIdsByGroup: [new Set()],+ });++ expect(result?.rolledUpToolCalls.map((part) => part.toolName)).toEqual([+ "existing_tool",+ "rolled_up_tool",+ ]);+ });++ it("deduplicates standalone tool calls only within their trace", () => {+ const toolCallMessage = {+ role: "assistant",+ source: "output",+ parts: [+ {+ type: "tool-call",+ toolCallId: "reused-call-id",+ toolName: "lookup",+ input: {},+ },+ ],+ } satisfies NormalizedMessage;+ const result = processTimelineMessages({+ messageGroups: [[toolCallMessage], [toolCallMessage]],+ reconcileHistory: [true, true],+ standaloneToolCallIdsByGroup: [new Set(["reused-call-id"]), new Set()],+ });++ expect(result[0]?.rolledUpToolCalls).toEqual([]);+ expect(result[1]?.rolledUpToolCalls).toHaveLength(1);+ });++ it("shows only the suffix added to cumulative conversation history", () => {+ const result = processTimelineMessages({+ messageGroups: [+ [+ {+ role: "system",+ source: "input",+ parts: [{ type: "text", text: "Instructions" }],+ },+ {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Initial request" }],+ },+ {+ id: "first-response-output",+ role: "assistant",+ source: "output",+ parts: [{ type: "text", text: "First response" }],+ },+ ],+ [+ {+ role: "system",+ source: "input",+ parts: [{ type: "text", text: "Instructions" }],+ },+ {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Initial request" }],+ },+ {+ id: "first-response-replayed",+ role: "assistant",+ source: "input",+ parts: [{ type: "text", text: "First response" }],+ },+ {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Follow-up request" }],+ },+ {+ role: "assistant",+ source: "output",+ parts: [{ type: "text", text: "Second response" }],+ },+ ],+ ] satisfies NormalizedMessage[][],+ reconcileHistory: [true, true],+ standaloneToolCallIdsByGroup: [new Set(), new Set()],+ });++ expect(result[1]?.messages).toEqual([+ {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Follow-up request" }],+ },+ {+ role: "assistant",+ source: "output",+ parts: [{ type: "text", text: "Second response" }],+ },+ ]);+ });++ it("preserves repeated new messages and identical new outputs", () => {+ const result = processTimelineMessages({+ messageGroups: [+ [+ {+ id: "request-1",+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Retry" }],+ },+ {+ id: "response-1",+ role: "assistant",+ source: "output",+ parts: [{ type: "text", text: "Done" }],+ },+ ],+ [+ {+ id: "request-1",+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Retry" }],+ },+ {+ id: "response-1",+ role: "assistant",+ source: "input",+ parts: [{ type: "text", text: "Done" }],+ },+ {+ id: "request-2",+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Retry" }],+ },+ {+ id: "response-2",+ role: "assistant",+ source: "output",+ parts: [{ type: "text", text: "Done" }],+ },+ ],+ ] satisfies NormalizedMessage[][],+ reconcileHistory: [true, true],+ standaloneToolCallIdsByGroup: [new Set(), new Set()],+ });++ expect(result[1]?.messages.map((message) => message.id)).toEqual([+ "request-2",+ "response-2",+ ]);+ });++ it("matches repeated history around newly inserted context", () => {+ const result = processTimelineMessages({+ messageGroups: [+ [+ {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Initial request" }],+ },+ {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Screen context" }],+ },+ ],+ [+ {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Initial request" }],+ },+ {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "New instruction" }],+ },+ {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Screen context" }],+ },+ ],+ ] satisfies NormalizedMessage[][],+ reconcileHistory: [true, true],+ standaloneToolCallIdsByGroup: [new Set(), new Set()],+ });++ expect(result[1]?.messages).toEqual([+ {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "New instruction" }],+ },+ ]);+ });++ it("matches historical parts when injected context changes their order", () => {+ const message = (text: string, source: "input" | "output") => ({+ role: "user" as const,+ source,+ parts: [{ type: "text" as const, text }],+ });+ const result = processTimelineMessages({+ messageGroups: [+ [message("A", "input"), message("B", "input"), message("C", "input")],+ [+ message("B", "input"),+ message("C", "input"),+ message("A", "input"),+ message("New", "input"),+ ],+ ],+ reconcileHistory: [true, true],+ standaloneToolCallIdsByGroup: [new Set(), new Set()],+ });++ expect(result[1]?.messages).toEqual([message("New", "input")]);+ });++ it("preserves history across groups that could not be parsed", () => {+ const repeatedMessage = {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Initial request" }],+ } satisfies NormalizedMessage;+ const result = processTimelineMessages({+ messageGroups: [[repeatedMessage], null, [repeatedMessage]],+ reconcileHistory: [true, false, true],+ standaloneToolCallIdsByGroup: [new Set(), new Set(), new Set()],+ });++ expect(result[2]?.messages).toEqual([]);+ });++ it("renders non-history groups without replacing generation history", () => {+ const repeatedMessage = {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Initial request" }],+ } satisfies NormalizedMessage;+ const eventMessage = {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Event payload" }],+ } satisfies NormalizedMessage;+ const result = processTimelineMessages({+ messageGroups: [[repeatedMessage], [eventMessage], [repeatedMessage]],+ reconcileHistory: [true, false, true],+ standaloneToolCallIdsByGroup: [new Set(), new Set(), new Set()],+ });++ expect(result[1]?.messages).toEqual([eventMessage]);+ expect(result[2]?.messages).toEqual([]);+ });+});diff --git a/web/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages.ts b/web/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages.tsnew file mode 100644index 0000000000..f413e8272d--- /dev/null+++ b/web/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages.ts@@ -0,0 +1,132 @@+import {+ type NormalizedMessage,+ type NormalizedMessagePart,+ type ToolCallPart,+} from "@langfuse/shared/src/utils/normalized-io";++import {+ getConversationEntries,+ type ConversationEntry,+} from "@/src/features/sessions/SessionConversationTimeline/fns/getConversationEntries";+import { getHistoricalInputIndices } from "@/src/features/sessions/SessionConversationTimeline/fns/getHistoricalInputIndices";++type ConversationPart = Exclude<+ NormalizedMessagePart,+ { type: "tool-call" | "tool-result" }+>;++export type SessionTimelineConversationMessage = Omit<+ NormalizedMessage,+ "parts"+> & {+ parts: ConversationPart[];+};++function getVisibleMessages({+ messages,+ currentInput,+ historicalInputIndices,+}: {+ messages: NormalizedMessage[];+ currentInput: ConversationEntry[];+ historicalInputIndices: ReadonlySet<number>;+}) {+ const historicalParts = new Set(+ currentInput+ .filter((_entry, index) => historicalInputIndices.has(index))+ .map((entry) => `${entry.messageIndex}:${entry.partIndex}`),+ );+ const visibleMessages: SessionTimelineConversationMessage[] = [];++ messages.forEach((message, messageIndex) => {+ const parts = message.parts.filter(+ (part, partIndex): part is ConversationPart => {+ if (part.type === "tool-call" || part.type === "tool-result") {+ return false;+ }+ if (message.source === "output") return true;++ return !historicalParts.has(`${messageIndex}:${partIndex}`);+ },+ );+ if (parts.length === 0) return;++ if (message.role !== "system") {+ visibleMessages.push({ ...message, parts });+ return;+ }++ const systemMessage = visibleMessages.find(+ (visibleMessage) => visibleMessage.role === "system",+ );+ if (systemMessage) {+ systemMessage.parts = systemMessage.parts.concat(parts);+ return;+ }++ visibleMessages.push({ ...message, parts });+ });++ return visibleMessages;+}++/**+ * Produces the newly added conversation and tool rows for each observation.+ * Input part occurrences already present in the previous conversation context+ * are omitted; outputs always remain visible and become the next history.+ */+export function processTimelineMessages({+ messageGroups,+ reconcileHistory,+ standaloneToolCallIdsByGroup,+}: {+ messageGroups: readonly (NormalizedMessage[] | null)[];+ reconcileHistory: readonly boolean[];+ standaloneToolCallIdsByGroup: readonly ReadonlySet<string>[];+}) {+ const processedGroups: Array<{+ messages: SessionTimelineConversationMessage[];+ rolledUpToolCalls: ToolCallPart[];+ }> = [];+ let previousContext: ConversationEntry[] = [];++ for (const [groupIndex, messages] of messageGroups.entries()) {+ if (messages === null) {+ processedGroups.push({ messages: [], rolledUpToolCalls: [] });+ continue;+ }++ const currentInput = getConversationEntries(messages, "input");+ const currentOutput = getConversationEntries(messages, "output");+ const shouldReconcileHistory = reconcileHistory[groupIndex] ?? false;+ const historicalInputIndices = shouldReconcileHistory+ ? getHistoricalInputIndices(previousContext, currentInput)+ : new Set<number>();+ const rolledUpToolCalls = messages.flatMap((message) =>+ message.source === "output"+ ? message.parts.filter(+ (part): part is ToolCallPart =>+ part.type === "tool-call" &&+ (!part.toolCallId ||+ !standaloneToolCallIdsByGroup[groupIndex]?.has(+ part.toolCallId,+ )),+ )+ : [],+ );++ processedGroups.push({+ messages: getVisibleMessages({+ messages,+ currentInput,+ historicalInputIndices,+ }),+ rolledUpToolCalls,+ });+ if (shouldReconcileHistory) {+ previousContext = currentInput.concat(currentOutput);+ }+ }++ return processedGroups;+}diff --git a/web/src/features/sessions/SessionPages.tsx b/web/src/features/sessions/SessionPages.tsxindex 7d38362c06..5cedd13508 100644--- a/web/src/features/sessions/SessionPages.tsx+++ b/web/src/features/sessions/SessionPages.tsx@@ -96,11 +96,8 @@ import { SessionDetailStoreProvider } from "@/src/features/sessions/SessionDetaiimport { SessionVirtualizedRow } from "@/src/features/sessions/SessionVirtualizedRow";import { createSessionDetailStore } from "@/src/features/sessions/sessionDetailStore";import { ModernSession } from "@/src/features/sessions/ModernSession";-import { ModernSessionHeader } from "@/src/features/sessions/ModernSessionHeader";-import { SessionMetadataJsonPathControl } from "@/src/features/sessions/SessionMetadataJsonPathControl";import { DropdownMenuTrigger } from "@/src/components/ui/dropdown-menu";import { ModernSessionHeaderActionsController } from "@/src/features/sessions/ModernSessionHeaderActionsController";-import { ModernSessionFilterControls } from "@/src/features/sessions/ModernSessionFilterControls";import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";import { useIsMobile } from "@/src/hooks/use-mobile";import { useStore } from "zustand";@@ -978,6 +975,9 @@ const LoadedSessionEventsPage: React.FC<{enableForAdmins: false,projectId,});+ const isSessionTimelineEnabled = useIsFeatureEnabled("sessionTimeline", {+ projectId,+ });const isMobile = useIsMobile();const parentRef = useRef<HTMLDivElement>(null);const webCalloutAction = useWebCalloutAction(@@ -1533,10 +1533,6 @@ const LoadedSessionEventsPage: React.FC<{getItemKey: (index) => traces?.[index]?.id ?? index,});const virtualItems = virtualizer.getVirtualItems();- const modernSessionTraces = isTracesSuccess- ? ({ state: "loaded", data: traces ?? [] } as const)- : ({ state: "loading" } as const);-return (<SessionDetailStoreProvider store={sessionDetailStore}><Page@@ -1690,12 +1686,17 @@ const LoadedSessionEventsPage: React.FC<{projectId={projectId}sessionId={sessionId}isPublic={session.public}- showCorrections={showCorrections}- showInlineToolCalls={showInlineToolCalls}- showSystemPrompt={showSystemPrompt}- onShowCorrectionsChange={setShowCorrectionsForSession}- onShowInlineToolCallsChange={setInlineToolCallsForSession}- onShowSystemPromptChange={setShowSystemPromptForSession}+ {...(!isSessionTimelineEnabled+ ? {+ showCorrections,+ showInlineToolCalls,+ showSystemPrompt,+ onShowCorrectionsChange: setShowCorrectionsForSession,+ onShowInlineToolCallsChange:+ setInlineToolCallsForSession,+ onShowSystemPromptChange: setShowSystemPromptForSession,+ }+ : {})}><DropdownMenuTrigger asChild><Button@@ -1817,7 +1818,7 @@ const LoadedSessionEventsPage: React.FC<{{webCalloutAction && (<WebCalloutButton action={webCalloutAction} layout="menu" />)}- {!isModernSessionEnabled ? (+ {!isModernSessionEnabled || !isSessionTimelineEnabled ? (<label className="hover:bg-accent flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5"><span className="text-sm">Show corrections</span><Switch@@ -1827,6 +1828,16 @@ const LoadedSessionEventsPage: React.FC<{/></label>) : null}+ {isModernSessionEnabled && !isSessionTimelineEnabled ? (+ <label className="hover:bg-accent flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5">+ <span className="text-sm">Show system prompt</span>+ <Switch+ checked={showSystemPrompt}+ onCheckedChange={setShowSystemPromptForSession}+ size="sm"+ />+ </label>+ ) : null}</>),}}@@ -1838,31 +1849,6 @@ const LoadedSessionEventsPage: React.FC<{: "flex h-full flex-col overflow-auto"}>- {isModernSessionEnabled ? (- <SessionMetadataJsonPathControl- key={`${projectId}:${sessionId}`}- projectId={projectId}- sessionId={sessionId}- traces={modernSessionTraces}- filterState={visibleFilterState}- >- {(metadataJsonPaths) => (- <ModernSessionHeader- projectId={projectId}- countTraces={session.countTraces}- traces={modernSessionTraces}- tokensIn={session.inputUsage}- tokensOut={session.outputUsage}- totalTokens={session.totalTokens}- totalCost={session.totalCost ?? 0}- environment={session.environment ?? null}- users={session.users ?? []}- metadataJsonPaths={metadataJsonPaths}- scores={session.scores}- />- )}- </SessionMetadataJsonPathControl>- ) : null}{!isModernSessionEnabled && hasSessionControls ? (<SessionControlsBarisMobile={isMobile && !isModernSessionEnabled}@@ -1987,44 +1973,40 @@ const LoadedSessionEventsPage: React.FC<{</div></div>) : (- <ModernSessionFilterControls+ <ModernSession+ isTimelineEnabled={isSessionTimelineEnabled}+ session={session}+ tracesState={+ isTracesSuccess+ ? { type: "loaded", traces: traces ?? [] }+ : { type: "loading" }+ }projectId={projectId}+ sessionId={sessionId}+ openPeek={openPeek}+ traceCommentCounts={asCommentCounts(traceCommentCounts.data)}filterState={visibleFilterState}- filterColumns={filterColumns}- filterColumnsWithCustomSelect={filterColumnsWithCustomSelect}- onChange={queryFilter.setFilterState}- viewControllers={viewControllers}- currentViewState={{- orderBy: null,- filters: queryFilter.filterState,- columnOrder,- columnVisibility,- searchQuery: "",+ filterMeasurementKey={visibleFilterMeasurementKey}+ viewLabel={viewLabel}+ showInlineToolCalls={showInlineToolCalls}+ showSystemPrompt={showSystemPrompt}+ filterControlsProps={{+ projectId,+ filterState: visibleFilterState,+ filterColumns,+ filterColumnsWithCustomSelect,+ onChange: queryFilter.setFilterState,+ viewControllers,+ currentViewState: {+ orderBy: null,+ filters: queryFilter.filterState,+ columnOrder,+ columnVisibility,+ searchQuery: "",+ },}}- >- {(sidebarFilterControls) => (- <ModernSession- tracesState={- isTracesSuccess- ? { type: "loaded", traces: traces ?? [] }- : { type: "loading" }- }- projectId={projectId}- sessionId={sessionId}- sessionMinTimestamp={session.minTimestamp}- sessionMaxTimestamp={session.maxTimestamp}- openPeek={openPeek}- traceCommentCounts={asCommentCounts(traceCommentCounts.data)}- filterState={visibleFilterState}- filterMeasurementKey={visibleFilterMeasurementKey}- viewLabel={viewLabel}- showInlineToolCalls={showInlineToolCalls}- showSystemPrompt={showSystemPrompt}- sidebarFilterControls={sidebarFilterControls}- onFilterObservationByName={filterObservationsByName}- />- )}- </ModernSessionFilterControls>+ onFilterObservationByName={filterObservationsByName}+ />)}</div><TablePeekViewTraceDetaildiff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.tsindex 9a88802800..33266e633d 100644--- a/web/src/server/api/routers/sessions.ts+++ b/web/src/server/api/routers/sessions.ts@@ -1049,7 +1049,7 @@ export const sessionRouter = createTRPCRouter({.input(z.object({projectId: z.string(),- sessionId: z.string(),+ sessionId: z.string().min(1),public: z.boolean(),}),)diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.tsindex cc431d2f64..49f8cfa1a9 100644--- a/web/src/server/api/trpc.ts+++ b/web/src/server/api/trpc.ts@@ -657,7 +657,7 @@ export const protectedGetEventsTraceProcedure = withOtelTracingProcedure*/const inputSessionSchema = z.object({- sessionId: z.string(),+ sessionId: z.string().min(1),projectId: z.string(),});