🪢 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): Make session view use trace transcripts (#18063)
Ben Bachem8b587645cf14
diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 5d168ce136..ae95ab53af 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -31,6 +31,18 @@"import": "./dist/src/server/index.js","require": "./dist/src/server/index.js"},+ "./src/server/transcript/ordering": {+ "import": "./dist/src/server/transcript/ordering.js",+ "require": "./dist/src/server/transcript/ordering.js"+ },+ "./src/server/transcript/transcript": {+ "import": "./dist/src/server/transcript/transcript.js",+ "require": "./dist/src/server/transcript/transcript.js"+ },+ "./src/server/transcript/types": {+ "import": "./dist/src/server/transcript/types.js",+ "require": "./dist/src/server/transcript/types.js"+ },"./src/server/clickhouse": {"import": "./dist/src/server/clickhouse/index.js","require": "./dist/src/server/clickhouse/index.js"diff --git a/web/src/__tests__/server/unit/events-transcript-access.servertest.ts b/web/src/__tests__/server/unit/events-transcript-access.servertest.tsnew file mode 100644index 0000000000..5aa34a9cca--- /dev/null+++ b/web/src/__tests__/server/unit/events-transcript-access.servertest.ts@@ -0,0 +1,136 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { type Session } from "next-auth";+import type * as SharedServer from "@langfuse/shared/src/server";+import { testFeatureFlags } from "@/src/__tests__/fixtures/feature-flags";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import { env } from "@/src/env.mjs";+import {+ getFeaturePreviewOptOutFlag,+ parseFlagsWithOrganizationDefaults,+} from "@/src/features/feature-flags/server";++const mocks = vi.hoisted(() => ({+ getObservationsForTraceFromEventsTable: vi.fn(async () => ({+ observations: [],+ totalCount: 0,+ })),+}));++vi.mock("@langfuse/shared/src/server", async (importOriginal) => ({+ ...(await importOriginal<typeof SharedServer>()),+ getObservationsForTraceFromEventsTable:+ mocks.getObservationsForTraceFromEventsTable,+ getTraceByIdFromEventsTable: vi.fn(async () => ({+ id: "trace-id",+ projectId: "project-id",+ timestamp: new Date("2026-01-01"),+ public: false,+ sessionId: null,+ input: null,+ output: null,+ })),+}));++describe("events.transcriptByTraceId preview access", () => {+ const originalExperimentalFeatures =+ env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES;+ const originalWriteMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;+ beforeEach(() => {+ mocks.getObservationsForTraceFromEventsTable.mockClear();+ Object.assign(env, {+ LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES: "false",+ LANGFUSE_MIGRATION_V4_WRITE_MODE: "events_only",+ });+ });++ afterEach(() => {+ Object.assign(env, {+ LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES: originalExperimentalFeatures,+ LANGFUSE_MIGRATION_V4_WRITE_MODE: originalWriteMode,+ });+ });++ it.each([+ {+ name: "user preview",+ flags: ["modernSession", "sessionTimeline"],+ defaults: [],+ allowed: true,+ },+ { name: "disabled preview", flags: [], defaults: [], allowed: false },+ {+ name: "organization default",+ flags: [],+ defaults: ["modernSession", "sessionTimeline"],+ allowed: true,+ },+ {+ name: "user opt-out",+ flags: [getFeaturePreviewOptOutFlag("sessionTimeline")],+ defaults: ["modernSession", "sessionTimeline"],+ allowed: false,+ },+ ])("respects $name", async ({ flags, defaults, allowed }) => {+ const session = {+ expires: "1",+ user: {+ id: "user-id",+ name: "Test User",+ admin: false,+ canCreateOrganizations: true,+ featureFlags: testFeatureFlags(),+ organizations: [+ {+ id: "org-id",+ name: "Test Organization",+ role: "MEMBER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,+ featureFlags: parseFlagsWithOrganizationDefaults(flags, defaults, {+ email: "[email protected]",+ v4BetaEnabled: true,+ }),+ projects: [+ {+ id: "project-id",+ name: "Test Project",+ role: "MEMBER",+ retentionDays: 30,+ deletedAt: null,+ hasTraces: false,+ metadata: {},+ createdAt: new Date().toISOString(),+ },+ ],+ },+ ],+ },+ environment: {+ enableExperimentalFeatures: false,+ selfHostedInstancePlan: null,+ },+ } satisfies Session;+ const caller = appRouter.createCaller(+ createInnerTRPCContext({ session, headers: {} }),+ );+ const result = caller.events.transcriptByTraceId({+ projectId: "project-id",+ traceId: "trace-id",+ });+ if (!allowed) {+ await expect(result).rejects.toMatchObject({ code: "FORBIDDEN" });+ expect(+ mocks.getObservationsForTraceFromEventsTable,+ ).not.toHaveBeenCalled();+ return;+ }+ await expect(result).resolves.toEqual({ transcript: null, cutoff: false });+ expect(mocks.getObservationsForTraceFromEventsTable).toHaveBeenCalledTimes(+ 2,+ );+ });+});diff --git a/web/src/__tests__/server/unit/loadTraceTranscript.servertest.ts b/web/src/__tests__/server/unit/loadTraceTranscript.servertest.tsnew file mode 100644index 0000000000..a644e76f17--- /dev/null+++ b/web/src/__tests__/server/unit/loadTraceTranscript.servertest.ts@@ -0,0 +1,183 @@+import { beforeEach, expect, it, vi } from "vitest";+import type { Transcript } from "@langfuse/shared/src/server";+import { loadTraceTranscript } from "@/src/features/events/server/loadTraceTranscript";++const mocks = vi.hoisted(() => ({ assemble: vi.fn(), observations: vi.fn() }));+vi.mock("@langfuse/shared/src/server", () => ({+ MAX_OBSERVATIONS_PER_TRACE: 10000,+ orderObservations: (observations: unknown[]) => observations,+ assembleTranscript: mocks.assemble,+ getObservationsForTraceFromEventsTable: mocks.observations,+}));+const trace = {+ projectId: "project",+ traceId: "trace",+ timestamp: new Date(0),+};+function fixture(+ names = ["search", "weather"],+ responses = ["weather", "search"],+) {+ const provenance = {+ traceId: "trace",+ startTime: new Date(0),+ endTime: null,+ };+ const transcript: Transcript = {+ threads: [+ {+ conversationHistory: [],+ currentTurn: {+ nestingLevel: 0,+ observations: [],+ messages: [+ {+ ...provenance,+ observationId: "generation",+ role: "assistant",+ source: "output",+ parts: names.map((toolName, index) => ({+ type: "tool-call",+ toolName,+ toolCallId: `call-${index}`,+ input: {},+ })),+ },+ ...responses.map((name, index) => ({+ ...provenance,+ observationId: `tool-${index}`,+ role: "tool" as const,+ source: "output" as const,+ parts: [{ type: "text" as const, text: name }],+ })),+ ],+ },+ },+ ],+ };+ mocks.assemble.mockReturnValue(transcript);+ mocks.observations.mockResolvedValue({+ observations: responses.map((name, index) => ({+ ...provenance,+ id: `tool-${index}`,+ type: "TOOL",+ name,+ parentObservationId: null,+ input: null,+ output: name,+ metadata: {},+ })),+ totalCount: responses.length,+ });+ return transcript;+}+beforeEach(() => vi.clearAllMocks());+it("opts into provenance-based reverse multi-call responses without mutating assembly", async () => {+ const original = fixture();+ const snapshot = structuredClone(original);+ const result = await loadTraceTranscript({+ ...trace,+ pairTextToolResponses: true,+ });+ expect(+ result.transcript?.threads[0]?.currentTurn.messages+ .slice(1)+ .map((m) => m.parts),+ ).toEqual([+ [+ {+ type: "tool-result",+ toolCallId: "call-1",+ toolName: "weather",+ output: "weather",+ },+ ],+ [+ {+ type: "tool-result",+ toolCallId: "call-0",+ toolName: "search",+ output: "search",+ },+ ],+ ]);+ expect(original).toEqual(snapshot);+ expect(result.transcript?.threads[0]?.currentTurn.messages[1]).toMatchObject({+ observationId: "tool-0",+ traceId: "trace",+ source: "output",+ startTime: new Date(0),+ endTime: null,+ });+ expect(mocks.observations).toHaveBeenCalledTimes(2);+});+it("leaves the default transcript unchanged", async () => {+ const original = fixture();+ expect((await loadTraceTranscript(trace)).transcript).toBe(original);+});+it.each([+ { names: ["search", "search"], responses: ["search"] },+ { names: ["search"], responses: ["search", "search"] },+])(+ "leaves ambiguous names and duplicate responses separate: %j",+ async ({ names, responses }) => {+ const original = fixture(names, responses);+ expect(+ (await loadTraceTranscript({ ...trace, pairTextToolResponses: true }))+ .transcript,+ ).toEqual(original);+ },+);+it("preserves explicit result precedence", async () => {+ const original = fixture(["search"], ["search"]);+ original.threads[0]!.currentTurn.messages.push({+ ...original.threads[0]!.currentTurn.messages[1]!,+ parts: [{ type: "tool-result", toolCallId: "call-0", output: "explicit" }],+ });+ expect(+ (await loadTraceTranscript({ ...trace, pairTextToolResponses: true }))+ .transcript,+ ).toEqual(original);+});+it("requires exact response trace provenance even for adjacent single calls", async () => {+ const original = fixture(["search"], ["search"]);+ original.threads[0]!.currentTurn.messages[1]!.traceId = "other-trace";+ expect(+ (await loadTraceTranscript({ ...trace, pairTextToolResponses: true }))+ .transcript,+ ).toEqual(original);+});+it.each(["missing-observation", "conflicting-name", "reused-id"])(+ "does not infer %s",+ async (scenario) => {+ const original = fixture(["search"], ["search"]);+ const messages = original.threads[0]!.currentTurn.messages;+ if (scenario === "missing-observation")+ messages[1]!.observationId = "missing";+ if (scenario === "conflicting-name") {+ const part = messages[0]!.parts[0]!;+ if (part.type === "tool-call") part.toolName = "weather";+ }+ if (scenario === "reused-id")+ messages[0]!.parts.push({ ...messages[0]!.parts[0]! });+ expect(+ (await loadTraceTranscript({ ...trace, pairTextToolResponses: true }))+ .transcript,+ ).toEqual(original);+ },+);+it("leaves history untouched when it shares current-turn message references", async () => {+ const original = fixture(["search"], ["search"]);+ original.threads[0]!.conversationHistory =+ original.threads[0]!.currentTurn.messages;+ const result = await loadTraceTranscript({+ ...trace,+ pairTextToolResponses: true,+ });+ expect(+ result.transcript?.threads[0]?.conversationHistory[1]?.parts[0]?.type,+ ).toBe("text");+ expect(+ result.transcript?.threads[0]?.currentTurn.messages[1]?.parts[0]?.type,+ ).toBe("tool-result");+});diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.tsindex 75e817f0e0..8cf07fb84b 100644--- a/web/src/features/events/server/eventsRouter.ts+++ b/web/src/features/events/server/eventsRouter.ts@@ -1,7 +1,10 @@import { type z, z as zodSchema } from "zod";import { TRPCError } from "@trpc/server";import { env } from "@/src/env.mjs";-import { hasInternalAccess } from "@/src/features/feature-flags/server";+import {+ getContextualFeatureFlags,+ hasInternalAccess,+} from "@/src/features/feature-flags/server";import {createTRPCRouter,protectedProjectProcedure,@@ -433,9 +436,8 @@ export const eventsRouter = createTRPCRouter({}),/*** Assemble the message transcript of a trace from its generations and tools,- * see `loadTraceTranscript`. Internal surface: Langfuse admins and- * deployments with experimental features enabled only, and only where the- * events tables are written.+ * see `loadTraceTranscript`. Available to internal users and Session Timeline+ * preview users, only where the events tables are written.*/transcriptByTraceId: protectedGetEventsTraceProcedure.input(@@ -443,10 +445,16 @@ export const eventsRouter = createTRPCRouter({projectId: zodSchema.string(),traceId: zodSchema.string(),timestamp: zodSchema.date().optional(),+ pairTextToolResponses: zodSchema.boolean().default(false),}),).query(async ({ input, ctx }) => {+ const isSessionTimelineEnabled =+ getContextualFeatureFlags(ctx.session?.user, {+ projectId: input.projectId,+ })?.sessionTimeline === true;if (+ !isSessionTimelineEnabled &&!hasInternalAccess({isAdmin: ctx.session?.user?.admin === true,isExperimentalFeaturesEnabled:@@ -455,7 +463,8 @@ export const eventsRouter = createTRPCRouter({) {throw new TRPCError({code: "FORBIDDEN",- message: "Transcripts are an internal preview.",+ message:+ "Transcripts require internal access or the Session Timeline preview.",});}if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "legacy") {@@ -484,6 +493,7 @@ export const eventsRouter = createTRPCRouter({projectId: input.projectId,traceId: input.traceId,timestamp,+ pairTextToolResponses: input.pairTextToolResponses,});},);diff --git a/web/src/features/events/server/loadTraceTranscript.ts b/web/src/features/events/server/loadTraceTranscript.tsindex 9fd78775eb..44be87d266 100644--- a/web/src/features/events/server/loadTraceTranscript.ts+++ b/web/src/features/events/server/loadTraceTranscript.ts@@ -5,6 +5,7 @@ import {orderObservations,type Transcript,} from "@langfuse/shared/src/server";+import type { ToolCallPart } from "@langfuse/shared/src/utils/normalized-io";/** Generations and tools whose I/O one transcript reads at most. */const MAX_TRANSCRIPT_OBSERVATIONS = 1_000;@@ -20,6 +21,12 @@ export async function loadTraceTranscript(trace: {traceId: string;/** Trace timestamp; observations from one hour before it onwards are read. */timestamp: Date;+ /**+ * For session rendering, convert text-only TOOL responses into ID-bearing+ * tool results when observation names uniquely identify their calls.+ * Ambiguous responses remain unchanged. Disabled by default.+ */+ pairTextToolResponses?: boolean;}): Promise<{transcript: Transcript | null;/** The trace has more observations than the transcript could read. */@@ -44,8 +51,112 @@ export async function loadTraceTranscript(trace: {if (withContent) return [withContent];return TRANSCRIPT_OBSERVATION_TYPES.has(o.type) ? [] : [o];});+ let transcript = assembleTranscript(orderObservations(observations));+ // TODO: Evaluate moving general pairing into shared transcript assembly once+ // it preserves resolved call identity for text-only tool responses.+ if (trace.pairTextToolResponses && transcript) {+ const observationsByTraceAndId = new Map<+ (typeof observations)[number]["traceId"],+ Map<string, (typeof observations)[number]>+ >();+ for (const observation of observations) {+ let byId = observationsByTraceAndId.get(observation.traceId);+ if (!byId) {+ byId = new Map();+ observationsByTraceAndId.set(observation.traceId, byId);+ }+ // Preserve the first match, as the previous array lookup did.+ if (!byId.has(observation.id)) byId.set(observation.id, observation);+ }+ transcript = {+ ...transcript,+ threads: transcript.threads.map((thread) => {+ const messages = thread.currentTurn.messages;+ const calls = messages.flatMap((message) =>+ message.parts.filter(+ (part): part is ToolCallPart => part.type === "tool-call",+ ),+ );+ const explicitIds = new Set(+ messages.flatMap((message) =>+ message.parts.flatMap((part) =>+ part.type === "tool-result" && part.toolCallId+ ? [part.toolCallId]+ : [],+ ),+ ),+ );+ const candidates = new Map<number, ToolCallPart>();+ let anchor: (typeof messages)[number] | undefined;+ for (const [index, message] of messages.entries()) {+ if (message.role !== "tool") {+ anchor =+ message.role === "assistant" && message.source === "output"+ ? message+ : undefined;+ continue;+ }+ if (+ message.source !== "output" ||+ !message.parts.length ||+ !message.parts.every((part) => part.type === "text")+ )+ continue;+ const observation = observationsByTraceAndId+ .get(message.traceId)+ ?.get(message.observationId);+ // Provenance must identify a TOOL; positional guessing cannot override it.+ if (observation?.type !== "TOOL" || !observation.name || !anchor)+ continue;+ const matches = anchor.parts.filter(+ (part): part is ToolCallPart =>+ part.type === "tool-call" && part.toolName === observation.name,+ );+ if (matches.length !== 1) continue;+ const call = matches[0]!;+ if (+ !call.toolCallId ||+ explicitIds.has(call.toolCallId) ||+ calls.filter((other) => other.toolCallId === call.toolCallId)+ .length !== 1+ )+ continue;+ candidates.set(index, call);+ }+ return {+ ...thread,+ currentTurn: {+ ...thread.currentTurn,+ messages: messages.map((message, index) => {+ const call = candidates.get(index);+ if (+ !call ||+ [...candidates.values()].filter(+ (other) => other.toolCallId === call.toolCallId,+ ).length !== 1+ )+ return message;+ return {+ ...message,+ parts: [+ {+ type: "tool-result" as const,+ toolCallId: call.toolCallId,+ toolName: call.toolName,+ output: message.parts+ .map((part) => (part.type === "text" ? part.text : ""))+ .join("\n"),+ },+ ],+ };+ }),+ },+ };+ }),+ };+ }return {- transcript: assembleTranscript(orderObservations(observations)),+ transcript,cutoff:structure.totalCount > MAX_OBSERVATIONS_PER_TRACE ||content.totalCount > MAX_TRANSCRIPT_OBSERVATIONS,diff --git a/web/src/features/feature-flags/server/index.ts b/web/src/features/feature-flags/server/index.tsindex fbb4dc26fd..3f049756ca 100644--- a/web/src/features/feature-flags/server/index.ts+++ b/web/src/features/feature-flags/server/index.ts@@ -17,6 +17,7 @@ export {setUserFeaturePreviewWithAuthorization,} from "@/src/features/feature-flags/server/organizationFeatureFlags";export {+ getContextualFeatureFlags,getFeaturePreviewOptOutFlag,hasInternalAccess,} from "@/src/features/feature-flags/utils";diff --git a/web/src/features/sessions/ConnectedModernSessionBodyTimeline.tsx b/web/src/features/sessions/ConnectedModernSessionBodyTimeline.tsxdeleted file mode 100644index b6ce9fea6e..0000000000--- a/web/src/features/sessions/ConnectedModernSessionBodyTimeline.tsx+++ /dev/null@@ -1,475 +0,0 @@-import { useEffect, useEffectEvent, useMemo, 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: "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 = useMemo(- () => new Map(traces.map((trace, index) => [trace.id, index] as const)),- [traces],- );- const activeChunkIndices = useMemo(() => {- 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);- }- }- return activeChunkIndices;- }, [- searchQuery,- loadedThroughChunkIndex,- traces.length,- visibleTraceIds,- traceIndexById,- ]);-- 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.sessionAll(- {- projectId,- sessionId,- 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"]["sessionAll"]["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[] = [];- const incompleteTimelineTraceIds = new Set<string>();- 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,- );- if (mayHaveMoreObservations) incompleteTimelineTraceIds.add(trace.id);- const observations = (() => {- if (isPending && !hasLoadedObservations) {- return undefined;- }- if (isError) {- return null;- }- if (mayHaveMoreObservations && !hasLoadedObservations) {- return undefined;- }- return 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 autoLoadMoreObservations = useEffectEvent(loadMoreObservations);-- useEffect(() => {- if (!hasMoreObservations || isLoadingMoreObservations) return;- autoLoadMoreObservations();- }, [hasMoreObservations, isLoadingMoreObservations]);-- 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 = (() => {- if (sidebarTrace?.observations === null) {- return null;- }- if (- sidebarTrace?.observations === undefined ||- incompleteTimelineTraceIds.has(trace.id)- ) {- return undefined;- }- return 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 session-review-stack:grid-rows-[minmax(7rem,9rem)_minmax(0,1fr)] session-review-stack:gap-x-0 relative grid min-h-0 flex-1 grid-rows-[minmax(10rem,13rem)_minmax(0,1fr)] gap-x-4 overflow-hidden @3xl/session-workspace:grid-cols-[clamp(200px,24cqw,296px)_minmax(0,1fr)] @3xl/session-workspace: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 session-review-stack:min-w-0 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}- onClearFilters={sidebarFilterControls.onClearFilters}- 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.tsxindex 50fe450080..867b51b1c0 100644--- a/web/src/features/sessions/ModernSession.clienttest.tsx+++ b/web/src/features/sessions/ModernSession.clienttest.tsx@@ -8,9 +8,12 @@ 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/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline",+ () => ({+ ConnectedModernSessionBodyTimeline: () => <div>Timeline body</div>,+ }),+);vi.mock("@/src/features/sessions/ModernSessionHeader", () => ({ModernSessionHeader: () => <div>Modern session header</div>,@@ -21,7 +24,7 @@ vi.mock("@/src/features/sessions/ModernSessionFilterControls", () => ({children,}: {children: (controls: never) => ReactNode;- }) => children({} as never),+ }) => <div data-testid="legacy-filter-controls">{children({} as never)}</div>,}));vi.mock("@/src/features/sessions/SessionMetadataJsonPathControl", () => ({@@ -100,6 +103,7 @@ describe("ModernSession", () => {expect(screen.getByText("Modern session header")).toBeInTheDocument();expect(screen.getByText("Legacy body")).toBeInTheDocument();+ expect(screen.getByTestId("legacy-filter-controls")).toBeInTheDocument();expect(screen.queryByText("Timeline body")).not.toBeInTheDocument();});@@ -108,6 +112,9 @@ describe("ModernSession", () => {expect(screen.getByText("Modern session header")).toBeInTheDocument();expect(screen.getByText("Timeline body")).toBeInTheDocument();+ expect(+ screen.queryByTestId("legacy-filter-controls"),+ ).not.toBeInTheDocument();expect(screen.queryByText("Legacy body")).not.toBeInTheDocument();});});diff --git a/web/src/features/sessions/ModernSession.tsx b/web/src/features/sessions/ModernSession.tsxindex 32746a7615..c246383584 100644--- a/web/src/features/sessions/ModernSession.tsx+++ b/web/src/features/sessions/ModernSession.tsx@@ -2,7 +2,7 @@ import { type ComponentProps } from "react";import { type FilterState } from "@langfuse/shared";import { ConnectedModernSessionBodyLegacy } from "@/src/features/sessions/ConnectedModernSessionBodyLegacy";-import { ConnectedModernSessionBodyTimeline } from "@/src/features/sessions/ConnectedModernSessionBodyTimeline";+import { ConnectedModernSessionBodyTimeline } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline";import { ModernSessionFilterControls } from "@/src/features/sessions/ModernSessionFilterControls";import { ModernSessionHeader } from "@/src/features/sessions/ModernSessionHeader";import { SessionReviewLeading } from "@/src/features/sessions/sessionReviewLeading";@@ -108,14 +108,16 @@ export function ModernSession({</SessionReviewLeading>)}</SessionMetadataJsonPathControl>- <ModernSessionFilterControls {...filterControlsProps}>- {(sidebarFilterControls) =>- isTimelineEnabled ? (- <ConnectedModernSessionBodyTimeline- {...sharedBodyProps}- sidebarFilterControls={sidebarFilterControls}- />- ) : (+ {isTimelineEnabled ? (+ <ConnectedModernSessionBodyTimeline+ tracesState={tracesState}+ projectId={projectId}+ sessionId={sessionId}+ openPeek={openPeek}+ />+ ) : (+ <ModernSessionFilterControls {...filterControlsProps}>+ {(sidebarFilterControls) => (<ConnectedModernSessionBodyLegacy{...sharedBodyProps}traceCommentCounts={traceCommentCounts}@@ -123,9 +125,9 @@ export function ModernSession({showSystemPrompt={showSystemPrompt}sidebarFilterControls={sidebarFilterControls}/>- )- }- </ModernSessionFilterControls>+ )}+ </ModernSessionFilterControls>+ )}</>);}diff --git a/web/src/features/sessions/ModernSessionSidebar.stories.tsx b/web/src/features/sessions/ModernSessionSidebar.stories.tsxindex 6c5d2fc9ed..ebbb5f2086 100644--- a/web/src/features/sessions/ModernSessionSidebar.stories.tsx+++ b/web/src/features/sessions/ModernSessionSidebar.stories.tsx@@ -283,7 +283,7 @@ function ModernSessionSidebarStory(const normalizedSearch = search.trim().toLowerCase();const visibleTraces = normalizedSearch- ? args.traces.flatMap((sidebarTrace) => {+ ? args.traces.flatMap<ModernSessionSidebarTrace>((sidebarTrace) => {const matchingObservations = sidebarTrace.observations?.filter((observation) =>(observation.name ?? "").toLowerCase().includes(normalizedSearch),@@ -494,7 +494,6 @@ export const TestSelectsFilteredTurnByStableNumber = meta.story({const canvas = within(canvasElement);await expect(canvas.getByText("3")).toBeInTheDocument();await expect(canvas.getByText("Matching observation")).toBeInTheDocument();- await expect(canvas.queryByText(/idle$/)).not.toBeInTheDocument();await userEvent.click(canvas.getByRole("button", { name: /Summarize findings/i }),@@ -514,7 +513,7 @@ export const TestSelectsObservation = meta.story({const canvas = within(canvasElement);await userEvent.click(- canvas.getByRole("button", { name: /^Search knowledge base 0.70s$/i }),+ await canvas.findByRole("button", { name: /^Search knowledge base\b/i }),);await expect(args.onSelect).toHaveBeenCalledWith(1, "tool-1");},diff --git a/web/src/features/sessions/ModernSessionSidebar.tsx b/web/src/features/sessions/ModernSessionSidebar.tsxindex b72f83ff8a..a3c437a7fa 100644--- a/web/src/features/sessions/ModernSessionSidebar.tsx+++ b/web/src/features/sessions/ModernSessionSidebar.tsx@@ -328,15 +328,10 @@ export function ModernSessionSidebar(state: "loaded";traces: ModernSessionSidebarTrace[];activeTraceId: string | undefined;- filterControls: ModernSessionSidebarFilterControls;search: string;onSearchChange: (search: string) => void;expandedTraceIds: ReadonlySet<string>;onToggleTraceExpanded: (traceId: string) => void;- onFilterObservationByName: (- name: string,- operator: "any of" | "none of",- ) => void;onSelect: (index: number, observationId?: string) => void;onVisibleTraceIdsChange: (traceIds: string[]) => void;hasMoreObservations: boolean;@@ -344,6 +339,11 @@ export function ModernSessionSidebar(observationLoadError: boolean;onLoadMoreObservations: () => void;onViewportUnderfilled?: () => void;+ filterControls: ModernSessionSidebarFilterControls;+ onFilterObservationByName: (+ name: string,+ operator: "any of" | "none of",+ ) => void;},) {const traces = props.state === "loaded" ? props.traces : EMPTY_TRACES;diff --git a/web/src/features/sessions/README.md b/web/src/features/sessions/README.mddeleted file mode 100644index 8e573317a3..0000000000--- a/web/src/features/sessions/README.md+++ /dev/null@@ -1,16 +0,0 @@-# Session review--`SessionPages` owns one keyed `TraceReviewPanelProvider` per project/session.-Header, trace-row, and timeline actions open the same persistent Comments or-Annotate editor. Query data stays in tRPC; draft state belongs to the mounted-editor and the shared review store.--`SessionReviewWorkspace` subscribes only to the active review mode. It measures-available space and lays out session content beside or above the review panel.-Its layout effects control the resizable-panel API and reveal review inside-the narrow workspace scrollport; changing layout-keeps the session and both editors mounted. Modern session minimap/feed grids-use the session column's container width.--Trace peek is a sibling outside the session review provider. Its review context-and mobile overlays remain independent of the underlying session.diff --git a/web/src/features/sessions/SessionConversationTimeline/ConnectedSessionConversationTimeline.tsx b/web/src/features/sessions/SessionConversationTimeline/ConnectedSessionConversationTimeline.tsxdeleted file mode 100644index e3c2bcf1f4..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/ConnectedSessionConversationTimeline.tsx+++ /dev/null@@ -1,308 +0,0 @@-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 { AnnotateDrawerController } from "@/src/features/scores";-import { CommentDrawerController } from "@/src/features/comments";-import { NewDatasetItemFromExistingObjectDialogController } from "@/src/features/datasets";-import { showErrorToast } from "@/src/features/notifications";-import { useHasProjectAccess } from "@/src/features/rbac";-import { api, sendAsPostOption, type RouterOutputs } from "@/src/utils/api";--const BATCH_IO_SIZE = 50;--type EventObservation =- RouterOutputs["events"]["sessionAll"]["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,- onClearFilters,- 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;- onClearFilters: () => void;- onFilterObservationByName: (- name: string,- operator: "any of" | "none of",- ) => void;- onLoadMoreObservations?: () => void;-}) {- const utils = api.useUtils();- const hasDatasetAccess = useHasProjectAccess({- projectId,- scope: "datasets:CUD",- });- 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,- },- {- ...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] || ioQueries[queryIndex].isPending,- )- ) {- return undefined;- }-- return observations.map((observation) => {- const io = ioByObservationKey.get(- getObservationKey(trace.id, observation.id),- );- return {- ...observation,- traceId: trace.id,- 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 emptyState =- filterState.length === 0- ? ({ type: "empty" } as const)- : ({- type: "filtered-empty",- viewLabel,- onClearFilters,- } as const);-- return (- <AnnotateDrawerController projectId={projectId}>- {({ disabled: annotateDisabled, openDrawer: openAnnotateDrawer }) => (- <CommentDrawerController projectId={projectId} mode="read-only">- {({ disabled: commentDisabled, openDrawer: openCommentDrawer }) => (- <NewDatasetItemFromExistingObjectDialogController- projectId={projectId}- >- {({ openDialog: openDatasetDialog }) => (- <SessionConversationTimeline- traces={timelineTraces}- filterMeasurementKey={filterMeasurementKey}- emptyState={emptyState}- onOpenTrace={(trace) => openPeek(trace.id, trace)}- onOpenObservation={(trace, observationId) =>- openPeek(trace.id, { ...trace, observationId })- }- controller={controller}- scrollTarget={scrollTarget}- observationActions={{- onFilterByName: onFilterObservationByName,- annotate: {- disabled: annotateDisabled,- onSelect: (observation) =>- openAnnotateDrawer({- scoreTarget: {- type: "trace",- traceId: observation.traceId,- observationId: observation.id,- },- analyticsData: {- type: "trace",- source: "SessionDetail",- isV4: true,- },- scoreMetadata: {- projectId,- environment: observation.environment,- },- }),- },- comment: {- disabled: commentDisabled,- onSelect: (observation) =>- openCommentDrawer({- type: "comments",- objectId: observation.id,- objectType: "OBSERVATION",- objectStartTime: observation.startTime,- }),- },- addToDataset: {- disabled: !hasDatasetAccess,- onSelect: async (observation) => {- try {- // Remove this fetch if the timeline starts loading full IO upfront.- const [fullObservation] =- await utils.events.batchIO.fetch({- projectId,- traceId: observation.traceId,- observations: [- {- id: observation.id,- traceId: observation.traceId,- },- ],- minStartTime: observation.startTime,- maxStartTime: observation.startTime,- truncated: false,- });- if (!fullObservation) throw new Error();-- openDatasetDialog({- traceId: observation.traceId,- observationId: observation.id,- input: fullObservation.input,- output: fullObservation.output,- metadata: fullObservation.metadata,- });- } catch {- showErrorToast(- "Failed to load observation",- "Could not fetch the observation's full I/O. Please try again.",- );- }- },- },- }}- onLoadMoreObservations={onLoadMoreObservations}- />- )}- </NewDatasetItemFromExistingObjectDialogController>- )}- </CommentDrawerController>- )}- </AnnotateDrawerController>- );-}diff --git a/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.tsx b/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.tsxdeleted file mode 100644index 6711007321..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.tsx+++ /dev/null@@ -1,320 +0,0 @@-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,- emptyState,- onOpenTrace,- onOpenObservation,- controller,- observationActions,- scrollTarget,- onLoadMoreObservations,-}: {- traces: readonly SessionConversationTimelineItem[];- filterMeasurementKey: string;- emptyState:- | { type: "empty" }- | {- type: "filtered-empty";- viewLabel: string | null;- onClearFilters: () => void;- };- 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 emptyState;-- return {- type: "loaded",- observations: preparedObservationGroups[traceIndex] ?? [],- };- },- ),- };- }, [emptyState, 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.tsxdeleted file mode 100644index ce72174989..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.clienttest.tsx+++ /dev/null@@ -1,215 +0,0 @@-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)),- observation("second-grandchild", "child", "TOOL", new Date(3)),-]);--const trace = {- id: "trace-1",- name: "Trace",- timestamp: new Date(0),- environment: "production",- userId: null,- observationCount: 4,- latencyMs: 1,- scores: [],-} satisfies TraceProps["trace"];--describe("SessionConversationTimelineTrace", () => {- it("clears filters from a filtered empty state", () => {- const onClearFilters = vi.fn();-- render(- <SessionConversationTimelineTrace- trace={trace}- turnNumber={1}- state={{- type: "filtered-empty",- viewLabel: null,- onClearFilters,- }}- onOpenTrace={vi.fn()}- onOpenObservation={vi.fn()}- scrollTarget={null}- />,- );-- fireEvent.click(screen.getByRole("button", { name: "Clear filters" }));-- expect(onClearFilters).toHaveBeenCalledOnce();- });-- 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 tools: grandchild and second-grandchild",- });- fireEvent.click(parentToggle);- expect(screen.queryByText("grandchild")).not.toBeInTheDocument();-- rerender(- <SessionConversationTimelineTrace- {...props}- scrollTarget={{ observationId: "grandchild", requestId: 2 }}- />,- );-- expect(screen.getByText("grandchild")).toBeInTheDocument();- });-- it("always shows a single nested tool without a collapse control", () => {- const loneToolObservations = prepareSessionTimelineObservations([- observation("parent", null, "AGENT", new Date(0)),- observation("tool", "parent", "TOOL", new Date(1)),- ]);-- render(- <SessionConversationTimelineTrace- trace={{ ...trace, observationCount: 2 }}- turnNumber={1}- state={{ type: "loaded", observations: loneToolObservations }}- onOpenTrace={vi.fn()}- onOpenObservation={vi.fn()}- scrollTarget={null}- />,- );-- expect(screen.getByText("tool")).toBeInTheDocument();- expect(- screen.queryByRole("button", { name: /tools: tool/i }),- ).not.toBeInTheDocument();- });-- it("shows a no-conversational-content marker with the correct accessible name", () => {- const emptyAgentTurn = prepareSessionTimelineObservations([- observation("agent-turn", null, "AGENT", new Date(0)),- ]);-- render(- <SessionConversationTimelineTrace- trace={{ ...trace, observationCount: 1 }}- turnNumber={1}- state={{ type: "loaded", observations: emptyAgentTurn }}- onOpenTrace={vi.fn()}- onOpenObservation={vi.fn()}- scrollTarget={null}- />,- );-- // The marker is rendered as an img role with the label as its accessible name.- // Floating-ui tooltip content is tested at the browser/integration level — jsdom's- // fireEvent.focus does not change document.activeElement so useFocus never opens.- expect(- screen.getByRole("img", { name: "No conversational content" }),- ).toBeInTheDocument();- });-- it("decodes Unicode escapes in truncated observation previews", () => {- const truncated = prepareSessionTimelineObservations([- {- ...observation("gen", null, "GENERATION", new Date(0)),- input: '{"text":"\\u4f60\\u597d"}',- output: "\\u4f60\\u597d",- inputTruncated: true,- outputTruncated: true,- },- ]);-- render(- <SessionConversationTimelineTrace- trace={{ ...trace, observationCount: 1 }}- turnNumber={1}- state={{ type: "loaded", observations: truncated }}- onOpenTrace={vi.fn()}- onOpenObservation={vi.fn()}- scrollTarget={null}- />,- );-- expect(screen.getAllByText(/你好/).length).toBeGreaterThan(0);- expect(screen.queryByText(/\\u4f60\\u597d/)).not.toBeInTheDocument();- });-- it("decodes Unicode escapes in full (non-truncated) timeline message text", () => {- // Modern timeline hydrates full I/O via sessionBatchIO without truncation- // flags; plain-string output still carries literal \uXXXX from storage.- const loaded = prepareSessionTimelineObservations([- {- ...observation("gen", null, "GENERATION", new Date(0)),- input: '[{"role":"user","content":"hi"}]',- output: "\\u4f60\\u597d world",- },- ]);-- render(- <SessionConversationTimelineTrace- trace={{ ...trace, observationCount: 1 }}- turnNumber={1}- state={{ type: "loaded", observations: loaded }}- onOpenTrace={vi.fn()}- onOpenObservation={vi.fn()}- scrollTarget={null}- />,- );-- expect(screen.getByText(/你好 world/)).toBeInTheDocument();- expect(screen.queryByText(/\\u4f60\\u597d/)).not.toBeInTheDocument();- });-});diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx b/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsxdeleted file mode 100644index 7211947d28..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx+++ /dev/null@@ -1,1189 +0,0 @@-/* eslint-disable no-nested-ternary */-import { useMemo, useState } from "react";-import {- ChevronDown,- ChevronsUpDown,- CircleAlert,- FileWarning,- Info,- type LucideIcon,- MessageSquareOff,- MoreHorizontal,- TriangleAlert,-} from "lucide-react";-import { renderFilterIcon } from "@/src/components/ItemBadge";-import {- type ParsedSessionTimelineObservation,- type PreparedSessionTimelineItem,- type PreparedSessionTimelineMessages,- type SessionTimelineObservation,-} from "@/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations";-import { SessionTimelineContentMessage } from "@/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTimelineContentMessage/SessionTimelineContentMessage";-import { SessionTimelineSystemMessage } from "@/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/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 { Tooltip as DSTooltip } from "@/src/components/design-system/Tooltip/Tooltip";-import { type RouterOutputs } from "@/src/utils/api";-import { formatIntervalSeconds } from "@/src/utils/dates";-import { cn } from "@/src/utils/tailwind";-import { getLevelColors } from "@/src/components/level-colors";-import { decodeUnicodeEscapesOnly } from "@/src/utils/unicode";--type EventObservation = RouterOutputs["events"]["all"]["observations"][number];-type EventObservationIO = RouterOutputs["events"]["batchIO"][number];-export type SessionObservation = Omit<- EventObservation,- "input" | "output" | "metadata" | "traceId"-> &- Omit<- SessionTimelineObservation,- "input" | "output" | "metadata" | "traceId"- > &- Pick<EventObservationIO, "input" | "output" | "metadata"> & {- traceId: string;- inputTruncated?: boolean;- outputTruncated?: boolean;- metadataTruncated?: boolean;- };--type SessionConversationTimelineTraceState =- | { type: "loading" }- | { type: "error" }- | { type: "empty" }- | {- type: "filtered-empty";- viewLabel: string | null;- onClearFilters: () => void;- }- | {- 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;- annotate: {- disabled: boolean;- onSelect: (observation: SessionObservation) => void;- };- comment: {- disabled: boolean;- onSelect: (observation: SessionObservation) => void;- };- addToDataset: {- disabled: boolean;- onSelect: (observation: SessionObservation) => void;- };-};--function SessionTimelineStatusIndicator({- observation,-}: {- observation: SessionObservation;-}) {- const Icon = (() => {- if (observation.level === "ERROR") {- return CircleAlert;- }- if (observation.level === "WARNING") {- return TriangleAlert;- }- return Info;- })();- const colors = getLevelColors(observation.level);-- return (- <Tooltip>- <TooltipTrigger asChild>- <span- className={cn(- "flex h-5 w-5 shrink-0 items-center justify-center rounded-md",- colors.bg,- colors.text,- )}- role="img"- aria-label={`${observation.level}: ${observation.statusMessage}`}- >- <Icon className="icon-base" aria-hidden="true" />- </span>- </TooltipTrigger>- <TooltipContent className="max-w-sm whitespace-pre-wrap">- {observation.statusMessage}- </TooltipContent>- </Tooltip>- );-}--/**- * Badge for a state an observation header reports next to its duration, e.g.- * truncated content. The label is both the accessible name and the tooltip.- */-function SessionTimelineMarkerIcon({- icon: Icon,- label,-}: {- icon: LucideIcon;- label: string;-}) {- return (- <DSTooltip label={label}>- {({ getTriggerProps }) => (- <span- {...getTriggerProps()}- className="bg-muted text-muted-foreground shrink-0 rounded-md p-1"- role="img"- aria-label={label}- >- <Icon className="icon-sm" aria-hidden="true" />- </span>- )}- </DSTooltip>- );-}--const toPreviewText = (value: unknown) => {- const text =- typeof value === "string"- ? value- : (JSON.stringify(value, undefined, 2) ?? String(value));- // Match PrettyJsonView / SessionObservationIO: decode \uXXXX so truncated- // previews show CJK and other non-ASCII characters instead of raw escapes.- return decodeUnicodeEscapesOnly(text, true);-};--const hasPreviewValue = (value: unknown) =>- value !== null && value !== undefined && value !== "";--function SessionObservationActionsMenuContent({- observation,- actions,-}: {- observation: SessionObservation;- actions: SessionObservationActions;-}) {- return (- <DropdownMenuContent align="end" sideOffset={0}>- <DropdownMenuItem- disabled={actions.annotate.disabled}- onSelect={() => actions.annotate.onSelect(observation)}- >- Annotate- </DropdownMenuItem>- <DropdownMenuItem- disabled={actions.comment.disabled}- onSelect={() => actions.comment.onSelect(observation)}- >- Comments- </DropdownMenuItem>- <DropdownMenuItem- disabled={actions.addToDataset.disabled}- onSelect={() => actions.addToDataset.onSelect(observation)}- >- Add to dataset- </DropdownMenuItem>- {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"];--function getNestedObservationSummary(- observations: readonly PreparedSessionTimelineItem<SessionObservation>[],-) {- const seenObservationIds = new Set<string>();- const toolNames = new Set<string>();- const counts: Record<string, number> = {};-- for (const item of observations) {- if (item.type === "tool") {- counts.TOOL = (counts.TOOL ?? 0) + 1;- toolNames.add(item.toolCall.toolName);- continue;- }-- const observationKey = `${item.observation.traceId ?? ""}:${item.observation.id}`;- if (seenObservationIds.has(observationKey)) continue;-- seenObservationIds.add(observationKey);- const type = item.observation.type ?? "EVENT";- counts[type] = (counts[type] ?? 0) + 1;- if (type === "TOOL" && item.observation.name) {- toolNames.add(item.observation.name);- }- }-- 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]) => {- if (type !== "TOOL") {- return `${count} ${type.toLowerCase()}${count === 1 ? "" : "s"}`;- }-- const names = count <= 3 ? Array.from(toolNames) : [];- const namesSummary = (() => {- if (names.length < 2) {- return names[0] ?? "";- }- if (names.length === 2) {- return `${names[0]} and ${names[1]}`;- }- return `${names.slice(0, -1).join(", ")}, and ${names.at(-1)}`;- })();- if (names.length === count) return `tools: ${namesSummary}`;-- return `${count} tool${count === 1 ? "" : "s"}${namesSummary ? ` using ${namesSummary}` : ""}`;- });-- 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,- showRailEnd,-}: {- observation: SessionObservation;- phase: "complete" | "start" | "end";- showRailEnd: boolean;-}) {- 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}- />- {showRailEnd &&- 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}- />- {showRailEnd ? <SessionTimelineRailEnd /> : null}- </div>- ) : null}- </div>- );-}--function SessionTimelineToolRow({- id,- name,- startTime,- latency,- input,- output,- inputTruncated,- outputTruncated,- isExpanded,- showRailEnd,- onExpandedChange,- onOpenInTraceView,- observation,- actions,-}: {- id: string;- name: string;- startTime: Date;- latency: number | null;- input: unknown;- output: unknown;- inputTruncated?: boolean;- outputTruncated?: boolean;- isExpanded: boolean;- showRailEnd: 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(- "icon-base transition-transform",- !isExpanded && "-rotate-90",- )}- aria-hidden="true"- />- </button>- <span className="ml-auto flex shrink-0 items-center gap-2">- {observation?.statusMessage && observation.level !== "DEFAULT" ? (- <SessionTimelineStatusIndicator observation={observation} />- ) : null}- {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="icon-sm text-icon-foreground"- 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="icon-base" 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) && showRailEnd ? (- <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>- {showRailEnd ? <SessionTimelineRailEnd /> : null}- </div>- ) : null}- {!hasPreviewValue(input) && !hasPreviewValue(output) ? (- <div className="relative">- <span className="text-muted-foreground text-xs">- No input or output- </span>- {showRailEnd ? <SessionTimelineRailEnd /> : null}- </div>- ) : null}- </div>- ) : null}- </section>- );-}--function SessionTimelineConversationObservation({- observation,- parsed,- processedMessages,- phase,- showRailEnd,- onOpenInTraceView,- actions,-}: {- observation: SessionObservation;- parsed: ParsedSessionTimelineObservation | null;- processedMessages: PreparedSessionTimelineMessages;- phase: "complete" | "start" | "end";- showRailEnd: boolean;- 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">- {observation.statusMessage && observation.level !== "DEFAULT" ? (- <SessionTimelineStatusIndicator observation={observation} />- ) : null}- {isTruncated ? (- <SessionTimelineMarkerIcon- icon={FileWarning}- label="Content truncated"- />- ) : null}- {hasNoConversationalContent ? (- <SessionTimelineMarkerIcon- icon={MessageSquareOff}- label="No conversational content"- />- ) : null}- {observation.metadataTruncated ? (- <SessionTimelineMarkerIcon- icon={FileWarning}- label="Metadata omitted because it is too large"- />- ) : 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="icon-sm text-icon-foreground"- 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}- showRailEnd={showRailEnd}- />- ) : 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}- {showRailEnd &&- phase !== "start" &&- index === visibleMessages.length - 1 ? (- <SessionTimelineRailEnd />- ) : null}- </div>- );- })- ) : null}- </div>- </section>- );-}--function SessionTimelineObservation({- observation,- parsed,- processedMessages,- phase,- isToolExpanded,- showRailEnd,- onToolExpandedChange,- onOpenInTraceView,- actions,-}: {- observation: SessionObservation;- parsed: ParsedSessionTimelineObservation | null;- processedMessages: PreparedSessionTimelineMessages;- phase: "complete" | "start" | "end";- isToolExpanded: boolean;- showRailEnd: 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}- showRailEnd={showRailEnd}- onExpandedChange={onToolExpandedChange}- onOpenInTraceView={onOpenInTraceView}- observation={observation}- actions={actions}- />- );- }-- return (- <SessionTimelineConversationObservation- observation={observation}- parsed={parsed}- processedMessages={processedMessages}- phase={phase}- showRailEnd={showRailEnd}- 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,- nestedObservationCounts,- }) => {- if (phase !== "start") return [];- if (- Object.keys(nestedObservationCounts).length === 1 &&- nestedObservationCounts.TOOL === 1- ) {- 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>(),- );- const [hoveredSubsectionId, setHoveredSubsectionId] = useState<string | null>(- null,- );- const [focusedSubsectionId, setFocusedSubsectionId] = useState<string | null>(- null,- );- const highlightedSubsectionId = hoveredSubsectionId ?? focusedSubsectionId;- const nestedObservationSummaries = useMemo(() => {- const observationsByAncestorId = new Map<- string,- PreparedSessionTimelineItem<SessionObservation>[]- >();- for (const item of observations) {- for (const ancestorId of item.ancestorObservationIds) {- const nestedObservations = observationsByAncestorId.get(ancestorId);- if (nestedObservations) nestedObservations.push(item);- else observationsByAncestorId.set(ancestorId, [item]);- }- }-- return new Map(- Array.from(observationsByAncestorId, ([observationId, nestedItems]) => [- observationId,- getNestedObservationSummary(nestedItems),- ]),- );- }, [observations]);- const collapsedObservationIds = useMemo(() => {- if (- !scrollTarget ||- scrollTarget.requestId === collapseState.scrollRequestId- ) {- return collapseState.observationIds;- }- const target = observations.find(- ({ observation }) => observation.id === scrollTarget.observationId,- );- const observationIds = new Set(collapseState.observationIds);- target?.ancestorObservationIds.forEach((id) => observationIds.delete(id));- return observationIds;- }, [scrollTarget, collapseState, observations]);- if (- scrollTarget &&- scrollTarget.requestId !== collapseState.scrollRequestId- ) {- setCollapseState({- scrollRequestId: scrollTarget.requestId,- observationIds: collapsedObservationIds,- });- }-- const visibleObservations = observations.filter((item) => {- if (- item.ancestorObservationIds.some((ancestorId) =>- collapsedObservationIds.has(ancestorId),- )- ) {- return false;- }- if (item.type === "tool") return true;- if (item.observation.type === "TOOL" && item.phase === "start") {- return Object.keys(item.nestedObservationCounts).length > 0;- }- if (item.phase !== "end") return true;- if (item.processedMessages.messages.length > 0) return true;- return Boolean(- item.observation.outputTruncated &&- hasPreviewValue(item.observation.output),- );- });-- return (- <TooltipProvider>- <div className="flex flex-col gap-1">- {visibleObservations.map((item, index) => {- const {- observation,- parsed,- processedMessages,- phase,- ancestorObservationIds,- nestedObservationCounts,- } = item;- 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 hasSingleNestedTool =- Object.keys(nestedObservationCounts).length === 1 &&- nestedObservationCounts.TOOL === 1;- const nestedObservationSummary = hasNestedObservations- ? (nestedObservationSummaries.get(observation.id) ?? "")- : "";- 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 moveCollapseControlUp = !isCollapsed && hasChatBubbles;- const isHighlightedSubsection =- highlightedSubsectionId === observation.id && phase === "start";- const isHighlightedDescendant = highlightedSubsectionId- ? ancestorObservationIds.includes(highlightedSubsectionId)- : false;-- const depth = ancestorObservationIds.length;-- return (- <div- key={- item.type === "tool" ? item.id : `${observation.id}-${phase}`- }- data-session-observation-depth={depth}- className="relative"- >- {ancestorObservationIds.length > 0 ? (- <span- data-session-observation-rail-depth={depth - 1}- className={cn(- "pointer-events-none absolute -top-1 -bottom-1 left-[7px] w-px transition-colors",- isHighlightedDescendant ? "bg-primary/60" : "bg-border",- )}- aria-hidden="true"- />- ) : null}- {depth === 0 &&- ((phase === "start" && !isToolStart) ||- (phase === "complete" &&- (hasChatBubbles || isToolExpanded))) ? (- <span- data-session-observation-rail-depth={depth}- className={cn(- "pointer-events-none absolute top-[22px] left-[7px] w-px transition-colors",- "bg-border",- phase === "start" ? "-bottom-1" : "bottom-0",- )}- aria-hidden="true"- />- ) : null}- {depth === 0 && phase === "end" ? (- <span- data-session-observation-rail-depth={depth}- className="bg-border pointer-events-none absolute -top-1 bottom-0 left-[7px] w-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}- showRailEnd={false}- onExpandedChange={(isExpanded) =>- setExpandedToolObservationIds((current) => {- const next = new Set(current);- if (isExpanded) next.add(itemId);- else next.delete(itemId);- return next;- })- }- onOpenInTraceView={() => onOpenObservation(observation.id)}- />- ) : !isEmptyEnd &&- (observation.type !== "TOOL" || phase !== "end") ? (- <SessionTimelineObservation- observation={observation}- parsed={parsed}- processedMessages={processedMessages}- phase={phase}- isToolExpanded={isToolExpanded}- showRailEnd={- depth === 0 &&- (observation.type !== "TOOL" ||- index === visibleObservations.length - 1)- }- 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 &&- !hasSingleNestedTool ? (- <div- className={cn(- "relative",- moveCollapseControlUp ? "h-0" : "h-7",- )}- >- {isHighlightedSubsection ? (- <span- data-session-collapse-rail-highlight- className={cn(- "bg-primary/60 pointer-events-none absolute -bottom-1 left-[7px] w-px",- moveCollapseControlUp ? "-top-2" : "top-5",- )}- aria-hidden="true"- />- ) : null}- <Button- type="button"- variant="ghost"- size="icon-xs"- className={cn(- "bg-background text-muted-foreground hover:text-foreground absolute z-[1] -translate-x-1/2 -translate-y-1/2 rounded-full",- moveCollapseControlUp ? "-top-2" : "top-5",- )}- style={{ left: "7.5px" }}- aria-expanded={!isCollapsed}- aria-label={`${isCollapsed ? "Show" : "Hide"} ${nestedObservationSummary}`}- onMouseEnter={() => {- if (!isCollapsed) {- setHoveredSubsectionId(observation.id);- }- }}- onMouseLeave={() => setHoveredSubsectionId(null)}- onFocus={() => {- if (!isCollapsed) {- setFocusedSubsectionId(observation.id);- }- }}- onBlur={() => setFocusedSubsectionId(null)}- onClick={() => {- setHoveredSubsectionId(null);- setFocusedSubsectionId(null);- 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="icon-sm text-icon-foreground"- aria-hidden="true"- />- ) : (- <ChevronDown- className="icon-sm text-icon-foreground"- aria-hidden="true"- />- )}- </Button>- {isCollapsed ? (- <span className="text-muted-foreground absolute top-5 left-5 -translate-y-1/2 text-xs">- {nestedObservationSummary}- </span>- ) : null}- </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" || state.type === "filtered-empty" ? (- <div className="text-muted-foreground flex items-center justify-between gap-4 rounded-lg border border-dashed p-4 text-xs">- <span>- {state.type === "empty"- ? "This trace has no observations."- : state.viewLabel- ? `No observation matches the “${state.viewLabel}” view in this trace.`- : "No observation matches the current filters in this trace."}- </span>- {state.type === "filtered-empty" ? (- <Button- type="button"- variant="outline"- size="sm"- className="shrink-0"- onClick={state.onClearFilters}- >- Clear filters- </Button>- ) : null}- </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/SessionConversationTimelineTrace/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.tsx b/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.tsxdeleted file mode 100644index cbbaa507fb..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.tsx+++ /dev/null@@ -1,27 +0,0 @@-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">- {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.tsdeleted file mode 100644index d357f6b7c6..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/fns/deduplicateTimelineInput.ts+++ /dev/null@@ -1,33 +0,0 @@-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 historicalParts = new Set(- (["input", "output"] as const).flatMap((source) => {- const currentEntries = getConversationEntries(messages, source);- const ancestorEntries = getConversationEntries(ancestorMessages, source);- const historicalEntryIndices = getHistoricalInputIndices(- ancestorEntries,- currentEntries,- );-- return currentEntries- .filter((_entry, index) => historicalEntryIndices.has(index))- .map((entry) => `${entry.messageIndex}:${entry.partIndex}`);- }),- );-- return messages.flatMap((message, messageIndex) => {- 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.tsdeleted file mode 100644index 11bb56b4ef..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/fns/getConversationEntries.ts+++ /dev/null@@ -1,35 +0,0 @@-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.tsdeleted file mode 100644index b11ec330d0..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/fns/getHistoricalInputIndices.ts+++ /dev/null@@ -1,25 +0,0 @@-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/getStandaloneToolCallIds.clienttest.ts b/web/src/features/sessions/SessionConversationTimeline/fns/getStandaloneToolCallIds.clienttest.tsdeleted file mode 100644index 255ffda18f..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/fns/getStandaloneToolCallIds.clienttest.ts+++ /dev/null@@ -1,39 +0,0 @@-// @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.tsdeleted file mode 100644index b638b59a84..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/fns/getStandaloneToolCallIds.ts+++ /dev/null@@ -1,18 +0,0 @@-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.tsdeleted file mode 100644index ab8e3629ff..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/fns/getToolObservationCallId.ts+++ /dev/null@@ -1,33 +0,0 @@-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.tsdeleted file mode 100644index dd032f1c2a..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.clienttest.ts+++ /dev/null@@ -1,911 +0,0 @@-// @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", () => {- // Force a parsing failure even when the parser copies enumerable fields.- const invalidInput = Object.defineProperty({}, "messages", {- enumerable: true,- 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("keeps duplicate nested output on the parent observation", () => {- const input = { role: "user", content: "Review this comment" };- const output = { role: "assistant", content: "PASS" };- const prepared = prepareSessionTimelineObservations([- observation("parent", input, output, "SPAN"),- observation(- "generation",- input,- output,- "GENERATION",- new Date(1),- "trace-1",- "parent",- ),- ]);-- const visibleTextByObservation = prepared.map((item) => ({- id: item.observation.id,- phase: item.phase,- text: item.processedMessages.messages.flatMap((message) =>- message.parts.flatMap((part) =>- part.type === "text" ? [part.text] : [],- ),- ),- }));-- expect(visibleTextByObservation).toEqual([- { id: "parent", phase: "start", text: ["Review this comment"] },- { id: "generation", phase: "complete", text: [] },- { id: "parent", phase: "end", text: ["PASS"] },- ]);- });-- it("preserves unique nested output", () => {- const prepared = prepareSessionTimelineObservations([- observation("parent", "Question", "Parent answer", "SPAN"),- observation(- "generation",- "Question",- "Generation answer",- "GENERATION",- new Date(1),- "trace-1",- "parent",- ),- ]);-- expect(prepared[1]?.processedMessages.messages).toMatchObject([- {- source: "output",- parts: [{ type: "text", text: "Generation answer" }],- },- ]);- });-- it("preserves nested output that only matches ancestor input", () => {- const repeatedAssistantMessage = {- role: "assistant",- content: "Shared message",- };- const prepared = prepareSessionTimelineObservations([- observation(- "parent",- [repeatedAssistantMessage],- "Parent answer",- "SPAN",- ),- observation(- "generation",- "Child question",- repeatedAssistantMessage,- "GENERATION",- new Date(1),- "trace-1",- "parent",- ),- ]);-- expect(prepared[1]?.processedMessages.messages).toMatchObject([- {- source: "input",- parts: [{ type: "text", text: "Child question" }],- },- {- source: "output",- parts: [{ type: "text", text: "Shared message" }],- },- ]);- });-- it("deduplicates large inherited input throughout a deeply nested trace", () => {- const inheritedText = "large inherited input ".repeat(600);- const inheritedInput = [{ role: "user", content: inheritedText }];- const observations = [- observation("level-0", inheritedInput, null, "AGENT"),- ];- for (let level = 1; level < 25; level += 1) {- observations.push(- observation(- `level-${level}`,- inheritedInput,- null,- "AGENT",- new Date(level),- "trace-1",- `level-${level - 1}`,- ),- );- }-- const prepared = prepareSessionTimelineObservations(observations);- const visibleText = prepared.flatMap(({ processedMessages }) =>- processedMessages.messages.flatMap((message) =>- message.parts.flatMap((part) =>- part.type === "text" ? [part.text] : [],- ),- ),- );-- expect(inheritedText.length).toBeGreaterThan(10_000);- expect(visibleText).toEqual([inheritedText]);- });-- 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("deduplicates a generation tool call by a sibling tool observation call id", () => {- const prepared = prepareSessionTimelineObservations([- observation("root", null, null, "SPAN"),- observation(- "generation",- null,- [- {- role: "assistant",- content: null,- tool_calls: [- {- id: "shared-call-id",- type: "function",- function: {- name: "search",- arguments: JSON.stringify({ query: "dashboard" }),- },- },- ],- },- ],- "GENERATION",- new Date(1),- "trace-1",- "root",- ),- observation(- "tool-observation",- { query: "dashboard" },- "Found dashboard",- "TOOL",- new Date(2),- "trace-1",- "root",- { toolCallId: "shared-call-id" },- "search",- ),- ]);-- expect(- prepared.filter(- (item) => item.type === "tool" && item.observation.id === "generation",- ),- ).toEqual([]);- expect(- prepared.filter(- (item) =>- item.type === "observation" &&- item.observation.id === "tool-observation",- ),- ).toHaveLength(1);- });-- it("does not deduplicate matching tool call ids across traces", () => {- const prepared = prepareSessionTimelineObservations([- observation(- "tool-observation",- {},- "Tool output",- "TOOL",- new Date(0),- "trace-1",- null,- { toolCallId: "reused-call-id" },- "lookup",- ),- observation(- "generation",- null,- [- {- role: "assistant",- content: null,- tool_calls: [- {- id: "reused-call-id",- type: "function",- function: {- name: "lookup",- arguments: "{}",- },- },- ],- },- ],- "GENERATION",- new Date(1),- "trace-2",- ),- ]);-- expect(- prepared.filter(- (item) => item.type === "tool" && item.observation.id === "generation",- ),- ).toHaveLength(1);- });-- it("keeps the latest representation of a repeated generation tool call", () => {- const toolCallOutput = (query: string) => [- {- role: "assistant",- content: null,- tool_calls: [- {- id: "repeated-call-id",- type: "function",- function: {- name: "search",- arguments: JSON.stringify({ query }),- },- },- ],- },- ];- const prepared = prepareSessionTimelineObservations([- observation(- "generation-1",- null,- toolCallOutput("initial query"),- "GENERATION",- new Date(0),- ),- observation(- "generation-2",- null,- toolCallOutput("enriched query"),- "GENERATION",- new Date(1),- ),- ]);-- expect(- prepared- .filter((item) => item.type === "tool")- .map((item) => ({- observationId: item.observation.id,- input: item.toolCall.input,- })),- ).toEqual([- {- observationId: "generation-2",- input: { query: "enriched query" },- },- ]);- });-- it("prefers a unique sibling tool observation over a semantic generation call", () => {- const prepared = prepareSessionTimelineObservations([- observation("root", null, null, "SPAN"),- observation(- "generation",- null,- [- {- role: "assistant",- content: null,- tool_calls: [- {- id: "generation-call-id",- type: "function",- function: {- name: "search",- arguments: JSON.stringify({ query: "dashboard" }),- },- },- ],- },- ],- "GENERATION",- new Date(1),- "trace-1",- "root",- ),- observation(- "tool-observation",- JSON.stringify({ query: "dashboard" }),- "Found dashboard",- "TOOL",- new Date(2),- "trace-1",- "root",- null,- "search",- ),- ]);-- expect(- prepared.filter(- (item) => item.type === "tool" && item.observation.id === "generation",- ),- ).toEqual([]);- });-- it("does not semantically match a tool observation already represented by id", () => {- const prepared = prepareSessionTimelineObservations([- observation("generation", null, [- {- role: "assistant",- content: null,- tool_calls: [- {- id: "observed-call-id",- type: "function",- function: {- name: "search",- arguments: JSON.stringify({ query: "dashboard" }),- },- },- {- id: "separate-call-id",- type: "function",- function: {- name: "search",- arguments: JSON.stringify({ query: "dashboard" }),- },- },- ],- },- ]),- observation(- "tool-observation",- { query: "dashboard" },- "Found dashboard",- "TOOL",- new Date(1),- "trace-1",- "generation",- { toolCallId: "observed-call-id" },- "search",- ),- ]);-- expect(- prepared- .filter((item) => item.type === "tool")- .map((item) => item.toolCall.toolCallId),- ).toEqual(["separate-call-id"]);- });-- 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("does not semantically match tool executions across branches", () => {- const prepared = prepareSessionTimelineObservations([- observation("root", null, null, "SPAN"),- observation(- "first-branch",- null,- null,- "SPAN",- new Date(1),- "trace-1",- "root",- ),- observation(- "first-tool",- {},- "First result",- "TOOL",- new Date(2),- "trace-1",- "first-branch",- null,- "lookup",- ),- observation(- "second-branch",- null,- null,- "SPAN",- new Date(3),- "trace-1",- "root",- ),- observation(- "second-generation",- null,- [- {- role: "assistant",- content: null,- tool_calls: [- {- id: "second-call-id",- type: "function",- function: { name: "lookup", arguments: "{}" },- },- ],- },- ],- "GENERATION",- new Date(4),- "trace-1",- "second-branch",- ),- ]);-- expect(- prepared.filter(- (item) =>- item.type === "tool" && item.observation.id === "second-generation",- ),- ).toHaveLength(1);- });-- it("deduplicates identical tool calls within their direct execution scopes", () => {- const generation = (id: string, toolCallId: string, startTime: Date) =>- observation(- id,- null,- [- {- role: "assistant",- content: null,- tool_calls: [- {- id: toolCallId,- type: "function",- function: { name: "lookup", arguments: "{}" },- },- ],- },- ],- "GENERATION",- startTime,- );- const prepared = prepareSessionTimelineObservations([- generation("first-generation", "first-call-id", new Date(0)),- observation(- "first-tool",- {},- "First result",- "TOOL",- new Date(1),- "trace-1",- "first-generation",- null,- "lookup",- ),- generation("second-generation", "second-call-id", new Date(2)),- observation(- "second-tool",- {},- "Second result",- "TOOL",- new Date(3),- "trace-1",- "second-generation",- null,- "lookup",- ),- ]);-- expect(prepared.filter((item) => item.type === "tool")).toEqual([]);- });-- 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.tsdeleted file mode 100644index 2c0b1067f5..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.ts+++ /dev/null@@ -1,471 +0,0 @@-import {- normalizeSpanIO,- type NormalizedMessage,- type ToolCallPart,-} from "@langfuse/shared/src/utils/normalized-io";--import { deduplicateTimelineInput } from "@/src/features/sessions/SessionConversationTimeline/fns/deduplicateTimelineInput";-import { getToolObservationCallId } from "@/src/features/sessions/SessionConversationTimeline/fns/getToolObservationCallId";-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();--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 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 chronologicalPreparedObservations = chronologicalObservations.map(- ({ observation, originalIndex }, index) => ({- originalIndex,- prepared: {- observation,- parsed: parsedObservations[index]?.parsed ?? null,- processedMessages: processedMessageGroups[index] ?? {- messages: [],- rolledUpToolCalls: [],- },- },- }),- );-- const latestToolCallById = new Map<string, ToolCallPart>();- for (const { prepared } of chronologicalPreparedObservations) {- for (const toolCall of prepared.processedMessages.rolledUpToolCalls) {- if (!toolCall.toolCallId) continue;- latestToolCallById.set(- `${prepared.observation.traceId ?? ""}\0${toolCall.toolCallId}`,- toolCall,- );- }- }- for (const { prepared } of chronologicalPreparedObservations) {- prepared.processedMessages.rolledUpToolCalls =- prepared.processedMessages.rolledUpToolCalls.filter(- (toolCall) =>- !toolCall.toolCallId ||- latestToolCallById.get(- `${prepared.observation.traceId ?? ""}\0${toolCall.toolCallId}`,- ) === toolCall,- );- }-- const toolObservationsBySemanticKey = new Map<string, Observation[]>();- const directToolCallsBySemanticKey = new Map<string, ToolCallPart[]>();- const siblingToolCallsBySemanticKey = new Map<string, ToolCallPart[]>();- const emittedToolCallIds = new Set<string>();- for (const { prepared } of chronologicalPreparedObservations) {- if (prepared.parsed?.type !== "loaded") continue;- for (const message of prepared.parsed.messages) {- for (const part of message.parts) {- if (part.type !== "tool-call" || !part.toolCallId) continue;- emittedToolCallIds.add(- `${prepared.observation.traceId ?? ""}\0${part.toolCallId}`,- );- }- }- }- for (const { prepared } of chronologicalPreparedObservations) {- const { observation } = prepared;- if (observation.type === "TOOL") {- const observationCallId = getToolObservationCallId(observation);- if (- observationCallId &&- emittedToolCallIds.has(- `${observation.traceId ?? ""}\0${observationCallId}`,- )- ) {- continue;- }-- const semanticKey = getToolSemanticKey(- observation.name,- observation.input,- );- if (semanticKey) {- const directKey = `${observation.traceId ?? ""}\0${observation.parentObservationId ?? ""}\0${semanticKey}`;- const directMatches = toolObservationsBySemanticKey.get(directKey);- if (directMatches) directMatches.push(observation);- else toolObservationsBySemanticKey.set(directKey, [observation]);- }- }-- for (const toolCall of prepared.processedMessages.rolledUpToolCalls) {- const semanticKey = getToolSemanticKey(toolCall.toolName, toolCall.input);- if (!semanticKey) continue;- const directKey = `${observation.traceId ?? ""}\0${observation.id}\0${semanticKey}`;- const directMatches = directToolCallsBySemanticKey.get(directKey);- if (directMatches) directMatches.push(toolCall);- else directToolCallsBySemanticKey.set(directKey, [toolCall]);-- const siblingKey = `${observation.traceId ?? ""}\0${observation.parentObservationId ?? ""}\0${semanticKey}`;- const siblingMatches = siblingToolCallsBySemanticKey.get(siblingKey);- if (siblingMatches) siblingMatches.push(toolCall);- else siblingToolCallsBySemanticKey.set(siblingKey, [toolCall]);- }- }- const matchedToolCalls = new Set<ToolCallPart>();- const matchedToolObservations = new Set<Observation>();- for (const [semanticKey, toolCalls] of directToolCallsBySemanticKey) {- if (toolCalls.length !== 1) continue;- const toolObservations = toolObservationsBySemanticKey.get(semanticKey);- if (toolObservations?.length !== 1) continue;- const matchingCall = toolCalls[0];- const matchingObservation = toolObservations[0];- if (!matchingCall || !matchingObservation) continue;- matchedToolCalls.add(matchingCall);- matchedToolObservations.add(matchingObservation);- }- for (const [semanticKey, toolCalls] of siblingToolCallsBySemanticKey) {- const unmatchedToolCalls = toolCalls.filter(- (toolCall) => !matchedToolCalls.has(toolCall),- );- if (unmatchedToolCalls.length !== 1) continue;- const unmatchedToolObservations = (- toolObservationsBySemanticKey.get(semanticKey) ?? []- ).filter((observation) => !matchedToolObservations.has(observation));- if (unmatchedToolObservations.length !== 1) continue;- const matchingCall = unmatchedToolCalls[0];- const matchingObservation = unmatchedToolObservations[0];- if (!matchingCall || !matchingObservation) continue;- matchedToolCalls.add(matchingCall);- matchedToolObservations.add(matchingObservation);- }- if (matchedToolCalls.size > 0) {- for (const { prepared } of chronologicalPreparedObservations) {- prepared.processedMessages.rolledUpToolCalls =- prepared.processedMessages.rolledUpToolCalls.filter(- (toolCall) => !matchedToolCalls.has(toolCall),- );- }- }-- const preparedObservations = chronologicalPreparedObservations- .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]);- }-- 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 ownMessages =- prepared.parsed?.type === "loaded" ? prepared.parsed.messages : messages;- const descendantContext = ancestorMessages.concat(ownMessages);- 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.tsdeleted file mode 100644index d060b6086d..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages.clienttest.ts+++ /dev/null@@ -1,359 +0,0 @@-// @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.tsdeleted file mode 100644index f413e8272d..0000000000--- a/web/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages.ts+++ /dev/null@@ -1,132 +0,0 @@-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/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline.tsxnew file mode 100644index 0000000000..21ddee6ee6--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline.tsx@@ -0,0 +1,253 @@+import { useRef, useState } from "react";++import {+ ConnectedSessionConversationTimeline,+ type ConnectedSessionConversationTimelineItem,+} from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/ConnectedSessionConversationTimeline";+import {+ type SessionConversationTimelineScrollTarget,+ useSessionConversationTimelineController,+} from "@/src/features/sessions/hooks/useSessionConversationTimelineController";+import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";+import { useDebounce } from "@/src/hooks/useDebounce";+import { api } from "@/src/utils/api";+import { useSessionTraceTranscripts } from "@/src/features/sessions/hooks/useSessionTraceTranscripts";+import { getSessionConversationEntries } from "./components/ConnectedSessionConversationTimeline/fns/getSessionConversationEntries";++const SIDEBAR_TRACE_CHUNK_SIZE = 20;+const EMPTY_TRACES: EventSessionTrace[] = [];++type OpenPeek = (id: string, row: EventSessionTrace) => void;++type ConnectedModernSessionBodyTimelineProps = {+ tracesState:+ | { type: "loading" }+ | { type: "loaded"; traces: EventSessionTrace[] };+ projectId: string;+ sessionId: string;+ openPeek: OpenPeek;+};++export function ConnectedModernSessionBodyTimeline({+ tracesState,+ projectId,+ sessionId,+ openPeek,+}: ConnectedModernSessionBodyTimelineProps) {+ const traces =+ tracesState.type === "loaded" ? tracesState.traces : EMPTY_TRACES;+ const [timelineVisibleTraceIds, setTimelineVisibleTraceIds] = useState<+ string[]+ >([]);+ const [search, setSearch] = useState("");+ const [debouncedSearchQuery, setSearchQuery] = useState("");+ const debouncedSetSearchQuery = useDebounce(+ (nextSearchQuery: string) => {+ if (nextSearchQuery === search.trim()) setSearchQuery(nextSearchQuery);+ },+ 500,+ false,+ );+ const utils = api.useUtils();+ 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 traceIndexById = new Map(+ traces.map((trace, index) => [trace.id, index] as const),+ );+ const activeChunkIndices = new Set<number>();+ {+ const highestChunkIndex = Math.max(+ debouncedSearchQuery+ ? Math.ceil(traces.length / SIDEBAR_TRACE_CHUNK_SIZE) - 1+ : Math.min(+ loadedThroughChunkIndex,+ Math.ceil(traces.length / SIDEBAR_TRACE_CHUNK_SIZE) - 1,+ ),+ ...[...visibleTraceIds, ...timelineVisibleTraceIds].flatMap((traceId) => {+ const traceIndex = traceIndexById.get(traceId);+ if (traceIndex === undefined) return [];+ return [Math.floor(traceIndex / SIDEBAR_TRACE_CHUNK_SIZE)];+ }),+ );+ for (let chunkIndex = 0; chunkIndex <= highestChunkIndex; chunkIndex++) {+ activeChunkIndices.add(chunkIndex);+ }+ }++ const activeTranscriptTraceIds = new Set(+ traces+ .filter((_, index) =>+ activeChunkIndices.has(Math.floor(index / SIDEBAR_TRACE_CHUNK_SIZE)),+ )+ .map((trace) => trace.id),+ );+ const resultsByTraceId = useSessionTraceTranscripts({+ projectId,+ traces: traces.map((trace, index) => ({ trace, turnNumber: index + 1 })),+ activeTraceIds: activeTranscriptTraceIds,+ });+ const allTranscriptsLoaded =+ tracesState.type === "loaded" &&+ traces.every(+ (trace) =>+ utils.events.transcriptByTraceId.getData({+ projectId,+ traceId: trace.id,+ timestamp: trace.timestamp,+ pairTextToolResponses: true,+ }) !== undefined,+ );+ const searchQuery = allTranscriptsLoaded+ ? search.trim()+ : debouncedSearchQuery;+ const isSearchPending = search.trim() !== searchQuery;+ const entries = getSessionConversationEntries(+ traces.map((trace) => {+ const result = resultsByTraceId.get(trace.id);+ return {+ trace,+ transcript: result?.state === "loaded" ? result.transcript : undefined,+ };+ }),+ );+ const timelineController = useSessionConversationTimelineController(+ entries.map((entry) => ({+ trace: traces[entry.traceIndex]!,+ itemId: entry.itemId,+ })),+ (nextTraceIds) =>+ setTimelineVisibleTraceIds((current) => {+ if (+ current.length === nextTraceIds.length &&+ current.every((id, index) => id === nextTraceIds[index])+ )+ return current;+ return nextTraceIds;+ }),+ );+ const expandedTraceIds = new Set(+ entries+ .filter((entry) => !collapsedTraceIds.has(entry.itemId))+ .map((entry) => entry.itemId),+ );++ const isLoadingTranscripts = Array.from(activeTranscriptTraceIds).some(+ (traceId) => resultsByTraceId.get(traceId)?.state === "loading",+ );+ const transcriptLoadError = Array.from(resultsByTraceId.values()).some(+ (result) => result.state === "error",+ );++ 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);+ if (allTranscriptsLoaded) {+ setSearchQuery(nextSearch.trim());+ return;+ }+ 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 timelineTraces: ConnectedSessionConversationTimelineItem[] = traces.map(+ (trace, index) => {+ return {+ trace,+ turnNumber: index + 1,+ };+ },+ );+ const handleSelect = (+ index: number,+ observationId?: string,+ rowId?: string,+ ) => {+ const entry = entries[index];+ const traceId = entry+ ? timelineTraces[entry.traceIndex]?.trace.id+ : undefined;+ if (observationId && traceId) {+ scrollRequestIdRef.current += 1;+ setScrollTarget({+ itemId: entry?.itemId,+ traceId,+ observationId,+ rowId,+ requestId: scrollRequestIdRef.current,+ });+ }+ timelineController.onSelect(index, observationId, rowId);+ };++ return (+ <ConnectedSessionConversationTimeline+ {...(tracesState.type === "loading"+ ? { state: "loading" }+ : {+ state: "loaded",+ search,+ searchQuery,+ isSearchPending,+ onSearchChange: handleSearchChange,+ expandedTraceIds,+ onToggleTraceExpanded: toggleTraceExpanded,+ onSelect: handleSelect,+ onVisibleTraceIdsChange: handleVisibleTraceIdsChange,+ isLoadingTranscripts: isSearchPending || isLoadingTranscripts,+ transcriptLoadError,+ })}+ traces={timelineTraces}+ projectId={projectId}+ openPeek={openPeek}+ controller={timelineController}+ resultsByTraceId={resultsByTraceId}+ scrollTarget={scrollTarget}+ />+ );+}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/ConnectedSessionConversationTimeline.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/ConnectedSessionConversationTimeline.tsxnew file mode 100644index 0000000000..815cd8afe0--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/ConnectedSessionConversationTimeline.tsx@@ -0,0 +1,73 @@+import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";+import { type ComponentProps } from "react";+import { SessionConversationalView } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView";+import {+ type SessionConversationTimelineController,+ type SessionConversationTimelineScrollTarget,+} from "@/src/features/sessions/hooks/useSessionConversationTimelineController";+import { type SessionTraceTranscriptState } from "@/src/features/sessions/hooks/useSessionTraceTranscripts";+import { getSessionTranscriptThreads } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptThreads";++export type ConnectedSessionConversationTimelineItem = {+ trace: EventSessionTrace;+ turnNumber: number;+};++export function ConnectedSessionConversationTimeline(+ props: (+ | { state: "loading" }+ | Omit<+ Extract<+ ComponentProps<typeof SessionConversationalView>,+ { state: "loaded" }+ >,+ "traces" | "controller"+ >+ ) & {+ traces: readonly ConnectedSessionConversationTimelineItem[];+ projectId: string;+ openPeek: (+ id: string,+ row: EventSessionTrace & { observationId?: string },+ ) => void;+ controller: SessionConversationTimelineController;+ resultsByTraceId: ReadonlyMap<string, SessionTraceTranscriptState>;+ scrollTarget: SessionConversationTimelineScrollTarget | null;+ },+) {+ const { traces, openPeek, controller, resultsByTraceId, scrollTarget } =+ props;++ return (+ <SessionConversationalView+ {...props}+ traces={traces.map(({ trace, turnNumber }) => {+ const result = resultsByTraceId.get(trace.id);+ const state = (() => {+ if (result?.state === "error") return { type: "error" as const };+ if (!result || result.state === "loading")+ return { type: "loading" as const };+ if (+ getSessionTranscriptThreads(result.transcript).visibleThreads+ .length === 0 &&+ getSessionTranscriptThreads(result.transcript).hiddenThreadCount ===+ 0+ )+ return { type: "empty" as const };+ return { type: "transcript" as const, result };+ })();+ return {+ trace,+ turnNumber,+ state,+ onOpenTrace: () => openPeek(trace.id, trace),+ onOpenObservation: (observationId: string) =>+ openPeek(trace.id, { ...trace, observationId }),+ scrollTarget:+ scrollTarget?.traceId === trace.id ? scrollTarget : null,+ };+ })}+ controller={controller}+ />+ );+}diff --git a/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsxsimilarity index 57%rename from web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.stories.tsxrename to web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsxindex b22ad1eaf5..88ac952e31 100644--- a/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.stories.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsx@@ -1,30 +1,32 @@-/* eslint-disable no-nested-ternary */+import { orderObservations } from "@langfuse/shared/src/server/transcript/ordering";+import { assembleTranscript } from "@langfuse/shared/src/server/transcript/transcript";+import { type TranscriptObservation } from "@langfuse/shared/src/server/transcript/types";import preview from "@/.storybook/preview";-import { expect, fn, userEvent, waitFor, within } from "storybook/test";-import { type ComponentProps } from "react";-+import { type ComponentProps, useRef, useState } from "react";+import { expect, fn, userEvent, within, waitFor } from "storybook/test";+import { SessionConversationalView } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView";import {- SessionConversationTimeline,useSessionConversationTimelineController,-} from "@/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline";+ type SessionConversationTimelineScrollTarget,+} from "@/src/features/sessions/hooks/useSessionConversationTimelineController";+import { type SessionConversationTimelineTrace } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace";+import { getSessionConversationEntries } from "../../fns/getSessionConversationEntries";-type TimelineProps = Omit<- ComponentProps<typeof SessionConversationTimeline>,- "controller"->;-type Observation = NonNullable<- TimelineProps["traces"][number]["observations"]->[number];+type TraceProps = ComponentProps<typeof SessionConversationTimelineTrace>;-function SessionConversationTimelineStory(props: TimelineProps) {- const controller = useSessionConversationTimelineController(props.traces);+type TranscriptState = Extract<TraceProps["state"], { type: "transcript" }>;+type WorkflowObservation = TranscriptObservation & {+ environment: string;+ latency: number | null;+ model: string | null;+ inputTruncated: boolean;+ outputTruncated: boolean;+ metadataTruncated: boolean;+};- return (- <div className="bg-card dark:bg-background h-screen min-w-[320px]">- <SessionConversationTimeline {...props} controller={controller} />- </div>- );-}+type WorkflowTrace = Pick<TraceProps, "trace" | "turnNumber"> & {+ state: TranscriptState;+};const trace = {id: "trace-order-support-8f3a2",@@ -35,9 +37,24 @@ const trace = {observationCount: 5,latencyMs: 4260,scores: [],-} satisfies TimelineProps["traces"][number]["trace"];--const observations = [+} satisfies TraceProps["trace"];++const observations: Array<+ Pick<+ WorkflowObservation,+ | "id"+ | "name"+ | "type"+ | "startTime"+ | "input"+ | "output"+ | "metadata"+ | "latency"+ | "inputTruncated"+ | "outputTruncated"+ | "metadataTruncated"+ > & { latency: number }+> = [{id: "generation-1",name: "Plan support response",@@ -63,7 +80,7 @@ const observations = [id: "call-order-lookup",type: "function",function: {- name: "get_order",+ name: "Get order",arguments: '{"orderId":"LF-20481"}',},},@@ -130,7 +147,7 @@ const observations = [id: "call-address-update",type: "function",function: {- name: "update_shipping_address",+ name: "Update shipping address",arguments: JSON.stringify({orderId: "LF-20481",address: {@@ -195,7 +212,7 @@ const observations = [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.";@@ -218,6 +235,37 @@ const telemetryMetadata = {"scope.version": "0.0.0-demo",};+const fixtureToolCallIds = new Map<string, string[]>();++function fixtureToolOutput(+ output: TranscriptObservation["output"],+ toolName: string,+ toolCallId: string | undefined,+) {+ if (output === null) return null;+ const payload: unknown = (() => {+ try {+ return typeof output === "string" ? JSON.parse(output) : output;+ } catch {+ return output;+ }+ })();+ if (+ typeof payload === "object" &&+ payload !== null &&+ "type" in payload &&+ payload.type === "tool-result"+ ) {+ return JSON.stringify(payload);+ }+ return JSON.stringify({+ type: "tool-result",+ toolName,+ toolCallId: toolCallId ?? fixtureToolCallIds.get(toolName)?.shift(),+ output: payload,+ });+}+function codingAgentObservation({traceId,id,@@ -248,8 +296,22 @@ function codingAgentObservation({name,type,startTime: new Date(fixtureStart + offsetMs),+ endTime:+ latency === null+ ? null+ : new Date(fixtureStart + offsetMs + latency * 1_000),+ environment: "storybook",input,- output,+ output:+ type === "TOOL"+ ? fixtureToolOutput(+ output,+ name,+ typeof metadata?.toolCallId === "string"+ ? metadata.toolCallId+ : undefined,+ )+ : output,metadata: {...telemetryMetadata,"attributes.langfuse.observation.type": type.toLowerCase(),@@ -273,7 +335,7 @@ function codingAgentObservation({inputTruncated: false,outputTruncated: false,metadataTruncated: false,- } as unknown as Observation;+ } satisfies WorkflowObservation;}const userMessage = JSON.stringify([@@ -289,8 +351,13 @@ const toolResult = (toolCallId: string, content: string) => ({const assistantToolCalls = (content: string | null,calls: Array<{ id: string; name: string; arguments: object }>,-) =>- JSON.stringify([+) => {+ for (const call of calls) {+ const ids = fixtureToolCallIds.get(call.name) ?? [];+ ids.push(call.id);+ fixtureToolCallIds.set(call.name, ids);+ }+ return JSON.stringify([{role: "assistant",content,@@ -304,6 +371,7 @@ const assistantToolCalls = (})),},]);+};const researchTurnId = "research-agent-turn";const researchCodingAgentObservations = [@@ -340,8 +408,40 @@ const researchCodingAgentObservations = [offsetMs: 6,latency: 13.224,input: userMessage,- output: assistantMessage(+ output: assistantToolCalls("I will load the frontend and Storybook guidance, index the fictional repository, and locate the dashboard entry points.",+ [+ {+ id: "call-research-tool-1",+ name: "skill",+ arguments: { name: "typescript" },+ },+ {+ id: "call-research-tool-2",+ name: "skill",+ arguments: { name: "storybook" },+ },+ {+ id: "call-research-tool-3",+ name: "skill",+ arguments: { name: "frontend-guidelines" },+ },+ {+ id: "call-research-tool-4",+ name: "grepika_add_workspace",+ arguments: { path: "~/demo/recipe-planner" },+ },+ {+ id: "call-research-tool-5",+ name: "tilth_tilth_search",+ arguments: { query: "RecipeDashboard" },+ },+ {+ id: "call-research-tool-6",+ name: "tilth_tilth_files",+ arguments: { patterns: ["src/features/recipes/**/*"] },+ },+ ],),}),...[@@ -1621,16 +1721,17 @@ const inAppAgentObservations = [args: tool.input,})),},- {+ ...previousAction.tools.map((tool, toolIndex) => ({role: "tool",- content: JSON.stringify(- previousAction.tools.map((tool, toolIndex) => ({+ content: [+ {+ type: "tool-result",toolCallId: `error-analysis-call-${previousActionIndex + 1}-${toolIndex + 1}`,toolName: tool.name,output: tool.output,- })),- ),- },+ },+ ],+ })),]);const runtimeContextOffsetMs = (() => {if (actionIndex < 6) {@@ -1699,34 +1800,36 @@ Active filter: level is ERROR{ name: "bash" },],});- const generationOutput = JSON.stringify(- actionIndex === inAppAgentActions.length - 1- ? {- role: "assistant",- content: [- {- taxonomy: {- primaryIssue: "tool-timeout",- affectedWorkflow: "booking-assistant",- recommendedFix: "Add bounded retries with backoff",- },- tracking: {- metric: "tool_error_rate",- owner: "agent-platform",- },+ const generationOutput = (() => {+ if (actionIndex === inAppAgentActions.length - 1) {+ return JSON.stringify({+ role: "assistant",+ content: [+ {+ taxonomy: {+ primaryIssue: "tool-timeout",+ affectedWorkflow: "booking-assistant",+ recommendedFix: "Add bounded retries with backoff",},- ],- }- : 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 },- );+ tracking: {+ metric: "tool_error_rate",+ owner: "agent-platform",+ },+ },+ ],+ });+ }+ if (action.tools.length > 0) {+ return JSON.stringify({+ tool_calls: action.tools.map((tool, toolIndex) => ({+ args: tool.input,+ toolCallId: `error-analysis-call-${actionIndex + 1}-${toolIndex + 1}`,+ toolName: tool.name,+ })),+ });+ }+ return JSON.stringify({ text: action.summary });+ })();return [codingAgentObservation({@@ -1781,7 +1884,7 @@ const inAppAgentTrace = {observationCount: inAppAgentObservations.length,latencyMs: 205_058,scores: [],-} satisfies TimelineProps["traces"][number]["trace"];+} satisfies TraceProps["trace"];const researchCodingAgentTrace = {id: researchTraceId,@@ -1792,7 +1895,7 @@ const researchCodingAgentTrace = {observationCount: researchCodingAgentObservations.length,latencyMs: 87_347,scores: [],-} satisfies TimelineProps["traces"][number]["trace"];+} satisfies TraceProps["trace"];const implementationCodingAgentTrace = {id: implementationTraceId,@@ -1803,1212 +1906,1200 @@ const implementationCodingAgentTrace = {observationCount: implementationCodingAgentObservations.length,latencyMs: 167_662,scores: [],-} satisfies TimelineProps["traces"][number]["trace"];+} satisfies TraceProps["trace"];-const observationActions = {- onFilterByName: fn(),- annotate: { disabled: false, onSelect: fn() },- comment: { disabled: false, onSelect: fn() },- addToDataset: { disabled: false, onSelect: fn() },-} satisfies NonNullable<TimelineProps["observationActions"]>;--const loadedArgs = {- traces: [{ trace, turnNumber: 1, observations }],- filterMeasurementKey: "default",- emptyState: { type: "empty" },- onOpenTrace: fn(),- onOpenObservation: fn(),- observationActions,-} satisfies TimelineProps;--type ToolShape = {- callId: string;- name: string;- input: Record<string, unknown>;+type WorkflowFixture = Pick<TraceProps, "trace" | "turnNumber"> & {+ observations: Array<TranscriptObservation & { environment: string }>;};-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({+const supportAgentWorkflow: WorkflowFixture[] = [+ {+ trace,+ turnNumber: 1,+ observations: observations.map((observation) => ({+ ...observation,+ output:+ observation.type === "TOOL"+ ? fixtureToolOutput(+ observation.output,+ observation.name ?? "",+ typeof observation.metadata?.toolCallId === "string"+ ? observation.metadata.toolCallId+ : undefined,+ )+ : observation.output,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, [+ endTime: new Date(+ observation.startTime.getTime() + observation.latency * 1_000,+ ),+ environment: trace.environment,+ })),+ },+];+const codingAgentWorkflow: WorkflowFixture[] = [+ {+ trace: researchCodingAgentTrace,+ turnNumber: 1,+ observations: researchCodingAgentObservations,+ },+ {+ trace: implementationCodingAgentTrace,+ turnNumber: 2,+ observations: implementationCodingAgentObservations,+ },+];+for (const workflow of codingAgentWorkflow) {+ const history: Array<{ role: string; [key: string]: unknown }> = [];+ for (const observation of workflow.observations) {+ if (observation.type !== "GENERATION") continue;+ const input = (observation.input as string).startsWith("[")+ ? (JSON.parse(observation.input as string) as typeof history)+ : [{ role: "user", content: observation.input }];+ history.push(+ ...(history.length === 0+ ? input+ : input.filter(+ (message) => message.role === "tool" || message.role === "user",+ )),+ );+ observation.input = JSON.stringify(history);+ history.push(+ ...(JSON.parse(observation.output as string) as typeof history),+ );+ }+}+const langfuseAssistantWorkflow: WorkflowFixture[] = [+ {+ trace: inAppAgentTrace,+ turnNumber: 4,+ observations: inAppAgentObservations,+ },+];++const manySimpleTurnsWorkflow: WorkflowFixture[] = Array.from(+ { length: 100 },+ (_, index) => {+ const turnNumber = index + 1;+ const traceId = `simple-turn-${turnNumber}`;+ const startTime = new Date(+ fixtureStart + index * 1_000 + Math.floor(index / 10) * 10 * 60 * 1_000,+ );+ return {+ trace: {+ id: traceId,+ name: `Turn ${turnNumber}`,+ timestamp: startTime,+ environment: "storybook",+ userId: null,+ observationCount: 1,+ latencyMs: 100,+ scores: [],+ },+ turnNumber,+ observations: [+ {+ id: `generation-${turnNumber}`,+ traceId,+ parentObservationId: null,+ type: "GENERATION",+ name: `Reply ${turnNumber}`,+ startTime,+ endTime: new Date(startTime.getTime() + 100),+ environment: "storybook",+ input: JSON.stringify([+ { role: "user", content: `Question ${turnNumber}` },+ ]),+ output: JSON.stringify([+ { role: "assistant", content: `Answer ${turnNumber}` },+ ]),+ metadata: {},+ },+ ],+ };+ },+);++const workflowTranscripts = new Map(+ [+ supportAgentWorkflow,+ codingAgentWorkflow,+ langfuseAssistantWorkflow,+ manySimpleTurnsWorkflow,+ ].map((workflow) => [+ workflow,+ workflow.map(+ (item): WorkflowTrace => ({+ trace: item.trace,+ turnNumber: item.turnNumber,+ state: {+ type: "transcript",+ result: {+ state: "loaded",+ cutoff: false,+ transcript: assembleTranscript(+ orderObservations(item.observations),+ ),+ },+ },+ }),+ ),+ ]),+);++const traces: TraceProps[] = [+ {+ trace: {+ id: "trace-1",+ name: "First turn",+ timestamp: new Date("2026-09-24T12:00:00Z"),+ environment: "default",+ userId: null,+ observationCount: 0,+ latencyMs: 1000,+ scores: [],+ },+ turnNumber: 1,+ state: {+ type: "transcript",+ result: {+ state: "loaded",+ cutoff: false,+ transcript: {+ threads: [{- id: generationTool.callId,- name: generationTool.name,- arguments: generationTool.input,+ conversationHistory: [],+ currentTurn: {+ nestingLevel: 0,+ observations: [],+ messages: [+ {+ observationId: "generation-1",+ traceId: "trace-1",+ startTime: new Date("2026-09-24T12:00:00Z"),+ endTime: null,+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Can you check my order?" }],+ },+ {+ observationId: "generation-1",+ traceId: "trace-1",+ startTime: new Date("2026-09-24T12:00:00Z"),+ endTime: null,+ role: "assistant",+ source: "output",+ parts: [{ type: "text", text: "I'll look it up." }],+ },+ ],+ },},- ])- : 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;-};+ },+ onOpenTrace: () => {},+ onOpenObservation: () => {},+ scrollTarget: null,+ },+ {+ trace: {+ id: "trace-2",+ name: "Next turn",+ timestamp: new Date("2026-09-24T12:01:00Z"),+ environment: "default",+ userId: null,+ observationCount: 1,+ latencyMs: null,+ scores: [],+ },+ turnNumber: 2,+ state: { type: "loading" },+ onOpenTrace: () => {},+ onOpenObservation: () => {},+ scrollTarget: null,+ },+];-const nestedObservation = ({- id,- parentObservationId,- type,- input,- output,- offset,+function SessionConversationalViewStory({+ workflowTraces,+ transcriptTraces,+ isLoading = false,+ isSearchPending = false,+ groupedTools = false,+ searchQueryOverride,+ viewportHeight,+ pageOffset = 0,+ delayedLoad = false,}: {- id: string;- parentObservationId: string | null;- type: "AGENT" | "GENERATION" | "TOOL" | "SPAN";- 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;+ workflowTraces?: WorkflowFixture[];+ transcriptTraces?: TraceProps[];+ isLoading?: boolean;+ isSearchPending?: boolean;+ groupedTools?: boolean;+ searchQueryOverride?: string;+ viewportHeight?: number;+ pageOffset?: number;+ delayedLoad?: boolean;+}) {+ const [transcriptsLoaded, setTranscriptsLoaded] = useState(!delayedLoad);+ const [search, setSearch] = useState("");+ const [collapsedTraceIds, setCollapsedTraceIds] = useState<Set<string>>(+ new Set(),+ );+ const [scrollTarget, setScrollTarget] =+ useState<SessionConversationTimelineScrollTarget | null>(null);+ const requestId = useRef(0);+ const toolTraces: TraceProps[] = [+ {+ ...traces[0]!,+ state: {+ type: "transcript",+ result: {+ state: "loaded",+ cutoff: false,+ transcript: {+ threads: [+ {+ conversationHistory: [],+ currentTurn: {+ nestingLevel: 0,+ observations: [],+ messages: [+ Array.from({ length: 5 }, () => "tool_1"),+ ["tool_a", "tool_b"],+ Array.from(+ { length: 7 },+ (_, index) => `very_long_tool_name_${index}`,+ ),+ ].flatMap((names, batchIndex) => {+ const provenance = {+ observationId: `batch-${batchIndex}`,+ traceId: traces[0]!.trace.id,+ startTime: traces[0]!.trace.timestamp,+ endTime: null,+ role: "assistant" as const,+ source: "output" as const,+ };+ return [+ {+ ...provenance,+ parts: [+ {+ type: "text" as const,+ text: `Tool batch ${batchIndex + 1}`,+ },+ ],+ },+ {+ ...provenance,+ parts: names.map((toolName, toolIndex) => ({+ type: "tool-call" as const,+ toolName,+ toolCallId: `${batchIndex}-${toolIndex}`,+ input: { toolIndex },+ })),+ },+ ];+ }),+ },+ },+ ],+ },+ },+ },+ },+ ];+ const workflowTraceProps = workflowTraces+ ? (workflowTranscripts.get(workflowTraces) ?? []).map((item) => ({+ ...item,+ onOpenTrace: fn(),+ onOpenObservation: fn(),+ scrollTarget: null,+ }))+ : (transcriptTraces ?? traces);+ const loadedTraces = groupedTools ? toolTraces : workflowTraceProps;+ const displayedTraces: TraceProps[] = transcriptsLoaded+ ? loadedTraces+ : loadedTraces.map((item) => ({ ...item, state: { type: "loading" } }));+ const entries = getSessionConversationEntries(+ displayedTraces.map((item) => ({+ trace: item.trace,+ transcript:+ item.state.type === "transcript"+ ? item.state.result.transcript+ : undefined,+ })),+ );+ const controller = useSessionConversationTimelineController(+ entries.map((entry) => ({+ trace: displayedTraces[entry.traceIndex]!.trace,+ itemId: entry.itemId,+ })),+ );+ if (isLoading) {+ return (+ <div className="@container/session-workspace flex h-screen min-w-[320px]">+ <SessionConversationalView+ state="loading"+ traces={displayedTraces.map((item) => ({+ ...item,+ state: { type: "loading" },+ }))}+ controller={controller}+ />+ </div>+ );+ }+ return (+ <div+ className="@container/session-workspace relative flex h-screen min-w-[320px]"+ style={{+ height:+ viewportHeight === undefined+ ? undefined+ : viewportHeight + pageOffset,+ paddingTop: pageOffset,+ }}+ >+ {delayedLoad && !transcriptsLoaded && (+ <button+ type="button"+ className="absolute top-0 left-0"+ onClick={() => setTranscriptsLoaded(true)}+ >+ Load transcripts+ </button>+ )}+ <SessionConversationalView+ state="loaded"+ search={search}+ searchQuery={searchQueryOverride ?? search.trim()}+ isSearchPending={+ isSearchPending ||+ (searchQueryOverride !== undefined &&+ search.trim() !== searchQueryOverride)+ }+ onSearchChange={setSearch}+ expandedTraceIds={+ new Set(+ entries+ .filter((item) => !collapsedTraceIds.has(item.itemId))+ .map((item) => item.itemId),+ )+ }+ onToggleTraceExpanded={(traceId) =>+ setCollapsedTraceIds((current) => {+ const next = new Set(current);+ if (next.has(traceId)) next.delete(traceId);+ else next.add(traceId);+ return next;+ })+ }+ onSelect={(index, observationId, rowId) => {+ const entry = entries[index];+ const traceId = entry+ ? displayedTraces[entry.traceIndex]?.trace.id+ : undefined;+ if (traceId && observationId) {+ setScrollTarget({+ itemId: entry?.itemId,+ traceId,+ observationId,+ rowId,+ requestId: ++requestId.current,+ });+ }+ controller.onSelect(index, observationId, rowId);+ }}+ onVisibleTraceIdsChange={fn()}+ isLoadingTranscripts={isSearchPending}+ transcriptLoadError={false}+ traces={displayedTraces.map((item) => ({+ ...item,+ scrollTarget,+ }))}+ controller={controller}+ />+ </div>+ );+}-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 navigationTraces: TraceProps[] = Array.from(+ { length: 32 },+ (_, index) => {+ const traceId = `scroll-turn-${index + 1}`;+ return {+ ...traces[0]!,+ trace: {+ ...traces[0]!.trace,+ id: traceId,+ name: `Navigation turn ${index + 1}`,+ },+ turnNumber: index + 1,+ state: {+ type: "transcript",+ observations: [],+ result: {+ state: "loaded",+ cutoff: false,+ transcript: {+ threads: [0, 1, 2].map((threadIndex) => {+ const provenance = {+ observationId: "shared-generation",+ traceId,+ startTime: traces[0]!.trace.timestamp,+ endTime: null,+ source: "output" as const,+ };+ return {+ conversationHistory: [],+ currentTurn: {+ nestingLevel: threadIndex === 1 ? 1 : 0,+ observations: [],+ messages: [+ ...(["system", "user", "assistant"] as const).map(+ (role) => ({+ ...provenance,+ role,+ parts: [+ {+ type: "text" as const,+ text: `Turn ${index + 1} thread ${threadIndex + 1} ${role}. ${+ role === "assistant" && index % 4 === 0+ ? "Variable height transcript content.\n\n".repeat(+ 25,+ )+ : "Navigation content."+ }`,+ },+ ],+ }),+ ),+ {+ ...provenance,+ role: "assistant" as const,+ parts: ["lookup", "save"].map((toolName) => ({+ type: "tool-call" as const,+ toolName,+ toolCallId: `${traceId}-${threadIndex}-${toolName}`,+ input: { toolName },+ })),+ },+ ],+ },+ };+ }),+ },+ },+ },+ };+ },+);++function viewportAnchor(feed: HTMLElement) {+ const maxOffset = Math.max(0, feed.scrollHeight - feed.clientHeight);+ const transition = Math.min(feed.clientHeight * 0.2, maxOffset);+ const inset = Math.max(+ 0,+ Math.min(+ feed.clientHeight * 0.2,+ feed.clientHeight - 1,+ feed.scrollHeight - 1,+ ),+ );+ if (transition === 0) return inset;+ const progress = Math.max(0, 1 - (maxOffset - feed.scrollTop) / transition);+ return inset + (feed.clientHeight - 1 - inset) * progress;+}++async function expectNavigation(+ canvasElement: HTMLElement,+ headerName: string | RegExp,+ itemId: string,+ rowId: string | false,+) {+ const canvas = within(canvasElement);+ const sidebar = within(canvas.getByRole("complementary"));+ const feed = canvas.getByLabelText("Session conversation timeline");+ await expect(+ sidebar.getByRole("button", { name: headerName }),+ ).toHaveAttribute("aria-current", "true");+ const assertGeometry = () => {+ const entry = feed.querySelector<HTMLElement>(+ `[data-session-item-id="${itemId}"]`,+ );+ const target = rowId+ ? entry?.querySelector<HTMLElement>(+ `[data-session-transcript-row-id="${rowId}"]`,+ )+ : entry?.closest<HTMLElement>("[data-index]");+ if (!target) throw new Error(`Target ${itemId} is not mounted`);+ const position =+ target.getBoundingClientRect().top -+ feed.getBoundingClientRect().top -+ feed.clientTop;+ const anchor = viewportAnchor(feed);+ const inset = feed.clientHeight * 0.2;+ const roundingTolerance =+ anchor === inset+ ? 2+ : 2 ++ (feed.clientHeight - 1 - inset) /+ Math.min(+ feed.clientHeight * 0.2,+ feed.scrollHeight - feed.clientHeight,+ );+ // The first entry cannot acquire an inset by scrolling before offset zero.+ const expectedAnchor =+ feed.scrollTop === 0 && position >= 0 && position < inset+ ? position+ : anchor;+ expect(Math.abs(position - expectedAnchor)).toBeLessThanOrEqual(+ roundingTolerance,+ );+ };+ await waitFor(assertGeometry, { timeout: 6_000 });+ await new Promise((resolve) => window.setTimeout(resolve, 200));+ assertGeometry();+ // A zero-distance user intent removes any navigation override: geometry must+ // independently yield the same active entry through the manual scroll spy.+ feed.dispatchEvent(new WheelEvent("wheel", { bubbles: true }));+ await waitFor(() =>+ expect(sidebar.getByRole("button", { name: headerName })).toHaveAttribute(+ "aria-current",+ "true",+ ),+ );+}const meta = preview.meta({- component: SessionConversationTimelineStory,- parameters: { layout: "fullscreen", a11y: { test: "error" } },+ component: SessionConversationalViewStory,+ parameters: { layout: "fullscreen" },});-export default meta;-export const SupportAgentWorkflow = meta.story({- args: loadedArgs,-});--export const CodingAgentWorkflow = meta.story({+export const ManualScrollSynchronization = meta.story({+ name: "(Test) Manual Scroll Synchronization",args: {- ...loadedArgs,- traces: [- {- trace: researchCodingAgentTrace,- turnNumber: 2,- observations: researchCodingAgentObservations,- },- {- trace: implementationCodingAgentTrace,- turnNumber: 3,- observations: implementationCodingAgentObservations,- },- ],+ transcriptTraces: navigationTraces,+ viewportHeight: 480,+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const feed = canvas.getByLabelText("Session conversation timeline");+ const sidebar = within(canvas.getByRole("complementary"));+ const initialPageScroll = window.scrollY;+ const assertVisibleActive = async () => {+ await waitFor(+ () => {+ const anchor =+ feed.getBoundingClientRect().top ++ feed.clientTop ++ viewportAnchor(feed);+ const entry = Array.from(+ feed.querySelectorAll<HTMLElement>("[data-session-item-id]"),+ ).find((element) => {+ const rect = element+ .closest<HTMLElement>("[data-index]")!+ .getBoundingClientRect();+ return rect.top <= anchor && rect.bottom > anchor;+ });+ if (!entry)+ throw new Error("No entry contains the scroll-spy anchor");+ const [traceId, threadIndex] =+ entry.dataset.sessionItemId!.split(":");+ const turn = Number(traceId!.replace("scroll-turn-", ""));+ const thread = threadIndex === "0" ? 1 : 2;+ expect(+ sidebar.getByRole("button", {+ name: (name) =>+ name.startsWith(`${turn}.${thread} Navigation turn ${turn}`),+ }),+ ).toHaveAttribute("aria-current", "true");+ },+ { timeout: 3_000 },+ );+ };+ await assertVisibleActive();+ for (const top of [180, 450, 900, 1_500, 900, 450, 180, 0]) {+ feed.scrollTo({ top, behavior: "instant" });+ await assertVisibleActive();+ }+ const secondEntry = feed+ .querySelector<HTMLElement>('[data-session-item-id="scroll-turn-1:2"]')!+ .closest<HTMLElement>("[data-index]")!;+ const boundary =+ secondEntry.getBoundingClientRect().top -+ feed.getBoundingClientRect().top ++ feed.scrollTop;+ for (const top of [+ boundary - feed.clientHeight * 0.2 - 2,+ boundary - feed.clientHeight * 0.2 + 2,+ boundary - feed.clientHeight * 0.2 - 2,+ 0,+ ]) {+ feed.scrollTo({ top, behavior: "instant" });+ await assertVisibleActive();+ }+ feed.scrollTo({ top: feed.scrollHeight, behavior: "instant" });+ await waitFor(+ () =>+ expect(+ sidebar.getByRole("button", { name: /^32\.2 Navigation turn 32/ }),+ ).toHaveAttribute("aria-current", "true"),+ { timeout: 3_000 },+ );+ feed.scrollTo({ top: 0, behavior: "instant" });+ await assertVisibleActive();+ await expect(window.scrollY).toBe(initialPageScroll);},});-export const LangfuseAssistantWorkflow = meta.story({+export const ExactMessageNavigation = meta.story({+ name: "(Test) Exact Message And Group Navigation",args: {- ...loadedArgs,- traces: [- {- trace: inAppAgentTrace,- turnNumber: 4,- observations: inAppAgentObservations,- },- ],+ transcriptTraces: navigationTraces,+ viewportHeight: 480,+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const sidebar = within(canvas.getByRole("complementary"));+ const search = sidebar.getByRole("textbox");+ await userEvent.type(search, "Turn 1 thread 3");+ const header = /^1\.2 Navigation turn 1/;+ for (const [name, rowId] of [+ ["System message", "2:0"],+ ["User message", "2:1"],+ ["Assistant message", "2:2"],+ ] as const) {+ await userEvent.click(sidebar.getByRole("button", { name }));+ await expectNavigation(canvasElement, header, "scroll-turn-1:2", rowId);+ }+ await userEvent.clear(search);+ await userEvent.type(search, "Turn 2 thread 1");+ const collapse = sidebar.getByRole("button", { name: "Collapse turn" });+ await userEvent.click(collapse);+ await expect(+ sidebar.queryByRole("button", { name: "User message" }),+ ).not.toBeInTheDocument();+ await userEvent.click(+ sidebar.getByRole("button", { name: /^2\.1 Navigation turn 2/ }),+ );+ await expectNavigation(+ canvasElement,+ /^2\.1 Navigation turn 2/,+ "scroll-turn-2:0",+ false,+ );+ await userEvent.click(sidebar.getByRole("button", { name: "Expand turn" }));+ await expect(+ sidebar.getByRole("button", { name: "User message" }),+ ).toBeInTheDocument();+ await userEvent.clear(search);+ const headerButton = sidebar.getByRole("button", {+ name: /^2\.1 Navigation turn 2/,+ });+ const card = within(headerButton.parentElement!.parentElement!);+ await userEvent.click(+ card.getByRole("button", { name: "Tool: lookup · save" }),+ );+ await expectNavigation(+ canvasElement,+ /^2\.1 Navigation turn 2/,+ "scroll-turn-2:0",+ "0:3",+ );+ const entry = canvas+ .getByLabelText("Session conversation timeline")+ .querySelector<HTMLElement>('[data-session-item-id="scroll-turn-2:0"]')!;+ await expect(+ within(entry).getByRole("button", { name: "Hide tools: lookup · save" }),+ ).toHaveAttribute("aria-expanded", "true");},});-export const Loading = meta.story({- args: {- ...loadedArgs,- traces: [{ trace, turnNumber: 1, observations: undefined }],+export const VirtualizedNavigation = meta.story({+ name: "(Test) Far Virtualized Navigation Both Directions",+ args: { transcriptTraces: navigationTraces, viewportHeight: 480 },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const sidebar = within(canvas.getByRole("complementary"));+ const search = sidebar.getByRole("textbox");+ const feed = canvas.getByLabelText("Session conversation timeline");+ for (const turn of [28, 3, 32, 1]) {+ const itemId = `scroll-turn-${turn}:2`;+ if (turn === 28)+ await expect(+ feed.querySelector(`[data-session-item-id="${itemId}"]`),+ ).not.toBeInTheDocument();+ await userEvent.clear(search);+ await userEvent.type(search, `Turn ${turn} thread 3`);+ const header = new RegExp(`^${turn}\\.2 Navigation turn ${turn}`);+ await userEvent.click(sidebar.getByRole("button", { name: header }));+ await expectNavigation(canvasElement, header, itemId, false);+ await userEvent.click(+ sidebar.getByRole("button", { name: "Assistant message" }),+ );+ await expectNavigation(canvasElement, header, itemId, "2:2");+ }},});-export const Error = meta.story({- args: {- ...loadedArgs,- traces: [{ trace, turnNumber: 1, observations: null }],+export const SearchThreadNavigation = meta.story({+ name: "(Test) Filtered Thread Indices And Individual Tools",+ args: { transcriptTraces: navigationTraces, viewportHeight: 480 },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const sidebar = within(canvas.getByRole("complementary"));+ const search = sidebar.getByRole("textbox");+ await userEvent.type(search, "Turn 9 thread 3 assistant");+ await expect(+ sidebar.queryByRole("button", { name: /^9\.1/ }),+ ).not.toBeInTheDocument();+ await userEvent.click(+ sidebar.getByRole("button", { name: "Assistant message" }),+ );+ await expectNavigation(+ canvasElement,+ /^9\.2 Navigation turn 9/,+ "scroll-turn-9:2",+ "2:2",+ );+ await userEvent.clear(search);+ await userEvent.type(search, "save");+ const header = await sidebar.findByRole("button", {+ name: /^9\.2 Navigation turn 9/,+ });+ const card = within(header.parentElement!.parentElement!);+ await userEvent.click(card.getByRole("button", { name: "tool: save" }));+ await expectNavigation(+ canvasElement,+ /^9\.2 Navigation turn 9/,+ "scroll-turn-9:2",+ "2:4",+ );+ await userEvent.clear(search);+ await waitFor(+ () =>+ expect(+ sidebar.getByRole("button", { name: /^9\.2 Navigation turn 9/ }),+ ).toHaveAttribute("aria-current", "true"),+ { timeout: 3_000 },+ );},});-export const Empty = meta.story({- args: {- ...loadedArgs,- traces: [{ trace, turnNumber: 1, observations: [] }],+export const NavigationInterruption = meta.story({+ name: "(Test) Latest Click Wins",+ args: { transcriptTraces: navigationTraces, viewportHeight: 480 },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const sidebar = within(canvas.getByRole("complementary"));+ const search = sidebar.getByRole("textbox");+ await userEvent.type(search, "Turn 2 thread");+ await userEvent.click(+ sidebar.getByRole("button", { name: /^2\.1 Navigation turn 2/ }),+ );+ await userEvent.click(+ sidebar.getByRole("button", { name: /^2\.2 Navigation turn 2/ }),+ );+ await expectNavigation(+ canvasElement,+ /^2\.2 Navigation turn 2/,+ "scroll-turn-2:2",+ false,+ );},});-export const FilteredEmpty = meta.story({- name: "(Test) Filtered Empty",+export const DelayedTranscriptNavigation = meta.story({+ name: "(Test) Navigation Across Delayed Transcript Loading",args: {- ...loadedArgs,- traces: [{ trace, turnNumber: 1, observations: [] }],- emptyState: {- type: "filtered-empty",- viewLabel: "Generations",- onClearFilters: fn(),- },+ transcriptTraces: navigationTraces,+ viewportHeight: 480,+ pageOffset: 80,+ delayedLoad: true,},- play: async ({ args, canvasElement }) => {+ play: async ({ canvasElement }) => {const canvas = within(canvasElement);+ const sidebar = within(canvas.getByRole("complementary"));+ await userEvent.click(+ sidebar.getByRole("button", { name: "2 Navigation turn 2" }),+ );+ await expect(+ sidebar.getByRole("button", { name: "2 Navigation turn 2" }),+ ).toHaveAttribute("aria-current", "true");await userEvent.click(- canvas.getByRole("button", { name: "Clear filters" }),+ canvas.getByRole("button", { name: "Load transcripts" }),+ );+ await expectNavigation(+ canvasElement,+ /^2\.1 Navigation turn 2/,+ "scroll-turn-2:0",+ false,);- if (args.emptyState.type !== "filtered-empty") throw new globalThis.Error();- await expect(args.emptyState.onClearFilters).toHaveBeenCalledOnce();},});-export const RenderLoadedConversation = meta.story({- name: "(Test) Renders Loaded Conversation",- args: SupportAgentWorkflow.input.args,+export const SidebarFollowResume = meta.story({+ name: "(Test) Sidebar Follow Resumes After User Idle",+ args: { transcriptTraces: navigationTraces, viewportHeight: 480 },play: async ({ canvasElement }) => {const canvas = within(canvasElement);- const traceButton = canvas.getByRole("button", {- name: /1.*trace.*trace-order-support-8f3a2/i,+ const feed = canvas.getByLabelText("Session conversation timeline");+ const list = canvas.getByRole("region", { name: "Session turns" });+ list.dispatchEvent(new WheelEvent("wheel", { deltaY: 100, bubbles: true }));+ feed.scrollTo({ top: feed.scrollHeight, behavior: "instant" });+ await waitFor(() => expect(list.scrollTop).toBeGreaterThan(0), {+ timeout: 3_000,});- 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",+ const sidebar = within(canvas.getByRole("complementary"));+ const active = await sidebar.findByRole("button", {+ name: /^32\.2 Navigation turn 32/,});- 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 .*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();+ await expect(active).toHaveAttribute("aria-current", "true");+ const activeRect = active.getBoundingClientRect();+ const listRect = list.getBoundingClientRect();+ await expect(activeRect.top).toBeGreaterThanOrEqual(listRect.top);+ await expect(activeRect.bottom).toBeLessThanOrEqual(listRect.bottom);},});--export const TruncatedObservation = meta.story({- name: "(Test) Renders Truncated Observation",+export const NestedThreadsHidden = meta.story({+ name: "(Test) Nested Threads Hidden",args: {- ...loadedArgs,- traces: [+ transcriptTraces: [{- 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,+ ...traces[0]!,+ state: {+ type: "transcript",+ result: {+ state: "loaded",+ cutoff: false,+ transcript: {+ threads: [+ { nestingLevel: 0, text: "Main agent checks the order." },+ { nestingLevel: 1, text: "Nested agent checks inventory." },+ { nestingLevel: 2, text: "Deeply nested agent checks stock." },+ { nestingLevel: 0, text: "Main agent confirms delivery." },+ ].map(({ nestingLevel, text }) => ({+ conversationHistory: [],+ currentTurn: {+ nestingLevel,+ observations: [],+ messages: [+ {+ observationId: "generation-1",+ traceId: "trace-1",+ startTime: traces[0]!.trace.timestamp,+ endTime: null,+ role: "assistant",+ source: "output",+ parts: [{ type: "text", text }],+ },+ ],+ },+ })),+ },},- ],+ },+ },+ { ...traces[1]!, turnNumber: 2, state: traces[0]!.state },+ {+ ...traces[1]!,+ trace: { ...traces[1]!.trace, id: "trace-3", name: "Loading turn" },+ turnNumber: 3,},],},play: async ({ canvasElement }) => {const canvas = within(canvasElement);+ const sidebar = within(canvas.getByRole("complementary"));+ const timeline = within(+ canvas.getByLabelText("Session conversation timeline"),+ );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.",- ),+ sidebar.queryByRole("button", { name: "2 nested threads hidden" }),).not.toBeInTheDocument();await expect(- canvas.queryByRole("button", { name: "Open in trace view" }),+ sidebar.queryByText("2 nested threads hidden"),).not.toBeInTheDocument();- await expect(canvasElement.querySelector("pre")).toBeNull();- },-});--export const ObservationIssues = meta.story({- name: "(Test) Renders Observation Issues",- args: {- ...loadedArgs,- traces: [- {- trace,- turnNumber: 1,- observations: [- {- ...observations[0]!,- level: "WARNING",- statusMessage:- "TimeoutError: Model response exceeded 30s\n at generateResponse (src/agent.ts:42:11)\n at async runTurn (src/session.ts:18:5)",- },- {- ...observations[1]!,- level: "ERROR",- statusMessage: JSON.stringify(- {- code: "TOOL_TIMEOUT",- tool: "get_order",- retryable: true,- },- null,- 2,- ),- },- ],- },- ],- },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- const warning = canvas.getByRole("img", {- name: /WARNING: TimeoutError: Model response exceeded 30s/,+ const warnings = await timeline.findAllByRole("button", {+ name: "2 nested threads hidden",});- const error = canvas.getByRole("img", {- name: /ERROR:.*TOOL_TIMEOUT/s,- });-- await expect(warning).toHaveClass("bg-light-yellow", "text-dark-yellow");- await expect(error).toHaveClass("bg-light-red", "text-dark-red");- await userEvent.hover(warning);- await expect(- await within(canvasElement.ownerDocument.body).findByRole("tooltip"),- ).toHaveTextContent("at generateResponse (src/agent.ts:42:11)");- await userEvent.unhover(warning);- await userEvent.hover(error);- await expect(- await within(canvasElement.ownerDocument.body).findByRole("tooltip"),- ).toHaveTextContent('"code": "TOOL_TIMEOUT"');- },-});--export const UseObservationFilters = meta.story({- name: "(Test) Uses Observation Filters",- args: {- ...loadedArgs,- observationActions: {- onFilterByName: fn(),- annotate: { disabled: false, onSelect: fn() },- comment: { disabled: false, onSelect: fn() },- addToDataset: { disabled: false, onSelect: 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 expect(warnings).toHaveLength(2);+ for (const surface of [timeline]) {+ for (const text of [+ "Main agent checks the order.",+ "Main agent confirms delivery.",+ ]) {+ await expect(await surface.findByText(text)).toBeInTheDocument();+ }+ for (const text of [+ "Nested agent checks inventory.",+ "Deeply nested agent checks stock.",+ ]) {+ await expect(surface.queryByText(text)).not.toBeInTheDocument();+ }+ }+ const search = sidebar.getByRole("textbox", {+ name: "Search messages and tools",});-- 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 userEvent.type(search, "confirms delivery");await expect(- page.getByRole("menuitem", { name: "Annotate" }),- ).toBeInTheDocument();- await expect(- page.getByRole("menuitem", { name: "Comments" }),- ).toBeInTheDocument();- await expect(- page.getByRole("menuitem", { name: "Add to dataset" }),- ).toBeInTheDocument();-+ await sidebar.findByRole("button", { name: "Assistant message" }),+ ).toHaveTextContent("Main agent confirms delivery.");+ await expect(sidebar.queryByText("1.1")).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",+ sidebar.getByRole("button", { name: "Assistant message" }),);await waitFor(() =>- expect(- canvasElement.ownerDocument.getElementById("__next"),- ).not.toHaveAttribute("aria-hidden", "true"),+ expect(sidebar.getByRole("button", { name: /^1\.2 / })).toHaveAttribute(+ "aria-current",+ "true",+ ),);+ await expect(+ canvasElement.querySelector(+ '[data-session-item-id="trace-1:3"] [data-session-transcript-row-id="3:0"]',+ ),+ ).toHaveAttribute("data-scroll-request-id");+ await userEvent.clear(search);},});--export const MetadataOmitted = meta.story({- name: "(Test) Renders Omitted Metadata",- args: {- ...loadedArgs,- traces: [- {- trace,- turnNumber: 1,- observations: [{ ...observations[0]!, metadataTruncated: true }],- },- ],- },+export const Loading = meta.story({+ name: "(Test) Loading",+ args: { isLoading: true },play: async ({ canvasElement }) => {- const canvas = within(canvasElement);+ const sidebar = within(canvasElement).getByRole("complementary");+ await expect(sidebar).toHaveAttribute("aria-busy", "true");await expect(- canvas.getByRole("img", {- name: "Metadata omitted because it is too large",+ within(sidebar).getByRole("textbox", {+ name: "Search messages and tools",}),- ).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();+ ).toBeDisabled();},});--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,- },- ],- },- ],- },+export const SupportAgentWorkflow = meta.story({+ name: "(Test) Support Agent Workflow",+ args: { workflowTraces: supportAgentWorkflow },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" }),+ const sidebar = within(canvas.getByRole("complementary"));+ for (const name of [+ "System message",+ "User message",+ "Assistant message",+ ]) {+ await expect(+ (await sidebar.findAllByRole("button", { name })).length,+ ).toBeGreaterThan(0);+ }+ await expect(+ await sidebar.findByRole("button", { name: "tool: Get order" }),+ ).toBeInTheDocument();+ await expect(+ sidebar.getByRole("textbox", { name: "Search messages and tools" }),+ ).toBeEnabled();+ await expect(+ await within(+ canvas.getByLabelText("Session conversation timeline"),+ ).findByText(/Hi, I just noticed order #LF-20481/),+ ).toBeInTheDocument();+ await expect(+ await within(+ canvas.getByLabelText("Session conversation timeline"),+ ).findByText(/Your shipping address has been updated/),+ ).toBeInTheDocument();+ const timeline = within(+ canvas.getByLabelText("Session conversation timeline"),);- await expect(args.onOpenObservation).toHaveBeenCalledWith(- trace,- "generation-1",+ for (const button of timeline.queryAllByRole("button", {+ name: /^Show tools:/,+ })) {+ await userEvent.click(button);+ }+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand Get order" }),);- },-});--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 expect(- expandButton- .closest("[data-session-observation-depth]")- ?.querySelector("[data-session-observation-rail-end]"),- ).not.toBeInTheDocument();-+ await expect(canvas.getByText(/800 Pine Street/)).toBeInTheDocument();await userEvent.click(- canvas.getByRole("button", { name: "Collapse Get order" }),+ canvas.getByRole("button", { name: "Expand Update shipping address" }),);- await expect(header.getBoundingClientRect().top).toBe(initialTop);- await expect(canvasElement.querySelectorAll("pre")).toHaveLength(0);+ await expect(canvas.getByText(/addr_7b19c2/)).toBeInTheDocument();},});--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]!],- },- ],- },+export const ConsecutiveToolGroups = meta.story({+ name: "(Test) Groups Consecutive Tools",+ args: { groupedTools: true },play: async ({ canvasElement }) => {const canvas = within(canvasElement);- 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",- },+ const sidebar = within(canvas.getByRole("complementary"));+ const timeline = within(+ canvas.getByLabelText("Session conversation timeline"),);-- await expect(toolRow).toHaveAttribute(- "data-session-observation-depth",- "1",+ const longNames = Array.from(+ { length: 7 },+ (_, index) => `very_long_tool_name_${index}`,+ ).join(" · ");+ for (const summary of ["5x tool_1", "tool_a · tool_b", longNames]) {+ await expect(+ sidebar.getByRole("button", { name: `Tool: ${summary}` }),+ ).toBeInTheDocument();+ await expect(+ timeline.getByRole("button", { name: `Show tools: ${summary}` }),+ ).toHaveAttribute("aria-expanded", "false");+ }+ await userEvent.click(+ sidebar.getByRole("button", { name: "Tool: tool_a · tool_b" }),);- await expect(toolRow).not.toHaveAttribute("style");- await expect(- toolRow?.querySelector('[data-session-observation-rail-depth="0"]'),- ).toHaveClass("left-[7px]");- 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?.querySelectorAll("[data-session-observation-rail-depth]"),- ).toHaveLength(1);await expect(- toolRow?.querySelector("[data-session-observation-rail-end]"),- ).not.toBeInTheDocument();- },-});--export const ExpandFinalToolObservation = meta.story({- name: "(Test) Ends Rail After Final Expanded Tool",- args: {- ...loadedArgs,- traces: [- {- trace: { ...trace, observationCount: 1 },- turnNumber: 1,- observations: [observations[1]!],- },- ],- },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- const expandButton = canvas.getByRole("button", {- name: "Expand Get order",- });-- await userEvent.click(expandButton);-+ timeline.getByRole("button", { name: "Hide tools: tool_a · tool_b" }),+ ).toHaveAttribute("aria-expanded", "true");await expect(- expandButton- .closest("[data-session-observation-depth]")- ?.querySelector("[data-session-observation-rail-end]"),+ timeline.getByRole("button", { name: "Expand tool_b" }),).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" }),+ timeline.getByRole("button", { name: "Hide tools: tool_a · tool_b" }),);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();+ timeline.getByRole("button", { name: "Show tools: tool_a · tool_b" }),+ ).toHaveAttribute("aria-expanded", "false");+ await userEvent.type(sidebar.getByRole("textbox"), "tool_1");await expect(- observation.getByText(- "Never expose identifiers or payloads from real users.",- ),- ).toBeInTheDocument();+ sidebar.getAllByRole("button", { name: "tool: tool_1" }),+ ).toHaveLength(5);await expect(- observation.queryByRole("button", { name: "skill" }),+ sidebar.queryByRole("button", { name: "Tool: tool_a · tool_b" }),).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.",- ),+ timeline.getByRole("button", { name: `Show tools: ${longNames}` }),).toBeInTheDocument();},});--export const ExpandNestedObservations = meta.story({- name: "(Test) Expands Nested Observations",- args: {- ...loadedArgs,- traces: [{ trace, turnNumber: 1, observations: nestedObservations }],- },+export const CodingAgentWorkflow = meta.story({+ args: { workflowTraces: codingAgentWorkflow },+});+export const LangfuseAssistantWorkflow = meta.story({+ args: { workflowTraces: langfuseAssistantWorkflow },+});+export const ManySimpleTurns = meta.story({+ args: { workflowTraces: manySimpleTurnsWorkflow },+});+export const MultipleTraces = meta.story({+ name: "(Test) Renders Multiple Traces",play: async ({ canvasElement }) => {- const canvas = within(canvasElement);-- await expect(canvas.getByText("Build the dashboard")).toBeInTheDocument();+ const sidebar = within(within(canvasElement).getByRole("complementary"));await expect(- canvas.getByText("Finished the dashboard"),+ await sidebar.findByRole("button", { name: "User message" }),).toBeInTheDocument();- const leafObservation = canvas- .getByText("Standalone answer")- .closest("[data-session-observation-depth]");await expect(- leafObservation?.querySelector(- '[data-session-observation-rail-depth="0"]',- ),+ await sidebar.findByRole("button", { name: "Assistant message" }),).toBeInTheDocument();await expect(- leafObservation?.querySelector("[data-session-observation-rail-end]"),+ await sidebar.findByRole("button", { name: "1 First turn" }),).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",- });await expect(- canvas.getByText("2 generations and 5 tools"),+ await sidebar.findByRole("button", { name: "2 Next turn" }),).toBeInTheDocument();- 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();- await userEvent.hover(rootToggle);- await expect(- rootStart?.querySelector('[data-session-observation-rail-depth="0"]'),- ).toHaveClass("bg-border");- await userEvent.unhover(rootToggle);- const initialRootToggleTop = rootToggle.getBoundingClientRect().top;-- // Expanding a parent reveals its direct children, but nested groups remain collapsed.- await userEvent.click(rootToggle);-- // Message content leaves room to move the collapse control up one row.- await expect(rootToggle.getBoundingClientRect().top).toBe(- initialRootToggleTop - 28,- );- 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-chevron-down"),- ).not.toBeNull();- await expect(- rootStart?.querySelector('[data-session-observation-rail-depth="0"]'),- ).toHaveClass("bg-border");- 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).not.toHaveAttribute("style");- await expect(- nestedGeneration?.querySelectorAll(- "[data-session-observation-rail-depth]",- ),- ).toHaveLength(1);- const nestedObservationIcon = nestedGeneration?.querySelector(- '[data-session-observation-id="generation-1"] button svg',+ const canvas = within(+ within(canvasElement).getByLabelText("Session conversation timeline"),);- await expect(nestedObservationIcon).not.toBeNull();- rootToggle.blur();- await userEvent.hover(rootToggle);await expect(- rootToggle.parentElement?.querySelector(- "[data-session-collapse-rail-highlight]",- ),+ await canvas.findByText("Can you check my order?"),).toBeInTheDocument();await expect(- rootStart?.querySelector('[data-session-observation-rail-depth="0"]'),- ).toHaveClass("bg-border");- await expect(- nestedGeneration?.querySelector("[data-session-observation-rail-depth]"),- ).toHaveClass("bg-primary/60");- await expect(- closingRailEnd- ?.closest("[data-session-observation-depth]")- ?.querySelector("[data-session-observation-rail-depth]"),- ).toHaveClass("bg-border");- await userEvent.unhover(rootToggle);- const nestedToggle = canvas.getByRole("button", {- name: "Show tools: tool-1, tool-2, and tool-3",- });- const initialNestedToggleTop = nestedToggle.getBoundingClientRect().top;-- // Nested observations expand independently from their ancestors.- await userEvent.click(nestedToggle);-- // A message-less observation retains its control row to avoid its icon.- 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).not.toHaveAttribute("style");- await expect(- nestedTool?.querySelectorAll("[data-session-observation-rail-depth]"),- ).toHaveLength(1);- await expect(- nestedTool?.querySelector("[data-session-observation-rail-depth]"),- ).toHaveClass("left-[7px]");-- nestedToggle.blur();- await userEvent.hover(nestedToggle);- await expect(- nestedTool?.querySelector("[data-session-observation-rail-depth]"),- ).toHaveClass("bg-primary/60");- await userEvent.unhover(nestedToggle);- await expect(- nestedTool?.querySelector("[data-session-observation-rail-depth]"),- ).toHaveClass("bg-border");-- await userEvent.click(- canvas.getByRole("button", { name: "Expand tool-1" }),- );- await expect(- nestedTool?.querySelectorAll("[data-session-observation-rail-depth]"),- ).toHaveLength(1);- await expect(- nestedTool?.querySelector("[data-session-observation-rail-end]"),- ).not.toBeInTheDocument();-- await userEvent.click(- canvas.getByRole("button", { name: "Collapse tool-1" }),- );- await expect(- nestedTool?.querySelectorAll("[data-session-observation-rail-depth]"),- ).toHaveLength(1);- 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 returns the expand control to its summary row.- await expect(nestedToggle.getBoundingClientRect().top).toBe(- initialNestedToggleTop,- );- await expect(canvas.queryByText("tool-1")).not.toBeInTheDocument();- await expect(- canvas.getByRole("button", {- name: "Show tools: tool-1, tool-2, and tool-3",- }),+ await canvas.findByText("I'll look it up."),).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,- ),- },- ],- },+export const SearchMatchingMessages = meta.story({+ name: "(Test) Filters Only Sidebar Messages",play: async ({ canvasElement }) => {const canvas = within(canvasElement);-- await expect(canvas.getByText("generation-1")).toBeInTheDocument();+ const sidebar = within(canvas.getByRole("complementary"));+ await sidebar.findByRole("button", { name: "User message" });+ const timeline = canvas.getByLabelText("Session conversation timeline");+ await within(timeline).findByText("I'll look it up.");+ await userEvent.type(sidebar.getByRole("textbox"), "ORDER");await expect(- canvas.getByRole("button", {- name: "Hide 2 generations and 5 tools",- }),+ sidebar.getByRole("button", { name: "User message" }),).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 expect(- canvas.getAllByRole("button", { name: "get_subscription_details" }),- ).toHaveLength(1);+ sidebar.queryByRole("button", { name: "Assistant message" }),+ ).not.toBeInTheDocument();await expect(- canvasElement.querySelector(- '[data-session-observation-id="tool-shape-observation"]',- ),+ sidebar.getByRole("button", { name: "1 First turn" }),).toBeInTheDocument();- },-});--export const ToolWithNestedObservation = meta.story({- name: "(Test) Tool With Nested Observation",- args: {- ...loadedArgs,- traces: [- {- trace: { ...trace, observationCount: 3 },- turnNumber: 1,- observations: [- nestedObservation({- id: "assistant-run",- parentObservationId: null,- type: "AGENT",- input: null,- output: null,- offset: 0,- }),- nestedObservation({- id: "lookup-record",- parentObservationId: "assistant-run",- type: "TOOL",- input: { recordId: "record-1" },- output: { found: true },- offset: 1,- }),- nestedObservation({- id: "lookup-log",- parentObservationId: "lookup-record",- type: "SPAN",- input: null,- output: null,- offset: 2,- }),- ],- },- ],- },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);await expect(- canvasElement.querySelector(- '[data-session-observation-id="lookup-record"]',+ within(canvas.getByLabelText("Session conversation timeline")).getByText(+ "I'll look it up.",),).toBeInTheDocument();- await userEvent.click(canvas.getByRole("button", { name: "Show 1 span" }));- await expect(canvas.getByText("lookup-log")).toBeInTheDocument();+ await userEvent.clear(sidebar.getByRole("textbox"));+ await userEvent.type(sidebar.getByRole("textbox"), "no-such-message");+ await waitFor(async () => {+ await expect(+ sidebar.queryByRole("button", { name: "User message" }),+ ).not.toBeInTheDocument();+ await expect(+ sidebar.queryByRole("button", { name: "Assistant message" }),+ ).not.toBeInTheDocument();+ });await expect(- canvasElement.querySelector(- '[data-session-observation-id="lookup-record"]',- ),+ within(timeline).getByText("I'll look it up."),).toBeInTheDocument();- },-});--export const CodingAgentSubagentTurn = meta.story({- name: "(Test) Coding Agent Subagent Turn Inside Tool",- args: {- ...loadedArgs,- traces: [- {- trace: { ...trace, observationCount: 6 },- turnNumber: 1,- observations: [- nestedObservation({- id: "coding-agent-turn",- parentObservationId: null,- type: "AGENT",- input: null,- output: null,- offset: 0,- }),- nestedObservation({- id: "spawn-reviewer",- parentObservationId: "coding-agent-turn",- type: "TOOL",- input: { task: "Review the new search endpoint" },- output: { summary: "Found one missing test" },- offset: 1,- }),- nestedObservation({- id: "reviewer-turn",- parentObservationId: "spawn-reviewer",- type: "AGENT",- input: null,- output: null,- offset: 2,- }),- nestedObservation({- id: "reviewer-analysis",- parentObservationId: "reviewer-turn",- type: "GENERATION",- input: "Review the search endpoint",- output: "I will inspect the handler and its tests.",- offset: 3,- }),- nestedObservation({- id: "read-search-tests",- parentObservationId: "reviewer-turn",- type: "TOOL",- input: { path: "search.test.ts" },- output: { cases: 3 },- offset: 4,- }),- nestedObservation({- id: "reviewer-summary",- parentObservationId: "reviewer-turn",- type: "GENERATION",- input: null,- output: "Add a test for an empty search query.",- offset: 5,- }),- ],- },- ],- },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);+ await userEvent.clear(sidebar.getByRole("textbox"));await expect(- canvasElement.querySelector(- '[data-session-observation-id="spawn-reviewer"]',- ),+ await sidebar.findByRole("button", { name: "User message" }),).toBeInTheDocument();-- await userEvent.click(- canvas.getByRole("button", {- name: "Show 2 generations, tools: read-search-tests, and 1 agent",- }),- );- await expect(canvas.getByText("reviewer-turn")).toBeInTheDocument();- await userEvent.click(- canvas.getByRole("button", {- name: "Show 2 generations and tools: read-search-tests",- }),- );- await expect(canvas.getByText("read-search-tests")).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 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"]',- ),+ await sidebar.findByRole("button", { name: "Assistant message" }),).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",- },- },- }),+export const ClearPendingSearch = meta.story({+ name: "(Test) Clears Highlights While Search Is Pending",+ args: { searchQueryOverride: "ORDER" },play: async ({ canvasElement }) => {const canvas = within(canvasElement);+ const input = canvas.getByRole("textbox", {+ name: "Search messages and tools",+ });+ const timeline = canvas.getByLabelText("Session conversation timeline");+ await userEvent.type(input, "ORDER");+ await waitFor(async () => {+ await expect(+ Array.from(CSS.highlights.values())+ .flatMap((highlight) => Array.from(highlight))+ .filter((range) => timeline.contains(range.startContainer))+ .map((range) => range.toString()),+ ).toContain("order");+ });+ await userEvent.clear(input);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();+ Array.from(CSS.highlights.values())+ .flatMap((highlight) => Array.from(highlight))+ .filter((range) => timeline.contains(range.startContainer)),+ ).toHaveLength(0);},});--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",- },- },- }),+export const PendingSearch = meta.story({+ name: "(Test) Clears Only Sidebar During Pending Search",+ args: { isSearchPending: true },play: async ({ canvasElement }) => {const canvas = within(canvasElement);- await userEvent.click(- canvas.getByRole("button", {- name: "Show tools: search_documentation and get_customer_profile",- }),- );- await expect(- canvas.getAllByRole("button", { name: "search_documentation" }),- ).toHaveLength(1);+ const sidebar = within(canvas.getByRole("complementary"));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"]',- ),+ sidebar.getByText("Loading transcripts..."),).toBeInTheDocument();await expect(- canvasElement.querySelector(- '[data-session-observation-id="tool-shape-observation"]',+ sidebar.queryByRole("button", { name: "1 First turn" }),+ ).not.toBeInTheDocument();+ await expect(+ within(canvas.getByLabelText("Session conversation timeline")).getByText(+ "Can you check my order?",),).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/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.tsxnew file mode 100644index 0000000000..1f9d92da71--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.tsx@@ -0,0 +1,218 @@+import { type ComponentProps, useLayoutEffect, useId, useRef } from "react";+import {+ SessionConversationSidebar,+ type SessionConversationSidebarTrace,+} from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar";+import { SessionConversationTimeline } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline";+import { type SessionConversationTimelineController } from "@/src/features/sessions/hooks/useSessionConversationTimelineController";+import { getSessionTranscriptRows } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows";+import { getSessionTranscriptThreads } from "../../fns/getSessionTranscriptThreads";+import { getSessionConversationEntries } from "../../fns/getSessionConversationEntries";+import { computeIdleGapSeconds } from "@/src/features/sessions/sessionIdleGap";++export function SessionConversationalView(+ props: (+ | { state: "loading" }+ | (Omit<+ Extract<+ ComponentProps<typeof SessionConversationSidebar>,+ { state: "loaded" }+ >,+ "traces" | "activeTraceId"+ > & {+ searchQuery: string;+ isSearchPending: boolean;+ })+ ) & {+ traces: ComponentProps<typeof SessionConversationTimeline>["traces"];+ controller: SessionConversationTimelineController;+ },+) {+ const transcriptRef = useRef<HTMLDivElement>(null);+ const highlightName = `session-transcript-${useId().replace(/[^a-z0-9_-]/gi, "")}`;+ const searchQuery = props.state === "loaded" ? props.search.trim() : "";+ useLayoutEffect(() => {+ const container = transcriptRef.current;+ if (!container || typeof Highlight === "undefined" || !CSS.highlights)+ return;+ if (!searchQuery) {+ CSS.highlights.get(highlightName)?.clear();+ CSS.highlights.delete(highlightName);+ return;+ }+ const updateHighlights = () => {+ const ranges: Range[] = [];+ const query = searchQuery.toLowerCase();+ const walker = document.createTreeWalker(+ container,+ NodeFilter.SHOW_TEXT,+ {+ acceptNode: (node) =>+ node.parentElement?.closest("[data-session-search-content]") &&+ !node.parentElement.closest("style, script")+ ? NodeFilter.FILTER_ACCEPT+ : NodeFilter.FILTER_REJECT,+ },+ );+ while (walker.nextNode()) {+ const node = walker.currentNode;+ const text = node.textContent ?? "";+ const normalizedText = text.toLowerCase();+ // Case folding can expand characters; ranges use original UTF-16 offsets.+ const offsets: number[] = [];+ if (normalizedText.length !== text.length) {+ let offset = 0;+ for (const character of text) {+ for (const normalizedCharacter of character.toLowerCase()) {+ offsets.push(offset);+ if (normalizedCharacter.length === 2) offsets.push(offset + 1);+ }+ offset += character.length;+ }+ }+ let index = normalizedText.indexOf(query);+ while (index !== -1) {+ const range = document.createRange();+ range.setStart(node, offsets[index] ?? index);+ range.setEnd(+ node,+ offsets.length+ ? offsets[index + query.length - 1]! + 1+ : index + query.length,+ );+ ranges.push(range);+ index = normalizedText.indexOf(query, index + query.length);+ }+ }+ CSS.highlights.set(highlightName, new Highlight(...ranges));+ };+ updateHighlights();+ const observer = new MutationObserver(updateHighlights);+ observer.observe(container, {+ childList: true,+ characterData: true,+ subtree: true,+ });+ return () => {+ observer.disconnect();+ CSS.highlights.get(highlightName)?.clear();+ CSS.highlights.delete(highlightName);+ };+ }, [highlightName, searchQuery]);+ const sidebarTraces: SessionConversationSidebarTrace[] = [];+ const entries = getSessionConversationEntries(+ props.traces.map((item) => ({+ trace: item.trace,+ transcript:+ item.state.type === "transcript"+ ? item.state.result.transcript+ : undefined,+ })),+ );+ const timelineItems = entries.map((entry) => {+ const item = props.traces[entry.traceIndex]!;+ return {+ ...item,+ ...entry,+ scrollTarget:+ item.scrollTarget?.itemId && item.scrollTarget.itemId !== entry.itemId+ ? null+ : item.scrollTarget,+ };+ });+ if (props.state === "loaded" && !props.isSearchPending) {+ for (const [itemIndex, item] of timelineItems.entries()) {+ const transcriptRows = (() => {+ if (item.state.type === "error") return null;+ if (item.state.type === "loading") return undefined;+ if (item.state.type === "empty") return [];+ let toolGroupId: string | undefined;+ return getSessionTranscriptRows(item.state.result.transcript)+ .filter((row) => row.threadIndex === item.threadIndex)+ .map(({ id, threadIndex, row }) => {+ if (row.type !== "tool") toolGroupId = undefined;+ else if (toolGroupId === undefined) toolGroupId = id;+ const label =+ row.type === "tool"+ ? (row.call?.toolName ?? row.result?.toolName ?? "Tool")+ : row.message.parts+ .map((part) => {+ if (part.type === "text") return part.text;+ if (part.type === "data" || part.type === "custom")+ return "JSON message";+ return part.type;+ })+ .join(" ") ||+ row.message.senderName ||+ row.message.role;+ return {+ id,+ threadIndex,+ toolGroupId:+ row.type === "tool"+ ? `${id.split(":")[0]}:${toolGroupId}`+ : undefined,+ observationId: row.message.observationId,+ label,+ role: row.type === "tool" ? ("tool" as const) : row.message.role,+ };+ });+ })();+ const matchingRows =+ props.searchQuery && transcriptRows+ ? transcriptRows.filter((row) =>+ `${row.role} ${row.label}`+ .toLowerCase()+ .includes(props.searchQuery.toLowerCase()),+ )+ : transcriptRows;+ if (props.searchQuery && matchingRows?.length === 0) continue;+ const threadVisibility =+ item.state.type === "transcript"+ ? getSessionTranscriptThreads(item.state.result.transcript)+ : undefined;+ sidebarTraces.push({+ trace: item.trace,+ itemId: item.itemId,+ itemIndex,+ displayNumber: item.displayNumber,+ threadNumber: item.threadNumber,+ turnNumber: item.turnNumber,+ idleGapSeconds:+ item.traceIndex === 0 || !item.isFirstThread+ ? null+ : computeIdleGapSeconds(+ props.traces[item.traceIndex - 1]!.trace,+ item.trace,+ ),+ transcriptRows: matchingRows,+ threadCount: threadVisibility?.visibleThreads.length,+ hiddenThreadCount: threadVisibility?.hiddenThreadCount,+ });+ }+ }+ return (+ <div className="bg-background session-review-stack:grid-rows-[minmax(7rem,9rem)_minmax(0,1fr)] session-review-stack:gap-x-0 relative grid min-h-0 flex-1 grid-rows-[minmax(10rem,13rem)_minmax(0,1fr)] gap-x-4 overflow-hidden @3xl/session-workspace:grid-cols-[clamp(200px,24cqw,296px)_minmax(0,1fr)] @3xl/session-workspace:grid-rows-1">+ {props.state === "loading" ? (+ <SessionConversationSidebar state="loading" />+ ) : (+ <SessionConversationSidebar+ {...props}+ traces={sidebarTraces}+ activeTraceId={props.controller.activeItemId ?? undefined}+ />+ )}+ <div+ ref={transcriptRef}+ className="bg-card dark:bg-background session-review-stack:min-w-0 relative min-h-0 min-w-[320px]"+ >+ <style>{`::highlight(${highlightName}) { background-color: ${searchQuery ? "hsl(var(--find-match-background))" : "transparent"}; color: ${searchQuery ? "hsl(var(--foreground))" : "inherit"}; }`}</style>+ <SessionConversationTimeline+ traces={timelineItems}+ controller={props.controller}+ filterMeasurementKey="transcript"+ />+ </div>+ </div>+ );+}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.stories.tsxnew file mode 100644index 0000000000..9e26d629f8--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.stories.tsx@@ -0,0 +1,403 @@+import preview from "@/.storybook/preview";+import { expect, fn, userEvent, within } from "storybook/test";+import { type ComponentProps, useState } from "react";+import { SessionConversationSidebar } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar";++type Props = ComponentProps<typeof SessionConversationSidebar>;+const loadedArgs = {+ state: "loaded",+ traces: [+ {+ trace: {+ id: "turn-1",+ name: "Configure tracing",+ timestamp: new Date(0),+ environment: "production",+ userId: null,+ observationCount: 1,+ latencyMs: 1000,+ scores: [],+ },+ turnNumber: 1,+ idleGapSeconds: null,+ transcriptRows: [+ {+ id: "0:0",+ observationId: "generation-1",+ role: "system",+ label: "You are a helpful assistant.",+ },+ {+ id: "0:1",+ observationId: "generation-1",+ role: "user",+ label: "How do I configure tracing?",+ },+ {+ id: "0:2",+ observationId: "generation-1",+ role: "assistant",+ label: "Let me check the documentation.",+ },+ {+ id: "0:3",+ observationId: "generation-1",+ role: "tool",+ label: "search_documentation",+ },+ {+ id: "0:4",+ observationId: "generation-1",+ role: "assistant",+ label: "Initialize the SDK to start tracing.",+ },+ ],+ },+ ],+ activeTraceId: "turn-1",+ search: "",+ onSearchChange: fn(),+ expandedTraceIds: new Set(["turn-1"]),+ onToggleTraceExpanded: fn(),+ onSelect: fn(),+ onVisibleTraceIdsChange: fn(),+ isLoadingTranscripts: false,+ transcriptLoadError: false,+} satisfies Extract<Props, { state: "loaded" }>;++function SessionConversationSidebarStory(args: Props) {+ const [search, setSearch] = useState(+ args.state === "loaded" ? args.search : "",+ );+ const [expandedTraceIds, setExpandedTraceIds] = useState(+ args.state === "loaded" ? args.expandedTraceIds : new Set<string>(),+ );+ if (args.state === "loading")+ return (+ <div className="h-screen w-[296px]">+ <SessionConversationSidebar state="loading" />+ </div>+ );+ const normalizedSearch = search.trim().toLowerCase();+ const traces = normalizedSearch+ ? args.traces.flatMap((trace) => {+ const transcriptRows = trace.transcriptRows?.filter((row) =>+ `${row.role} ${row.label}`.toLowerCase().includes(normalizedSearch),+ );+ if (transcriptRows?.length === 0) return [];+ return [{ ...trace, transcriptRows }];+ })+ : args.traces;+ return (+ <div className="h-screen w-[296px]">+ <SessionConversationSidebar+ {...args}+ traces={traces}+ search={search}+ onSearchChange={(value) => {+ setSearch(value);+ args.onSearchChange(value);+ }}+ expandedTraceIds={expandedTraceIds}+ onToggleTraceExpanded={(id) => {+ setExpandedTraceIds((current) => {+ const next = new Set(current);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ args.onToggleTraceExpanded(id);+ }}+ />+ </div>+ );+}++const meta = preview.meta({+ component: SessionConversationSidebar,+ parameters: { layout: "fullscreen", a11y: { test: "error" } },+ render: (args) => <SessionConversationSidebarStory {...args} />,+});+export default meta;+export const DarkMode = meta.story({+ args: loadedArgs,+ globals: { theme: "dark" },+});+export const Empty = meta.story({ args: { ...loadedArgs, traces: [] } });+export const Error = meta.story({+ args: {+ ...loadedArgs,+ traces: [{ ...loadedArgs.traces[0]!, transcriptRows: null }],+ },+});+export const SelectMessagesAndTools = meta.story({+ name: "(Test) Select messages and tools",+ args: loadedArgs,+ play: async ({ canvasElement, args }) => {+ if (args.state !== "loaded")+ throw new globalThis.Error("Expected loaded sidebar");+ const canvas = within(canvasElement);+ await userEvent.click(+ await canvas.findByRole("button", {+ name: /tool: search_documentation/i,+ }),+ );+ await expect(args.onSelect).toHaveBeenCalledWith(0, "generation-1", "0:3");+ await userEvent.click(+ canvas.getAllByRole("button", {+ name: "Assistant message",+ })[1]!,+ );+ await expect(args.onSelect).toHaveBeenCalledWith(0, "generation-1", "0:4");+ },+});+export const SearchAndCollapse = meta.story({+ name: "(Test) Searches and Collapses Turns",+ args: loadedArgs,+ play: async ({ canvasElement, args }) => {+ if (args.state !== "loaded")+ throw new globalThis.Error("Expected loaded sidebar");+ const canvas = within(canvasElement);+ const input = canvas.getByRole("textbox", {+ name: "Search messages and tools",+ });+ await userEvent.type(input, "Initialize");+ await expect(args.onSearchChange).toHaveBeenLastCalledWith("Initialize");+ await expect(+ canvas.getByRole("button", { name: "Assistant message" }),+ ).toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole("button", { name: "Collapse turn" }),+ );+ await expect(args.onToggleTraceExpanded).toHaveBeenCalledWith("turn-1");+ await expect(+ canvas.queryByRole("button", { name: "Assistant message" }),+ ).not.toBeInTheDocument();+ await userEvent.click(canvas.getByRole("button", { name: "Expand turn" }));+ await expect(+ canvas.getByRole("button", { name: "Assistant message" }),+ ).toBeInTheDocument();+ await userEvent.clear(input);+ await userEvent.type(input, "missing");+ await expect(canvas.getByText("No matching turns")).toBeInTheDocument();+ },+});+export const MultipleThreads = meta.story({+ name: "(Test) Multiple Threads",+ args: {+ ...loadedArgs,+ traces: [+ {+ ...loadedArgs.traces[0]!,+ threadCount: 2,+ transcriptRows: [+ {+ id: "0:0",+ threadIndex: 0,+ observationId: "generation-1",+ role: "tool",+ label: "apply_patch",+ },+ {+ id: "1:0",+ threadIndex: 1,+ observationId: "generation-2",+ role: "tool",+ label: "read_file",+ },+ ],+ },+ ],+ },+ play: async ({ canvasElement, args }) => {+ if (args.state !== "loaded")+ throw new globalThis.Error("Expected loaded sidebar");+ const canvas = within(canvasElement);+ const firstThread = within(+ await canvas.findByRole("region", { name: "Thread 1" }),+ );+ const secondThread = within(+ canvas.getByRole("region", { name: "Thread 2" }),+ );+ await expect(+ firstThread.getByRole("button", { name: /tool: apply_patch/i }),+ ).toBeInTheDocument();+ await userEvent.click(+ secondThread.getByRole("button", { name: /tool: read_file/i }),+ );+ await expect(args.onSelect).toHaveBeenCalledWith(0, "generation-2", "1:0");+ await userEvent.type(canvas.getByRole("textbox"), "apply_patch");+ await expect(+ canvas.getByRole("heading", { name: "Thread 1" }),+ ).toBeInTheDocument();+ await expect(+ canvas.queryByRole("heading", { name: "Thread 2" }),+ ).not.toBeInTheDocument();+ },+});+export const GroupedTools = meta.story({+ name: "(Test) Grouped Tools",+ args: {+ ...loadedArgs,+ traces: [+ {+ ...loadedArgs.traces[0]!,+ transcriptRows: [+ {+ id: "0:0",+ observationId: "generation-1",+ role: "tool",+ label: "read_file",+ },+ {+ id: "0:1",+ observationId: "generation-2",+ role: "tool",+ label: "apply_patch",+ },+ ],+ },+ ],+ },+ play: async ({ canvasElement, args }) => {+ if (args.state !== "loaded")+ throw new globalThis.Error("Expected loaded sidebar");+ const canvas = within(canvasElement);+ const group = await canvas.findByRole("button", {+ name: /^Tool:.*read_file.*apply_patch/,+ });+ await expect(group).not.toHaveAttribute("aria-expanded");+ await expect(+ canvas.queryByRole("button", { name: "tool: apply_patch" }),+ ).not.toBeInTheDocument();+ await userEvent.click(group);+ await expect(args.onSelect).toHaveBeenCalledWith(0, "generation-1", "0:0");+ await userEvent.type(canvas.getByRole("textbox"), "tool");+ await expect(+ canvas.queryByRole("button", { name: /^Tool:.*read_file.*apply_patch/ }),+ ).not.toBeInTheDocument();+ await expect(+ canvas.getByRole("button", { name: "tool: read_file" }),+ ).toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole("button", { name: "tool: apply_patch" }),+ );+ await expect(args.onSelect).toHaveBeenCalledWith(0, "generation-2", "0:1");+ await userEvent.clear(canvas.getByRole("textbox"));+ await userEvent.type(canvas.getByRole("textbox"), "PATCH");+ await expect(+ within(+ canvas.getByRole("button", { name: "tool: apply_patch" }),+ ).getByRole("mark"),+ ).toHaveTextContent("patch");+ await userEvent.clear(canvas.getByRole("textbox"));+ await expect(+ canvas.getByRole("button", { name: /^Tool:.*read_file.*apply_patch/ }),+ ).toBeInTheDocument();+ },+});+export const ConsecutiveMessages = meta.story({+ name: "(Test) Consecutive Messages",+ args: {+ ...loadedArgs,+ traces: [+ {+ ...loadedArgs.traces[0]!,+ threadCount: 2,+ transcriptRows: [+ {+ id: "0:0",+ threadIndex: 0,+ observationId: "generation-1",+ role: "user",+ label: `${"Earlier context. ".repeat(30)}First NEEDLE request with needle details.${" Later context.".repeat(30)}`,+ },+ {+ id: "0:1",+ threadIndex: 0,+ observationId: "generation-2",+ role: "user",+ label: "More needle context",+ },+ {+ id: "0:2",+ threadIndex: 0,+ observationId: "generation-2",+ role: "assistant",+ label: "First response",+ },+ {+ id: "0:3",+ threadIndex: 0,+ observationId: "generation-3",+ role: "assistant",+ label: "More detail",+ },+ {+ id: "0:4",+ threadIndex: 0,+ observationId: "generation-3",+ role: "tool",+ label: "read_file",+ },+ {+ id: "0:5",+ threadIndex: 0,+ observationId: "generation-4",+ role: "assistant",+ label: "Done",+ },+ {+ id: "1:0",+ threadIndex: 1,+ observationId: "generation-5",+ role: "assistant",+ label: "Next thread",+ },+ ],+ },+ ],+ },+ play: async ({ canvasElement, args }) => {+ if (args.state !== "loaded")+ throw new globalThis.Error("Expected loaded sidebar");+ const canvas = within(canvasElement);+ const firstThread = within(+ await canvas.findByRole("region", { name: "Thread 1" }),+ );+ await userEvent.click(+ firstThread.getByRole("button", { name: "2 User messages" }),+ );+ await expect(args.onSelect).toHaveBeenCalledWith(0, "generation-1", "0:0");+ await userEvent.click(+ firstThread.getByRole("button", { name: "2 Assistant messages" }),+ );+ await expect(args.onSelect).toHaveBeenCalledWith(0, "generation-2", "0:2");+ await expect(+ firstThread.getByRole("button", { name: "Assistant message" }),+ ).toBeInTheDocument();+ await expect(+ within(canvas.getByRole("region", { name: "Thread 2" })).getByRole(+ "button",+ { name: "Assistant message" },+ ),+ ).toBeInTheDocument();+ await userEvent.type(canvas.getByRole("textbox"), "needle");+ const messages = canvas.getAllByRole("button", { name: "User message" });+ await expect(messages).toHaveLength(2);+ await expect(+ canvas.queryByRole("button", { name: "2 User messages" }),+ ).not.toBeInTheDocument();+ await userEvent.click(messages[1]!);+ await expect(args.onSelect).toHaveBeenCalledWith(0, "generation-2", "0:1");+ await userEvent.clear(canvas.getByRole("textbox"));+ await userEvent.type(canvas.getByRole("textbox"), "user");+ await expect(+ canvas.getAllByRole("button", { name: "User message" }),+ ).toHaveLength(2);+ await userEvent.clear(canvas.getByRole("textbox"));+ await expect(+ canvas.getByRole("button", { name: "2 User messages" }),+ ).toBeInTheDocument();+ },+});diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.tsxnew file mode 100644index 0000000000..431b3a89bc--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.tsx@@ -0,0 +1,633 @@+import {+ useCallback,+ useLayoutEffect,+ useRef,+ useState,+ type ReactNode,+} from "react";+import { useVirtualizer } from "@tanstack/react-virtual";+import { ChevronDown, Search } from "lucide-react";+import { Input } from "@/src/components/ui/input";+import { CustomTooltip } from "@/src/components/design-system/CustomTooltip/CustomTooltip";+import { SessionVirtualizedRow } from "@/src/features/sessions/SessionVirtualizedRow";+import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";+import {+ formatIdleGap,+ IDLE_GAP_THRESHOLD_SECONDS,+} from "@/src/features/sessions/sessionIdleGap";+import { cn } from "@/src/utils/tailwind";+import { groupConsecutiveTools } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/fns/groupConsecutiveTools";++export type SessionConversationSidebarTrace = {+ itemId?: string;+ itemIndex?: number;+ displayNumber?: string;+ threadNumber?: number;+ trace: EventSessionTrace;+ turnNumber: number;+ idleGapSeconds: number | null;+ threadCount?: number;+ hiddenThreadCount?: number;+ transcriptRows:+ | Array<{+ id: string;+ threadIndex?: number;+ observationId: string;+ label: string;+ role: "system" | "user" | "assistant" | "tool";+ toolGroupId?: string;+ }>+ | null+ | undefined;+};++const EMPTY_TRACES: SessionConversationSidebarTrace[] = [];+const SIDEBAR_AUTO_FOLLOW_IDLE_MS = 750;++export function SessionConversationSidebar(+ props:+ | { state: "loading" }+ | {+ state: "loaded";+ traces: SessionConversationSidebarTrace[];+ activeTraceId: string | undefined;+ search: string;+ onSearchChange: (search: string) => void;+ expandedTraceIds: ReadonlySet<string>;+ onToggleTraceExpanded: (traceId: string) => void;+ onSelect: (+ index: number,+ observationId?: string,+ rowId?: string,+ ) => void;+ onVisibleTraceIdsChange: (traceIds: string[]) => void;+ isLoadingTranscripts: boolean;+ transcriptLoadError: boolean;+ },+) {+ const traces = props.state === "loaded" ? props.traces : EMPTY_TRACES;+ const activeTraceId =+ props.state === "loaded" ? props.activeTraceId : undefined;+ const sidebarSearch = props.state === "loaded" ? props.search : "";+ const listRef = useRef<HTMLDivElement>(null);+ const textContextRef = useRef<CanvasRenderingContext2D | null>(null);+ const [toolGroupMeasurement, setToolGroupMeasurement] = useState<{+ width: number;+ fontKey: string;+ measureSummary: (summary: string) => number;+ } | null>(null);+ const measureToolGroupLabel = useCallback(() => {+ const label = listRef.current?.querySelector<HTMLElement>(+ "[data-session-tool-group-label]",+ );+ if (!label) return;+ const context =+ textContextRef.current ??+ document.createElement("canvas").getContext("2d");+ if (!context) return;+ textContextRef.current = context;+ const style = getComputedStyle(label);+ context.font =+ style.font ||+ `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;+ const letterSpacing = Number.parseFloat(style.letterSpacing) || 0;+ const fontKey = `${context.font}:${letterSpacing}:${context.measureText("Wmi0123456789").width}`;+ const width = Math.max(0, label.getBoundingClientRect().width - 1);+ setToolGroupMeasurement((previous) => {+ if (previous?.width === width && previous.fontKey === fontKey)+ return previous;+ return {+ width,+ fontKey,+ measureSummary: (summary) => {+ const text = /^[0-9]+x\s/.test(summary)+ ? summary+ : `Tool: ${summary}`;+ return (+ context.measureText(text).width + [...text].length * letterSpacing+ );+ },+ };+ });+ }, []);+ // Virtualized labels can mount after the sidebar's initial layout.+ useLayoutEffect(measureToolGroupLabel);+ useLayoutEffect(() => {+ const list = listRef.current;+ if (!list) return;+ const observer =+ typeof ResizeObserver === "undefined"+ ? undefined+ : new ResizeObserver(measureToolGroupLabel);+ observer?.observe(list);+ let active = true;+ document.fonts?.ready.then(() => {+ if (active) measureToolGroupLabel();+ });+ document.fonts?.addEventListener("loadingdone", measureToolGroupLabel);+ return () => {+ active = false;+ observer?.disconnect();+ document.fonts?.removeEventListener("loadingdone", measureToolGroupLabel);+ };+ }, [measureToolGroupLabel, props.state]);+ const isSidebarPointerDownRef = useRef(false);+ const autoFollowPausedUntilRef = useRef(0);+ const autoFollowTimerRef = useRef<number | undefined>(undefined);+ const resumeAutoFollowRef = useRef<(() => void) | null>(null);+ const virtualizer = useVirtualizer({+ count: traces.length,+ getScrollElement: () => listRef.current,+ estimateSize: () => 160,+ overscan: 5,+ getItemKey: (index) =>+ traces[index]?.itemId ?? traces[index]?.trace.id ?? index,+ onChange: (instance) => {+ if (props.state !== "loaded") return;+ props.onVisibleTraceIdsChange([+ ...new Set(+ instance.getVirtualItems().flatMap((item) => {+ const traceId = traces[item.index]?.trace.id;+ return traceId ? [traceId] : [];+ }),+ ),+ ]);+ },+ });+ const activeTraceIndex = activeTraceId+ ? traces.findIndex(+ ({ trace, itemId }) => (itemId ?? trace.id) === activeTraceId,+ )+ : -1;+ const setListElement = useCallback(+ (element: HTMLDivElement | null) => {+ listRef.current = element;+ if (+ !element ||+ activeTraceIndex === -1 ||+ isSidebarPointerDownRef.current ||+ Date.now() < autoFollowPausedUntilRef.current+ )+ return;+ // `auto` preserves the viewport when the active turn is already visible.+ virtualizer.scrollToIndex(activeTraceIndex, { align: "auto" });+ },+ [activeTraceIndex, virtualizer],+ );+ useLayoutEffect(() => {+ resumeAutoFollowRef.current = () => {+ setListElement(listRef.current);+ };+ setListElement(listRef.current);+ }, [setListElement, sidebarSearch]);+ useLayoutEffect(+ () => () => window.clearTimeout(autoFollowTimerRef.current),+ [],+ );+ const pauseAutoFollow = () => {+ autoFollowPausedUntilRef.current = Date.now() + SIDEBAR_AUTO_FOLLOW_IDLE_MS;+ window.clearTimeout(autoFollowTimerRef.current);+ autoFollowTimerRef.current = window.setTimeout(+ () => resumeAutoFollowRef.current?.(),+ SIDEBAR_AUTO_FOLLOW_IDLE_MS,+ );+ };+ const handlePointerEnd = () => {+ isSidebarPointerDownRef.current = false;+ pauseAutoFollow();+ };++ if (props.state === "loading") {+ return (+ <div+ role="complementary"+ aria-label="Session messages and tools"+ aria-busy="true"+ className="bg-background session-review-stack:border-r-0 session-review-stack:border-b relative flex h-full min-h-0 flex-col border-r"+ >+ <div className="shrink-0 border-b px-2 py-2.5">+ <div className="relative min-w-0">+ <Search className="icon-base text-foreground-tertiary absolute top-1/2 left-2 -translate-y-1/2" />+ <Input+ disabled+ value=""+ aria-label="Search messages and tools"+ placeholder="Search messages and tools"+ className="h-7 rounded-sm bg-transparent pl-7 font-mono text-xs"+ />+ </div>+ </div>+ <div className="flex min-h-0 flex-1 flex-col gap-2 px-1 pt-0.5 pb-4">+ {[0, 1, 2].map((index) => (+ <div+ key={index}+ className="flex flex-col gap-2 rounded-sm border border-transparent p-2"+ >+ <div className="bg-muted h-3 w-3/4 animate-pulse rounded-sm" />+ <div className="bg-muted h-2.5 w-1/2 animate-pulse rounded-sm" />+ </div>+ ))}+ </div>+ </div>+ );+ }++ const searchQuery = props.search.trim();+ const emptyLabel = (() => {+ if (props.isLoadingTranscripts) return "Loading transcripts...";+ if (props.transcriptLoadError) return "Failed to load transcripts";+ if (props.search) return "No matching turns";+ return "No turns";+ })();++ return (+ <div+ role="complementary"+ aria-label="Session messages and tools"+ className="bg-background session-review-stack:border-r-0 session-review-stack:border-b relative flex h-full min-h-0 flex-col border-r"+ >+ <div className="shrink-0 border-b px-2 py-2.5">+ <div className="relative min-w-0">+ <Search className="icon-base text-foreground-tertiary absolute top-1/2 left-2 -translate-y-1/2" />+ <Input+ value={props.search}+ onChange={(event) => {+ virtualizer.scrollToOffset(0);+ props.onSearchChange(event.target.value);+ }}+ aria-label="Search messages and tools"+ placeholder="Search messages and tools"+ className="h-7 rounded-sm bg-transparent pl-7 font-mono text-xs"+ />+ </div>+ </div>+ <div+ ref={setListElement}+ role="region"+ aria-label="Session turns"+ className="min-h-0 flex-1 overflow-y-auto pt-2.5 pb-4"+ onWheel={pauseAutoFollow}+ onTouchMove={pauseAutoFollow}+ onKeyDown={(event) => {+ if (+ [+ "ArrowUp",+ "ArrowDown",+ "PageUp",+ "PageDown",+ "Home",+ "End",+ " ",+ ].includes(event.key)+ ) {+ pauseAutoFollow();+ }+ }}+ onPointerDown={() => {+ isSidebarPointerDownRef.current = true;+ }}+ onPointerUp={handlePointerEnd}+ onPointerCancel={handlePointerEnd}+ onPointerLeave={handlePointerEnd}+ >+ {traces.length === 0 ? (+ <div className="text-muted-foreground px-3 py-6 text-center text-xs">+ {emptyLabel}+ </div>+ ) : (+ <div+ style={{+ height: `${virtualizer.getTotalSize()}px`,+ position: "relative",+ width: "100%",+ }}+ >+ {virtualizer.getVirtualItems().map((item) => {+ const sidebarTrace = traces[item.index];+ if (!sidebarTrace) return null;+ const { trace, turnNumber, idleGapSeconds, transcriptRows } =+ sidebarTrace;+ const itemId = sidebarTrace.itemId ?? trace.id;+ const targetIndex = sidebarTrace.itemIndex ?? turnNumber - 1;+ const isCollapsed = !props.expandedTraceIds.has(itemId);+ const isActive = itemId === activeTraceId;+ const threads = new Map<+ number,+ NonNullable<SessionConversationSidebarTrace["transcriptRows"]>+ >();+ for (const row of transcriptRows ?? []) {+ const threadIndex = row.threadIndex ?? 0;+ const threadRows = threads.get(threadIndex);+ if (threadRows) threadRows.push(row);+ else threads.set(threadIndex, [row]);+ }+ const showThreadHeaders =+ !sidebarTrace.itemId &&+ (sidebarTrace.threadCount ?? threads.size) > 1;+ return (+ <SessionVirtualizedRow+ key={item.key}+ itemKey={String(item.key)}+ measurementKey={`${String(item.key)}:${isCollapsed}:${props.search}`}+ source="modern"+ virtualItem={item}+ virtualizer={virtualizer}+ >+ {props.search.trim() === "" &&+ idleGapSeconds !== null &&+ idleGapSeconds >= IDLE_GAP_THRESHOLD_SECONDS && (+ <div className="my-0.5 mb-2 flex items-center bg-[repeating-linear-gradient(315deg,hsl(var(--foreground)/0.07)_0_1px,transparent_1px_5px)] px-3 py-[5px]">+ <span className="text-muted-foreground font-mono text-[11px] whitespace-nowrap">+ +{formatIdleGap(idleGapSeconds)} idle+ </span>+ </div>+ )}+ <div className="px-2 pb-2">+ <div+ className={cn(+ "group border-border/50 hover:bg-muted/60 rounded-sm border p-2 transition-colors duration-150",+ isActive &&+ "border-primary-accent/50 bg-background dark:bg-muted",+ )}+ >+ <div className="flex w-full items-center gap-2">+ <button+ type="button"+ onClick={() => props.onSelect(targetIndex)}+ className="flex min-w-0 flex-1 items-center gap-2 text-left"+ aria-current={isActive ? "true" : undefined}+ >+ <span className="border-border bg-tertiary text-foreground flex h-4 min-w-4 shrink-0 items-center justify-center rounded-sm border px-0.5 font-mono text-[10px]">+ {sidebarTrace.displayNumber ?? turnNumber}+ </span>+ <span+ className="min-w-0 flex-1 truncate text-[13px] font-bold"+ title={trace.name ?? "Trace"}+ >+ {trace.name ?? "Trace"}+ </span>+ </button>+ <button+ type="button"+ aria-label={+ isCollapsed ? "Expand turn" : "Collapse turn"+ }+ onClick={() => props.onToggleTraceExpanded(itemId)}+ className="text-muted-foreground -my-2 -mr-2.5 -ml-2 flex h-8 w-8 shrink-0 items-center justify-center"+ >+ <ChevronDown+ className={cn(+ "icon-sm transition-transform duration-150",+ isCollapsed ? "-rotate-90" : "rotate-0",+ )}+ />+ </button>+ </div>+ {!isCollapsed && (+ <div+ className={transcriptRows?.length ? "mt-2" : "-mx-1"}+ >+ {transcriptRows === undefined && (+ <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>+ )}+ {transcriptRows === null && (+ <p className="text-muted-foreground px-1 py-2 text-xs">+ Failed to load transcript+ </p>+ )}+ {transcriptRows?.length === 0 && (+ <p className="text-muted-foreground px-1 py-2 text-xs">+ {props.search.trim()+ ? "No matching messages or tools"+ : "No messages or tools"}+ </p>+ )}+ <div className="flex flex-col">+ {Array.from(threads, ([threadIndex, rows]) => (+ <section+ key={threadIndex}+ aria-label={+ showThreadHeaders+ ? `Thread ${threadIndex + 1}`+ : undefined+ }+ className={cn(+ "flex min-w-0 flex-col",+ showThreadHeaders &&+ "border-border mt-2 border-t pt-2 first:mt-0 first:border-t-0 first:pt-0",+ )}+ >+ {showThreadHeaders && (+ <h4 className="text-muted-foreground pb-1 text-xs font-bold">+ Thread {threadIndex + 1}+ </h4>+ )}+ {groupConsecutiveTools(rows, {+ isTool: (row) =>+ props.search.trim() === "" &&+ row.role === "tool",+ getBoundary: (row) => row.toolGroupId,+ getToolName: (row) => row.label,+ summaryBudget:+ toolGroupMeasurement?.width ?? Infinity,+ measureSummary:+ toolGroupMeasurement?.measureSummary,+ }).map((group, groupIndex, groups) => {+ if (group.type === "tools") {+ const firstTool = group.rows[0]!;+ return (+ <CustomTooltip+ key={firstTool.id}+ placement="right"+ delay={200}+ content={+ <div className="flex flex-col gap-2">+ <h4 className="text-sm font-bold">+ Tool calls+ </h4>+ <div className="text-muted-foreground whitespace-pre-line">+ {group.title}+ </div>+ </div>+ }+ >+ {({ getTriggerProps }) => (+ <button+ {...getTriggerProps()}+ type="button"+ aria-label={`Tool: ${group.title}`}+ onClick={() =>+ props.onSelect(+ targetIndex,+ firstTool.observationId,+ firstTool.id,+ )+ }+ className="ph-no-capture text-muted-foreground hover:bg-foreground/10 -mr-2 -ml-1 flex min-w-0 items-center gap-2 rounded-sm px-1 py-1 text-left text-[13px] transition-colors duration-150"+ >+ <span+ className="min-w-0 flex-1 truncate"+ data-session-tool-group-label+ title={group.title}+ >+ {/^[0-9]+x\s/.test(group.summary)+ ? group.summary+ : `Tool: ${group.summary}`}+ </span>+ </button>+ )}+ </CustomTooltip>+ );+ }+ const row = group.row;+ const previousGroup = groups[groupIndex - 1];+ if (+ !searchQuery &&+ row.role !== "tool" &&+ previousGroup?.type === "row" &&+ previousGroup.row.role === row.role+ )+ return null;+ let messageCount = 1;+ if (!searchQuery && row.role !== "tool") {+ for (+ let index = groupIndex + 1;+ index < groups.length;+ index+++ ) {+ const nextGroup = groups[index]!;+ if (+ nextGroup.type !== "row" ||+ nextGroup.row.role !== row.role+ )+ break;+ messageCount++;+ }+ }+ const messageLabel = {+ user: "User message",+ assistant: "Assistant message",+ system: "System message",+ tool: `Tool: ${row.label}`,+ }[row.role];+ const label =+ messageCount === 1+ ? messageLabel+ : `${messageCount} ${messageLabel}s`;+ const excerpt: ReactNode[] = [];+ if (searchQuery) {+ const normalizedQuery =+ searchQuery.toLowerCase();+ const matchIndex = row.label+ .toLowerCase()+ .indexOf(normalizedQuery);+ const start =+ row.role === "tool"+ ? 0+ : Math.max(0, matchIndex - 24);+ const end =+ row.role === "tool"+ ? row.label.length+ : Math.min(+ row.label.length,+ start ++ Math.max(+ 120,+ searchQuery.length + 48,+ ),+ );+ const text = row.label.slice(start, end);+ const normalizedText = text.toLowerCase();+ if (start > 0) excerpt.push("…");+ let position = 0;+ while (position < text.length) {+ const nextMatch = normalizedText.indexOf(+ normalizedQuery,+ position,+ );+ if (nextMatch === -1) {+ excerpt.push(text.slice(position));+ break;+ }+ excerpt.push(+ text.slice(position, nextMatch),+ );+ excerpt.push(+ <mark+ key={nextMatch}+ className="bg-find-match-background text-foreground"+ >+ {text.slice(+ nextMatch,+ nextMatch + searchQuery.length,+ )}+ </mark>,+ );+ position = nextMatch + searchQuery.length;+ }+ if (end < row.label.length)+ excerpt.push("…");+ }+ return (+ <button+ key={row.id}+ type="button"+ onClick={() =>+ props.onSelect(+ targetIndex,+ row.observationId,+ row.id,+ )+ }+ className="ph-no-capture hover:bg-foreground/10 -mr-2 -ml-1 flex min-w-0 items-center gap-2 rounded-sm px-1 py-1 text-left transition-colors duration-150"+ aria-label={+ row.role === "tool"+ ? `tool: ${row.label}`+ : label+ }+ >+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span+ className="text-muted-foreground truncate text-[13px]"+ title={label}+ >+ {row.role === "tool" &&+ searchQuery ? (+ <>+ Tool:{" "}+ <span className="italic">+ {excerpt}+ </span>+ </>+ ) : (+ label+ )}+ </span>+ {searchQuery && row.role !== "tool" && (+ <span className="text-muted-foreground line-clamp-2 text-xs break-words whitespace-normal italic">+ {excerpt}+ </span>+ )}+ </span>+ </button>+ );+ })}+ </section>+ ))}+ </div>+ </div>+ )}+ </div>+ </div>+ </SessionVirtualizedRow>+ );+ })}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.stories.tsxnew file mode 100644index 0000000000..a01b36022d--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.stories.tsx@@ -0,0 +1,53 @@+import preview from "@/.storybook/preview";+import { expect, fn, waitFor } from "storybook/test";+import { SessionConversationTimeline } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline";+import { useSessionConversationTimelineController } from "@/src/features/sessions/hooks/useSessionConversationTimelineController";++function SessionConversationTimelineStory() {+ const traces = Array.from({ length: 3 }, (_, index) => ({+ trace: {+ id: `trace-${index + 1}`,+ name: `Turn ${index + 1}`,+ timestamp: new Date("2026-09-24T12:00:00Z"),+ environment: "default",+ userId: null,+ observationCount: 0,+ latencyMs: null,+ scores: [],+ },+ turnNumber: index + 1,+ state: { type: "loading" as const },+ onOpenTrace: fn(),+ onOpenObservation: fn(),+ scrollTarget: null,+ }));+ const controller = useSessionConversationTimelineController(traces);+ return (+ <div className="h-[200px]">+ <SessionConversationTimeline+ traces={traces}+ filterMeasurementKey="storybook"+ controller={controller}+ />+ </div>+ );+}++const meta = preview.meta({ component: SessionConversationTimelineStory });+export default meta;++export const ScrollableTimeline = meta.story({+ name: "(Test) Scrollable Timeline",+ play: async ({ canvas }) => {+ const timeline = canvas.getByLabelText("Session conversation timeline");+ await canvas.findByRole("button", { name: /Turn 1.*trace-1/ });+ await waitFor(() => {+ expect(timeline.scrollHeight).toBeGreaterThan(timeline.clientHeight);+ });+ timeline.scrollTop = timeline.scrollHeight;+ timeline.dispatchEvent(new Event("scroll", { bubbles: true }));+ await waitFor(() => {+ expect(timeline.scrollTop).toBeGreaterThan(0);+ });+ },+});diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.tsxnew file mode 100644index 0000000000..3f0dfb6321--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.tsx@@ -0,0 +1,50 @@+import { type ComponentProps } from "react";+import { SessionVirtualizedRow } from "@/src/features/sessions/SessionVirtualizedRow";+import { SessionConversationTimelineTrace } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace";+import { type SessionConversationTimelineController } from "@/src/features/sessions/hooks/useSessionConversationTimelineController";++export function SessionConversationTimeline({+ traces,+ filterMeasurementKey,+ controller,+}: {+ traces: readonly ComponentProps<typeof SessionConversationTimelineTrace>[];+ filterMeasurementKey: string;+ controller: SessionConversationTimelineController;+}) {+ const { feedRef, virtualItems, virtualizer } = controller;++ return (+ <div+ ref={feedRef}+ aria-label="Session conversation timeline"+ 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 traceProps = traces[virtualItem.index];+ if (!traceProps) return null;++ return (+ <SessionVirtualizedRow+ key={virtualItem.key}+ itemKey={String(virtualItem.key)}+ measurementKey={`${String(virtualItem.key)}:${filterMeasurementKey}`}+ source="modern"+ virtualItem={virtualItem}+ virtualizer={virtualizer}+ >+ <SessionConversationTimelineTrace {...traceProps} />+ </SessionVirtualizedRow>+ );+ })}+ </div>+ </div>+ );+}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsxnew file mode 100644index 0000000000..8cfeff35cc--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsx@@ -0,0 +1,605 @@+import preview from "@/.storybook/preview";+import { type ComponentProps } from "react";+import { expect, fn, userEvent, within } from "storybook/test";+import { SessionConversationTimelineTrace } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace";++type Props = ComponentProps<typeof SessionConversationTimelineTrace>;+type TranscriptState = Extract<Props["state"], { type: "transcript" }>;+type Thread = NonNullable<+ TranscriptState["result"]["transcript"]+>["threads"][number];+const trace: Props["trace"] = {+ id: "trace-1",+ name: "Weather assistant",+ timestamp: new Date("2026-09-24T12:00:00Z"),+ environment: "default",+ userId: null,+ observationCount: 3,+ latencyMs: 1000,+ scores: [],+};+const provenance = {+ observationId: "generation-1",+ traceId: trace.id,+ startTime: trace.timestamp,+ endTime: new Date("2026-09-24T12:00:01Z"),+};+const result: Extract<Props["state"], { type: "transcript" }>["result"] = {+ state: "loaded",+ cutoff: false,+ transcript: {+ threads: [+ {+ conversationHistory: [+ {+ role: "system",+ source: "input",+ parts: [{ type: "text", text: "Help the user plan their trip." }],+ },+ {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "I am visiting Berlin." }],+ },+ ],+ currentTurn: {+ nestingLevel: 0,+ observations: [],+ messages: [+ {+ ...provenance,+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "What is the weather?" }],+ },+ {+ ...provenance,+ role: "assistant",+ source: "output",+ parts: [+ { type: "text", text: "Let me check." },+ {+ type: "tool-call",+ toolCallId: "weather-1",+ toolName: "weather",+ input: { city: "Berlin" },+ },+ ],+ },+ {+ ...provenance,+ role: "tool",+ source: "output",+ parts: [+ {+ type: "tool-result",+ toolCallId: "weather-1",+ toolName: "weather",+ output: { temperature: 12, conditions: "Sunny" },+ },+ ],+ },+ {+ ...provenance,+ role: "assistant",+ source: "output",+ parts: [+ { type: "text", text: "It is **12°C and sunny** in Berlin." },+ ],+ },+ ],+ },+ },+ {+ conversationHistory: [],+ currentTurn: {+ nestingLevel: 0,+ observations: [],+ messages: [+ {+ ...provenance,+ endTime: null,+ role: "assistant",+ source: "output",+ senderName: "Trip planner",+ parts: [{ type: "text", text: "Looking up outdoor activities…" }],+ },+ ],+ },+ },+ ],+ },+};+const meta = preview.meta({ component: SessionConversationTimelineTrace });+export default meta;+const commonArgs = {+ trace,+ turnNumber: 1,+ onOpenTrace: () => {},+ onOpenObservation: () => {},+ scrollTarget: null,+};+function transcriptState({+ messages,+ history,+}: {+ messages: Thread["currentTurn"]["messages"];+ history: Thread["conversationHistory"];+}): TranscriptState {+ return {+ type: "transcript",+ result: {+ state: "loaded",+ cutoff: false,+ transcript: {+ threads: [+ {+ conversationHistory: history,+ currentTurn: { nestingLevel: 0, observations: [], messages },+ },+ ],+ },+ },+ };+}++const weatherState = transcriptState({+ messages: result.transcript?.threads[0]?.currentTurn.messages ?? [],+ history: result.transcript?.threads[0]?.conversationHistory ?? [],+});+export const NestedThreadsHidden = meta.story({+ name: "(Test) Nested Threads Hidden",+ args: {+ ...commonArgs,+ state: {+ type: "transcript",+ result: {+ ...result,+ transcript: {+ threads: (result.transcript?.threads ?? []).map((thread, index) => ({+ ...thread,+ currentTurn: { ...thread.currentTurn, nestingLevel: index + 2 },+ })),+ },+ },+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(+ canvas.queryByText("Looking up outdoor activities…"),+ ).not.toBeInTheDocument();+ },+});+export const MultipleThreads = meta.story({+ name: "(Test) Multiple Threads Without History",+ args: {+ ...commonArgs,+ state: {+ type: "transcript",+ result,+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(+ canvas.queryByText("I am visiting Berlin."),+ ).not.toBeInTheDocument();+ await expect(+ canvas.queryByText("Help the user plan their trip."),+ ).not.toBeInTheDocument();+ await expect(+ canvas.getByText("Looking up outdoor activities…"),+ ).toBeInTheDocument();+ const text = canvasElement.textContent!;+ await expect(text.indexOf("Let me check.")).toBeGreaterThanOrEqual(0);+ await expect(text.indexOf("Let me check.")).toBeLessThan(+ text.indexOf("Looking up outdoor activities…"),+ );+ },+});+export const Cutoff = meta.story({+ args: {+ ...commonArgs,+ state: {+ type: "transcript",+ result: { ...result, cutoff: true },+ },+ },+});+export const Error = meta.story({+ args: { ...commonArgs, state: { type: "error" } },+});+export const Empty = meta.story({+ args: { ...commonArgs, state: { type: "empty" } },+});++export const RenderLoadedConversation = meta.story({+ name: "(Test) Renders Transcript Conversation",+ args: { ...commonArgs, state: weatherState },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(canvas.getByText("What is the weather?")).toBeInTheDocument();+ await expect(canvas.getByText("Let me check.")).toBeInTheDocument();+ await expect(+ canvas.getByRole("button", { name: "Expand weather" }),+ ).toBeInTheDocument();+ },+});++export const OpenObservation = meta.story({+ name: "(Test) Opens Source Observation",+ args: { ...commonArgs, state: weatherState, onOpenObservation: fn() },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const message = canvas+ .getByText("What is the weather?")+ .closest("article")!;+ await userEvent.hover(message);+ await userEvent.click(+ within(message).getByText(/open observation/i, {+ selector: "button",+ }),+ );+ await expect(args.onOpenObservation).toHaveBeenCalledWith("generation-1");+ },+});++export const ExpandTool = meta.story({+ name: "(Test) Expands Transcript Tool",+ args: { ...commonArgs, state: weatherState, onOpenObservation: fn() },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(canvas.getByRole("button", { name: "weather" }));+ await expect(canvas.getByText("Input")).toBeInTheDocument();+ await expect(args.onOpenObservation).not.toHaveBeenCalled();+ await userEvent.click(canvas.getByRole("button", { name: "weather" }));+ await expect(canvas.queryByText("Input")).not.toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand weather" }),+ );+ await expect(canvas.getByText(/"city": "Berlin"/)).toBeInTheDocument();+ await expect(canvas.getByText(/"temperature": 12/)).toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole("button", { name: "Collapse weather" }),+ );+ await expect(+ canvas.queryByText(/"temperature": 12/),+ ).not.toBeInTheDocument();+ },+});++export const OpenToolObservation = meta.story({+ name: "(Test) Opens Tool Observation",+ args: {+ ...commonArgs,+ state: weatherState,+ onOpenObservation: fn(),+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const toolRow = canvas+ .getByRole("button", { name: "Expand weather" })+ .closest("section")!;+ await userEvent.hover(toolRow);+ const openObservation = within(toolRow).getByText(/open observation/i, {+ selector: "button",+ });+ await userEvent.click(openObservation);+ await expect(args.onOpenObservation).toHaveBeenCalledWith("generation-1");+ },+});++export const EmptyTranscript = meta.story({+ args: {+ ...commonArgs,+ state: transcriptState({+ history: [],+ messages: [],+ }),+ },+});++export const RenderFalsyValues = meta.story({+ name: "(Test) Renders Falsy Message Values",+ args: {+ ...commonArgs,+ state: transcriptState({+ history: [],+ messages: [+ {+ ...provenance,+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "0" }],+ },+ {+ ...provenance,+ role: "assistant",+ source: "output",+ parts: [{ type: "text", text: "false" }],+ },+ ],+ }),+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(canvas.getByText("0")).toBeInTheDocument();+ await expect(canvas.getByText("false")).toBeInTheDocument();+ },+});++export const GenerationToolCallOnly = meta.story({+ name: "(Test) Generation Tool Call Only",+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(+ canvas.getByRole("button", { name: "Expand get_subscription_details" }),+ ).toBeInTheDocument();+ await expect(canvas.queryByText("Assistant")).not.toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand get_subscription_details" }),+ );+ await expect(canvas.getByText(/CUS-48291/)).toBeInTheDocument();+ },+ args: {+ ...commonArgs,+ state: transcriptState({+ history: [],+ messages: [+ {+ ...provenance,+ role: "assistant",+ source: "output",+ parts: [+ {+ type: "tool-call",+ toolCallId: "call-only",+ toolName: "get_subscription_details",+ input: { customerId: "CUS-48291" },+ },+ ],+ },+ ],+ }),+ },+});++export const ToolResultOnly = meta.story({+ name: "(Test) Tool Result Only",+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand get_subscription_details" }),+ );+ await expect(canvas.getByText(/annual_pro/)).toBeInTheDocument();+ },+ args: {+ ...commonArgs,+ state: transcriptState({+ history: [],+ messages: [+ {+ ...provenance,+ role: "tool",+ source: "output",+ parts: [+ {+ type: "tool-result",+ toolCallId: "result-only",+ toolName: "get_subscription_details",+ output: { plan: "annual_pro" },+ },+ ],+ },+ ],+ }),+ },+});++export const PairMatchingToolData = meta.story({+ name: "(Test) Pairs Matching Tool Call and Result",+ args: { ...commonArgs, state: weatherState },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(+ canvas.getAllByRole("button", { name: "Expand weather" }),+ ).toHaveLength(1);+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand weather" }),+ );+ const toolRow = canvas+ .getByRole("button", { name: "Collapse weather" })+ .closest("section")!;+ await expect(+ within(toolRow).getByText(/"city": "Berlin"/),+ ).toBeInTheDocument();+ await expect(+ within(toolRow).getByText(/"temperature": 12/),+ ).toBeInTheDocument();+ },+});++export const KeepDifferentToolData = meta.story({+ name: "(Test) Keeps Different Tool Calls",+ args: {+ ...commonArgs,+ state: transcriptState({+ history: [],+ messages: [+ {+ ...provenance,+ role: "assistant",+ source: "output",+ parts: [+ {+ type: "tool-call",+ toolCallId: "docs",+ toolName: "search_documentation",+ input: { query: "cancellation policy" },+ },+ {+ type: "tool-call",+ toolCallId: "profile",+ toolName: "get_customer_profile",+ input: { customerId: "CUS-48291" },+ },+ ],+ },+ {+ ...provenance,+ role: "tool",+ source: "output",+ parts: [+ {+ type: "tool-result",+ toolCallId: "docs",+ toolName: "search_documentation",+ output: { found: true },+ },+ {+ type: "tool-result",+ toolCallId: "profile",+ toolName: "get_customer_profile",+ output: { plan: "annual_pro" },+ },+ ],+ },+ ],+ }),+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(+ canvas.getByRole("button", {+ name: /^Show tools:.*search_documentation.*get_customer_profile/,+ }),+ ).toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole("button", {+ name: /^Show tools:.*search_documentation.*get_customer_profile/,+ }),+ );+ await expect(+ canvas.getByRole("button", { name: "Expand search_documentation" }),+ ).toBeInTheDocument();+ await expect(+ canvas.getByRole("button", { name: "Expand get_customer_profile" }),+ ).toBeInTheDocument();+ },+});++export const SystemPromptHistory = meta.story({+ name: "(Test) System Prompt Navigation",+ args: {+ ...commonArgs,+ onOpenTrace: fn(),+ onOpenObservation: fn(),+ state: transcriptState({+ history: [+ {+ role: "system",+ source: "input",+ parts: [+ {+ type: "text",+ text: "You are a demo observability analyst. Use only fictional project data.",+ },+ ],+ },+ {+ role: "user",+ source: "input",+ parts: [{ type: "text", text: "Inspect representative failures." }],+ },+ ],+ messages: [+ {+ ...provenance,+ role: "system",+ source: "input",+ parts: [{ type: "text", text: "Current system instructions" }],+ },+ {+ ...provenance,+ role: "assistant",+ source: "output",+ parts: [+ { type: "text", text: "Start by investigating the timeout." },+ ],+ },+ ],+ }),+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(+ canvas.queryByText("Inspect representative failures."),+ ).not.toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole("button", { name: /Weather assistant.*trace-1/ }),+ );+ await expect(args.onOpenTrace).toHaveBeenCalledTimes(1);+ const header = canvas.getByRole("button", {+ name: "System prompt",+ }).parentElement!;+ const timestamp = header.querySelector("time")!;+ const openObservation = within(header).getByText("Open observation", {+ selector: "button",+ });+ await expect(timestamp.dateTime).toBe(provenance.startTime.toISOString());+ await userEvent.hover(header);+ await userEvent.click(openObservation);+ await expect(args.onOpenObservation).toHaveBeenCalledTimes(1);+ await expect(args.onOpenObservation).toHaveBeenCalledWith("generation-1");+ await userEvent.unhover(header);+ },+});++export const ToolFailure = meta.story({+ name: "(Test) Renders Tool Failure",+ args: {+ ...commonArgs,+ state: transcriptState({+ history: [],+ messages: [+ {+ ...provenance,+ role: "assistant",+ source: "output",+ parts: [+ {+ type: "tool-call",+ toolCallId: "timeout",+ toolName: "get_order",+ input: { orderId: "LF-20481" },+ },+ ],+ },+ {+ ...provenance,+ role: "tool",+ source: "output",+ endTime: null,+ parts: [+ {+ type: "tool-result",+ toolCallId: "timeout",+ toolName: "get_order",+ output: { code: "TOOL_TIMEOUT" },+ isError: true,+ },+ ],+ },+ ],+ }),+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(canvas.getByLabelText("Failed")).toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand get_order" }),+ );+ await expect(canvas.getByText(/TOOL_TIMEOUT/)).toBeInTheDocument();+ },+});diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsxnew file mode 100644index 0000000000..0e311715b6--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx@@ -0,0 +1,172 @@+import { GitBranch, MessageSquareOff } from "lucide-react";+import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";+import { Skeleton } from "@/src/components/ui/skeleton";+import { Tooltip } from "@/src/components/design-system/Tooltip/Tooltip";+import { cn } from "@/src/utils/tailwind";+import { SessionTranscriptContent } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/SessionTranscriptContent";+import { type SessionTraceTranscriptState } from "@/src/features/sessions/hooks/useSessionTraceTranscripts";+import { getSessionTranscriptThreads } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptThreads";++type PreparedSessionConversationTimelineTraceState =+ | { type: "loading" }+ | { type: "error" }+ | { type: "empty" }+ | {+ type: "transcript";+ result: Extract<SessionTraceTranscriptState, { state: "loaded" }>;+ };++export function SessionConversationTimelineTrace({+ trace,+ turnNumber,+ state,+ onOpenTrace,+ onOpenObservation,+ scrollTarget,+ itemId,+ threadIndex,+ threadNumber,+ displayNumber,+}: {+ itemId?: string;+ threadIndex?: number;+ threadNumber?: number;+ displayNumber?: string;+ threadCount?: number;+ trace: EventSessionTrace;+ turnNumber: number;+ state: PreparedSessionConversationTimelineTraceState;+ onOpenTrace: () => void;+ onOpenObservation: (observationId: string) => void;+ scrollTarget: {+ itemId?: string;+ observationId: string;+ rowId?: string;+ requestId: number;+ } | null;+}) {+ const hiddenThreadCount =+ state.type === "transcript"+ ? getSessionTranscriptThreads(state.result.transcript).hiddenThreadCount+ : 0;+ return (+ <div+ className="px-4 pb-14 sm:px-6 lg:px-10"+ data-session-trace-id={trace.id}+ data-session-item-id={itemId}+ >+ <div className="group/trace-header mb-6 flex items-center gap-4 pt-5">+ <button+ type="button"+ className="text-muted-foreground hover:text-foreground ph-no-capture flex min-w-0 items-center gap-2 font-mono text-xs transition-colors"+ onClick={onOpenTrace}+ title={`${trace.name ?? "Trace"} (${trace.id})`}+ >+ <span className="border-border bg-tertiary text-foreground flex h-4 min-w-4 shrink-0 items-center justify-center rounded-sm border px-0.5 font-mono text-[10px]">+ {displayNumber ?? turnNumber}+ </span>+ <span+ className="truncate"+ title={`${trace.name ?? "Trace"} · ${trace.id}`}+ >+ {trace.name ?? "Trace"} · {trace.id}+ </span>+ {threadNumber !== undefined && (+ <span className="shrink-0">(Thread {threadNumber})</span>+ )}+ </button>+ <div className="border-border min-w-0 flex-1 border-t border-dashed" />+ <button+ type="button"+ className="text-muted-foreground hover:text-foreground hidden shrink-0 font-mono text-xs group-focus-within/trace-header:block group-hover/trace-header:block hover:underline"+ onClick={onOpenTrace}+ >+ Open trace+ </button>+ {hiddenThreadCount > 0 && (+ <Tooltip+ label={`${hiddenThreadCount} nested ${hiddenThreadCount === 1 ? "thread" : "threads"} hidden`}+ >+ {({ getTriggerProps }) => (+ <button+ {...getTriggerProps()}+ type="button"+ className="bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors"+ aria-label={`${hiddenThreadCount} nested ${hiddenThreadCount === 1 ? "thread" : "threads"} hidden`}+ >+ <GitBranch className="icon-base" aria-hidden="true" />+ </button>+ )}+ </Tooltip>+ )}+ {state.type === "transcript" && state.result.cutoff && (+ <Tooltip label="This transcript may be incomplete because the observation limit was reached.">+ {({ getTriggerProps }) => (+ <button+ {...getTriggerProps()}+ type="button"+ className="bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors"+ aria-label="Transcript may be incomplete"+ >+ <MessageSquareOff className="icon-base" aria-hidden="true" />+ </button>+ )}+ </Tooltip>+ )}+ </div>++ {state.type === "loading" && (+ <div+ role="status"+ aria-label="Loading transcript"+ className="flex flex-col gap-5 py-2"+ >+ <div className="flex items-center gap-2 py-1">+ <Skeleton className="h-3.5 w-3.5 shrink-0 rounded-full" />+ <Skeleton className="h-3 w-28" />+ <Skeleton className="h-3 w-3 shrink-0" />+ </div>+ {(["user", "assistant"] as const).map((role) => (+ <div+ key={role}+ className={cn(+ "flex w-full",+ role === "user" ? "justify-end" : "justify-start",+ )}+ >+ <Skeleton+ className={cn(+ "max-w-[min(85%,48rem)] rounded-2xl",+ role === "user" ? "h-20 w-3/5" : "h-24 w-4/5",+ )}+ />+ </div>+ ))}+ <div className="flex items-center gap-2 py-1">+ <Skeleton className="h-3.5 w-3.5 shrink-0 rounded-full" />+ <Skeleton className="h-3 w-24" />+ <Skeleton className="h-3 w-3 shrink-0" />+ </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 transcript.+ </div>+ )}+ {state.type === "empty" && (+ <div className="text-muted-foreground flex items-center justify-between gap-4 rounded-lg border border-dashed p-4 text-xs">+ <span>This trace has no transcript messages.</span>+ </div>+ )}+ {state.type === "transcript" && (+ <SessionTranscriptContent+ {...state}+ onOpenObservation={onOpenObservation}+ scrollTarget={scrollTarget}+ threadIndex={threadIndex}+ />+ )}+ </div>+ );+}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/SessionTranscriptContent.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/SessionTranscriptContent.tsxnew file mode 100644index 0000000000..872357f348--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/SessionTranscriptContent.tsx@@ -0,0 +1,283 @@+import { useState, type ComponentProps, type ReactNode } from "react";+import { type TranscriptMessageGroup } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/groupTranscriptMessages";+import { getSessionTranscriptRows } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows";+import { getSessionTranscriptThreads } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptThreads";+import { SessionTimelineToolRow } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineToolRow/SessionTimelineToolRow";+import { Wrench } from "lucide-react";+import { type NormalizedMessage } from "@langfuse/shared/src/utils/normalized-io";+import { type SessionTraceTranscriptState } from "@/src/features/sessions/hooks/useSessionTraceTranscripts";+import { SessionTimelineContentMessage } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage";+import { SessionTimelineSystemMessage } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage";+import { SessionTimelineCollapsibleRow } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineCollapsibleRow/SessionTimelineCollapsibleRow";+import { formatIntervalSeconds } from "@/src/utils/dates";+import { groupConsecutiveTools } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/fns/groupConsecutiveTools";++export function SessionTranscriptContent({+ result,+ onOpenObservation,+ scrollTarget,+ threadIndex: selectedThreadIndex,+}: {+ threadIndex?: number;+ result: Extract<SessionTraceTranscriptState, { state: "loaded" }>;+ onOpenObservation: (observationId: string) => void;+ scrollTarget: {+ observationId: string;+ rowId?: string;+ requestId: number;+ } | null;+}) {+ const rows = getSessionTranscriptRows(result.transcript).filter(+ ({ threadIndex }) =>+ selectedThreadIndex === undefined || threadIndex === selectedThreadIndex,+ );+ const { visibleThreads } = getSessionTranscriptThreads(result.transcript);+ return (+ <div className="ph-no-capture space-y-4">+ {rows.length === 0 && (+ <p className="text-muted-foreground text-sm">No transcript messages.</p>+ )}+ {visibleThreads+ .filter(+ ({ threadIndex }) =>+ selectedThreadIndex === undefined ||+ threadIndex === selectedThreadIndex,+ )+ .map(({ threadIndex }) => (+ <div+ key={threadIndex}+ className="space-y-4 [&>[data-session-system-row]:has(+[data-session-system-row])]:mb-1 [&>[data-session-tool-row]:has(+[data-session-tool-row])]:mb-1"+ >+ {selectedThreadIndex === undefined && visibleThreads.length > 1 && (+ <h3 className="text-muted-foreground text-xs font-bold">+ Thread {threadIndex + 1}+ </h3>+ )}+ <SessionTranscriptThread+ rows={rows.filter((row) => row.threadIndex === threadIndex)}+ onOpenObservation={onOpenObservation}+ scrollTarget={scrollTarget}+ />+ </div>+ ))}+ </div>+ );+}++type DisplayMessage = NormalizedMessage & {+ timing: { startTime: Date; endTime: Date | null } | null;+ observationId: string | null;+};++function SessionTranscriptThread({+ rows,+ onOpenObservation,+ scrollTarget,+}: {+ rows: ReturnType<typeof getSessionTranscriptRows>;+ onOpenObservation: (observationId: string) => void;+ scrollTarget: {+ observationId: string;+ rowId?: string;+ requestId: number;+ } | null;+}) {+ const groups = groupConsecutiveTools(rows, {+ isTool: ({ row }) => row.type === "tool",+ getBoundary: ({ threadIndex }) => threadIndex,+ getToolName: ({ row }) =>+ row.type === "tool"+ ? (row.call?.toolName ?? row.result?.toolName)+ : undefined,+ summaryBudget: 72,+ });+ return groups.map((group) => {+ if (group.type === "tools") {+ return (+ <SessionTranscriptToolGroup+ key={group.rows[0]!.id}+ summary={group.summary}+ title={group.title}+ rows={group.rows}+ onOpenObservation={onOpenObservation}+ scrollTarget={scrollTarget}+ />+ );+ }+ return (+ <SessionTranscriptRow+ key={group.row.id}+ item={group.row}+ onOpenObservation={onOpenObservation}+ scrollTarget={scrollTarget}+ />+ );+ });+}++function SessionTranscriptRow({+ item,+ onOpenObservation,+ scrollTarget,+}: {+ item: ReturnType<typeof getSessionTranscriptRows>[number];+} & Omit<ComponentProps<typeof SessionTranscriptThread>, "rows">) {+ const { row, id } = item;+ const timing = row.message.timing;+ const isTool = row.type === "tool";+ const isSystem = row.message.role === "system";+ const metadata = (isTool || isSystem) &&+ (timing || row.message.observationId) && (+ <div className="text-muted-foreground invisible flex items-center gap-3 font-mono text-xs group-focus-within/collapsible-row:visible group-hover/collapsible-row:visible group-data-[expanded=true]/collapsible-row:visible">+ {row.message.observationId && (+ <button+ type="button"+ className="hover:text-foreground hover:underline"+ onClick={() => onOpenObservation(row.message.observationId!)}+ >+ Open observation+ </button>+ )}+ {isTool && timing && timing.endTime !== null && (+ <span>+ {formatIntervalSeconds(+ (timing.endTime.getTime() - timing.startTime.getTime()) / 1000,+ )}+ </span>+ )}+ {timing && (isTool || isSystem) && (+ <time dateTime={timing.startTime.toISOString()}>+ {timing.startTime.toLocaleTimeString()}+ </time>+ )}+ </div>+ );+ return (+ <div+ key={id}+ className="group space-y-1"+ data-session-tool-row={isTool ? "" : undefined}+ data-session-system-row={isSystem ? "" : undefined}+ data-session-observation-id={row.message.observationId ?? undefined}+ data-session-transcript-row-id={id}+ data-scroll-request-id={+ (+ scrollTarget?.rowId+ ? scrollTarget.rowId === id+ : scrollTarget?.observationId === row.message.observationId+ )+ ? scrollTarget?.requestId+ : undefined+ }+ >+ {row.type === "tool" ? (+ <SessionTranscriptTool row={row} trailingContent={metadata} />+ ) : (+ <SessionTranscriptMessage+ message={row.message}+ trailingContent={isSystem ? metadata : null}+ onOpenObservation={onOpenObservation}+ />+ )}+ </div>+ );+}++function SessionTranscriptToolGroup({+ summary,+ title,+ rows,+ ...props+}: {+ summary: string;+ title: string;+} & ComponentProps<typeof SessionTranscriptThread>) {+ const [expansion, setExpansion] = useState<{+ isExpanded: boolean;+ requestId: number | undefined;+ }>({ isExpanded: false, requestId: undefined });+ const containsTarget = rows.some(({ id, row }) =>+ props.scrollTarget?.rowId+ ? props.scrollTarget.rowId === id+ : props.scrollTarget?.observationId === row.message.observationId,+ );+ const isOpen =+ expansion.isExpanded ||+ (containsTarget && props.scrollTarget?.requestId !== expansion.requestId);+ return (+ <SessionTimelineCollapsibleRow+ label={summary}+ labelTitle={title}+ showHoverDivider={false}+ labelActionName={`${isOpen ? "Hide" : "Show"} tools: ${title}`}+ icon={<Wrench className="icon-base text-observation-tool shrink-0" />}+ isExpanded={isOpen}+ onExpandedChange={(isExpanded) =>+ setExpansion({+ isExpanded,+ requestId: props.scrollTarget?.requestId,+ })+ }+ >+ <div className="space-y-1">+ {rows.map((item) => (+ <SessionTranscriptRow key={item.id} {...props} item={item} />+ ))}+ </div>+ </SessionTimelineCollapsibleRow>+ );+}++function SessionTranscriptTool({+ row,+ trailingContent,+}: {+ row: Extract<TranscriptMessageGroup<DisplayMessage>, { type: "tool" }>;+ trailingContent: ReactNode;+}) {+ const [isExpanded, setIsExpanded] = useState(false);+ return (+ <SessionTimelineToolRow+ name={row.call?.toolName ?? row.result?.toolName ?? "Tool"}+ input={row.call?.input}+ output={row.result?.output}+ isError={row.result?.isError}+ isExpanded={isExpanded}+ onExpandedChange={setIsExpanded}+ trailingContent={trailingContent}+ />+ );+}++function SessionTranscriptMessage({+ message,+ trailingContent,+ onOpenObservation,+}: {+ message: DisplayMessage;+ trailingContent: ReactNode;+ onOpenObservation: (observationId: string) => void;+}) {+ if (message.role === "system") {+ return (+ <SessionTimelineSystemMessage+ parts={message.parts}+ senderName={message.senderName}+ trailingContent={trailingContent}+ />+ );+ }+ return (+ <SessionTimelineContentMessage+ role={message.role}+ parts={message.parts}+ senderName={message.senderName}+ timestamp={message.timing?.startTime ?? null}+ onOpenObservation={+ message.observationId+ ? () => onOpenObservation(message.observationId!)+ : undefined+ }+ />+ );+}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineCollapsibleRow/SessionTimelineCollapsibleRow.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineCollapsibleRow/SessionTimelineCollapsibleRow.tsxnew file mode 100644index 0000000000..48712520c5--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineCollapsibleRow/SessionTimelineCollapsibleRow.tsx@@ -0,0 +1,92 @@+import { type ReactNode } from "react";+import { ChevronDown } from "lucide-react";+import { cn } from "@/src/utils/tailwind";++export function SessionTimelineCollapsibleRow({+ label,+ labelActionName,+ labelTitle,+ searchableLabel,+ icon,+ isExpanded,+ onExpandedChange,+ onOpenObservation,+ trailingContent,+ showHoverDivider = true,+ children,+}: {+ label: string;+ labelActionName?: string;+ labelTitle?: string;+ searchableLabel?: boolean;+ icon?: ReactNode;+ isExpanded: boolean;+ onExpandedChange: (isExpanded: boolean) => void;+ onOpenObservation?: () => void;+ trailingContent?: ReactNode;+ showHoverDivider?: boolean;+ children: ReactNode;+}) {+ return (+ <section+ className={cn(+ "flex w-full scroll-mt-16 flex-col py-1",+ isExpanded && "gap-2",+ )}+ data-expanded={isExpanded}+ >+ <div+ className="group/collapsible-row flex w-full min-w-0 items-center gap-0.5"+ data-expanded={isExpanded}+ >+ <button+ type="button"+ onClick={onOpenObservation ?? (() => onExpandedChange(!isExpanded))}+ className="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"+ aria-expanded={onOpenObservation ? undefined : isExpanded}+ aria-label={labelActionName}+ >+ {icon && (+ <span className="bg-background relative z-[1] flex shrink-0 rounded-full">+ {icon}+ </span>+ )}+ <span+ className="min-w-0 truncate text-xs font-normal hover:underline"+ title={labelTitle ?? label}+ data-session-search-content={searchableLabel || undefined}+ >+ {label}+ </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"} ${label}`}+ onClick={() => onExpandedChange(!isExpanded)}+ >+ <ChevronDown+ className={cn(+ "icon-base transition-transform",+ !isExpanded && "-rotate-90",+ )}+ aria-hidden="true"+ />+ </button>+ <div+ className={cn(+ "mx-3 min-w-0 flex-1",+ showHoverDivider &&+ "border-border invisible border-t border-dashed group-focus-within/collapsible-row:visible group-hover/collapsible-row:visible",+ )}+ aria-hidden="true"+ />+ <span className="flex shrink-0 items-center gap-2">+ {trailingContent}+ </span>+ </div>+ {isExpanded && <div className="min-w-0">{children}</div>}+ </section>+ );+}diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsxsimilarity index 81%rename from web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsxrename to web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsxindex 357dc4846e..8bbd2a40c9 100644--- a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsx@@ -1,7 +1,7 @@import preview from "@/.storybook/preview";import { expect, userEvent, within } from "storybook/test";-import { SessionTimelineContentMessage } from "@/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTimelineContentMessage/SessionTimelineContentMessage";+import { SessionTimelineContentMessage } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage";const meta = preview.meta({component: SessionTimelineContentMessage,@@ -11,18 +11,6 @@ const meta = preview.meta({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",@@ -59,12 +47,16 @@ export const StructuredData = meta.story({});await expect(toggle).toHaveAttribute("aria-expanded", "false");- await expect(canvas.queryAllByRole("table")).toHaveLength(0);+ await expect(canvas.queryByText("0.9")).not.toBeInTheDocument();+ await expect(canvas.queryByText("7")).not.toBeInTheDocument();await userEvent.click(toggle);await expect(toggle).toHaveAttribute("aria-expanded", "true");- await expect(canvas.getAllByRole("table")).toHaveLength(2);+ await expect(canvas.getAllByText("0.9").length).toBeGreaterThan(0);+ await expect(canvas.getAllByText("7").length).toBeGreaterThan(0);await userEvent.click(toggle);- await expect(canvas.queryAllByRole("table")).toHaveLength(0);+ await expect(toggle).toHaveAttribute("aria-expanded", "false");+ await expect(canvas.queryByText("0.9")).not.toBeInTheDocument();+ await expect(canvas.queryByText("7")).not.toBeInTheDocument();},});@@ -89,22 +81,6 @@ export const MixedTextAndData = meta.story({},});-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",@@ -172,7 +148,7 @@ export const EmbeddedImages = meta.story({});export const FileAttachment = meta.story({- name: "(Test) File Attachment Layout",+ name: "(Test) Safe File Attachment Link",args: {role: "user",parts: [@@ -190,14 +166,16 @@ export const FileAttachment = meta.story({},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",+ await expect(canvas.getByText("inspection-report.pdf")).toBeVisible();+ const link = canvas.getByRole("link", {+ name: "https://example.com/inspection-report.pdf",+ });+ await expect(link).toHaveAttribute(+ "href",+ "https://example.com/inspection-report.pdf",);+ await expect(link).toHaveAttribute("target", "_blank");+ await expect(link).toHaveAttribute("rel", "noreferrer");},});diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsxsimilarity index 67%rename from web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsxrename to web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsxindex 3ab6a7d3df..cf00cba196 100644--- a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsx@@ -1,9 +1,10 @@import React, { useState } from "react";import { Bot, ChevronDown, 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 {+ type NormalizedMessage,+ type ReasoningPart,+} from "@langfuse/shared/src/utils/normalized-io";+import { SessionTimelinePart } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/SessionTimelinePart";import { cn } from "@/src/utils/tailwind";const rolePresentation = {@@ -11,7 +12,8 @@ const rolePresentation = {label: "User",icon: UserRound,wrapper: "justify-end",- container: "bg-muted max-w-[min(85%,48rem)] rounded-2xl px-4 py-2.5",+ container:+ "bg-blue-50 dark:bg-[color-mix(in_srgb,var(--color-muted)_85%,var(--color-light-blue))] max-w-[min(85%,48rem)] rounded-2xl px-4 py-2.5",},assistant: {label: "Assistant",@@ -26,7 +28,7 @@ const rolePresentation = {container: "w-full",},} satisfies Record<- Exclude<SessionTimelineConversationMessage["role"], "system">,+ Exclude<NormalizedMessage["role"], "system">,{label: string;icon: React.ComponentType<{ className?: string }>;@@ -39,10 +41,14 @@ export function SessionTimelineContentMessage({role,parts,senderName,+ timestamp,+ onOpenObservation,}: {- role: Exclude<SessionTimelineConversationMessage["role"], "system">;- parts: SessionTimelineConversationMessage["parts"];- senderName: SessionTimelineConversationMessage["senderName"];+ role: Exclude<NormalizedMessage["role"], "system">;+ parts: NormalizedMessage["parts"];+ senderName: NormalizedMessage["senderName"];+ timestamp?: Date | null;+ onOpenObservation?: () => void;}) {const presentation = rolePresentation[role];const Icon = presentation.icon;@@ -50,7 +56,7 @@ export function SessionTimelineContentMessage({const [expandedJsonGroupIndices, setExpandedJsonGroupIndices] = useState(() => new Set<number>(),);- type MessagePart = SessionTimelineConversationMessage["parts"][number];+ type MessagePart = NormalizedMessage["parts"][number];type ContentPart = Exclude<MessagePart, ReasoningPart>;const groups: Array<| { type: "reasoning"; parts: ReasoningPart[] }@@ -102,6 +108,9 @@ export function SessionTimelineContentMessage({(part) => part.type === "data" || part.type === "custom",);const isJsonExpanded = expandedJsonGroupIndices.has(groupIndex);+ const hasToolParts = group.parts.some(+ (part) => part.type === "tool-call" || part.type === "tool-result",+ );return (<div@@ -110,9 +119,9 @@ export function SessionTimelineContentMessage({><articleclassName={cn(- "min-w-0 overflow-hidden",+ "group/bubble min-w-0 overflow-hidden",presentation.container,- isJsonOnly && isJsonExpanded && "w-full",+ ((isJsonOnly && isJsonExpanded) || hasToolParts) && "w-full",)}>{showSender && groupIndex === firstContentGroupIndex ? (@@ -165,6 +174,33 @@ export function SessionTimelineContentMessage({))}</div>) : null}+ {(timestamp || onOpenObservation) &&+ groupIndex === groups.length - 1 && (+ <div+ className={cn(+ "text-muted-foreground mt-1 flex items-center gap-3 font-mono text-[10px]",+ role === "user" ? "justify-end" : "justify-start",+ )}+ >+ {onOpenObservation && (+ <button+ type="button"+ className={cn(+ "hover:text-foreground invisible group-focus-within/bubble:visible group-hover/bubble:visible hover:underline",+ role !== "user" && "order-1",+ )}+ onClick={onOpenObservation}+ >+ Open observation+ </button>+ )}+ {timestamp && (+ <time dateTime={timestamp.toISOString()}>+ {timestamp.toLocaleTimeString()}+ </time>+ )}+ </div>+ )}</article></div>);diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelinePart/SessionTimelinePart.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/SessionTimelinePart.tsxsimilarity index 77%rename from web/src/features/sessions/SessionConversationTimeline/components/SessionTimelinePart/SessionTimelinePart.tsxrename to web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/SessionTimelinePart.tsxindex 1f3be9dc33..12b2330b18 100644--- a/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelinePart/SessionTimelinePart.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/SessionTimelinePart.tsx@@ -1,13 +1,12 @@/* eslint-disable no-nested-ternary */-import { FileIcon } from "lucide-react";+import { FileIcon, Wrench } from "lucide-react";import { assertUnreachable } from "@langfuse/shared";import {type FilePart,+ type NormalizedMessage,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 { SessionTimelineCollapsiblePart } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/components/SessionTimelineCollapsiblePart/SessionTimelineCollapsiblePart";import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";import { MarkdownView } from "@/src/components/ui/MarkdownViewer";import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";@@ -113,7 +112,7 @@ function SessionTimelineFile({ part }: { part: FilePart }) {export function SessionTimelinePart({part,}: {- part: SessionTimelineConversationMessage["parts"][number];+ part: NormalizedMessage["parts"][number];}) {if (part.type === "text") {return (@@ -121,10 +120,12 @@ export function SessionTimelinePart({{part.refusal ? (<span className="text-dark-red text-[11px] font-bold">Refusal</span>) : null}- <MarkdownView- markdown={decodeUnicodeEscapesOnly(part.text, true)}- className="px-0 py-0"- />+ <div data-session-search-content>+ <MarkdownView+ markdown={decodeUnicodeEscapesOnly(part.text, true)}+ className="px-0 py-0"+ />+ </div></div>);}@@ -137,6 +138,26 @@ export function SessionTimelinePart({return <SessionTimelineFile part={part} />;}+ if (part.type === "tool-call" || part.type === "tool-result") {+ const isCall = part.type === "tool-call";+ return (+ <SessionTimelineCollapsiblePart+ label={`${part.toolName ?? "Tool"} · ${isCall ? "Call" : "Result"}`}+ icon={Wrench}+ status={+ part.type === "tool-result" && part.isError ? "error" : undefined+ }+ variant="plain"+ alignment="row"+ >+ <PrettyJsonView+ json={part.type === "tool-call" ? part.input : part.output}+ currentView="pretty"+ />+ </SessionTimelineCollapsiblePart>+ );+ }+if (part.type === "data") {return <PrettyJsonView json={part.value} currentView="pretty" />;}diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineCollapsiblePart/SessionTimelineCollapsiblePart.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/components/SessionTimelineCollapsiblePart/SessionTimelineCollapsiblePart.tsxsimilarity index 94%rename from web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineCollapsiblePart/SessionTimelineCollapsiblePart.tsxrename to web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/components/SessionTimelineCollapsiblePart/SessionTimelineCollapsiblePart.tsxindex e78fc80daf..26d0cf4f66 100644--- a/web/src/features/sessions/SessionConversationTimeline/components/SessionTimelineCollapsiblePart/SessionTimelineCollapsiblePart.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/components/SessionTimelineCollapsiblePart/SessionTimelineCollapsiblePart.tsx@@ -10,6 +10,7 @@ export function SessionTimelineCollapsiblePart({status,variant,alignment,+ trailingContent,children,}: {label: string;@@ -17,6 +18,7 @@ export function SessionTimelineCollapsiblePart({status?: "success" | "error";variant: "plain" | "card";alignment: "start" | "center" | "row";+ trailingContent?: React.ReactNode;children: React.ReactNode;}) {const [isExpanded, setIsExpanded] = useState(false);@@ -62,8 +64,8 @@ export function SessionTimelineCollapsiblePart({aria-hidden="true"/></button>- {alignment === "row" ? (- <div className="border-border min-w-0 flex-1 border-t border-dashed" />+ {trailingContent ? (+ <div className="ml-auto shrink-0">{trailingContent}</div>) : null}</div>{isExpanded ? (diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.stories.tsxsimilarity index 79%rename from web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.stories.tsxrename to web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.stories.tsxindex e910f3b147..f872f8aa99 100644--- a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.stories.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.stories.tsx@@ -1,7 +1,7 @@import preview from "@/.storybook/preview";import { expect, userEvent, within } from "storybook/test";-import { SessionTimelineSystemMessage } from "@/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage";+import { SessionTimelineSystemMessage } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage";const systemPromptParts = [{@@ -26,10 +26,6 @@ const meta = preview.meta({export default meta;-export const SystemPrompt = meta.story({- args: { parts: systemPromptParts },-});-export const ExpandSystemPrompt = meta.story({name: "(Test) Expands System Prompt",args: { parts: systemPromptParts },diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.tsxnew file mode 100644index 0000000000..b3b4fc99d0--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineSystemMessage/SessionTimelineSystemMessage.tsx@@ -0,0 +1,32 @@+import { useState, type ReactNode } from "react";+import { type NormalizedMessage } from "@langfuse/shared/src/utils/normalized-io";+import { SessionTimelineCollapsibleRow } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineCollapsibleRow/SessionTimelineCollapsibleRow";+import { SessionTimelinePart } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/SessionTimelinePart";++export function SessionTimelineSystemMessage({+ parts,+ senderName,+ trailingContent,+}: {+ parts: NormalizedMessage["parts"];+ senderName: NormalizedMessage["senderName"];+ trailingContent?: ReactNode;+}) {+ const [isExpanded, setIsExpanded] = useState(false);+ return (+ <div className="ph-no-capture flex w-full">+ <SessionTimelineCollapsibleRow+ label={senderName ?? "System prompt"}+ isExpanded={isExpanded}+ onExpandedChange={setIsExpanded}+ trailingContent={trailingContent}+ >+ <div className="text-muted-foreground flex flex-col gap-2 text-sm">+ {parts.map((part, index) => (+ <SessionTimelinePart key={`${part.type}-${index}`} part={part} />+ ))}+ </div>+ </SessionTimelineCollapsibleRow>+ </div>+ );+}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineToolRow/SessionTimelineToolRow.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineToolRow/SessionTimelineToolRow.tsxnew file mode 100644index 0000000000..cdeab12325--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineToolRow/SessionTimelineToolRow.tsx@@ -0,0 +1,85 @@+import { CircleAlert } from "lucide-react";+import { type ReactNode } from "react";+import { renderFilterIcon } from "@/src/components/ItemBadge";+import { SessionTimelineCollapsibleRow } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineCollapsibleRow/SessionTimelineCollapsibleRow";+import { decodeUnicodeEscapesOnly } from "@/src/utils/unicode";++const toPreviewText = (value: unknown) => {+ const text =+ typeof value === "string"+ ? value+ : (JSON.stringify(value, undefined, 2) ?? String(value));+ return decodeUnicodeEscapesOnly(text, true);+};++const hasPreviewValue = (value: unknown) =>+ value !== null && value !== undefined && value !== "";++export function SessionTimelineToolRow({+ name,+ input,+ output,+ isExpanded,+ onExpandedChange,+ isError,+ trailingContent,+}: {+ name: string;+ input: unknown;+ output: unknown;+ isExpanded: boolean;+ onExpandedChange: (isExpanded: boolean) => void;+ isError?: boolean;+ trailingContent?: ReactNode;+}) {+ return (+ <SessionTimelineCollapsibleRow+ label={name}+ searchableLabel+ icon={renderFilterIcon("TOOL")}+ isExpanded={isExpanded}+ onExpandedChange={onExpandedChange}+ trailingContent={+ <>+ {trailingContent}+ {isError ? (+ <CircleAlert+ className="icon-sm text-destructive"+ aria-label="Failed"+ />+ ) : null}+ </>+ }+ >+ <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+ </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>+ </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+ </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>+ </div>+ ) : null}+ {!hasPreviewValue(input) && !hasPreviewValue(output) ? (+ <div className="relative">+ <span className="text-muted-foreground text-xs">+ No input or output+ </span>+ </div>+ ) : null}+ </div>+ </SessionTimelineCollapsibleRow>+ );+}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/fns/groupConsecutiveTools.clienttest.ts b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/fns/groupConsecutiveTools.clienttest.tsnew file mode 100644index 0000000000..feef4ffb18--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/fns/groupConsecutiveTools.clienttest.ts@@ -0,0 +1,156 @@+import { describe, expect, it } from "vitest";+import { groupConsecutiveTools } from "./groupConsecutiveTools";++const options = {+ isTool: (row: { role: string }) => row.role === "tool",+ getBoundary: (row: { boundary: number }) => row.boundary,+ getToolName: (row: { name: string }) => row.name,+ summaryBudget: 36,+};++describe("groupConsecutiveTools", () => {+ it("fits measured glyph widths, including the conditional sidebar prefix", () => {+ const rows = ["iiii", "WWWW"].map((name) => ({+ role: "tool",+ name,+ boundary: 0,+ }));+ const measureSummary = (summary: string) => {+ const label = /^[0-9]+x\s/.test(summary) ? summary : `Tool: ${summary}`;+ return [...label].reduce(+ (width, character) => width + (character === "W" ? 8 : 1),+ 0,+ );+ };+ expect(+ groupConsecutiveTools(rows, {+ ...options,+ summaryBudget: 22,+ measureSummary,+ })[0],+ ).toMatchObject({ summary: "iiii · +1 more", title: "iiii · WWWW" });+ expect(+ groupConsecutiveTools(rows, {+ ...options,+ summaryBudget: 45,+ measureSummary,+ })[0],+ ).toMatchObject({ summary: "iiii · WWWW" });+ expect(+ groupConsecutiveTools(rows, {+ ...options,+ summaryBudget: 19,+ measureSummary,+ })[0],+ ).toMatchObject({ summary: "ii… · +1 more" });+ });++ it("reserves measured repetition counts, ellipsis, and omitted calls at the boundary", () => {+ const rows = ["WWWW", "WWWW", "read"].map((name) => ({+ role: "tool",+ name,+ boundary: 0,+ }));+ const measureSummary = (summary: string) =>+ [...summary].reduce(+ (width, character) => width + (character === "W" ? 8 : 1),+ 0,+ );+ expect(+ groupConsecutiveTools(rows, {+ ...options,+ summaryBudget: 22,+ measureSummary,+ })[0],+ ).toMatchObject({ summary: "2x W… · +1 more", title: "2x WWWW · read" });+ expect(+ groupConsecutiveTools(rows, {+ ...options,+ summaryBudget: 21,+ measureSummary,+ })[0],+ ).toMatchObject({ summary: "2x … · +1 more" });+ });++ it("counts all tool calls in mixed groups", () => {+ const rows = ["tool_a", "tool_a", "tool_a", "tool_b"].map((name) => ({+ role: "tool",+ name,+ boundary: 0,+ }));+ expect(groupConsecutiveTools(rows, options)).toEqual([+ {+ type: "tools",+ rows,+ summary: "3x tool_a · tool_b",+ title: "3x tool_a · tool_b",+ },+ ]);+ });++ it("shows only fitting names and preserves full tooltip names", () => {+ const rows = Array.from({ length: 7 }, (_, index) => ({+ role: "tool",+ name: `very_long_tool_name_${index}`,+ boundary: 0,+ }));+ const group = groupConsecutiveTools(rows, options)[0]!;+ expect(group.type).toBe("tools");+ if (group.type !== "tools") return;+ expect(group.summary).toBe("very_long_tool_name_0 · +6 more");+ expect(group.summary.length).toBeLessThanOrEqual(36);+ expect(group.title).toBe(rows.map((row) => row.name).join(" · "));+ expect(+ groupConsecutiveTools(rows, { ...options, summaryBudget: 16 })[0],+ ).toMatchObject({ summary: "very_… · +6 more" });+ });++ it("ranks by frequency with stable ties and counts omitted calls", () => {+ const rows = [+ "read",+ "search",+ "other",+ "search",+ "read",+ "search",+ "last",+ "last",+ "search",+ "read",+ ].map((name) => ({ role: "tool", name, boundary: 0 }));+ const group = groupConsecutiveTools(rows, {+ ...options,+ summaryBudget: 27,+ })[0]!;+ expect(group).toMatchObject({+ summary: "4x search · +6 more",+ title: "4x search · 3x read · 2x last · other",+ });+ });++ it("falls back for missing and blank names", () => {+ const rows = [undefined, " ", null].map((name) => ({+ role: "tool",+ name,+ boundary: 0,+ }));+ expect(+ groupConsecutiveTools(rows, {+ ...options,+ getToolName: (row) => row.name,+ })[0],+ ).toMatchObject({ summary: "3x Tool", title: "3x Tool" });+ });++ it("does not group across messages or original run boundaries", () => {+ const rows = [+ { role: "tool", name: "tool_a", boundary: 0 },+ { role: "assistant", name: "message", boundary: 0 },+ { role: "tool", name: "tool_b", boundary: 0 },+ { role: "tool", name: "tool_c", boundary: 1 },+ ];+ expect(groupConsecutiveTools(rows, options)).toEqual(+ rows.map((row) => ({ type: "row", row })),+ );+ });+});diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/fns/groupConsecutiveTools.ts b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/fns/groupConsecutiveTools.tsnew file mode 100644index 0000000000..b516cbabc0--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/fns/groupConsecutiveTools.ts@@ -0,0 +1,84 @@+export function groupConsecutiveTools<T>(+ rows: readonly T[],+ options: {+ isTool: (row: T) => boolean;+ getBoundary: (row: T) => string | number | undefined;+ getToolName: (row: T) => string | null | undefined;+ summaryBudget: number;+ measureSummary?: (summary: string) => number;+ },+) {+ const measureSummary =+ options.measureSummary ?? ((summary: string) => summary.length);+ const groups: Array<+ | { type: "row"; row: T }+ | { type: "tools"; rows: T[]; summary: string; title: string }+ > = [];+ for (let index = 0; index < rows.length; index++) {+ const row = rows[index]!;+ if (!options.isTool(row)) {+ groups.push({ type: "row", row });+ continue;+ }+ const tools = [row];+ while (+ index + 1 < rows.length &&+ options.isTool(rows[index + 1]!) &&+ options.getBoundary(rows[index + 1]!) === options.getBoundary(row)+ ) {+ tools.push(rows[++index]!);+ }+ if (tools.length === 1) {+ groups.push({ type: "row", row });+ continue;+ }+ const counts = new Map<string, number>();+ for (const tool of tools) {+ const name = options.getToolName(tool)?.trim() || "Tool";+ counts.set(name, (counts.get(name) ?? 0) + 1);+ }+ const names = [...counts].sort((a, b) => b[1] - a[1]);+ const labels = names.map(([name, count]) =>+ count > 1 ? `${count}x ${name}` : name,+ );+ const title = labels.join(" · ");+ let shown =+ measureSummary(title) <= options.summaryBudget ? names.length : 0;+ while (shown < names.length) {+ const omitted = names+ .slice(shown + 1)+ .reduce((sum, [, count]) => sum + count, 0);+ const candidate =+ labels.slice(0, shown + 1).join(" · ") ++ (omitted ? ` · +${omitted} more` : "");+ if (measureSummary(candidate) > options.summaryBudget) break;+ shown++;+ }+ if (shown === 0) {+ const [name, count] = names[0]!;+ const prefix = count > 1 ? `${count}x ` : "";+ const remainingCalls = tools.length - count;+ const firstSuffix = remainingCalls ? ` · +${remainingCalls} more` : "";+ const characters = [...name];+ let fittingLength = 0;+ let upperBound = characters.length;+ while (fittingLength < upperBound) {+ const length = Math.ceil((fittingLength + upperBound) / 2);+ const candidate =+ prefix + characters.slice(0, length).join("") + "…" + firstSuffix;+ if (measureSummary(candidate) <= options.summaryBudget)+ fittingLength = length;+ else upperBound = length - 1;+ }+ labels[0] = prefix + characters.slice(0, fittingLength).join("") + "…";+ shown = 1;+ }+ const omitted = names+ .slice(shown)+ .reduce((sum, [, count]) => sum + count, 0);+ const suffix = omitted ? ` · +${omitted} more` : "";+ const summary = labels.slice(0, shown).join(" · ") + suffix;+ groups.push({ type: "tools", rows: tools, summary, title });+ }+ return groups;+}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionConversationEntries.ts b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionConversationEntries.tsnew file mode 100644index 0000000000..eefa8c8008--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionConversationEntries.ts@@ -0,0 +1,40 @@+import { type RouterOutputs } from "@/src/utils/api";+import { getSessionTranscriptThreads } from "./getSessionTranscriptThreads";++export function getSessionConversationEntries(+ traces: readonly {+ trace: { id: string };+ transcript:+ | RouterOutputs["events"]["transcriptByTraceId"]["transcript"]+ | undefined;+ }[],+) {+ const visibility = traces.map(({ transcript }) =>+ getSessionTranscriptThreads(transcript ?? null),+ );+ const useThreadNumbers = visibility.some(+ ({ visibleThreads }) => visibleThreads.length > 1,+ );+ return traces.flatMap(({ trace, transcript }, traceIndex) => {+ const { visibleThreads } = visibility[traceIndex]!;+ const threads = visibleThreads.length+ ? visibleThreads+ : [{ threadIndex: undefined }];+ return threads.map(({ threadIndex }, visibleIndex) => ({+ itemId:+ threadIndex === undefined ? trace.id : `${trace.id}:${threadIndex}`,+ traceIndex,+ threadIndex,+ threadCount: transcript === undefined ? undefined : visibleThreads.length,+ threadNumber:+ useThreadNumbers && threadIndex !== undefined+ ? visibleIndex + 1+ : undefined,+ displayNumber:+ useThreadNumbers && threadIndex !== undefined+ ? `${traceIndex + 1}.${visibleIndex + 1}`+ : String(traceIndex + 1),+ isFirstThread: visibleIndex === 0,+ }));+ });+}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows.clienttest.ts b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows.clienttest.tsnew file mode 100644index 0000000000..22fdad6742--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows.clienttest.ts@@ -0,0 +1,220 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import { type RouterOutputs } from "@/src/utils/api";+import { getSessionTranscriptRows } from "./getSessionTranscriptRows";+import { getSessionTranscriptThreads } from "./getSessionTranscriptThreads";+import { getSessionConversationEntries } from "./getSessionConversationEntries";++const transcript = {+ threads: [+ {+ conversationHistory: [],+ currentTurn: {+ nestingLevel: 0,+ observations: [],+ messages: [+ {+ observationId: "generation",+ traceId: "trace",+ startTime: new Date(0),+ endTime: new Date(1000),+ role: "assistant",+ source: "output",+ parts: [+ { type: "text", text: "Before" },+ {+ type: "tool-call",+ toolName: "search",+ toolCallId: "call",+ input: {},+ },+ { type: "text", text: "After" },+ ],+ },+ {+ observationId: "tool",+ traceId: "trace",+ startTime: new Date(1000),+ endTime: new Date(2000),+ role: "tool",+ source: "output",+ parts: [+ { type: "tool-result", toolCallId: "call", output: "Found" },+ ],+ },+ ],+ },+ },+ ],+} satisfies NonNullable<+ RouterOutputs["events"]["transcriptByTraceId"]["transcript"]+>;++describe("getSessionTranscriptRows", () => {+ it("flattens visible threads with contiguous labels but original identities", () => {+ const base = transcript.threads[0]!;+ const entries = getSessionConversationEntries([+ { trace: { id: "single" }, transcript },+ {+ trace: { id: "multi" },+ transcript: {+ threads: [+ base,+ { ...base, currentTurn: { ...base.currentTurn, nestingLevel: 1 } },+ base,+ ],+ },+ },+ { trace: { id: "loading" }, transcript: undefined },+ ]);+ expect(entries).toMatchObject([+ {+ itemId: "single:0",+ traceIndex: 0,+ threadIndex: 0,+ threadNumber: 1,+ displayNumber: "1.1",+ threadCount: 1,+ },+ {+ itemId: "multi:0",+ traceIndex: 1,+ threadIndex: 0,+ threadNumber: 1,+ displayNumber: "2.1",+ threadCount: 2,+ },+ {+ itemId: "multi:2",+ traceIndex: 1,+ threadIndex: 2,+ threadNumber: 2,+ displayNumber: "2.2",+ threadCount: 2,+ },+ {+ itemId: "loading",+ traceIndex: 2,+ displayNumber: "3",+ threadNumber: undefined,+ },+ ]);+ expect(+ getSessionConversationEntries([+ { trace: { id: "single" }, transcript },+ ])[0],+ ).toMatchObject({ displayNumber: "1", threadNumber: undefined });+ });+ it("keeps empty visible threads and does not count hidden threads for decimal mode", () => {+ const base = transcript.threads[0]!;+ expect(+ getSessionConversationEntries([+ {+ trace: { id: "empty-thread" },+ transcript: {+ threads: [+ { ...base, currentTurn: { ...base.currentTurn, messages: [] } },+ {+ ...base,+ currentTurn: { ...base.currentTurn, nestingLevel: 1 },+ },+ ],+ },+ },+ { trace: { id: "no-transcript" }, transcript: null },+ ]),+ ).toMatchObject([+ {+ itemId: "empty-thread:0",+ displayNumber: "1",+ threadCount: 1,+ threadNumber: undefined,+ },+ {+ itemId: "no-transcript",+ displayNumber: "2",+ threadIndex: undefined,+ threadCount: 0,+ },+ ]);+ });++ it("gives messages and paired tools distinct IDs while preserving result provenance", () => {+ const rows = getSessionTranscriptRows(transcript);+ expect(+ rows.map(({ id, row }) => [id, row.type, row.message.observationId]),+ ).toEqual([+ ["0:0", "message", "generation"],+ ["0:1", "tool", "tool"],+ ["0:2", "message", "generation"],+ ]);+ expect(rows[1]?.row).toMatchObject({+ call: { toolName: "search" },+ result: { output: "Found" },+ });+ });++ it("returns no rows for an absent transcript", () => {+ expect(getSessionTranscriptRows(null)).toEqual([]);+ });++ it("only projects the shallowest threads and preserves original row IDs", () => {+ const baseThread = transcript.threads[0]!;+ const nestedTranscript = {+ threads: [3, 2, 4, 2].map((nestingLevel) => ({+ ...baseThread,+ currentTurn: { ...baseThread.currentTurn, nestingLevel },+ })),+ };++ expect(+ getSessionTranscriptRows(nestedTranscript).map(({ id }) => id),+ ).toEqual(["1:0", "1:1", "1:2", "3:0", "3:1", "3:2"]);+ expect(getSessionTranscriptThreads(nestedTranscript)).toMatchObject({+ hiddenThreadCount: 2,+ visibleThreads: [{ threadIndex: 1 }, { threadIndex: 3 }],+ });+ });++ it("does not project nested-only search content or hide equal-depth threads", () => {+ const baseThread = transcript.threads[0]!;+ const nestedTranscript = {+ threads: [+ baseThread,+ {+ ...baseThread,+ currentTurn: {+ ...baseThread.currentTurn,+ nestingLevel: 1,+ messages: [+ {+ ...baseThread.currentTurn.messages[0]!,+ parts: [+ { type: "text" as const, text: "Nested-only search match" },+ ],+ },+ ],+ },+ },+ baseThread,+ ],+ };+ const rows = getSessionTranscriptRows(nestedTranscript);+ expect(rows.map(({ threadIndex }) => threadIndex)).toEqual([+ 0, 0, 0, 2, 2, 2,+ ]);+ expect(JSON.stringify(rows)).not.toContain("Nested-only search match");+ });++ it("reports no hidden threads for absent or empty transcripts", () => {+ expect(getSessionTranscriptThreads(null)).toEqual({+ visibleThreads: [],+ hiddenThreadCount: 0,+ });+ expect(getSessionTranscriptThreads({ threads: [] })).toEqual({+ visibleThreads: [],+ hiddenThreadCount: 0,+ });+ });+});diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows.ts b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows.tsnew file mode 100644index 0000000000..3f92ca0a12--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptRows.ts@@ -0,0 +1,21 @@+import { type RouterOutputs } from "@/src/utils/api";+import { groupTranscriptMessages } from "./groupTranscriptMessages";+import { getSessionTranscriptThreads } from "./getSessionTranscriptThreads";++export function getSessionTranscriptRows(+ transcript: RouterOutputs["events"]["transcriptByTraceId"]["transcript"],+) {+ return getSessionTranscriptThreads(transcript).visibleThreads.flatMap(+ ({ thread, threadIndex }) => {+ const messages = thread.currentTurn.messages.map((message) => ({+ ...message,+ timing: { startTime: message.startTime, endTime: message.endTime },+ }));+ return groupTranscriptMessages(messages).map((row, rowIndex) => ({+ id: `${threadIndex}:${rowIndex}`,+ threadIndex,+ row,+ }));+ },+ );+}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptThreads.ts b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptThreads.tsnew file mode 100644index 0000000000..2913345832--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/getSessionTranscriptThreads.ts@@ -0,0 +1,20 @@+import { type RouterOutputs } from "@/src/utils/api";++export function getSessionTranscriptThreads(+ transcript: RouterOutputs["events"]["transcriptByTraceId"]["transcript"],+) {+ const threads = transcript?.threads ?? [];+ const shallowestLevel = threads.reduce(+ (level, thread) => Math.min(level, thread.currentTurn.nestingLevel),+ Infinity,+ );+ const visibleThreads = threads+ .map((thread, threadIndex) => ({ thread, threadIndex }))+ .filter(+ ({ thread }) => thread.currentTurn.nestingLevel === shallowestLevel,+ );+ return {+ visibleThreads,+ hiddenThreadCount: threads.length - visibleThreads.length,+ };+}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/groupTranscriptMessages.clienttest.ts b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/groupTranscriptMessages.clienttest.tsnew file mode 100644index 0000000000..17c3f03579--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/groupTranscriptMessages.clienttest.ts@@ -0,0 +1,223 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import {+ type NormalizedMessage,+ type NormalizedMessagePart,+ type ToolCallPart,+ type ToolResultPart,+} from "@langfuse/shared/src/utils/normalized-io";+import { groupTranscriptMessages } from "./groupTranscriptMessages";++const call = (id: string | null): ToolCallPart => ({+ type: "tool-call",+ toolCallId: id,+ toolName: "search",+ input: { query: "hello" },+});+const result = (id: string | null): ToolResultPart => ({+ type: "tool-result",+ toolCallId: id,+ output: "found",+});+const text = (value: string): NormalizedMessagePart => ({+ type: "text",+ text: value,+});+const message = (parts: NormalizedMessagePart[]): NormalizedMessage => ({+ role: "assistant",+ source: "output",+ parts,+});++describe("groupTranscriptMessages", () => {+ it("groups results at call positions while preserving surrounding parts and metadata", () => {+ const firstCall = call("a");+ const secondCall = call("b");+ const firstResult = result("a");+ const secondResult = result("b");+ const messages = [+ {+ ...message([+ text("before"),+ firstCall,+ text("between"),+ secondCall,+ text("after"),+ ]),+ observationId: "generation",+ startTime: new Date(0),+ timing: { startTime: new Date(0), endTime: new Date(1000) },+ },+ {+ ...message([secondResult, text("result context"), firstResult]),+ observationId: "tool",+ startTime: new Date(1),+ timing: { startTime: new Date(1), endTime: new Date(101) },+ },+ ];++ expect(groupTranscriptMessages(messages)).toEqual([+ { type: "message", message: { ...messages[0], parts: [text("before")] } },+ {+ type: "tool",+ message: messages[1],+ call: firstCall,+ result: firstResult,+ },+ {+ type: "message",+ message: { ...messages[0], parts: [text("between")] },+ },+ {+ type: "tool",+ message: messages[1],+ call: secondCall,+ result: secondResult,+ },+ { type: "message", message: { ...messages[0], parts: [text("after")] } },+ {+ type: "message",+ message: { ...messages[1], parts: [text("result context")] },+ },+ ]);+ });++ it("pairs a server-produced identified tool response", () => {+ const output = "found";+ const parts = [{ ...result("a"), toolName: "search", output }];+ const toolCall = call("a");+ const response = {+ ...message(parts),+ role: "tool" as const,+ observationId: "tool",+ };+ const input = { ...message([toolCall]), observationId: "generation" };++ expect(groupTranscriptMessages([input, response])).toEqual([+ {+ type: "tool",+ message: response,+ call: toolCall,+ result: {+ type: "tool-result",+ toolCallId: "a",+ toolName: "search",+ output,+ },+ },+ ]);+ });++ it.each(["search", "weather"])(+ "keeps a text response separate from multiple calls including %s",+ (toolName) => {+ const input = message([call("a"), { ...call("b"), toolName }]);+ const response = { ...message([text("found")]), role: "tool" as const };+ expect(groupTranscriptMessages([input, response])).toEqual([+ { type: "tool", message: input, call: input.parts[0], result: null },+ { type: "tool", message: input, call: input.parts[1], result: null },+ { type: "message", message: response },+ ]);+ },+ );++ it("keeps unnamed later responses separate rather than skipping intervening tools", () => {+ const input = message([call("a")]);+ const first = { ...message([text("first")]), role: "tool" as const };+ const second = { ...message([text("second")]), role: "tool" as const };+ expect(+ groupTranscriptMessages([input, first, second]).map((row) => row.message),+ ).toEqual([input, first, second]);+ });++ it("does not invent an ID for a text response to an unidentified call", () => {+ const toolCall = call(null);+ const input = message([toolCall]);+ const response = { ...message([text("found")]), role: "tool" as const };+ expect(groupTranscriptMessages([input, response])).toEqual([+ { type: "tool", message: input, call: toolCall, result: null },+ { type: "message", message: response },+ ]);+ });++ it("prefers an explicitly identified result over an adjacent text response", () => {+ const toolCall = call("a");+ const toolResult = result("a");+ const input = message([toolCall]);+ const response = {+ ...message([text("unidentified")]),+ role: "tool" as const,+ };+ const identifiedResponse = message([toolResult]);+ expect(+ groupTranscriptMessages([input, response, identifiedResponse]),+ ).toEqual([+ {+ type: "tool",+ message: identifiedResponse,+ call: toolCall,+ result: toolResult,+ },+ { type: "message", message: response },+ ]);+ });++ it.each([+ [call(null), result(null)],+ [call(""), result("")],+ [call("a"), result("b")],+ [call("a"), call("a"), result("a")],+ [call("a"), result("a"), result("a")],+ [result("a"), call("a")],+ ])(+ "extracts missing, ambiguous and out-of-order IDs without pairing: %j",+ (...parts) => {+ const messages = parts.map((part) => message([part]));+ expect(groupTranscriptMessages(messages)).toEqual(+ messages.map((message, index) => ({+ type: "tool",+ message,+ call: parts[index]!.type === "tool-call" ? parts[index] : null,+ result: parts[index]!.type === "tool-result" ? parts[index] : null,+ })),+ );+ },+ );++ it.each([call("a"), result("a")])(+ "extracts an unmatched tool part while preserving surrounding text: %j",+ (part) => {+ const input = message([text("before"), part, text("after")]);+ expect(groupTranscriptMessages([input])).toEqual([+ { type: "message", message: { ...input, parts: [text("before")] } },+ {+ type: "tool",+ message: input,+ call: part.type === "tool-call" ? part : null,+ result: part.type === "tool-result" ? part : null,+ },+ { type: "message", message: { ...input, parts: [text("after")] } },+ ]);+ },+ );++ it("pairs a call and later result in the same message without mutating input", () => {+ const toolCall = call("a");+ const toolResult = result("a");+ const input = message([toolCall, text("middle"), toolResult, text("end")]);+ const original = structuredClone(input);+ input.parts.forEach(Object.freeze);+ Object.freeze(input.parts);+ Object.freeze(input);+ const groups = groupTranscriptMessages(Object.freeze([input]));+ expect(groups).toEqual([+ { type: "tool", message: input, call: toolCall, result: toolResult },+ {+ type: "message",+ message: { ...input, parts: [text("middle"), text("end")] },+ },+ ]);+ expect(input).toEqual(original);+ });+});diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/groupTranscriptMessages.ts b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/groupTranscriptMessages.tsnew file mode 100644index 0000000000..d3e2210dce--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/fns/groupTranscriptMessages.ts@@ -0,0 +1,119 @@+import {+ type NormalizedMessage,+ type NormalizedMessagePart,+ type ToolCallPart,+ type ToolResultPart,+} from "@langfuse/shared/src/utils/normalized-io";++export type TranscriptMessageGroup<T extends NormalizedMessage> =+ | { type: "message"; message: T }+ | {+ type: "tool";+ message: T;+ call: ToolCallPart;+ result: ToolResultPart;+ }+ | { type: "tool"; message: T; call: ToolCallPart; result: null }+ | { type: "tool"; message: T; call: null; result: ToolResultPart };++/** Only pair unique, ordered IDs; keep unmatched tool parts as standalone rows. */+export function groupTranscriptMessages<T extends NormalizedMessage>(+ messages: readonly T[],+): TranscriptMessageGroup<T>[] {+ const calls = new Map<+ string,+ { part: ToolCallPart; position: number; count: number }+ >();+ const results = new Map<+ string,+ {+ part: ToolResultPart;+ message: T;+ position: number;+ partCount: number;+ count: number;+ }+ >();+ let position = 0;+ for (const message of messages) {+ for (const part of message.parts) {+ if (part.type === "tool-call" && part.toolCallId) {+ const previous = calls.get(part.toolCallId);+ calls.set(part.toolCallId, {+ part,+ position,+ count: (previous?.count ?? 0) + 1,+ });+ } else if (part.type === "tool-result" && part.toolCallId) {+ const previous = results.get(part.toolCallId);+ results.set(part.toolCallId, {+ part,+ message,+ position,+ partCount: 1,+ count: (previous?.count ?? 0) + 1,+ });+ }+ position++;+ }+ }++ const pairs = new Map<+ number,+ { call: ToolCallPart; result: ToolResultPart; message: T }+ >();+ const consumedResults = new Set<number>();+ for (const [id, call] of calls) {+ const result = results.get(id);+ if (+ call.count !== 1 ||+ result?.count !== 1 ||+ result.position <= call.position+ )+ continue;+ pairs.set(call.position, {+ call: call.part,+ result: result.part,+ message: result.message,+ });+ for (let offset = 0; offset < result.partCount; offset++) {+ consumedResults.add(result.position + offset);+ }+ }++ const groups: TranscriptMessageGroup<T>[] = [];+ position = 0;+ for (const message of messages) {+ let parts: NormalizedMessagePart[] = [];+ let changed = false;+ const flush = () => {+ if (parts.length)+ groups.push({ type: "message", message: { ...message, parts } });+ parts = [];+ };+ for (const part of message.parts) {+ const pair = pairs.get(position);+ if (pair) {+ changed = true;+ flush();+ groups.push({ type: "tool", ...pair });+ } else if (consumedResults.has(position)) {+ changed = true;+ } else if (part.type === "tool-call") {+ changed = true;+ flush();+ groups.push({ type: "tool", message, call: part, result: null });+ } else if (part.type === "tool-result") {+ changed = true;+ flush();+ groups.push({ type: "tool", message, call: null, result: part });+ } else {+ parts.push(part);+ }+ position++;+ }+ if (changed) flush();+ else groups.push({ type: "message", message });+ }+ return groups;+}diff --git a/web/src/features/sessions/hooks/useSessionConversationTimelineController.clienttest.tsx b/web/src/features/sessions/hooks/useSessionConversationTimelineController.clienttest.tsxnew file mode 100644index 0000000000..824895588a--- /dev/null+++ b/web/src/features/sessions/hooks/useSessionConversationTimelineController.clienttest.tsx@@ -0,0 +1,467 @@+import { act, fireEvent, renderHook, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useSessionConversationTimelineController } from "./useSessionConversationTimelineController";+import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";+import { getScrollSpyAnchor } from "@/src/hooks/useVirtualizedScrollSpy";++const { feedRef, virtualizer } = vi.hoisted(() => ({+ feedRef: { current: null as HTMLDivElement | null },+ virtualizer: {+ scrollOffset: 0,+ getTotalSize: (): number => 10_000,+ getOffsetForIndex: (index: number) => [index * 100],+ get measurementsCache() {+ return Array.from({ length: 100 }, (_, index) => ({+ start: index * 100,+ }));+ },+ getVirtualItems: () => [+ { index: 0, start: 0, end: 100 },+ { index: 1, start: 100, end: 200 },+ { index: 2, start: 200, end: 10_000 },+ ],+ },+}));++vi.mock("@tanstack/react-virtual", () => ({+ useVirtualizer: () => virtualizer,+}));+vi.mock("@/src/hooks/useElementSize", () => ({+ useElementSize: () => [feedRef, { height: 500 }],+}));++const trace = {+ id: "trace",+ name: "Trace",+ timestamp: new Date(0),+ environment: "production",+ userId: null,+ observationCount: 1,+ latencyMs: 1000,+ scores: [],+} satisfies EventSessionTrace;++afterEach(() => {+ feedRef.current = null;+ virtualizer.scrollOffset = 0;+ vi.restoreAllMocks();+ vi.useRealTimers();+ vi.clearAllMocks();+});++function createMeasuredFeed() {+ const feed = document.createElement("div");+ feedRef.current = feed;+ Object.defineProperty(feed, "clientHeight", {+ value: 500,+ configurable: true,+ });+ feed.getBoundingClientRect = () => new DOMRect(0, 200, 100, 500);+ feed.scrollTo = vi.fn((options?: ScrollToOptions | number) => {+ if (typeof options !== "object") return;+ feed.scrollTop = options.top ?? 0;+ virtualizer.scrollOffset = feed.scrollTop;+ });+ return feed;+}++function appendMeasuredRow(+ feed: HTMLDivElement,+ itemId: string,+ rowId: string,+ top: number,+) {+ const entry = document.createElement("div");+ entry.dataset.sessionTraceId = trace.id;+ entry.dataset.sessionItemId = itemId;+ const row = document.createElement("div");+ row.dataset.sessionTranscriptRowId = rowId;+ row.getBoundingClientRect = () =>+ new DOMRect(0, 200 + top - feed.scrollTop, 100, 100);+ entry.append(row);+ feed.append(entry);+ return row;+}++describe("useSessionConversationTimelineController", () => {+ it.each([300, 500, 800])(+ "aligns with 20%% of the actual %spx scroll viewport rather than the bounding box or window",+ (height) => {+ const feed = createMeasuredFeed();+ Object.defineProperty(feed, "clientHeight", {+ value: height,+ configurable: true,+ });+ appendMeasuredRow(feed, "trace:0", "0:0", 700);+ const { result } = renderHook(() =>+ useSessionConversationTimelineController([+ { trace, itemId: "trace:0" },+ ]),+ );+ act(() => result.current.onSelect(0, undefined, "0:0"));+ expect(feed.scrollTop).toBe(700 - height * 0.2);+ },+ );++ it("corrects navigation and recomputes the scroll-spy anchor when the viewport resizes", async () => {+ const feed = createMeasuredFeed();+ appendMeasuredRow(feed, "trace:2", "2:0", 140);+ const { result, rerender } = renderHook(() =>+ useSessionConversationTimelineController([+ { trace, itemId: "trace:0" },+ { trace, itemId: "trace:2" },+ ]),+ );+ act(() => result.current.onSelect(1, undefined, "2:0"));+ expect(feed.scrollTop).toBe(40);+ Object.defineProperty(feed, "clientHeight", { value: 300 });+ rerender();+ await waitFor(() => expect(feed.scrollTop).toBe(80));+ await act(+ async () =>+ await new Promise((resolve) => window.setTimeout(resolve, 300)),+ );+ virtualizer.scrollOffset = 0;+ rerender();+ expect(result.current.activeItemId).toBe("trace:0");+ });++ it("bounds the fallback for a short entry before the earliest reachable anchor and releases it on resize", async () => {+ const feed = createMeasuredFeed();+ Object.defineProperty(feed, "clientHeight", {+ value: 800,+ configurable: true,+ });+ appendMeasuredRow(feed, "trace:0", "0:0", 0);+ const { result, rerender } = renderHook(() =>+ useSessionConversationTimelineController([+ { trace, itemId: "trace:0" },+ { trace, itemId: "trace:2" },+ ]),+ );+ act(() => result.current.onSelect(0));+ await act(+ async () =>+ await new Promise((resolve) => window.setTimeout(resolve, 300)),+ );+ expect(result.current.activeItemId).toBe("trace:0");+ Object.defineProperty(feed, "clientHeight", { value: 300 });+ feed.scrollTop = 100;+ virtualizer.scrollOffset = 100;+ rerender();+ expect(result.current.activeItemId).toBe("trace:2");+ });++ it.each(["wheel", "touchstart", "pointerdown", "keydown"])(+ "keeps fallback selection after %s until scrolling past the buffer",+ async (eventType) => {+ const feed = createMeasuredFeed();+ Object.defineProperty(feed, "clientHeight", { value: 800 });+ appendMeasuredRow(feed, "trace:0", "0:0", 0);+ const { result } = renderHook(() =>+ useSessionConversationTimelineController([+ { trace, itemId: "trace:0" },+ { trace, itemId: "trace:2" },+ ]),+ );+ act(() => result.current.onSelect(0));+ await act(+ async () =>+ await new Promise((resolve) => window.setTimeout(resolve, 300)),+ );+ fireEvent(+ feed,+ eventType === "keydown"+ ? new KeyboardEvent(eventType, { key: "ArrowDown" })+ : new Event(eventType),+ );+ expect(result.current.activeItemId).toBe("trace:0");+ feed.scrollTop = 80;+ fireEvent.scroll(feed);+ expect(result.current.activeItemId).toBe("trace:0");+ feed.scrollTop = 81;+ fireEvent.scroll(feed);+ expect(result.current.activeItemId).toBe("trace:2");+ },+ );++ it("uses content starts rather than clamped scroll offsets at the natural bottom", () => {+ const feed = createMeasuredFeed();+ appendMeasuredRow(feed, "trace:2", "2:0", 9_750);+ vi.spyOn(virtualizer, "getOffsetForIndex").mockReturnValue([9_500]);+ vi.spyOn(virtualizer, "measurementsCache", "get").mockReturnValue([+ { start: 0 },+ { start: 9_700 },+ { start: 10_000 },+ ]);+ const { result } = renderHook(() =>+ useSessionConversationTimelineController([+ { trace, itemId: "trace:0" },+ { trace, itemId: "trace:2" },+ ]),+ );+ act(() => result.current.onSelect(1));+ expect(+ getScrollSpyAnchor({+ scrollOffset: feed.scrollTop,+ viewportHeight: 500,+ totalSize: 10_000,+ endTransitionRatio: 0.2,+ viewportInset: 100,+ }),+ ).toBeCloseTo(9_700);+ });++ it("navigates to rows without an observation and releases selection to the scroll spy", async () => {+ const feed = createMeasuredFeed();+ appendMeasuredRow(feed, "trace:2", "2:0", 140);+ const { result, rerender } = renderHook(() =>+ useSessionConversationTimelineController([+ { trace, itemId: "trace:0" },+ { trace, itemId: "trace:2" },+ { trace, itemId: "trace:4" },+ ]),+ );+ act(() => result.current.onSelect(1, undefined, "2:0"));+ expect(result.current.activeItemId).toBe("trace:2");+ expect(feed.scrollTop).toBe(40);+ await act(+ async () =>+ await new Promise((resolve) => window.setTimeout(resolve, 300)),+ );+ virtualizer.scrollOffset = 200;+ rerender();+ expect(result.current.activeItemId).toBe("trace:4");+ });++ it("lets the latest click win when an earlier row mounts later", async () => {+ const feed = createMeasuredFeed();+ const { result } = renderHook(() =>+ useSessionConversationTimelineController([+ { trace, itemId: "trace:0" },+ { trace, itemId: "trace:2" },+ ]),+ );+ act(() => result.current.onSelect(0, "generation", "0:0"));+ appendMeasuredRow(feed, "trace:2", "2:0", 150);+ act(() => result.current.onSelect(1, undefined, "2:0"));+ appendMeasuredRow(feed, "trace:0", "0:0", 40);+ await waitFor(() => expect(feed.scrollTop).toBe(50));+ await act(+ async () =>+ await new Promise((resolve) => window.setTimeout(resolve, 180)),+ );+ expect(feed.scrollTop).toBe(50);+ expect(result.current.activeItemId).toBe("trace:2");+ });++ it("corrects a target when mounted content changes its measured position", async () => {+ const feed = createMeasuredFeed();+ const row = appendMeasuredRow(feed, "trace:2", "2:0", 120);+ const { result } = renderHook(() =>+ useSessionConversationTimelineController([+ { trace, itemId: "trace:0" },+ { trace, itemId: "trace:2" },+ ]),+ );+ act(() => result.current.onSelect(1, undefined, "2:0"));+ expect(feed.scrollTop).toBe(20);+ row.getBoundingClientRect = () =>+ new DOMRect(0, 200 + 170 - feed.scrollTop, 100, 100);+ await waitFor(() => expect(feed.scrollTop).toBe(70));+ });++ it("reconciles a loading placeholder that splits into threads", async () => {+ const feed = createMeasuredFeed();+ const { result, rerender } = renderHook(+ ({ loaded }) =>+ useSessionConversationTimelineController(+ loaded+ ? [+ { trace, itemId: "trace:0" },+ { trace, itemId: "trace:2" },+ ]+ : [{ trace }],+ ),+ { initialProps: { loaded: false } },+ );+ act(() => result.current.onSelect(0));+ appendMeasuredRow(feed, "trace:0", "0:0", 10);+ rerender({ loaded: true });+ await waitFor(() => expect(result.current.activeItemId).toBe("trace:0"));+ expect(feed.scrollTop).toBe(0);+ });++ it("aligns rows with the scroll-spy anchor in offset containers rather than centering", () => {+ const feed = document.createElement("div");+ feedRef.current = feed;+ Object.defineProperty(feed, "clientHeight", { value: 500 });+ feed.scrollTop = 100;+ feed.getBoundingClientRect = () => new DOMRect(0, 200, 100, 500);+ feed.scrollTo = vi.fn();+ const item = document.createElement("div");+ item.dataset.sessionTraceId = trace.id;+ const row = document.createElement("div");+ row.dataset.sessionObservationId = "generation";+ row.dataset.sessionTranscriptRowId = "0:1";+ row.getBoundingClientRect = () => new DOMRect(0, 450, 100, 100);+ item.append(row);+ feed.append(item);+ const { result } = renderHook(() =>+ useSessionConversationTimelineController([{ trace }]),+ );+ act(() => result.current.onSelect(0, "generation", "0:1"));+ expect(feed.scrollTo).toHaveBeenCalledWith({+ top: 250,+ behavior: "smooth",+ });+ });++ it.each(["wheel", "touchstart", "pointerdown", "keydown"])(+ "cancels delayed row navigation on %s intent",+ async (eventType) => {+ const feed = document.createElement("div");+ feedRef.current = feed;+ feed.scrollTo = vi.fn();+ const { result } = renderHook(() =>+ useSessionConversationTimelineController([{ trace }]),+ );+ act(() => result.current.onSelect(0, "generation", "0:1"));+ fireEvent(+ feed,+ eventType === "keydown"+ ? new KeyboardEvent("keydown", { key: "PageUp" })+ : new Event(eventType),+ );+ vi.mocked(feed.scrollTo).mockClear();+ const item = document.createElement("div");+ item.dataset.sessionTraceId = trace.id;+ const row = document.createElement("div");+ row.dataset.sessionObservationId = "generation";+ row.dataset.sessionTranscriptRowId = "0:1";+ item.append(row);+ feed.append(item);+ await act(async () => await Promise.resolve());+ expect(feed.scrollTo).not.toHaveBeenCalled();+ },+ );++ it("expires a missing row request without scrolling when it eventually mounts", async () => {+ vi.useFakeTimers();+ const feed = createMeasuredFeed();+ const { result } = renderHook(() =>+ useSessionConversationTimelineController([+ { trace, itemId: "trace:0" },+ { trace, itemId: "trace:2" },+ ]),+ );+ act(() => result.current.onSelect(1, undefined, "2:0"));+ await act(async () => await vi.advanceTimersByTimeAsync(5_001));+ vi.mocked(feed.scrollTo).mockClear();+ appendMeasuredRow(feed, "trace:2", "2:0", 150);+ await act(async () => await vi.advanceTimersByTimeAsync(100));+ expect(feed.scrollTo).not.toHaveBeenCalled();+ });++ it("retains only a fitting-list fallback and discards it when scrolling becomes possible", async () => {+ const feed = createMeasuredFeed();+ appendMeasuredRow(feed, "trace:4", "4:0", 200);+ const totalSize = vi+ .spyOn(virtualizer, "getTotalSize")+ .mockReturnValue(400);+ const { result, rerender } = renderHook(() =>+ useSessionConversationTimelineController([+ { trace, itemId: "trace:0" },+ { trace, itemId: "trace:2" },+ { trace, itemId: "trace:4" },+ ]),+ );+ act(() => result.current.onSelect(2));+ expect(result.current.activeItemId).toBe("trace:4");+ await act(+ async () =>+ await new Promise((resolve) => window.setTimeout(resolve, 300)),+ );+ expect(result.current.activeItemId).toBe("trace:4");+ totalSize.mockReturnValue(10_000);+ rerender();+ expect(result.current.activeItemId).toBe("trace:2");+ });++ it("selects the exact thread item when observations repeat", () => {+ const feed = document.createElement("div");+ Object.defineProperty(feed, "clientHeight", { value: 500 });+ feedRef.current = feed;+ feed.scrollTo = vi.fn();+ for (const [index, itemId] of ["trace:0", "trace:2"].entries()) {+ const item = document.createElement("div");+ item.dataset.sessionTraceId = trace.id;+ item.dataset.sessionItemId = itemId;+ const row = document.createElement("div");+ row.dataset.sessionObservationId = "generation";+ row.getBoundingClientRect = () => new DOMRect(0, index * 100, 100, 0);+ item.append(row);+ feed.append(item);+ }+ const { result } = renderHook(() =>+ useSessionConversationTimelineController([+ { trace, itemId: "trace:0" },+ { trace, itemId: "trace:2" },+ ]),+ );+ act(() => result.current.onSelect(1, "generation"));+ expect(result.current.activeItemId).toBe("trace:2");+ expect(feed.scrollTo).toHaveBeenCalledWith({+ top: 0,+ behavior: "smooth",+ });+ });+ it("scrolls to the exact row when multiple rows share an observation", () => {+ const feed = document.createElement("div");+ Object.defineProperty(feed, "clientHeight", { value: 500 });+ const traceElement = document.createElement("div");+ traceElement.dataset.sessionTraceId = trace.id;+ feed.append(traceElement);+ feedRef.current = feed;+ feed.scrollTo = vi.fn();+ for (const [index, rowId] of ["0:0", "0:1", "0:2"].entries()) {+ const row = document.createElement("div");+ row.dataset.sessionObservationId = "generation";+ row.dataset.sessionTranscriptRowId = rowId;+ row.getBoundingClientRect = () => new DOMRect(0, index * 100, 100, 0);+ traceElement.append(row);+ }++ const { result } = renderHook(() =>+ useSessionConversationTimelineController([{ trace }]),+ );+ act(() => result.current.onSelect(0, "generation", "0:2"));+ expect(result.current.activeItemId).toBe("trace");+ expect(feed.scrollTo).toHaveBeenCalledWith({+ top: 100,+ behavior: "smooth",+ });+ });++ it("waits for a virtualized row to mount before scrolling", async () => {+ const feed = document.createElement("div");+ feedRef.current = feed;+ feed.scrollTo = vi.fn();+ const { result } = renderHook(() =>+ useSessionConversationTimelineController([{ trace }]),+ );+ act(() => result.current.onSelect(0, "generation", "0:1"));+ expect(feed.scrollTo).toHaveBeenCalledWith({ top: 0, behavior: "smooth" });+ vi.mocked(feed.scrollTo).mockClear();++ const traceElement = document.createElement("div");+ traceElement.dataset.sessionTraceId = trace.id;+ const row = document.createElement("div");+ row.dataset.sessionObservationId = "generation";+ row.dataset.sessionTranscriptRowId = "0:1";+ row.getBoundingClientRect = () => new DOMRect(0, 200, 100, 0);+ traceElement.append(row);+ feed.append(traceElement);+ await waitFor(() => expect(feed.scrollTo).toHaveBeenCalledOnce());+ });+});diff --git a/web/src/features/sessions/hooks/useSessionConversationTimelineController.ts b/web/src/features/sessions/hooks/useSessionConversationTimelineController.tsnew file mode 100644index 0000000000..ae8d944494--- /dev/null+++ b/web/src/features/sessions/hooks/useSessionConversationTimelineController.ts@@ -0,0 +1,321 @@+import { useEffect, useLayoutEffect, useRef, useState } from "react";+import { useVirtualizer } from "@tanstack/react-virtual";++import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";+import { useElementSize } from "@/src/hooks/useElementSize";+import { STABLE_VIRTUAL_ROW_MEASUREMENT_CONFIG } from "@/src/features/sessions/stableVirtualRowMeasurementState";+import {+ getScrollOffsetForScrollSpyAnchor,+ getScrollSpyAnchor,+ useVirtualizedScrollSpy,+} from "@/src/hooks/useVirtualizedScrollSpy";++const SESSION_TIMELINE_OVERSCAN = 5;+const SESSION_TIMELINE_ANCHOR_RATIO = 0.2;+export type SessionConversationTimelineScrollTarget = {+ itemId?: string;+ traceId: string;+ observationId: string;+ rowId?: string;+ requestId: number;+};++export function useSessionConversationTimelineController(+ traces: readonly { trace: EventSessionTrace; itemId?: string }[],+ onVisibleTraceIdsChange?: (traceIds: string[]) => void,+) {+ const items = traces.map(({ trace, itemId }) => ({+ ...trace,+ id: itemId ?? trace.id,+ }));+ const [feedRef, feedSize] = useElementSize<HTMLDivElement>();+ const viewportHeight = feedSize+ ? (feedRef.current?.clientHeight ?? feedSize.height)+ : 0;+ const virtualizer = useVirtualizer({+ count: traces.length,+ getScrollElement: () => feedRef.current,+ estimateSize: () => 520,+ overscan: SESSION_TIMELINE_OVERSCAN,+ getItemKey: (index) =>+ traces[index]?.itemId ?? traces[index]?.trace.id ?? index,+ onChange: (instance) => {+ onVisibleTraceIdsChange?.([+ ...new Set(+ instance.getVirtualItems().flatMap((item) => {+ const traceId = traces[item.index]?.trace.id;+ return traceId ? [traceId] : [];+ }),+ ),+ ]);+ },+ });+ const { activeItemId, virtualItems } = useVirtualizedScrollSpy({+ items,+ virtualizer,+ scrollElementRef: feedRef,+ viewportHeight,+ endTransitionRatio: 0.2,+ viewportInset: viewportHeight * SESSION_TIMELINE_ANCHOR_RATIO,+ });+ const [selection, setSelection] = useState<{+ itemId: string;+ fallbackOffset?: number;+ } | null>(null);+ const navigationCleanupRef = useRef<(() => void) | null>(null);+ const latestTracesRef = useRef(traces);+ useLayoutEffect(() => {+ latestTracesRef.current = traces;+ }, [traces]);+ useEffect(() => () => navigationCleanupRef.current?.(), []);++ useEffect(() => {+ const feed = feedRef.current;+ const fallbackOffset = selection?.fallbackOffset;+ if (!feed || fallbackOffset === undefined) return;+ const clearFallback = () => {+ if (+ Math.abs(feed.scrollTop - fallbackOffset) >+ Math.min(96, feed.clientHeight * 0.1)+ ) {+ navigationCleanupRef.current?.();+ navigationCleanupRef.current = null;+ setSelection(null);+ }+ };+ feed.addEventListener("scroll", clearFallback, { passive: true });+ return () => feed.removeEventListener("scroll", clearFallback);+ }, [feedRef, selection]);++ const onSelect = (index: number, observationId?: string, rowId?: string) => {+ navigationCleanupRef.current?.();+ navigationCleanupRef.current = null;+ setSelection(null);+ const feed = feedRef.current;+ const traceId = traces[index]?.trace.id;+ const itemId = traces[index]?.itemId ?? traceId;+ if (!feed || !traceId) return;+ if (!itemId) return;+ setSelection({ itemId });++ let frame = 0;+ let timeout = 0;+ let previousTarget: number | undefined;+ let stableSince = performance.now();+ let previousScrollTop = feed.scrollTop;+ let stopped = false;+ const cleanup = () => {+ stopped = true;+ window.cancelAnimationFrame(frame);+ window.clearTimeout(timeout);+ feed.removeEventListener("wheel", cancel);+ feed.removeEventListener("touchstart", cancel);+ feed.removeEventListener("pointerdown", cancel);+ feed.removeEventListener("keydown", cancelOnKey);+ };+ const cancel = () => {+ cleanup();+ navigationCleanupRef.current = null;+ feed.scrollTo({ top: feed.scrollTop, behavior: "instant" });+ setSelection(null);+ };+ const cancelOnKey = (event: KeyboardEvent) => {+ if (+ [+ "ArrowUp",+ "ArrowDown",+ "PageUp",+ "PageDown",+ "Home",+ "End",+ " ",+ ].includes(event.key) &&+ !(+ event.target instanceof HTMLElement &&+ event.target.closest("input, textarea, [contenteditable=true]")+ )+ ) {+ cancel();+ }+ };+ feed.addEventListener("wheel", cancel, { passive: true });+ feed.addEventListener("touchstart", cancel, { passive: true });+ feed.addEventListener("pointerdown", cancel, { passive: true });+ feed.addEventListener("keydown", cancelOnKey);+ navigationCleanupRef.current = cleanup;++ const correctPosition = () => {+ if (stopped) return;+ const currentTraces = latestTracesRef.current;+ let currentIndex = currentTraces.findIndex(+ (item) => (item.itemId ?? item.trace.id) === itemId,+ );+ // A loading placeholder can split into independently virtualized threads.+ if (currentIndex === -1 && itemId === traceId) {+ currentIndex = currentTraces.findIndex(+ (item) => item.trace.id === traceId,+ );+ }+ if (currentIndex === -1) {+ cleanup();+ navigationCleanupRef.current = null;+ setSelection(null);+ return;+ }+ const currentItemId = currentTraces[currentIndex]!.itemId ?? traceId;+ const entry = Array.from(+ feed.querySelectorAll<HTMLElement>("[data-session-trace-id]"),+ ).find(+ (element) =>+ element.dataset.sessionTraceId === traceId &&+ (!element.dataset.sessionItemId ||+ element.dataset.sessionItemId === currentItemId),+ );+ const row =+ entry && (rowId || observationId)+ ? Array.from(+ entry.querySelectorAll<HTMLElement>(+ "[data-session-transcript-row-id], [data-session-observation-id]",+ ),+ ).find((element) =>+ rowId+ ? element.dataset.sessionTranscriptRowId === rowId+ : element.dataset.sessionObservationId === observationId,+ )+ : undefined;+ const mountedTarget = rowId || observationId ? row : entry;+ const measurements = virtualizer.measurementsCache;+ const itemOffset = measurements[currentIndex]?.start;+ if (itemOffset === undefined) {+ frame = window.requestAnimationFrame(correctPosition);+ return;+ }+ const anchor = row+ ? feed.scrollTop ++ row.getBoundingClientRect().top -+ feed.getBoundingClientRect().top -+ feed.clientTop+ : itemOffset;+ const viewportHeight = feed.clientHeight;+ const totalSize = virtualizer.getTotalSize();+ const top = getScrollOffsetForScrollSpyAnchor({+ anchor,+ viewportHeight,+ totalSize,+ endTransitionRatio: 0.2,+ viewportInset: viewportHeight * SESSION_TIMELINE_ANCHOR_RATIO,+ });+ if (previousTarget === undefined || Math.abs(previousTarget - top) > 1) {+ previousTarget = top;+ stableSince = performance.now();+ feed.scrollTo({ top, behavior: "smooth" });+ }+ if (+ virtualizer.isScrolling ||+ Math.abs(previousScrollTop - feed.scrollTop) > 0.5+ ) {+ previousScrollTop = feed.scrollTop;+ stableSince = performance.now();+ }+ if (+ mountedTarget &&+ Math.abs(feed.scrollTop - top) <= 1 &&+ performance.now() - stableSince >=+ STABLE_VIRTUAL_ROW_MEASUREMENT_CONFIG.scrollIdleMs + 50+ ) {+ const actualAnchor = getScrollSpyAnchor({+ scrollOffset: feed.scrollTop,+ viewportHeight,+ totalSize,+ endTransitionRatio: 0.2,+ viewportInset: viewportHeight * SESSION_TIMELINE_ANCHOR_RATIO,+ });+ const nextOffset = measurements[currentIndex + 1]?.start ?? totalSize;+ const minimumAnchor = getScrollSpyAnchor({+ scrollOffset: 0,+ viewportHeight,+ totalSize,+ endTransitionRatio: 0.2,+ viewportInset: viewportHeight * SESSION_TIMELINE_ANCHOR_RATIO,+ });+ const maximumAnchor = getScrollSpyAnchor({+ scrollOffset: Math.max(0, totalSize - viewportHeight),+ viewportHeight,+ totalSize,+ endTransitionRatio: 0.2,+ viewportInset: viewportHeight * SESSION_TIMELINE_ANCHOR_RATIO,+ });+ const canRepresentSelection =+ itemOffset <= maximumAnchor && nextOffset > minimumAnchor;+ if (canRepresentSelection && actualAnchor < itemOffset) {+ // Browser scroll positions can round just below an entry boundary.+ feed.scrollTo({+ top: Math.min(top + 1, Math.max(0, totalSize - viewportHeight)),+ behavior: "instant",+ });+ }+ cleanup();+ navigationCleanupRef.current = null;+ if (+ !canRepresentSelection &&+ (actualAnchor < itemOffset || actualAnchor >= nextOffset)+ ) {+ setSelection({+ itemId: currentItemId,+ fallbackOffset: feed.scrollTop,+ });+ } else {+ setSelection(null);+ }+ return;+ }+ frame = window.requestAnimationFrame(correctPosition);+ };+ timeout = window.setTimeout(cancel, 5_000);+ correctPosition();+ };++ const selectedItem = selection+ ? (traces.find(+ (item) => (item.itemId ?? item.trace.id) === selection.itemId,+ ) ?? traces.find((item) => item.trace.id === selection.itemId))+ : undefined;+ const selectedIndex = selectedItem ? traces.indexOf(selectedItem) : -1;+ const selectedStart = virtualizer.measurementsCache[selectedIndex]?.start;+ const totalSize = virtualizer.getTotalSize();+ const selectedEnd =+ virtualizer.measurementsCache[selectedIndex + 1]?.start ?? totalSize;+ const minimumAnchor = getScrollSpyAnchor({+ scrollOffset: 0,+ viewportHeight,+ totalSize,+ endTransitionRatio: 0.2,+ viewportInset: viewportHeight * SESSION_TIMELINE_ANCHOR_RATIO,+ });+ const maximumAnchor = getScrollSpyAnchor({+ scrollOffset: Math.max(0, totalSize - viewportHeight),+ viewportHeight,+ totalSize,+ endTransitionRatio: 0.2,+ viewportInset: viewportHeight * SESSION_TIMELINE_ANCHOR_RATIO,+ });+ const fallbackIsNeeded =+ selectedStart !== undefined &&+ (selectedStart > maximumAnchor || selectedEnd <= minimumAnchor);+ return {+ activeItemId:+ selection &&+ selectedItem &&+ (selection.fallbackOffset === undefined || fallbackIsNeeded)+ ? (selectedItem.itemId ?? selectedItem.trace.id)+ : (activeItemId ?? null),+ feedRef,+ onSelect,+ virtualItems,+ virtualizer,+ };+}++export type SessionConversationTimelineController = ReturnType<+ typeof useSessionConversationTimelineController+>;diff --git a/web/src/features/sessions/hooks/useSessionTraceTranscripts.clienttest.tsx b/web/src/features/sessions/hooks/useSessionTraceTranscripts.clienttest.tsxnew file mode 100644index 0000000000..e78477f76d--- /dev/null+++ b/web/src/features/sessions/hooks/useSessionTraceTranscripts.clienttest.tsx@@ -0,0 +1,113 @@+import { act, renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { type ReactNode } from "react";+import { type AppRouter } from "@/src/server/api/root";+import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";+import { useSessionTraceTranscripts } from "./useSessionTraceTranscripts";++const { query } = vi.hoisted(() => ({ query: vi.fn() }));++vi.mock("@/src/utils/api", async () => {+ const { createTRPCReact } = await import("@trpc/react-query");+ const trpc = createTRPCReact<AppRouter>();+ return {+ api: {+ events: trpc.events,+ useUtils: () => ({+ client: { events: { transcriptByTraceId: { query } } },+ }),+ },+ };+});++const traces = Array.from({ length: 7 }, (_, index) => ({+ trace: {+ id: `trace-${index}`,+ name: "Test trace",+ timestamp: new Date("2026-01-01T00:00:00Z"),+ environment: "test",+ userId: null,+ observationCount: 1,+ latencyMs: 100,+ scores: [],+ } satisfies EventSessionTrace,+ turnNumber: index + 1,+}));+const output = { transcript: null, cutoff: false };++function setup(client = new QueryClient()) {+ return {+ client,+ ...renderHook(+ () =>+ useSessionTraceTranscripts({+ projectId: "project",+ traces,+ activeTraceIds: new Set(+ traces.slice(0, 6).map(({ trace }) => trace.id),+ ),+ }),+ {+ wrapper: ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ ),+ },+ ),+ };+}++beforeEach(() => {+ query.mockReset();+});++it("bounds concurrent requests and releases slots after success and failure", async () => {+ const pending: Array<{+ resolve: (value: typeof output) => void;+ reject: (reason: Error) => void;+ }> = [];+ query.mockImplementation(+ () =>+ new Promise((resolve, reject) => {+ pending.push({ resolve, reject });+ }),+ );+ const { result, unmount, client } = setup();+ await waitFor(() => expect(query).toHaveBeenCalledTimes(4));+ expect(+ query.mock.calls.every(([input]) => input.pairTextToolResponses === true),+ ).toBe(true);+ expect(result.current.get("trace-4")).toEqual({ state: "loading" });+ expect(result.current.has("trace-6")).toBe(false);++ await act(async () => pending[0]!.resolve(output));+ await waitFor(() => expect(query).toHaveBeenCalledTimes(5));+ await act(async () => pending[1]!.reject(new Error("Request failed")));+ await waitFor(() => expect(query).toHaveBeenCalledTimes(6));+ await waitFor(() =>+ expect(result.current.get("trace-1")).toEqual({ state: "error" }),+ );+ expect(result.current.get("trace-0")).toEqual({ state: "loaded", ...output });+ expect(query.mock.calls.some(([input]) => input.traceId === "trace-6")).toBe(+ false,+ );+ unmount();+ client.clear();+});++it("aborts active requests and does not start queued requests after unmount", async () => {+ const signals: AbortSignal[] = [];+ query.mockImplementation((_input, { signal }: { signal: AbortSignal }) => {+ signals.push(signal);+ return new Promise((_resolve, reject) => {+ signal.addEventListener("abort", () => reject(signal.reason), {+ once: true,+ });+ });+ });+ const { unmount, client } = setup();+ await waitFor(() => expect(query).toHaveBeenCalledTimes(4));+ await act(async () => unmount());+ expect(signals.every((signal) => signal.aborted)).toBe(true);+ expect(query).toHaveBeenCalledTimes(4);+ client.clear();+});diff --git a/web/src/features/sessions/hooks/useSessionTraceTranscripts.ts b/web/src/features/sessions/hooks/useSessionTraceTranscripts.tsnew file mode 100644index 0000000000..5f67026042--- /dev/null+++ b/web/src/features/sessions/hooks/useSessionTraceTranscripts.ts@@ -0,0 +1,63 @@+import { useState } from "react";+import { useQueries } from "@tanstack/react-query";+import { getQueryKey } from "@trpc/react-query";+import PQueue from "p-queue";+import { api, type RouterOutputs } from "@/src/utils/api";+import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";++export type SessionTraceTranscriptState =+ | { state: "loading" }+ | { state: "error" }+ | ({ state: "loaded" } & RouterOutputs["events"]["transcriptByTraceId"]);++export function useSessionTraceTranscripts({+ projectId,+ traces,+ activeTraceIds,+}: {+ projectId: string;+ traces: readonly { trace: EventSessionTrace; turnNumber: number }[];+ activeTraceIds: ReadonlySet<string>;+}): Map<string, SessionTraceTranscriptState> {+ const [queue] = useState(() => new PQueue({ concurrency: 4 }));+ const utils = api.useUtils();+ const activeTraces = traces.filter(({ trace }) =>+ activeTraceIds.has(trace.id),+ );+ const results = useQueries({+ queries: activeTraces.map(({ trace }) => {+ const input = {+ projectId,+ traceId: trace.id,+ timestamp: trace.timestamp,+ pairTextToolResponses: true,+ };+ return {+ queryKey: getQueryKey(api.events.transcriptByTraceId, input, "query"),+ queryFn: ({ signal }: { signal: AbortSignal }) =>+ queue.add(+ () =>+ utils.client.events.transcriptByTraceId.query(input, { signal }),+ { signal },+ ),+ staleTime: 5 * 60 * 1_000,+ refetchOnWindowFocus: false,+ retry: false,+ meta: { silentAllErrors: true },+ };+ }),+ });++ return new Map(+ activeTraces.map(({ trace }, index) => {+ const result = results[index];+ let state: SessionTraceTranscriptState = { state: "loading" };+ if (result?.data) {+ state = { state: "loaded", ...result.data };+ } else if (result?.isError) {+ state = { state: "error" };+ }+ return [trace.id, state];+ }),+ );+}diff --git a/web/src/hooks/useVirtualizedScrollSpy.clienttest.ts b/web/src/hooks/useVirtualizedScrollSpy.clienttest.tsindex 758b52b7da..e7c3f9d0ce 100644--- a/web/src/hooks/useVirtualizedScrollSpy.clienttest.ts+++ b/web/src/hooks/useVirtualizedScrollSpy.clienttest.ts@@ -2,7 +2,11 @@ import { act, fireEvent, renderHook } from "@testing-library/react";import { type Virtualizer } from "@tanstack/react-virtual";import { describe, expect, it, vi } from "vitest";-import { useVirtualizedScrollSpy } from "@/src/hooks/useVirtualizedScrollSpy";+import {+ getScrollOffsetForScrollSpyAnchor,+ getScrollSpyAnchor,+ useVirtualizedScrollSpy,+} from "@/src/hooks/useVirtualizedScrollSpy";const items = Array.from({ length: 100 }, (_, index) => ({id: String(index),@@ -16,7 +20,7 @@ const virtualItems = items.map((_, index) => ({lane: 0,}));-function renderScrollSpy(scrollOffset: number) {+function renderScrollSpy(scrollOffset: number, viewportInset = 0) {const scrollElement = document.createElement("div");scrollElement.scrollTo = vi.fn();const virtualizer = {@@ -33,6 +37,7 @@ function renderScrollSpy(scrollOffset: number) {scrollElementRef: { current: scrollElement },viewportHeight: 1_000,endTransitionRatio: 0.2,+ viewportInset,}),);@@ -65,6 +70,78 @@ function renderFittingScrollSpy() {}describe("useVirtualizedScrollSpy", () => {+ it("crosses item boundaries at the inset during manual scrolling in both directions", () => {+ for (const offset of [99, 100, 101, 100, 99]) {+ expect(renderScrollSpy(offset, 200).result.current.activeItemId).toBe(+ offset < 100 ? "2" : "3",+ );+ }+ expect(renderScrollSpy(9_000, 200).result.current.activeItemId).toBe("99");+ });++ it("clamps the inset and scroll target in a fitting viewport", () => {+ const geometry = {+ viewportHeight: 8,+ totalSize: 4,+ endTransitionRatio: 0.2,+ viewportInset: 8 * 0.2,+ };+ expect(getScrollSpyAnchor({ scrollOffset: 0, ...geometry })).toBe(1.6);+ expect(getScrollOffsetForScrollSpyAnchor({ anchor: 0, ...geometry })).toBe(+ 0,+ );+ });++ it.each([300, 500, 800])(+ "round-trips inset anchors at %spx across the end transition",+ (viewportHeight) => {+ const geometry = {+ viewportHeight,+ totalSize: 10_000,+ endTransitionRatio: 0.2,+ viewportInset: viewportHeight * 0.2,+ };+ for (const anchor of [viewportHeight * 0.2, 350, 9_416, 9_700, 9_999]) {+ const scrollOffset = getScrollOffsetForScrollSpyAnchor({+ anchor,+ ...geometry,+ });+ expect(getScrollSpyAnchor({ scrollOffset, ...geometry })).toBeCloseTo(+ anchor,+ );+ }+ },+ );++ it.each([0, 100, 8_800, 8_900, 9_000, 9_999])(+ "aligns content coordinate %s with the manual scroll-spy anchor",+ (anchor) => {+ const geometry = {+ viewportHeight: 1_000,+ totalSize: 10_000,+ endTransitionRatio: 0.2,+ };+ const scrollOffset = getScrollOffsetForScrollSpyAnchor({+ anchor,+ ...geometry,+ });+ expect(getScrollSpyAnchor({ scrollOffset, ...geometry })).toBeCloseTo(+ anchor,+ );+ },+ );++ it("clamps an impossible anchor in a fitting list", () => {+ expect(+ getScrollOffsetForScrollSpyAnchor({+ anchor: 400,+ viewportHeight: 1_000,+ totalSize: 500,+ endTransitionRatio: 0.2,+ }),+ ).toBe(0);+ });+it("tracks the item at the sticky top edge until the end transition", () => {expect(renderScrollSpy(0).result.current.activeItemId).toBe("0");expect(renderScrollSpy(100).result.current.activeItemId).toBe("1");diff --git a/web/src/hooks/useVirtualizedScrollSpy.ts b/web/src/hooks/useVirtualizedScrollSpy.tsindex fa539878db..a903bcc3d5 100644--- a/web/src/hooks/useVirtualizedScrollSpy.ts+++ b/web/src/hooks/useVirtualizedScrollSpy.ts@@ -6,9 +6,8 @@ import { type Virtualizer } from "@tanstack/react-virtual";** The anchor moves through two phases as the user scrolls:*- * 1. Through the normal scroll range, it stays at the viewport's top edge so- * the active item matches a sticky item header.- * 2. Near the end, it moves from the top to the viewport's bottom edge. This+ * 1. Through the normal scroll range, it stays at the configured viewport inset.+ * 2. Near the end, it moves from that inset to the viewport's bottom edge. This* allows the final items to become active without adding empty padding after* the content.*@@ -16,19 +15,25 @@ import { type Virtualizer } from "@tanstack/react-virtual";* viewport. It can therefore be compared directly with TanStack Virtual's* `VirtualItem.start` and `VirtualItem.end` values.*/-function getScrollSpyAnchor({+export function getScrollSpyAnchor({scrollOffset,viewportHeight,totalSize,endTransitionRatio,+ viewportInset = 0,}: {scrollOffset: number;viewportHeight: number;totalSize: number;endTransitionRatio: number;+ viewportInset?: number;}) {const maxScrollOffset = Math.max(0, totalSize - viewportHeight);- if (viewportHeight <= 0 || maxScrollOffset === 0) return scrollOffset;+ const inset = Math.max(+ 0,+ Math.min(viewportInset, viewportHeight - 1, totalSize - 1),+ );+ if (viewportHeight <= 0 || maxScrollOffset === 0) return scrollOffset + inset;const clampedScrollOffset = Math.max(0,@@ -43,21 +48,55 @@ function getScrollSpyAnchor({viewportHeight * clampedEndTransitionRatio,maxScrollOffset,);- if (transitionDistance === 0) return clampedScrollOffset;+ if (transitionDistance === 0) return clampedScrollOffset + inset;const distanceToBottom = maxScrollOffset - clampedScrollOffset;if (distanceToBottom >= transitionDistance) {- return clampedScrollOffset;+ return clampedScrollOffset + inset;}const endProgress = 1 - distanceToBottom / transitionDistance;// Stop one pixel before the viewport boundary. The item range comparison is// end-exclusive, so using viewportHeight exactly could produce totalSize and// leave no item containing the anchor at the natural scroll bottom.- const anchorOffset = viewportBottomOffset * endProgress;+ const anchorOffset = inset + (viewportBottomOffset - inset) * endProgress;return clampedScrollOffset + anchorOffset;}+/** Inverts the scroll-spy anchor, including its transition at the natural bottom. */+export function getScrollOffsetForScrollSpyAnchor({+ anchor,+ viewportHeight,+ totalSize,+ endTransitionRatio,+ viewportInset = 0,+}: {+ anchor: number;+ viewportHeight: number;+ totalSize: number;+ endTransitionRatio: number;+ viewportInset?: number;+}) {+ const maxScrollOffset = Math.max(0, totalSize - viewportHeight);+ const inset = Math.max(+ 0,+ Math.min(viewportInset, viewportHeight - 1, totalSize - 1),+ );+ const transitionDistance = Math.min(+ viewportHeight * Math.max(0, Math.min(endTransitionRatio, 1)),+ maxScrollOffset,+ );+ const transitionStart = maxScrollOffset - transitionDistance;+ if (anchor <= transitionStart + inset || transitionDistance === 0) {+ return Math.max(0, Math.min(anchor - inset, maxScrollOffset));+ }+ const offset =+ transitionStart ++ (anchor - transitionStart - inset) /+ (1 + Math.max(0, viewportHeight - 1 - inset) / transitionDistance);+ return Math.max(0, Math.min(offset, maxScrollOffset));+}+/*** Coordinates scroll-spy state for a TanStack Virtual list.*@@ -84,12 +123,14 @@ export function useVirtualizedScrollSpy<scrollElementRef,viewportHeight,endTransitionRatio,+ viewportInset = 0,}: {items: TItem[];virtualizer: Virtualizer<TScrollElement, TItemElement>;scrollElementRef: RefObject<TScrollElement | null>;viewportHeight: number;endTransitionRatio: number;+ viewportInset?: number;}) {const [selectedFallback, setSelectedFallback] = useState<{itemId: string;@@ -103,6 +144,7 @@ export function useVirtualizedScrollSpy<viewportHeight,totalSize: virtualizer.getTotalSize(),endTransitionRatio,+ viewportInset,});const activeVirtualItem =virtualItems.find(@@ -143,15 +185,22 @@ export function useVirtualizedScrollSpy<if (!item || !scrollElement || offset === undefined) return;const totalSize = virtualizer.getTotalSize();- const scrollTarget = Math.min(- offset,- Math.max(0, totalSize - viewportHeight),- );+ const scrollTarget =+ viewportInset === 0+ ? Math.min(offset, Math.max(0, totalSize - viewportHeight))+ : getScrollOffsetForScrollSpyAnchor({+ anchor: offset,+ viewportHeight,+ totalSize,+ endTransitionRatio,+ viewportInset,+ });const targetAnchor = getScrollSpyAnchor({scrollOffset: scrollTarget,viewportHeight,totalSize,endTransitionRatio,+ viewportInset,});const nextItemOffset =virtualizer.getOffsetForIndex(index + 1, "start")?.[0] ?? totalSize;@@ -168,7 +217,14 @@ export function useVirtualizedScrollSpy<// dynamically measured rows stopping one row before the target.scrollElement.scrollTo({ top: scrollTarget, behavior: "smooth" });},- [endTransitionRatio, items, scrollElementRef, viewportHeight, virtualizer],+ [+ endTransitionRatio,+ items,+ scrollElementRef,+ viewportHeight,+ viewportInset,+ virtualizer,+ ],);return {