🪢 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
fix(sessions): Internal session customization dialog (#18477)
Ben Bachem6e53df7927b6
diff --git a/packages/shared/src/features/filters/sessionTraceFilters.ts b/packages/shared/src/features/filters/sessionTraceFilters.tsnew file mode 100644index 0000000000..7d197f10be--- /dev/null+++ b/packages/shared/src/features/filters/sessionTraceFilters.ts@@ -0,0 +1,94 @@+import { z } from "zod";+import {+ singleFilterList,+ stringFilter,+ stringOptionsFilter,+ arrayOptionsFilter,+ stringObjectFilter,+ booleanFilter,+} from "../../interfaces/filters";+import { type ColumnDefinition } from "../../tableDefinitions/types";++export const sessionTraceFilterColumns: ColumnDefinition[] = [+ {+ id: "isRootObservation",+ name: "Root observation",+ type: "boolean",+ internal: "is_root_observation",+ },+ { id: "traceName", name: "Trace name", type: "string", internal: "name" },+ { id: "userId", name: "User ID", type: "string", internal: "user_id" },+ {+ id: "environment",+ name: "Environment",+ type: "string",+ internal: "environment",+ },+ {+ id: "traceTags",+ name: "Trace tags",+ type: "arrayOptions",+ internal: "tags",+ options: [],+ },+ {+ id: "name",+ name: "Observation name",+ type: "string",+ internal: "name",+ },+ {+ id: "type",+ name: "Observation type",+ type: "string",+ internal: "type",+ },+ {+ id: "level",+ name: "Observation level",+ type: "string",+ internal: "level",+ },+ {+ id: "metadata",+ name: "Observation metadata",+ type: "stringObject",+ internal: "metadata",+ },+];++// Saved views and shared URLs created before observation filtering used root fields.+const legacyObservationColumns: Record<string, string> = {+ rootName: "name",+ rootType: "type",+ rootLevel: "level",+ rootMetadata: "metadata",+};++export const sessionTraceFilterSchema = singleFilterList+ .transform((filters) =>+ filters.map((filter) => ({+ ...filter,+ column: legacyObservationColumns[filter.column] ?? filter.column,+ })),+ )+ .pipe(+ z.array(+ z.discriminatedUnion("type", [+ booleanFilter.extend({ column: z.literal("isRootObservation") }),+ stringOptionsFilter.extend({ column: z.enum(["name", "traceName"]) }),+ stringFilter.extend({+ column: z.enum([+ "traceName",+ "userId",+ "environment",+ "name",+ "type",+ "level",+ ]),+ }),+ arrayOptionsFilter.safeExtend({ column: z.literal("traceTags") }),+ stringObjectFilter.extend({ column: z.literal("metadata") }),+ ]),+ ),+ );diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex af9cf2033e..45d7d6118d 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -98,6 +98,7 @@ export * from "./features/rbac/projectAccessRights";export * from "./features/filters/internalEnvironments";export * from "./features/filters/filterQueryEncoding";export * from "./features/filters/sessionPositionInTrace";+export * from "./features/filters/sessionTraceFilters";// date rangesexport * from "./utils/dateRanges";diff --git a/packages/shared/src/server/repositories/events-field-sets.ts b/packages/shared/src/server/repositories/events-field-sets.tsindex 141445c95d..75a34d9fda 100644--- a/packages/shared/src/server/repositories/events-field-sets.ts+++ b/packages/shared/src/server/repositories/events-field-sets.ts@@ -108,6 +108,7 @@ export const FIELD_SETS = {"statusMessage","version","parentObservationId",+ "isRootObservation","createdAt","updatedAt","providedModelName",@@ -148,6 +149,7 @@ export const FIELD_SETS = {"statusMessage","version","parentObservationId",+ "isRootObservation","createdAt","updatedAt","providedModelName",diff --git a/packages/shared/src/server/repositories/events.test.ts b/packages/shared/src/server/repositories/events.test.tsindex a018033047..324c0f4344 100644--- a/packages/shared/src/server/repositories/events.test.ts+++ b/packages/shared/src/server/repositories/events.test.ts@@ -42,6 +42,7 @@ vi.mock("./clickhouse", async () => {});import {+ getObservationsForTraceFromEventsTable,getObservationsV2FromEventsTableForPublicApi,getObservationsV2PageFromEventsTableForPublicApi,} from "./events";@@ -105,6 +106,50 @@ const mockProgressError = (error: Error) => {});};+describe("getObservationsForTraceFromEventsTable root flag", () => {+ beforeEach(() => {+ charCounter = 0;+ vi.clearAllMocks();+ mockQueryClickhouse.mockResolvedValue([]);+ });++ it.each([+ { selectMetadata: true, selectIOAndMetadata: false },+ { selectMetadata: false, selectIOAndMetadata: true },+ { selectMetadata: true, selectIOAndMetadata: true },+ { selectMetadata: false, selectIOAndMetadata: false },+ ])("selects metadata independently of I/O: %j", async (selection) => {+ await getObservationsForTraceFromEventsTable({+ projectId: "proj-1",+ traceId: "trace-1",+ ...selection,+ });++ const query = captureQuery();+ expect(query.includes("e.metadata")).toBe(+ selection.selectMetadata || selection.selectIOAndMetadata,+ );+ expect(/\binput\b/.test(query)).toBe(selection.selectIOAndMetadata);+ expect(/\boutput\b/.test(query)).toBe(selection.selectIOAndMetadata);+ });++ it.each([false, true])(+ "selects natural and application roots with tool data=%s",+ async (selectToolData) => {+ await getObservationsForTraceFromEventsTable({+ projectId: "proj-1",+ traceId: "trace-1",+ selectToolData,+ });++ const query = captureQuery();+ expect(query).toContain(+ "toBool((e.parent_span_id = '' or e.is_app_root = true)) as \"is_root_observation\"",+ );+ },+ );+});+describe("getObservationsV2FromEventsTableForPublicApi query shape", () => {beforeEach(() => {charCounter = 0;diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex 78b5b2a916..22bbb8d35d 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -534,9 +534,11 @@ export const getObservationsForTraceFromEventsTable = async (params: {traceId: string;timestamp?: Date;selectIOAndMetadata?: boolean;+ selectMetadata?: boolean;selectToolData?: boolean;/** Restrict to these observation types. All types when omitted. */types?: ObservationType[];+ filter?: FilterState;/** Rows read at most; `totalCount` exceeds it when the trace has more. */limit?: number;}): Promise<{ observations: FullEventsObservations; totalCount: number }> => {@@ -545,12 +547,14 @@ export const getObservationsForTraceFromEventsTable = async (params: {traceId,timestamp,selectIOAndMetadata = false,+ selectMetadata = false,selectToolData = false,types,limit = MAX_OBSERVATIONS_PER_TRACE,} = params;const filter: FilterState = [+ ...(params.filter ?? []),{column: "traceId",operator: "=" as const,@@ -587,6 +591,7 @@ export const getObservationsForTraceFromEventsTable = async (params: {offset: 0,select: "rows",selectIOAndMetadata,+ selectMetadata,selectToolData,});@@ -872,6 +877,7 @@ export const getTraceDeleteCursorPageFromEvents = async (props: {async function getObservationsFromEventsTableInternal<T>(opts: ObservationTableQuery & {+ selectMetadata?: boolean;select:| "count"| "count-with-unique-traces"@@ -885,6 +891,7 @@ async function getObservationsFromEventsTableInternal<T>(projectId,filter,selectIOAndMetadata,+ selectMetadata,selectToolData = true,renderingProps = DEFAULT_RENDERING_PROPS,limit,@@ -932,21 +939,20 @@ async function getObservationsFromEventsTableInternal<T>();if (selectIOAndMetadata) {if (opts.ioSizeCap) {- queryBuilder- .selectIOWithSizeCap(- opts.ioSizeCap.inlineChars,- opts.ioSizeCap.previewChars,- )- .selectFieldSet("metadata");+ queryBuilder.selectIOWithSizeCap(+ opts.ioSizeCap.inlineChars,+ opts.ioSizeCap.previewChars,+ );} else {- queryBuilder- .selectIO(- renderingProps.truncated,- env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT,- )- .selectFieldSet("metadata");+ queryBuilder.selectIO(+ renderingProps.truncated,+ env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT,+ );}}+ if (selectIOAndMetadata || selectMetadata) {+ queryBuilder.selectFieldSet("metadata");+ }}const isTraceDeleteCursorSelect = opts.select === "trace-delete-cursor";diff --git a/packages/shared/src/server/services/sessions-ui-table-events-service.golden.test.ts b/packages/shared/src/server/services/sessions-ui-table-events-service.golden.test.tsindex 1d12ca7ef0..7b19bedb63 100644--- a/packages/shared/src/server/services/sessions-ui-table-events-service.golden.test.ts+++ b/packages/shared/src/server/services/sessions-ui-table-events-service.golden.test.ts@@ -37,6 +37,7 @@ describeWithClickhouse("golden: sessions simple aggregates family", () => {await getSessionTracesFromEvents({projectId: "golden-project",sessionId: "golden-session",+ filter: [],});expect(normalizeCapturedQueries(capturedQueries)).toMatchSnapshot();});diff --git a/packages/shared/src/server/services/sessions-ui-table-events-service.test.ts b/packages/shared/src/server/services/sessions-ui-table-events-service.test.tsnew file mode 100644index 0000000000..5f8f37f777--- /dev/null+++ b/packages/shared/src/server/services/sessions-ui-table-events-service.test.ts@@ -0,0 +1,240 @@+import { assert, beforeEach, describe, expect, it, vi } from "vitest";+import { type FilterState } from "../../types";++const mocks = vi.hoisted(() => ({ query: vi.fn(), random: vi.fn() }));+vi.mock("../../env", () => ({ env: {} }));+vi.mock("../logger", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },+}));+vi.mock("../instrumentation", () => ({}));+vi.mock("../repositories/clickhouse", () => ({+ OBSERVATIONS_TO_TRACE_INTERVAL: "INTERVAL 2 DAY",+ SCORE_TO_TRACE_OBSERVATIONS_INTERVAL: "INTERVAL 1 HOUR",+ clickhouseCompliantRandomCharacters: mocks.random,+ queryClickhouse: mocks.query,+ reduceUsageOrCostDetails: (details: Record<string, number>) => details,+}));++import { getSessionTracesFromEvents } from "./sessions-ui-table-events-service";+import { sessionTraceFilterSchema } from "../../features/filters/sessionTraceFilters";++const capturedQuery = () => {+ const request = mocks.query.mock.calls[0][0] as {+ query: string;+ params: Record<string, unknown>;+ };+ return { ...request, query: request.query.replace(/\s+/g, " ") };+};++describe("session trace filtering", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ let counter = 0;+ mocks.random.mockImplementation(() => `x${++counter}`);+ mocks.query.mockResolvedValue([]);+ });++ it("keeps session membership and chronological order without filters", async () => {+ await getSessionTracesFromEvents({+ projectId: "project",+ sessionId: "session",+ filter: [],+ });+ const { query, params } = capturedQuery();+ const sessionParam = /e\.session_id = \{(\w+):\s*String\}/.exec(query)?.[1];+ const projectParam = /e\.project_id = \{(\w+):\s*String\}/.exec(query)?.[1];+ assert(sessionParam);+ assert(projectParam);+ expect(params[sessionParam]).toBe("session");+ expect(params[projectParam]).toBe("project");+ expect(query).toMatch(/order by (?:t\.)?timestamp asc/i);+ expect(query).not.toContain("t.id IN (");+ });++ it("filters aggregated trace attributes, not individual transcript observations", async () => {+ await getSessionTracesFromEvents({+ projectId: "project",+ sessionId: "session",+ filter: [+ {+ column: "traceName",+ type: "string",+ operator: "=",+ value: "conversation",+ },+ {+ column: "traceTags",+ type: "arrayOptions",+ operator: "none of",+ value: ["internal"],+ },+ ],+ });+ const { query, params } = capturedQuery();+ expect(query).toMatch(/SELECT t\.\* FROM session_traces t WHERE 1 = 1 AND/);+ expect(query).toContain("t.name");+ expect(query).toContain("t.tags");+ expect(Object.values(params)).toContain("conversation");+ expect(Object.values(params)).toContainEqual(["internal"]);+ expect(query).not.toContain("AND t.id IN (");+ });++ it("matches all observation predicates on the same observation, including children, within the authorized session", async () => {+ const filter: FilterState = [+ { column: "name", type: "string", operator: "=", value: "agent" },+ { column: "level", type: "string", operator: "=", value: "ERROR" },+ ];+ await getSessionTracesFromEvents({+ projectId: "project",+ sessionId: "session",+ filter,+ });+ const { query, params } = capturedQuery();+ expect(query).toContain("AND t.id IN (");+ const observationQuery = query.slice(query.indexOf("AND t.id IN ("));+ expect(observationQuery).not.toContain("e.is_app_root = true");+ expect(observationQuery).not.toContain("e.parent_span_id = ''");+ expect(observationQuery).not.toContain("FROM session_traces");+ expect(observationQuery).toMatch(+ /e\.trace_id IN \(select e\.trace_id from/i,+ );+ const sessionParam = /e\.session_id = \{(\w+):\s*String\}/.exec(+ observationQuery,+ )?.[1];+ assert(sessionParam);+ expect(params[sessionParam]).toBe("session");+ expect(observationQuery).not.toMatch(/group by/i);+ expect(query).toContain("e.is_deleted = 0");+ expect(query).toContain("e.name");+ expect(query).toContain("e.level");+ expect(Object.values(params)).toContain("agent");+ expect(Object.values(params)).toContain("ERROR");+ });++ it("filters root observations within the session", async () => {+ await getSessionTracesFromEvents({+ projectId: "project",+ sessionId: "session",+ filter: [+ {+ column: "isRootObservation",+ type: "boolean",+ operator: "=",+ value: true,+ },+ ],+ });+ const { query } = capturedQuery();+ expect(query).toContain("AND t.id IN (");+ expect(query).toMatch(/e\.trace_id IN \(select e\.trace_id from/i);+ expect(query).toContain("e.is_app_root");+ });++ it("applies trace names separately from observation matching when hiding empty traces", async () => {+ await getSessionTracesFromEvents({+ projectId: "project",+ sessionId: "session",+ filter: [+ {+ column: "traceName",+ type: "string",+ operator: "=",+ value: "conversation",+ },+ { column: "name", type: "string", operator: "=", value: "agent" },+ ],+ });++ const { query, params } = capturedQuery();+ expect(query).toContain("t.name");+ expect(query).toContain("AND t.id IN (");+ const observationQuery = query.slice(query.indexOf("AND t.id IN ("));+ expect(observationQuery).toContain("e.name");+ expect(observationQuery).not.toContain("t.name");+ expect(Object.values(params)).toContain("conversation");+ expect(Object.values(params)).toContain("agent");+ });++ it("uses full metadata rather than truncated observation metadata", async () => {+ await getSessionTracesFromEvents({+ projectId: "project",+ sessionId: "session",+ filter: [+ {+ column: "metadata",+ type: "stringObject",+ key: "kind",+ operator: "=",+ value: "customer",+ },+ ],+ });+ const { query } = capturedQuery();+ expect(query).toContain("FROM events_full");+ expect(query).toContain("e.metadata_values");+ });++ it.each([+ {+ filter: [+ {+ column: "unsupported",+ type: "string",+ operator: "=",+ value: "child",+ },+ ],+ },+ {+ filter: [+ {+ column: "positionInTrace",+ type: "positionInTrace",+ operator: "=",+ key: "root",+ },+ ],+ },+ {+ filter: [{ column: "rootName", type: "number", operator: "=", value: 1 }],+ },+ ])(+ "rejects unsupported filters instead of silently ignoring them",+ ({ filter }) => {+ expect(sessionTraceFilterSchema.safeParse(filter).success).toBe(false);+ },+ );++ it("normalizes saved root filters to observation filters", () => {+ expect(+ sessionTraceFilterSchema.parse([+ { column: "rootName", type: "string", operator: "=", value: "agent" },+ {+ column: "rootType",+ type: "string",+ operator: "=",+ value: "GENERATION",+ },+ { column: "rootLevel", type: "string", operator: "=", value: "ERROR" },+ {+ column: "rootMetadata",+ type: "stringObject",+ key: "region",+ operator: "=",+ value: "eu",+ },+ ]),+ ).toEqual([+ { column: "name", type: "string", operator: "=", value: "agent" },+ { column: "type", type: "string", operator: "=", value: "GENERATION" },+ { column: "level", type: "string", operator: "=", value: "ERROR" },+ {+ column: "metadata",+ type: "stringObject",+ key: "region",+ operator: "=",+ value: "eu",+ },+ ]);+ });+});diff --git a/packages/shared/src/server/services/sessions-ui-table-events-service.ts b/packages/shared/src/server/services/sessions-ui-table-events-service.tsindex ee400e84e1..c5e7c4eb3e 100644--- a/packages/shared/src/server/services/sessions-ui-table-events-service.ts+++ b/packages/shared/src/server/services/sessions-ui-table-events-service.ts@@ -43,6 +43,13 @@ import {} from "../tableMappings/mapSessionTable";import { sessionsEventsViewCols } from "../../tableDefinitions/sessionsView";import { findUiColumnMapping } from "../../tableDefinitions/types";+import {+ sessionTraceFilterSchema,+ sessionTraceFilterColumns,+} from "../../features/filters/sessionTraceFilters";+import { tracesTableUiColumnDefinitions } from "../tableMappings/mapTracesTable";+import { eventsTableNativeUiColumnDefinitions } from "../tableMappings/mapEventsTable";+import { EventsQueryBuilder } from "../queries/clickhouse-sql/event-query-builder";export type SessionTraceFromEvents = {id: string;@@ -57,15 +64,87 @@ export type SessionTraceFromEvents = {export const getSessionTracesFromEvents = async (props: {projectId: string;sessionId: string;+ filter: FilterState;+ limit?: number;+ traceIds?: string[];}) => {const { projectId, sessionId } = props;- const builder = getClickhouseKysely()+ let builder = getClickhouseKysely().selectFrom("events as e").select(traceAggregationSelects(TRACE_AGGREGATION_FIELDS)).where("e.session_id", "=", sessionId).groupBy(["trace_id", "project_id"]).orderBy("timestamp", "asc");- const { sql: query, params } = compileClickhouseQuery(builder, projectId);+ if (props.traceIds)+ builder = builder.where("e.trace_id", "in", props.traceIds);+ const { sql: tracesQuery, params: tracesParams } = compileClickhouseQuery(+ builder,+ projectId,+ );+ const filters = sessionTraceFilterSchema.parse(props.filter);+ const traceFilters = new FilterList(+ createFilterFromFilterState(+ filters.filter(+ (filter) =>+ !["name", "type", "level", "metadata", "isRootObservation"].includes(+ filter.column,+ ),+ ),+ tracesTableUiColumnDefinitions,+ sessionTraceFilterColumns,+ ),+ ).apply();+ const observationFilters = filters.filter((filter) =>+ ["name", "type", "level", "metadata", "isRootObservation"].includes(+ filter.column,+ ),+ );+ const sessionTraceIdsQuery = compileClickhouseQuery(+ builder.clearSelect().select("e.trace_id").clearGroupBy().clearOrderBy(),+ projectId,+ );+ const observationQuery =+ observationFilters.length > 0+ ? new EventsQueryBuilder({ projectId: props.projectId })+ .selectRaw("e.trace_id")+ .when(+ observationFilters.some((filter) => filter.column === "metadata"),+ (builder) => builder.forceFullTable(),+ )+ .whereRaw("e.is_deleted = 0")+ .whereRaw(`e.trace_id IN (${sessionTraceIdsQuery.sql})`)+ .where(+ new FilterList(+ createFilterFromFilterState(+ observationFilters,+ eventsTableNativeUiColumnDefinitions,+ sessionTraceFilterColumns,+ ),+ ).apply(),+ )+ .buildWithParams()+ : null;+ const query =+ filters.length === 0+ ? tracesQuery+ : `+ WITH session_traces AS (${tracesQuery})+ SELECT t.* FROM session_traces t+ WHERE 1 = 1 ${traceFilters.query ? `AND ${traceFilters.query}` : ""}+ ${observationQuery ? `AND t.id IN (${observationQuery.query})` : ""}+ ORDER BY t.timestamp ASC+ `;++ const params =+ filters.length === 0+ ? tracesParams+ : {+ ...tracesParams,+ ...traceFilters.params,+ ...observationQuery?.params,+ ...sessionTraceIdsQuery.params,+ projectId,+ };const rows = await queryClickhouse<{id: string;@@ -76,7 +155,9 @@ export const getSessionTracesFromEvents = async (props: {observation_count: number | string;latency_milliseconds: number | string | null;}>({- query,+ query: props.limit+ ? `${query} LIMIT ${Math.max(1, Math.floor(props.limit))}`+ : query,params,tags: { projectId },preferredClickhouseService: "EventsReadOnly",diff --git a/web/src/__tests__/server/unit/loadTraceTranscript.servertest.ts b/web/src/__tests__/server/unit/loadTraceTranscript.servertest.tsindex 97816f24f9..8451f8b05e 100644--- a/web/src/__tests__/server/unit/loadTraceTranscript.servertest.ts+++ b/web/src/__tests__/server/unit/loadTraceTranscript.servertest.ts@@ -360,65 +360,6 @@ it("returns the shared transcript unchanged without fetching root I/O", async ()expect(mocks.root).not.toHaveBeenCalled();});-it("uses only root I/O in root mode even when generations exist", async () => {- const root = {- id: "root",- parentObservationId: null,- startTime: new Date(0),- endTime: new Date(1),- input: "Root question",- output: "Root answer",- metadata: {},- };- mocks.observations.mockResolvedValue({- observations: [root, { id: "generation", type: "GENERATION" }],- totalCount: 2,- });- mocks.root.mockResolvedValue(root);-- const result = await loadTraceTranscript({- ...trace,- transcriptSource: "root",- });-- expect(mocks.observations).toHaveBeenCalledTimes(1);- expect(mocks.assemble).not.toHaveBeenCalled();- expect(result.cutoff).toBe(false);- expect(result.transcript?.threads[0]?.currentTurn.messages).toMatchObject([- { observationId: "root", parts: [{ type: "text", text: "Root question" }] },- { observationId: "root", parts: [{ type: "text", text: "Root answer" }] },- ]);-});--it.each(["missing", "empty"])(- "does not use generations when root I/O is %s in root mode",- async (rootState) => {- mocks.observations.mockResolvedValue({- observations:- rootState === "missing"- ? [- {- id: "generation",- parentObservationId: "root",- type: "GENERATION",- },- ]- : [{ id: "root", parentObservationId: null, startTime: new Date(0) }],- totalCount: 1,- });- mocks.root.mockResolvedValue({ input: null, output: null, metadata: {} });-- const result = await loadTraceTranscript({- ...trace,- transcriptSource: "root",- });-- expect(result.transcript).toBeNull();- expect(mocks.observations).toHaveBeenCalledTimes(1);- expect(mocks.assemble).not.toHaveBeenCalled();- },-);-it("leaves an empty transcript unchanged unless fallback is enabled", async () => {mocks.assemble.mockReturnValue(null);mocks.observations.mockResolvedValue({@@ -453,3 +394,115 @@ it("leaves the transcript empty when the root has no input/output", async () =>.transcript,).toBeNull();});++it("loads and normalizes matching span I/O without assembly or ancestors", async () => {+ const message = {+ role: "assistant" as const,+ source: "output" as const,+ parts: [{ type: "text" as const, text: "Response" }],+ observationId: "match",+ traceId: "trace",+ startTime: new Date(0),+ endTime: new Date(1),+ };+ mocks.observations.mockResolvedValue({+ observations: [+ {+ id: "match",+ type: "SPAN",+ startTime: new Date(0),+ endTime: new Date(1),+ input: null,+ output: "Response",+ metadata: {},+ },+ ],+ totalCount: 1,+ });+ const filter = [+ {+ column: "name",+ type: "string" as const,+ operator: "=" as const,+ value: "child",+ },+ ];+ const result = await loadTraceTranscript({ ...trace, filter });+ expect(mocks.observations).toHaveBeenCalledExactlyOnceWith({+ ...trace,+ filter,+ selectIOAndMetadata: true,+ limit: 1000,+ });+ expect(mocks.assemble).not.toHaveBeenCalled();+ expect(result.transcript?.threads).toEqual([+ {+ conversationHistory: [],+ currentTurn: {+ nestingLevel: 0,+ observations: [{ id: "match", traceId: "trace" }],+ messages: [message],+ },+ },+ ]);+});++it("does not restore unmatched root I/O when no observations match", async () => {+ mocks.assemble.mockReturnValue(null);+ mocks.observations.mockResolvedValue({ observations: [], totalCount: 0 });+ const result = await loadTraceTranscript({+ ...trace,+ fallbackToRootIO: true,+ filter: [+ { column: "level", type: "string", operator: "=", value: "ERROR" },+ ],+ });+ expect(result.transcript).toBeNull();+ expect(mocks.root).not.toHaveBeenCalled();+});++it("bypasses assembly for trace-only filters and keeps each observation's full I/O in chronological order", async () => {+ const observations = [2, 1].map((index) => ({+ id: `span-${index}`,+ type: "SPAN",+ startTime: new Date(index),+ endTime: new Date(index + 1),+ input: [{ role: "user", content: "Repeated history" }],+ output: `Answer ${index}`,+ metadata: {},+ }));+ mocks.observations.mockResolvedValue({ observations, totalCount: 1001 });+ const result = await loadTraceTranscript({+ ...trace,+ fallbackToRootIO: true,+ filter: [+ { column: "traceName", type: "string", operator: "=", value: "chat" },+ ],+ });+ expect(mocks.observations).toHaveBeenCalledExactlyOnceWith({+ ...trace,+ fallbackToRootIO: true,+ filter: [],+ selectIOAndMetadata: true,+ limit: 1000,+ });+ expect(mocks.assemble).not.toHaveBeenCalled();+ expect(mocks.root).not.toHaveBeenCalled();+ expect(result.cutoff).toBe(true);+ expect(+ result.transcript?.threads.map((thread) => ({+ history: thread.conversationHistory,+ id: thread.currentTurn.observations[0]?.id,+ messages: thread.currentTurn.messages.map((message) => message.parts),+ })),+ ).toEqual(+ [1, 2].map((index) => ({+ history: [],+ id: `span-${index}`,+ messages: [+ [{ type: "text", text: "Repeated history" }],+ [{ type: "text", text: `Answer ${index}` }],+ ],+ })),+ );+});diff --git a/web/src/components/design-system/RadioCardGroup/RadioCardGroup.stories.tsx b/web/src/components/design-system/RadioCardGroup/RadioCardGroup.stories.tsxnew file mode 100644index 0000000000..858a5078a0--- /dev/null+++ b/web/src/components/design-system/RadioCardGroup/RadioCardGroup.stories.tsx@@ -0,0 +1,50 @@+import { useState } from "react";+import { expect, fn, waitFor } from "storybook/test";+import preview from "@/.storybook/preview";+import { RadioCardGroup } from "./RadioCardGroup";++const meta = preview.meta({+ component: RadioCardGroup,+ args: {+ "aria-label": "Trace visibility",+ options: [+ { value: "show", label: "Show" },+ { value: "hide", label: "Hide" },+ ],+ value: "show",+ onValueChange: fn(),+ },+ render: function Render(args) {+ const [value, setValue] = useState(args.value);+ return (+ <RadioCardGroup+ {...args}+ value={value}+ onValueChange={(nextValue) => {+ setValue(nextValue);+ args.onValueChange(nextValue);+ }}+ />+ );+ },+});++export const Default = meta.story({});++export const KeyboardSelection = meta.story({+ name: "(Test) Keyboard selection",+ play: async ({ canvas, args, userEvent }) => {+ await userEvent.click(canvas.getByRole("radio", { name: "Show" }));+ await userEvent.keyboard("{ArrowRight>}");+ await waitFor(() =>+ expect(canvas.getByRole("radio", { name: "Hide" })).toBeChecked(),+ );+ await userEvent.keyboard("{/ArrowRight}");+ await expect(args.onValueChange).toHaveBeenCalledWith("hide");+ await userEvent.keyboard("{ArrowLeft>}");+ await waitFor(() =>+ expect(canvas.getByRole("radio", { name: "Show" })).toBeChecked(),+ );+ await userEvent.keyboard("{/ArrowLeft}");+ },+});diff --git a/web/src/components/design-system/RadioCardGroup/RadioCardGroup.tsx b/web/src/components/design-system/RadioCardGroup/RadioCardGroup.tsxnew file mode 100644index 0000000000..5af986e7ce--- /dev/null+++ b/web/src/components/design-system/RadioCardGroup/RadioCardGroup.tsx@@ -0,0 +1,45 @@+"use client";++import { useId } from "react";+import * as RadioGroupPrimitive from "@radix-ui/react-radio-group";+import { RadioGroup } from "../RadioGroup/RadioGroup";++export function RadioCardGroup<TValue extends string>({+ options,+ value,+ onValueChange,+ ...props+}: {+ id?: string;+ "aria-label": string;+ "aria-describedby"?: string;+ options: readonly { value: TValue; label: string }[];+ value: TValue;+ onValueChange: (value: TValue) => void;+}) {+ const groupId = useId();++ return (+ <RadioGroupPrimitive.Root+ {...props}+ className="flex gap-2"+ orientation="horizontal"+ value={value}+ onValueChange={(nextValue) => {+ const option = options.find((option) => option.value === nextValue);+ if (option) onValueChange(option.value);+ }}+ >+ {options.map((option, index) => (+ <label+ key={option.value}+ htmlFor={`${groupId}-${index}`}+ className="has-[[data-state=checked]]:border-primary has-[[data-state=checked]]:bg-primary/5 hover:bg-accent flex min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-md border p-3 text-sm"+ >+ <RadioGroup.Item id={`${groupId}-${index}`} value={option.value} />+ {option.label}+ </label>+ ))}+ </RadioGroupPrimitive.Root>+ );+}diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.tsindex db967a2a10..a07e5a068d 100644--- a/web/src/features/events/server/eventsRouter.ts+++ b/web/src/features/events/server/eventsRouter.ts@@ -20,6 +20,7 @@ import {normalizeOrderByForTable,paginationZod,singleFilterList,+ sessionTraceFilterSchema,timeFilter,toAuditLogResourceRef,} from "@langfuse/shared";@@ -464,7 +465,7 @@ export const eventsRouter = createTRPCRouter({traceId: zodSchema.string(),timestamp: zodSchema.date().optional(),fallbackToRootIO: zodSchema.boolean().default(false),- transcriptSource: zodSchema.enum(["generations", "root"]).optional(),+ filter: sessionTraceFilterSchema.optional(),}),).query(async ({ input, ctx }) => {@@ -513,7 +514,7 @@ export const eventsRouter = createTRPCRouter({traceId: input.traceId,timestamp,fallbackToRootIO: input.fallbackToRootIO,- transcriptSource: input.transcriptSource,+ filter: input.filter,});},);diff --git a/web/src/features/events/server/loadTraceTranscript.ts b/web/src/features/events/server/loadTraceTranscript.tsindex cb40e07947..60a516bcdc 100644--- a/web/src/features/events/server/loadTraceTranscript.ts+++ b/web/src/features/events/server/loadTraceTranscript.ts@@ -7,8 +7,9 @@ import {normalizeIO,type Transcript,} from "@langfuse/shared/src/server";+import { sessionTraceFilterSchema, type FilterState } from "@langfuse/shared";-/** Generations and tools whose I/O one transcript reads at most. */+/** Bound expensive I/O reads separately from lightweight observation structure. */const MAX_TRANSCRIPT_OBSERVATIONS = 1_000;const TRANSCRIPT_OBSERVATION_TYPES = new Set(["GENERATION", "TOOL"]);@@ -41,18 +42,64 @@ export async function loadTraceTranscript(trace: {timestamp: Date;/** Use root observation I/O when no generation/tool transcript exists. */fallbackToRootIO?: boolean;- transcriptSource?: "generations" | "root";+ filter?: FilterState;}): Promise<{ transcript: SessionTranscript | null; cutoff: boolean }> {+ const filters = sessionTraceFilterSchema.parse(trace.filter ?? []);+ const { filter: _, ...source } = trace;+ if (filters.length > 0) {+ const observationFilters = filters.filter((filter) =>+ ["name", "type", "level", "metadata", "isRootObservation"].includes(+ filter.column,+ ),+ );+ const content = await getObservationsForTraceFromEventsTable({+ ...source,+ filter: observationFilters,+ selectIOAndMetadata: true,+ limit: MAX_TRANSCRIPT_OBSERVATIONS,+ });+ const threads = [...content.observations]+ .sort(+ (a, b) =>+ a.startTime.getTime() - b.startTime.getTime() ||+ a.id.localeCompare(b.id),+ )+ .map((observation) => ({+ conversationHistory: [],+ currentTurn: {+ nestingLevel: 0,+ observations: [{ id: observation.id, traceId: trace.traceId }],+ messages: normalizeIO({+ kind: "io",+ io: {+ input: observation.input,+ output: observation.output,+ metadata: observation.metadata,+ },+ }).messages.map((message) => ({+ ...message,+ observationId: observation.id,+ traceId: trace.traceId,+ startTime: observation.startTime,+ endTime: observation.endTime,+ level: observation.level,+ statusMessage: observation.statusMessage,+ })),+ },+ }));+ return {+ transcript: threads.length > 0 ? { threads } : null,+ cutoff: content.totalCount > MAX_TRANSCRIPT_OBSERVATIONS,+ };+ }const [structure, content] = await Promise.all([- getObservationsForTraceFromEventsTable(trace),- trace.transcriptSource === "root"- ? Promise.resolve({ observations: [], totalCount: 0 })- : getObservationsForTraceFromEventsTable({- ...trace,- selectIOAndMetadata: true,- types: ["GENERATION", "TOOL"],- limit: MAX_TRANSCRIPT_OBSERVATIONS,- }),+ getObservationsForTraceFromEventsTable(source),+ getObservationsForTraceFromEventsTable({+ ...source,+ selectIOAndMetadata: true,+ types: ["GENERATION", "TOOL"],+ limit: MAX_TRANSCRIPT_OBSERVATIONS,+ }),]);const contentById = new Map(content.observations.map((o) => [o.id, o]));// Generations and tools past the content cap have no I/O to show; leaving@@ -93,14 +140,8 @@ export async function loadTraceTranscript(trace: {}return TRANSCRIPT_OBSERVATION_TYPES.has(o.type) ? [] : [o];});- let transcript =- trace.transcriptSource === "root"- ? null- : assembleTranscript(orderObservations(observations));- if (- !transcript &&- (trace.transcriptSource === "root" || trace.fallbackToRootIO)- ) {+ let transcript = assembleTranscript(orderObservations(observations));+ if (!transcript && trace.fallbackToRootIO) {const root = structure.observations.find((observation) =>observation.isRootObservation === true ||diff --git a/web/src/features/search-bar/components/EventsSearchBarRow.tsx b/web/src/features/search-bar/components/EventsSearchBarRow.tsxindex a5e4b4ee53..82e54a63d3 100644--- a/web/src/features/search-bar/components/EventsSearchBarRow.tsx+++ b/web/src/features/search-bar/components/EventsSearchBarRow.tsx@@ -61,6 +61,7 @@ function ProjectSearchBarRow(props: EventsSearchBarRowProps) {}function EventsSearchBarRowContent({+ inputId,aiFeaturesEnabled,projectId,tableName,@@ -80,8 +81,11 @@ function EventsSearchBarRowContent({className,registry = EVENTS_FIELD_REGISTRY,size = "default",+ spacing = "table",}: {aiFeaturesEnabled: boolean;+ inputId?: string;+ spacing?: "table" | "flush";projectId?: string;/** Table this bar filters — threaded to AI-prompt analytics (LFE-10781). */tableName: string;@@ -158,7 +162,13 @@ function EventsSearchBarRowContent({}, [onRequestColumns, registry]);return (- <div className={cn("min-w-0 px-2 pt-2 pb-1", className)}>+ <div+ className={cn(+ "min-w-0",+ spacing === "table" && "px-2 pt-2 pb-1",+ className,+ )}+ >{aiOpen && aiAvailable && aiRegistryId && projectId ? (<SearchBarAiPromptprojectId={projectId}@@ -175,6 +185,7 @@ function EventsSearchBarRowContent({) : (<SearchBarStoreProvider store={store} commit={commit}><ComposerWithPreview+ inputId={inputId}projectId={projectId}observed={observed}erroredColumns={erroredColumns}diff --git a/web/src/features/search-bar/components/SearchComposer.tsx b/web/src/features/search-bar/components/SearchComposer.tsxindex a04546b93a..34fc3bd0cc 100644--- a/web/src/features/search-bar/components/SearchComposer.tsx+++ b/web/src/features/search-bar/components/SearchComposer.tsx@@ -318,6 +318,7 @@ function useLatest<T>(value: T) {}export function SearchComposer({+ inputId,projectId,observed,erroredColumns,@@ -330,6 +331,7 @@ export function SearchComposer({registry = EVENTS_FIELD_REGISTRY,size = "default",}: {+ inputId?: string;projectId?: string;/** `large` on full-page lists; embedded toolbars keep the default. */size?: ComposerSize;@@ -1443,6 +1445,7 @@ export function SearchComposer({<ComposerText><divref={rootRef}+ id={inputId}role="combobox"aria-label="Search"aria-expanded={plan !== null}diff --git a/web/src/features/search-bar/components/presentation.ts b/web/src/features/search-bar/components/presentation.tsindex 33661202c6..6f00d8b492 100644--- a/web/src/features/search-bar/components/presentation.ts+++ b/web/src/features/search-bar/components/presentation.ts@@ -7,6 +7,7 @@ import type { FieldRegistry } from "@/src/features/search-bar/lib/fields";/** Per-view: the examples have to name fields the view actually has. */export function composerPlaceholder(registry: FieldRegistry): string {+ if (registry.searchPlaceholder) return registry.searchPlaceholder;return registry.searchExamples.length > 0? `Search — e.g. ${registry.searchExamples.join(", ")}`: "Search";diff --git a/web/src/features/search-bar/lib/fields.ts b/web/src/features/search-bar/lib/fields.tsindex ec2383bddd..5d51b718d2 100644--- a/web/src/features/search-bar/lib/fields.ts+++ b/web/src/features/search-bar/lib/fields.ts@@ -100,6 +100,7 @@ export type FieldRegistry = {| "evaluatorSamples"| "ruleSamples"| "sessions"+ | "sessionTraces"| "scores"| "experiments"| "users"@@ -148,6 +149,7 @@ export type FieldRegistry = {/** Placeholder examples. Written per view, never derived from field ids: the* events examples advertise `latency:`/`level:` on a view that has neither. */searchExamples: readonly string[];+ searchPlaceholder?: string;/*** Field id used in the `has:` hint. Written per view like `searchExamples`:* deriving it (e.g. "first nullable field") silently rewrites the hint@@ -211,6 +213,7 @@ export function fieldRegistryFromColumns(defaultTextField?: string;freeTextScopeLabel?: string;searchExamples?: readonly string[];+ searchPlaceholder?: string;hasExample?: string;recentSearches?: boolean;aiFilterPrompt?: boolean;@@ -278,6 +281,7 @@ export function fieldRegistryFromColumns(defaultTextField: overlay.defaultTextField ?? null,freeTextScopeLabel: overlay.freeTextScopeLabel ?? null,searchExamples: overlay.searchExamples ?? [],+ searchPlaceholder: overlay.searchPlaceholder,hasExample: overlay.hasExample ?? null,recentSearches: overlay.recentSearches ?? false,aiFilterPrompt: overlay.aiFilterPrompt ?? false,@@ -487,6 +491,7 @@ export function createFieldRegistry({defaultTextField,freeTextScopeLabel,searchExamples,+ searchPlaceholder,hasExample,recentSearches,aiFilterPrompt,@@ -508,6 +513,7 @@ export function createFieldRegistry({defaultTextField: string | null;freeTextScopeLabel: string | null;searchExamples: readonly string[];+ searchPlaceholder?: string;hasExample: string | null;recentSearches: boolean;aiFilterPrompt: boolean;@@ -549,6 +555,7 @@ export function createFieldRegistry({defaultTextField,freeTextScopeLabel,searchExamples,+ searchPlaceholder,hasExample,recentSearches,aiFilterPrompt,diff --git a/web/src/features/sessions/ModernSession.clienttest.tsx b/web/src/features/sessions/ModernSession.clienttest.tsxindex 3852e07129..867b51b1c0 100644--- a/web/src/features/sessions/ModernSession.clienttest.tsx+++ b/web/src/features/sessions/ModernSession.clienttest.tsx@@ -11,11 +11,7 @@ vi.mock("@/src/features/sessions/ConnectedModernSessionBodyLegacy", () => ({vi.mock("@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline",() => ({- ConnectedModernSessionBodyTimeline: ({- transcriptSource,- }: Pick<ComponentProps<typeof ModernSession>, "transcriptSource">) => (- <div data-source={transcriptSource}>Timeline body</div>- ),+ ConnectedModernSessionBodyTimeline: () => <div>Timeline body</div>,}),);@@ -54,7 +50,6 @@ vi.mock("@/src/features/sessions/SessionMetadataJsonPathControl", () => ({const defaultProps = {isTimelineEnabled: false,- transcriptSource: "generations",session: {countTraces: 0,inputUsage: 0,@@ -103,24 +98,6 @@ const defaultProps = {} satisfies ComponentProps<typeof ModernSession>;describe("ModernSession", () => {- it.each(["root", "generations"] as const)(- "passes the resolved %s transcript source to the timeline",- (transcriptSource) => {- render(- <ModernSession- {...defaultProps}- isTimelineEnabled- transcriptSource={transcriptSource}- />,- );-- expect(screen.getByText("Timeline body")).toHaveAttribute(- "data-source",- transcriptSource,- );- },- );-it("renders the shared header and legacy connected body by default", () => {render(<ModernSession {...defaultProps} />);diff --git a/web/src/features/sessions/ModernSession.tsx b/web/src/features/sessions/ModernSession.tsxindex 1203c16875..384ecac1e5 100644--- a/web/src/features/sessions/ModernSession.tsx+++ b/web/src/features/sessions/ModernSession.tsx@@ -1,4 +1,5 @@import { type ComponentProps } from "react";+import { SessionFiltersBanner } from "@/src/features/sessions/SessionFiltersBanner";import { type FilterState } from "@langfuse/shared";import { ConnectedModernSessionBodyLegacy } from "@/src/features/sessions/ConnectedModernSessionBodyLegacy";@@ -13,11 +14,13 @@ import {} from "@/src/features/sessions/sessionDetailPageTypes";type ModernSessionProps = {+ customization?: NonNullable<+ ComponentProps<typeof ConnectedModernSessionBodyTimeline>["customization"]+ > & {+ onClearFilters: () => void;+ };headerDividerTone?: ComponentProps<typeof ModernSessionHeader>["dividerTone"];isTimelineEnabled: boolean;- transcriptSource: ComponentProps<- typeof ConnectedModernSessionBodyTimeline- >["transcriptSource"];session: Pick<EventSession,| "countTraces"@@ -53,9 +56,9 @@ type ModernSessionProps = {};export function ModernSession({+ customization,headerDividerTone,isTimelineEnabled,- transcriptSource,session,tracesState,projectId,@@ -115,13 +118,20 @@ export function ModernSession({</SessionReviewLeading>)}</SessionMetadataJsonPathControl>+ {customization && customization.activeFilterCount > 0 && (+ <SessionFiltersBanner+ onEdit={customization.onCustomizeView}+ onClear={customization.onClearFilters}+ />+ )}{isTimelineEnabled ? (<ConnectedModernSessionBodyTimeline- transcriptSource={transcriptSource}+ customization={customization}tracesState={tracesState}projectId={projectId}sessionId={sessionId}openPeek={openPeek}+ filterState={filterState}/>) : (<ModernSessionFilterControls {...filterControlsProps}>diff --git a/web/src/features/sessions/ModernSessionHeaderActionsController.clienttest.tsx b/web/src/features/sessions/ModernSessionHeaderActionsController.clienttest.tsxindex 69772b47fd..1aee3d5cc0 100644--- a/web/src/features/sessions/ModernSessionHeaderActionsController.clienttest.tsx+++ b/web/src/features/sessions/ModernSessionHeaderActionsController.clienttest.tsx@@ -5,25 +5,13 @@ import { vi } from "vitest";import { type DropdownMenuItemDefinition } from "@/src/components/design-system/DropdownMenu/DropdownMenu";import { ModernSessionHeaderActionsController } from "@/src/features/sessions/ModernSessionHeaderActionsController";-const {- mockUseSession,- mockInternalFeaturesEnabled,- copy,- copyTextToClipboard,-} = vi.hoisted(() => ({+const { mockUseSession, copy, copyTextToClipboard } = vi.hoisted(() => ({mockUseSession: vi.fn(),- mockInternalFeaturesEnabled: vi.fn(),copy: vi.fn(),copyTextToClipboard: vi.fn(),}));vi.mock("next-auth/react", () => ({ useSession: mockUseSession }));-vi.mock(- "@/src/features/feature-flags/hooks/useInternalFeaturesEnabled",- () => ({- useInternalFeaturesEnabled: mockInternalFeaturesEnabled,- }),-);vi.mock("next/router", () => ({useRouter: () => ({ asPath: "/", push: vi.fn() }),@@ -118,7 +106,6 @@ vi.mock("@/src/utils/clipboard", () => ({ copyTextToClipboard }));describe("ModernSessionHeaderActionsController", () => {beforeEach(() => {vi.clearAllMocks();- mockInternalFeaturesEnabled.mockReturnValue(true);mockUseSession.mockReturnValue({ data: { user: { admin: false } } });});@@ -228,34 +215,12 @@ describe("ModernSessionHeaderActionsController", () => {expect(onShowInlineToolCallsChange).toHaveBeenCalledWith(true);});- it("changes the transcript source from the actions display menu", () => {- const onUseRootIOChange = vi.fn();- render(- <ModernSessionHeaderActionsController- projectId="project-id"- sessionId="session-id"- isPublic={false}- useRootIO={false}- onUseRootIOChange={onUseRootIOChange}- />,- );-- expect(screen.getByText("Display Internal")).toBeInTheDocument();- fireEvent.click(- screen.getByRole("menuitemcheckbox", { name: "Use root input/output" }),- );- expect(onUseRootIOChange).toHaveBeenCalledWith(true);- });-- it("hides the timeline Display submenu without internal access", () => {- mockInternalFeaturesEnabled.mockReturnValue(false);+ it("hides the Display submenu when no display settings are provided", () => {render(<ModernSessionHeaderActionsControllerprojectId="project-id"sessionId="session-id"isPublic={false}- useRootIO={false}- onUseRootIOChange={vi.fn()}/>,);diff --git a/web/src/features/sessions/ModernSessionHeaderActionsController.tsx b/web/src/features/sessions/ModernSessionHeaderActionsController.tsxindex a835923bd3..4fe301defa 100644--- a/web/src/features/sessions/ModernSessionHeaderActionsController.tsx+++ b/web/src/features/sessions/ModernSessionHeaderActionsController.tsx@@ -1,6 +1,5 @@import { CopyIcon, MoreVertical } from "@langfuse/icons";import { useSession } from "next-auth/react";-import { useInternalFeaturesEnabled } from "@/src/features/feature-flags/hooks/useInternalFeaturesEnabled";import { HeaderActionButton } from "@/src/components/HeaderActionButton";import { HeaderActionMenuRows } from "@/src/components/HeaderActionMenuRows";@@ -49,30 +48,20 @@ type DisplaySettingProps = {showCorrections?: boolean;showInlineToolCalls?: boolean;showSystemPrompt?: boolean;- useRootIO?: boolean;onShowCorrectionsChange?: (isEnabled: boolean) => void;onShowInlineToolCallsChange?: (isEnabled: boolean) => void;onShowSystemPromptChange?: (isEnabled: boolean) => void;- onUseRootIOChange?: (isEnabled: boolean) => void;};function buildDisplayItems({showCorrections,showInlineToolCalls,showSystemPrompt,- useRootIO,onShowCorrectionsChange,onShowInlineToolCallsChange,onShowSystemPromptChange,- onUseRootIOChange,}: DisplaySettingProps): DropdownMenuItemDefinition[] {const settings = [- {- id: "use-root-io",- title: "Use root input/output",- checked: useRootIO,- onChange: onUseRootIOChange,- },{id: "show-corrections",title: "Show corrections",@@ -134,11 +123,7 @@ export function ModernSessionHeaderActionsController({objectId: sessionId,isPublic,});- const internalFeaturesEnabled = useInternalFeaturesEnabled();- const displayItems = buildDisplayItems({- ...displaySettings,- useRootIO: internalFeaturesEnabled ? displaySettings.useRootIO : undefined,- });+ const displayItems = buildDisplayItems(displaySettings);const adminItems: DropdownMenuItemDefinition[] =session.data?.user?.admin === true@@ -181,7 +166,6 @@ export function ModernSessionHeaderActionsController({type: "submenu" as const,id: "display",title: "Display",- internal: displaySettings.useRootIO !== undefined,items: displayItems,},]diff --git a/web/src/features/sessions/ModernSessionSaveViewDialogContent.tsx b/web/src/features/sessions/ModernSessionSaveViewDialogContent.tsxindex dcfe8953aa..010b417cca 100644--- a/web/src/features/sessions/ModernSessionSaveViewDialogContent.tsx+++ b/web/src/features/sessions/ModernSessionSaveViewDialogContent.tsx@@ -1,35 +1,27 @@-/* eslint-disable @typescript-eslint/no-deprecated -- Legacy UI usage retained during migration to design-system components. */-import { Button } from "@/src/components/ui/button";import { useState } from "react";-import {- DialogBody,- DialogContent,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/src/components/ui/dialog";-import { Input } from "@/src/components/ui/input";+import { Button } from "@/src/components/design-system/Button/Button";+import { Dialog } from "@/src/components/design-system/Dialog/Dialog";+import { Input } from "@/src/components/design-system/Input/Input";type ModernSessionSaveViewDialogContentProps = {isSaving: boolean;onCancel: () => void;onSave: (viewName: string) => void;+ error?: string;};export function ModernSessionSaveViewDialogContent({isSaving,onCancel,onSave,+ error,}: ModernSessionSaveViewDialogContentProps) {const [viewName, setViewName] = useState("");const saveView = () => onSave(viewName.trim());return (- <DialogContent>- <DialogHeader>- <DialogTitle>Save as new view</DialogTitle>- </DialogHeader>- <DialogBody>+ <Dialog title="Save as new view">+ <Dialog.Body><div><labelhtmlFor="modern-session-view-name"@@ -50,19 +42,21 @@ export function ModernSessionSaveViewDialogContent({}}/></div>- </DialogBody>- <DialogFooter>- <Button variant="outline" onClick={onCancel}>- Cancel- </Button>- <Button- loading={isSaving}- disabled={!viewName.trim()}- onClick={saveView}- >- Save view- </Button>- </DialogFooter>- </DialogContent>+ {error ? (+ <p role="alert" className="text-destructive">+ {error}+ </p>+ ) : null}+ <div className="flex justify-end gap-2">+ <Button variant="secondary" text="Cancel" onClick={onCancel} />+ <Button+ text="Save view"+ loading={isSaving}+ disabled={!viewName.trim()}+ onClick={saveView}+ />+ </div>+ </Dialog.Body>+ </Dialog>);}diff --git a/web/src/features/sessions/SessionCustomizationDialog/ConnectedSessionCustomizationDialog.tsx b/web/src/features/sessions/SessionCustomizationDialog/ConnectedSessionCustomizationDialog.tsxnew file mode 100644index 0000000000..f7637bc419--- /dev/null+++ b/web/src/features/sessions/SessionCustomizationDialog/ConnectedSessionCustomizationDialog.tsx@@ -0,0 +1,28 @@+import { type ComponentProps } from "react";+import { api } from "@/src/utils/api";+import { SessionCustomizationDialog } from "./SessionCustomizationDialog";++export function ConnectedSessionCustomizationDialog({+ sessionId,+ isOpen,+ ...props+}: Pick<+ ComponentProps<typeof SessionCustomizationDialog>,+ "projectId" | "initialFilters" | "initialUnmatchedTraces" | "onApply"+> & { sessionId: string; isOpen: boolean }) {+ const preview = api.sessions.previewTree.useQuery(+ { projectId: props.projectId, sessionId },+ { enabled: isOpen },+ );++ return (+ <SessionCustomizationDialog+ {...props}+ preview={{+ traces: preview.data,+ pending: preview.isFetching,+ error: preview.error?.message,+ }}+ />+ );+}diff --git a/web/src/features/sessions/SessionCustomizationDialog/SessionCustomizationDialog.stories.tsx b/web/src/features/sessions/SessionCustomizationDialog/SessionCustomizationDialog.stories.tsxnew file mode 100644index 0000000000..6ddfff8199--- /dev/null+++ b/web/src/features/sessions/SessionCustomizationDialog/SessionCustomizationDialog.stories.tsx@@ -0,0 +1,272 @@+import { expect, fn, userEvent, within } from "storybook/test";+import preview from "../../../../.storybook/preview";+import { DialogController } from "@/src/components/design-system/DialogController/DialogController";+import { SessionCustomizationDialog } from "./SessionCustomizationDialog";++const meta = preview.meta({+ component: SessionCustomizationDialog,+ parameters: { layout: "fullscreen" },+ decorators: [+ (Story) => (+ <DialogController<null>+ initialState={() => null}+ renderDialog={() => <Story />}+ >+ {() => null}+ </DialogController>+ ),+ ],+ args: {+ projectId: "storybook-project",+ initialFilters: [],+ initialUnmatchedTraces: "show" as const,+ onApply: fn(),+ preview: { traces: [], pending: false, error: undefined },+ },+});++export default meta;++export const TestObservationFilters = meta.story({+ name: "(Test) Observation filters",+ play: async ({ args }) => {+ const body = within(document.body);+ const completion = await body.findByRole("group", {+ name: "Observation completion",+ });+ const input = body.getByRole("combobox", { name: "Search" });+ await userEvent.click(input);+ await userEvent.paste("traceName:=other name:=completion");+ await expect(+ within(completion).getByText("Excluded by filters"),+ ).toBeInTheDocument();+ await userEvent.clear(input);+ await userEvent.paste("traceName:=chat observationName:=completion");+ await expect(+ within(completion).queryByText("Excluded by filters"),+ ).not.toBeInTheDocument();+ await expect(+ within(body.getByRole("group", { name: "Observation agent" })).getByText(+ "Excluded by filters",+ ),+ ).toBeInTheDocument();+ await userEvent.click(body.getByRole("radio", { name: "Hide" }));+ await expect(args.onApply).not.toHaveBeenCalled();+ await userEvent.click(body.getByRole("button", { name: "Apply filters" }));+ await expect(args.onApply).toHaveBeenCalledWith(+ [+ { column: "traceName", type: "string", operator: "=", value: "chat" },+ { column: "name", type: "string", operator: "=", value: "completion" },+ ],+ "hide",+ );+ },+ args: {+ preview: {+ pending: false,+ error: undefined,+ traces: [+ {+ id: "trace-1",+ name: "chat",+ truncated: true,+ observations: [+ {+ id: "root",+ userId: null,+ environment: "default",+ traceTags: [],+ metadata: {},+ name: "agent",+ type: "SPAN",+ level: "DEFAULT",+ isRootObservation: true,+ parentObservationId: null,+ },+ {+ id: "child",+ userId: null,+ environment: "default",+ traceTags: [],+ metadata: {},+ name: "completion",+ type: "GENERATION",+ level: "DEFAULT",+ isRootObservation: false,+ parentObservationId: "root",+ },+ ],+ },+ {+ id: "unmatched",+ name: "other",+ truncated: false,+ observations: [+ {+ id: "other-root",+ userId: null,+ environment: "default",+ traceTags: [],+ metadata: {},+ name: "other root",+ type: "SPAN",+ level: "DEFAULT",+ isRootObservation: true,+ parentObservationId: null,+ },+ ],+ },+ ],+ },+ },+});++export const Default = meta.story({ args: TestObservationFilters.input.args });++export const TestInvalidDraftKeepsPreview = Default.extend({+ play: async ({ args }) => {+ const body = within(document.body);+ const input = body.getByRole("combobox", { name: "Search" });+ await userEvent.click(input);+ await userEvent.paste("name:=completion");+ const completion = body.getByRole("group", {+ name: "Observation completion",+ });+ const agent = body.getByRole("group", { name: "Observation agent" });+ await expect(+ within(completion).queryByText("Excluded by filters"),+ ).not.toBeInTheDocument();+ await expect(+ within(agent).getByText("Excluded by filters"),+ ).toBeInTheDocument();++ await userEvent.type(input, " unknown:value");+ await userEvent.type(input, " more");+ await expect(+ body.getByRole("button", { name: "Generations" }),+ ).toBeDisabled();+ await expect(+ within(completion).queryByText("Excluded by filters"),+ ).not.toBeInTheDocument();+ await expect(+ within(agent).getByText("Excluded by filters"),+ ).toBeInTheDocument();+ await userEvent.click(body.getByRole("button", { name: "Apply filters" }));+ await expect(args.onApply).not.toHaveBeenCalled();++ await userEvent.clear(input);+ await userEvent.paste("name:=agent");+ await expect(+ within(completion).getByText("Excluded by filters"),+ ).toBeInTheDocument();+ await userEvent.click(body.getByRole("button", { name: "Apply filters" }));+ await expect(args.onApply).toHaveBeenCalledWith(+ [{ column: "name", type: "string", operator: "=", value: "agent" }],+ "show",+ );+ },+});++export const TestPreserveSkippedFilters = Default.extend({+ args: {+ initialFilters: [+ { column: "userId", type: "string", operator: "=", value: "user" },+ {+ column: "environment",+ type: "string",+ operator: "=",+ value: "production",+ },+ {+ column: "traceTags",+ type: "arrayOptions",+ operator: "any of",+ value: ["important"],+ },+ {+ column: "metadata",+ type: "stringObject",+ key: "region",+ operator: "=",+ value: "eu",+ },+ ],+ preview: {+ pending: false,+ error: undefined,+ traces: [+ {+ id: "trace",+ name: "chat",+ truncated: false,+ observations: [+ {+ id: "root",+ parentObservationId: null,+ name: "agent",+ type: "GENERATION",+ level: "DEFAULT",+ isRootObservation: true,+ userId: "user",+ environment: "production",+ traceTags: ["important"],+ metadata: { region: "eu" },+ },+ ],+ },+ ],+ },+ },+ play: async ({ args }) => {+ const body = within(document.body);+ await expect(+ body.queryByText("Excluded by filters"),+ ).not.toBeInTheDocument();+ await userEvent.click(body.getByRole("button", { name: "Apply filters" }));+ await expect(args.onApply).toHaveBeenCalledWith(+ args.initialFilters,+ "show",+ );+ await userEvent.click(body.getByRole("button", { name: "Generations" }));+ await userEvent.click(body.getByRole("button", { name: "Apply filters" }));+ await expect(args.onApply).toHaveBeenLastCalledWith(+ [+ { column: "type", type: "string", operator: "=", value: "GENERATION" },+ ...args.initialFilters,+ ],+ "show",+ );+ },+});++export const TestConfirmAllObservationsExcluded = Default.extend({+ args: {+ initialFilters: [+ { column: "name", type: "string", operator: "=", value: "no-match" },+ ],+ },+ play: async ({ args }) => {+ const body = within(document.body);+ await userEvent.click(body.getByRole("button", { name: "Apply filters" }));+ const confirmation = await body.findByRole("dialog", {+ name: "Apply filters with no matching observations?",+ });+ await expect(args.onApply).not.toHaveBeenCalled();+ await userEvent.click(+ within(confirmation).getByRole("button", { name: "Cancel" }),+ );+ await expect(args.onApply).not.toHaveBeenCalled();+ await expect(+ await body.findByRole("dialog", { name: "Customize session view" }),+ ).toBeInTheDocument();+ await userEvent.click(body.getByRole("button", { name: "Apply filters" }));+ await userEvent.click(+ await body.findByRole("button", { name: "Apply filters anyway" }),+ );+ await expect(args.onApply).toHaveBeenCalledTimes(1);+ await expect(args.onApply).toHaveBeenCalledWith(+ args.initialFilters,+ "show",+ );+ },+});diff --git a/web/src/features/sessions/SessionCustomizationDialog/SessionCustomizationDialog.tsx b/web/src/features/sessions/SessionCustomizationDialog/SessionCustomizationDialog.tsxnew file mode 100644index 0000000000..a040bf2342--- /dev/null+++ b/web/src/features/sessions/SessionCustomizationDialog/SessionCustomizationDialog.tsx@@ -0,0 +1,223 @@+import { type ComponentProps, useId } from "react";+import { Controller, useForm, useWatch } from "react-hook-form";+import { type FilterState } from "@langfuse/shared";+import { type RouterOutputs } from "@/src/utils/api";+import { ListTree, Sparkles } from "@langfuse/icons";+import { Button } from "@/src/components/ui/button";+import { Dialog } from "@/src/components/design-system/Dialog/Dialog";+import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";+import { Form } from "@/src/components/design-system/Form/Form";+import { RadioCardGroup } from "@/src/components/design-system/RadioCardGroup/RadioCardGroup";+import {+ SessionFilterInput,+ useSessionFilterInput,+} from "./components/SessionFilterInput/SessionFilterInput";+import { SessionFilterPreview } from "./components/SessionFilterPreview/SessionFilterPreview";+import { useSessionFilterPreview } from "./useSessionFilterPreview";++export function SessionCustomizationDialog({+ projectId,+ initialFilters,+ initialUnmatchedTraces,+ onApply,+ preview,+}: {+ projectId: string;+ initialFilters: FilterState;+ initialUnmatchedTraces: "show" | "hide";+ onApply: (filters: FilterState, unmatchedTraces: "show" | "hide") => void;+ preview: Pick<+ ComponentProps<typeof SessionFilterPreview>,+ "pending" | "error"+ > & { traces: RouterOutputs["sessions"]["previewTree"] | undefined };+}) {+ const formId = useId();+ const form = useForm({+ defaultValues: {+ filters: initialFilters,+ unmatchedTraces: initialUnmatchedTraces,+ },+ });+ const draft = useWatch({ control: form.control, name: "filters" });+ const filterInput = useSessionFilterInput({+ projectId,+ filters: draft,+ onFiltersChange: (filters) => form.setValue("filters", filters),+ });+ const matchingTraces = useSessionFilterPreview(+ preview.traces,+ filterInput.filters,+ );+ const handlePresetToggle = (filter: FilterState[number]) => {+ const filters = filterInput.readFilters();+ if (filters === null) return;+ const present = filters.some(+ (existing) =>+ existing.column === filter.column &&+ existing.type === filter.type &&+ existing.operator === filter.operator &&+ existing.value === filter.value,+ );+ const remaining = filters.filter(+ (existing) =>+ existing.column !== filter.column ||+ existing.operator !== filter.operator,+ );+ filterInput.applyFilters(present ? remaining : [...remaining, filter]);+ };+ const handlePreviewFilter = (filter: FilterState[number]) => {+ const filters = filterInput.readFilters();+ if (filters === null) return;+ if (+ filters.some(+ (existing) => JSON.stringify(existing) === JSON.stringify(filter),+ )+ )+ return;+ filterInput.applyFilters([...filters, filter]);+ };+ const handleSubmit = (+ values: { unmatchedTraces: Parameters<typeof onApply>[1] },+ confirm: (args: Parameters<typeof onApply>) => void,+ ) => {+ const filters = filterInput.readFilters();+ if (filters === null) return;+ if (+ !preview.pending &&+ !preview.error &&+ matchingTraces?.some((trace) => trace.observations.length > 0) &&+ !matchingTraces.some((trace) =>+ trace.observations.some((observation) => observation.matches),+ )+ ) {+ confirm([filters, values.unmatchedTraces]);+ return;+ }+ onApply(filters, values.unmatchedTraces);+ };++ return (+ <Dialog+ size="lg"+ title="Customize session view"+ actions={[{ label: "Apply filters", type: "submit", form: formId }]}+ >+ <ConfirmationDialogController<Parameters<typeof onApply>>+ title="Apply filters with no matching observations?"+ text="These filters exclude every observation in the preview. Applying them may make it appear that session data is missing."+ confirmLabel="Apply filters anyway"+ variant="default"+ onConfirm={([filters, nextUnmatchedTraces]) =>+ onApply(filters, nextUnmatchedTraces)+ }+ >+ {({ openDialog }) => (+ <form+ id={formId}+ className="min-h-0 overflow-y-auto border-y text-sm"+ onSubmit={form.handleSubmit((values) =>+ handleSubmit(values, openDialog),+ )}+ >+ <div className="grid min-w-0 md:grid-cols-2">+ <div className="flex flex-col gap-2 p-4">+ <Form.Field label="Observation filters">+ {({ id }) => (+ <SessionFilterInput+ {...filterInput.inputProps}+ inputId={id}+ />+ )}+ </Form.Field>+ <p className="text-muted-foreground text-xs font-bold">+ Presets+ </p>+ <div className="flex flex-wrap gap-2">+ {(+ [+ {+ label: "Root spans",+ icon: ListTree,+ filter: {+ column: "isRootObservation",+ type: "boolean",+ operator: "=",+ value: true,+ },+ },+ {+ label: "Generations",+ icon: Sparkles,+ filter: {+ column: "type",+ type: "string",+ operator: "=",+ value: "GENERATION",+ },+ },+ ] satisfies Array<{+ label: string;+ icon: typeof ListTree;+ filter: FilterState[number];+ }>+ ).map(({ label, icon: Icon, filter }) => (+ <Button+ key={label}+ type="button"+ variant="outline"+ size="sm"+ className="flex h-8 items-center gap-2 text-sm"+ disabled={filterInput.invalid}+ onClick={() => handlePresetToggle(filter)}+ >+ <Icon size="base" />+ {label}+ </Button>+ ))}+ </div>+ <p className="text-muted-foreground text-sm">+ By default, the session view automatically hides repeated+ messages. Adding observation filters turns this off, so all+ matching observations are shown exactly as recorded. Your+ filters determine which data appears in the session view.+ </p>+ <div className="mt-2 border-t pt-4">+ <Form.Field+ label="Traces without matching observations"+ description="Hiding removes traces left empty by observation filters, which may make data appear missing. Trace name filters always apply."+ >+ {({ id, inputDescribedById }) => (+ <Controller+ control={form.control}+ name="unmatchedTraces"+ render={({ field }) => (+ <RadioCardGroup<"show" | "hide">+ id={id}+ aria-label="Traces without matching observations"+ aria-describedby={inputDescribedById}+ value={field.value}+ onValueChange={field.onChange}+ options={[+ { value: "show", label: "Show" },+ { value: "hide", label: "Hide" },+ ]}+ />+ )}+ />+ )}+ </Form.Field>+ </div>+ </div>+ <SessionFilterPreview+ {...preview}+ traces={matchingTraces}+ invalid={filterInput.invalid}+ onFilter={handlePreviewFilter}+ />+ </div>+ </form>+ )}+ </ConfirmationDialogController>+ </Dialog>+ );+}diff --git a/web/src/features/sessions/SessionCustomizationDialog/components/SessionFilterInput/SessionFilterInput.tsx b/web/src/features/sessions/SessionCustomizationDialog/components/SessionFilterInput/SessionFilterInput.tsxnew file mode 100644index 0000000000..96f8102cb8--- /dev/null+++ b/web/src/features/sessions/SessionCustomizationDialog/components/SessionFilterInput/SessionFilterInput.tsx@@ -0,0 +1,111 @@+import { useMemo, useSyncExternalStore } from "react";+import { type FilterState } from "@langfuse/shared";+import { EventsSearchBarRow } from "@/src/features/search-bar/components/EventsSearchBarRow";+import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";+import { planCommit } from "@/src/features/search-bar/lib/commit";+import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSearchBar";+import { usePrevious } from "@/src/hooks/usePrevious";+import { SESSION_TRACE_FIELD_REGISTRY } from "../../../sessionTraceSearchRegistry";++export function useSessionFilterInput({+ projectId,+ filters,+ onFiltersChange,+}: {+ projectId: string;+ filters: FilterState;+ onFiltersChange: (filters: FilterState) => void;+}) {+ const { store, commit, applyFilters } = useEventsSearchBar({+ projectId,+ tableName: "session-traces",+ registry: SESSION_TRACE_FIELD_REGISTRY,+ enabled: true,+ isV4: true,+ filterState: filters,+ setFilterState: onFiltersChange,+ observed: undefined,+ searchQuery: null,+ searchType: [],+ setSearchQuery: () => {},+ setSearchType: () => {},+ });+ const query = useSyncExternalStore(+ store.subscribe,+ () => store.getState().draft,+ () => store.getState().draft,+ );+ const plan = useMemo(() => {+ const parsed = planCommit(query, undefined, SESSION_TRACE_FIELD_REGISTRY);+ if (parsed.status === "invalid") return parsed;+ const { skippedFilters } = filterStateToQueryText(+ filters,+ {},+ SESSION_TRACE_FIELD_REGISTRY,+ );+ // Editing a field replaces its hidden filter; unrelated hidden filters survive.+ const preserved = skippedFilters.filter(+ (skipped) =>+ !parsed.filters.some(+ (filter) =>+ filter.column === skipped.column &&+ filter.target === skipped.target &&+ (filter.type === "stringObject" ||+ filter.type === "numberObject" ||+ filter.type === "booleanObject" ||+ filter.type === "categoryOptions" ||+ filter.type === "positionInTrace"+ ? filter.key+ : undefined) ===+ (skipped.type === "stringObject" ||+ skipped.type === "numberObject" ||+ skipped.type === "booleanObject" ||+ skipped.type === "categoryOptions" ||+ skipped.type === "positionInTrace"+ ? skipped.key+ : undefined),+ ),+ );+ return { ...parsed, filters: [...parsed.filters, ...preserved] };+ }, [query, filters]);+ const lastValidFilters = usePrevious(+ plan.status === "invalid" ? undefined : plan.filters,+ plan.status !== "invalid",+ );+ const activeFilters = useMemo(+ () =>+ plan.status === "invalid" ? (lastValidFilters ?? filters) : plan.filters,+ [plan, lastValidFilters, filters],+ );++ return {+ filters: activeFilters,+ invalid: plan.status === "invalid",+ readFilters: () => {+ commit();+ if (plan.status === "invalid") return null;+ return plan.filters;+ },+ applyFilters,+ inputProps: { projectId, store, commit, onApplyFilters: applyFilters },+ };+}++export function SessionFilterInput({+ inputId,+ ...props+}: ReturnType<typeof useSessionFilterInput>["inputProps"] & {+ inputId: string;+}) {+ return (+ <EventsSearchBarRow+ {...props}+ inputId={inputId}+ spacing="flush"+ tableName="session-traces"+ registry={SESSION_TRACE_FIELD_REGISTRY}+ isV4+ observed={undefined}+ />+ );+}diff --git a/web/src/features/sessions/SessionCustomizationDialog/components/SessionFilterPreview/SessionFilterPreview.tsx b/web/src/features/sessions/SessionCustomizationDialog/components/SessionFilterPreview/SessionFilterPreview.tsxnew file mode 100644index 0000000000..83bc262caf--- /dev/null+++ b/web/src/features/sessions/SessionCustomizationDialog/components/SessionFilterPreview/SessionFilterPreview.tsx@@ -0,0 +1,255 @@+import { type RouterOutputs } from "@/src/utils/api";+import { useMemo, useState } from "react";+import { type FilterState } from "@langfuse/shared";+import { MoreHorizontal } from "@langfuse/icons";+import { type LangfuseItemType } from "@/src/components/ItemBadge";+import { VirtualizedTree } from "@/src/features/traces/components/VirtualizedTree";+import { VirtualizedTreeNodeWrapper } from "@/src/features/traces/components/VirtualizedTreeNodeWrapper";+import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";++type PreviewNode = Pick<+ RouterOutputs["sessions"]["previewTree"][number],+ "name"+> & {+ id: string;+ matches: boolean;+ type: LangfuseItemType;+ column: "name" | "traceName";+ children: PreviewNode[];+};++function PreviewRow({+ name,+ matches,+ column,+ disabled,+ onFilter,+}: {+ name: string | null;+ matches: boolean;+ column: "name" | "traceName";+ disabled: boolean;+ onFilter: (filter: FilterState[number]) => void;+}) {+ return (+ <div className="flex min-w-0 flex-1 items-center gap-2 py-1">+ <span+ className={matches ? "truncate" : "truncate opacity-35"}+ title={name ?? "Unnamed"}+ >+ {column === "traceName" ? "Trace: " : ""}+ {name ?? "Unnamed"}+ </span>+ {!matches ? <span className="sr-only">Excluded by filters</span> : null}+ <DropdownMenu+ disabled={disabled || name === null}+ placement="bottom-end"+ items={[+ {+ id: "include-by-name",+ type: "item",+ title: "Include by name",+ onClick: () => {+ if (name !== null)+ onFilter({+ column,+ type: "string",+ operator: "=",+ value: name,+ });+ },+ },+ {+ id: "exclude-by-name",+ type: "item",+ title: "Exclude by name",+ onClick: () => {+ if (name !== null)+ onFilter({+ column,+ type: "stringOptions",+ operator: "none of",+ value: [name],+ });+ },+ },+ ]}+ >+ {({ getTriggerProps }) => (+ <button+ type="button"+ disabled={disabled || name === null}+ aria-label={`Filter ${column === "traceName" ? "trace" : "observation"} ${name ?? "Unnamed"}`}+ className="hover:bg-accent ml-auto shrink-0 rounded px-2"+ {...getTriggerProps({+ onClick: (event) => event.stopPropagation(),+ })}+ >+ <MoreHorizontal size="sm" aria-hidden="true" />+ </button>+ )}+ </DropdownMenu>+ </div>+ );+}++export function SessionFilterPreview({+ traces,+ pending,+ error,+ invalid,+ onFilter,+}: {+ traces:+ | Array<+ Pick<+ RouterOutputs["sessions"]["previewTree"][number],+ "id" | "name" | "truncated"+ > & {+ matches: boolean;+ observations: Array<+ RouterOutputs["sessions"]["previewTree"][number]["observations"][number] & {+ matches: boolean;+ }+ >;+ }+ >+ | undefined;+ pending: boolean;+ error: string | undefined;+ invalid: boolean;+ onFilter: (filter: FilterState[number]) => void;+}) {+ const [collapsedNodes, setCollapsedNodes] = useState<Set<string>>(+ () => new Set(),+ );+ const roots = useMemo(+ () =>+ (traces ?? []).map((trace) => {+ const root: PreviewNode = {+ id: `trace:${trace.id}`,+ name: trace.name,+ matches: trace.matches,+ type: "TRACE",+ column: "traceName",+ children: [],+ };+ const observationsById = new Map(+ trace.observations.map((observation) => [+ observation.id,+ observation,+ ]),+ );+ const children = new Map<string | null, typeof trace.observations>();+ for (const observation of trace.observations) {+ const parentId =+ observation.parentObservationId &&+ observationsById.has(observation.parentObservationId)+ ? observation.parentObservationId+ : null;+ const siblings = children.get(parentId) ?? [];+ siblings.push(observation);+ children.set(parentId, siblings);+ }+ const visited = new Set<string>();+ const visit = (+ observation: (typeof trace.observations)[number],+ parent: PreviewNode,+ ) => {+ if (visited.has(observation.id)) return;+ visited.add(observation.id);+ const node: PreviewNode = {+ id: `trace:${trace.id}:observation:${observation.id}`,+ name: observation.name,+ matches: observation.matches,+ type: observation.type,+ column: "name",+ children: [],+ };+ parent.children.push(node);+ for (const child of children.get(observation.id) ?? [])+ visit(child, node);+ };+ for (const observation of children.get(null) ?? [])+ visit(observation, root);+ // Keep orphaned and cyclic observations visible without creating a cyclic tree.+ for (const observation of trace.observations) visit(observation, root);+ return root;+ }),+ [traces],+ );+ const toggleCollapsed = (id: string) =>+ setCollapsedNodes((previous) => {+ const next = new Set(previous);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ return (+ <section+ aria-label="Filter preview"+ className="ph-no-capture bg-muted/30 min-w-0 border-t md:border-t-0 md:border-l"+ >+ <header className="bg-modal sticky top-0 z-10 border-b p-4">+ <h3 className="font-bold">Filter preview</h3>+ <p className="text-muted-foreground text-xs">+ Previewing the first 5 traces, with up to 200 observations per trace.+ Observations that don’t match your filters are dimmed.+ </p>+ </header>+ <div className="flex h-[45vh] min-h-40 flex-col" aria-busy={pending}>+ {pending || error || traces?.length === 0 ? (+ <div className="space-y-2 p-4">+ {pending ? <p role="status">Updating preview…</p> : null}+ {error ? <p role="alert">{error}</p> : null}+ {!pending && !error && traces?.length === 0 ? (+ <p>No traces to preview.</p>+ ) : null}+ </div>+ ) : null}+ <div className="min-h-0 flex-1 px-2">+ <VirtualizedTree+ roots={roots}+ collapsedNodes={collapsedNodes}+ selectedNodeId={null}+ onToggleCollapse={toggleCollapsed}+ onSelectNode={(id) => {+ if (id !== null) toggleCollapsed(id);+ }}+ renderNode={({+ node,+ treeMetadata,+ isCollapsed,+ onToggleCollapse,+ onSelect,+ }) => (+ <div+ role="group"+ aria-label={`${node.column === "traceName" ? "Trace" : "Observation"} ${node.name ?? "Unnamed"}`}+ >+ <VirtualizedTreeNodeWrapper+ className="rounded-md [&_[data-expand-button]>span]:inline-flex [&_[data-expand-button]>span]:items-center [&_[data-expand-button]>span]:justify-center"+ metadata={treeMetadata}+ nodeType={node.type}+ hasChildren={node.children.length > 0}+ isCollapsed={isCollapsed}+ onToggleCollapse={onToggleCollapse}+ isSelected={false}+ onSelect={onSelect}+ >+ <PreviewRow+ name={node.name}+ matches={node.matches}+ column={node.column}+ disabled={invalid || pending}+ onFilter={onFilter}+ />+ </VirtualizedTreeNodeWrapper>+ </div>+ )}+ />+ </div>+ </div>+ </section>+ );+}diff --git a/web/src/features/sessions/SessionCustomizationDialog/useSessionFilterPreview.ts b/web/src/features/sessions/SessionCustomizationDialog/useSessionFilterPreview.tsnew file mode 100644index 0000000000..d42eaf31f8--- /dev/null+++ b/web/src/features/sessions/SessionCustomizationDialog/useSessionFilterPreview.ts@@ -0,0 +1,123 @@+import { useMemo } from "react";+import { type FilterState } from "@langfuse/shared";+import { type RouterOutputs } from "@/src/utils/api";++export function useSessionFilterPreview(+ traces: RouterOutputs["sessions"]["previewTree"] | undefined,+ filters: FilterState,+) {+ return useMemo(+ () =>+ traces?.map((trace) => {+ const observations = trace.observations.map((observation) => ({+ ...observation,+ matches: filters.every((filter) => {+ if (+ filter.column === "isRootObservation" &&+ filter.type === "boolean"+ ) {+ const equal =+ (observation.isRootObservation === true) === filter.value;+ switch (filter.operator) {+ case "=":+ return equal;+ case "<>":+ return !equal;+ default:+ throw new Error(+ `Unsupported boolean filter: ${filter satisfies never}`,+ );+ }+ }+ if (+ filter.type === "arrayOptions" &&+ filter.column === "traceTags"+ ) {+ const tags = observation.traceTags ?? [];+ switch (filter.operator) {+ case "all of":+ return filter.value.every((tag) => tags.includes(tag));+ case "any of":+ return filter.value.some((tag) => tags.includes(tag));+ case "none of":+ return !filter.value.some((tag) => tags.includes(tag));+ default:+ throw new Error(+ `Unsupported tag filter: ${filter satisfies never}`,+ );+ }+ }+ if (+ filter.type !== "string" &&+ filter.type !== "stringOptions" &&+ filter.type !== "stringObject"+ )+ return false;+ const value = (() => {+ if (+ filter.type === "stringObject" &&+ filter.column === "metadata"+ ) {+ const metadata = observation.metadata;+ if (+ !metadata ||+ typeof metadata !== "object" ||+ Array.isArray(metadata)+ )+ return undefined;+ const entry = metadata[filter.key];+ if (entry === undefined || entry === null) return undefined;+ return typeof entry === "string"+ ? entry+ : JSON.stringify(entry);+ }+ if (filter.column === "name") return observation.name;+ if (filter.column === "traceName") return trace.name;+ if (filter.column === "type") return observation.type;+ if (filter.column === "level") return observation.level;+ if (filter.column === "userId") return observation.userId;+ if (filter.column === "environment")+ return observation.environment;+ return undefined;+ })();+ if (filter.operator === "is set")+ return value !== undefined && value !== null;+ if (filter.operator === "is not set")+ return value === undefined || value === null;+ if (value === null || value === undefined) return false;+ if (filter.type === "stringOptions") {+ const included = filter.value.includes(value);+ switch (filter.operator) {+ case "any of":+ return included;+ case "none of":+ return !included;+ default:+ throw new Error(+ `Unsupported name filter: ${filter satisfies never}`,+ );+ }+ }+ if (filter.operator === "=") return value === filter.value;+ if (filter.operator === "is not empty") return value.length > 0;+ if (filter.operator === "starts with")+ return value.startsWith(filter.value);+ if (filter.operator === "ends with")+ return value.endsWith(filter.value);+ const contains = value.includes(filter.value);+ if (filter.operator === "contains") return contains;+ if (filter.operator === "does not contain") return !contains;+ return false;+ }),+ }));+ return {+ ...trace,+ observations,+ matches:+ filters.length === 0 ||+ observations.some((observation) => observation.matches),+ };+ }),+ [traces, filters],+ );+}diff --git a/web/src/features/sessions/SessionFiltersBanner.stories.tsx b/web/src/features/sessions/SessionFiltersBanner.stories.tsxnew file mode 100644index 0000000000..3ee7a1df32--- /dev/null+++ b/web/src/features/sessions/SessionFiltersBanner.stories.tsx@@ -0,0 +1,10 @@+import preview from "@/.storybook/preview";+import { fn } from "storybook/test";+import { SessionFiltersBanner } from "./SessionFiltersBanner";++const meta = preview.meta({+ component: SessionFiltersBanner,+ args: { onEdit: fn(), onClear: fn() },+});++export const Default = meta.story({});diff --git a/web/src/features/sessions/SessionFiltersBanner.tsx b/web/src/features/sessions/SessionFiltersBanner.tsxnew file mode 100644index 0000000000..b75618e902--- /dev/null+++ b/web/src/features/sessions/SessionFiltersBanner.tsx@@ -0,0 +1,27 @@+import { Button } from "@/src/components/design-system/Button/Button";++export function SessionFiltersBanner({+ onEdit,+ onClear,+}: {+ onEdit: () => void;+ onClear: () => void;+}) {+ return (+ <div+ role="status"+ className="bg-muted/40 text-muted-foreground flex shrink-0 flex-wrap items-center gap-2 border-b px-4 py-2 text-sm"+ >+ <span className="flex-1">+ Filters are active. Some session data may be hidden.+ </span>+ <Button variant="ghost" size="sm" text="Edit filters" onClick={onEdit} />+ <Button+ variant="ghost"+ size="sm"+ text="Clear filters"+ onClick={onClear}+ />+ </div>+ );+}diff --git a/web/src/features/sessions/SessionPages.tsx b/web/src/features/sessions/SessionPages.tsxindex 0b9fcd0e8c..478c7d3007 100644--- a/web/src/features/sessions/SessionPages.tsx+++ b/web/src/features/sessions/SessionPages.tsx@@ -66,6 +66,9 @@ import {type ScoreDomain,TableViewPresetTableName,normalizeLegacySessionPositionInTraceFilters,+ sessionTraceFilterSchema,+ decodeFiltersGeneric,+ encodeFiltersGeneric,} from "@langfuse/shared";import { AnnotationQueueItemDropdownMenuController } from "@/src/features/annotation-queues/components/AnnotationQueueItemDropdownMenuController";import { AnnotationQueueItemCountBadge } from "@/src/features/annotation-queues/components/AnnotationQueueItemCountBadge";@@ -117,11 +120,13 @@ import { createSessionDetailStore } from "@/src/features/sessions/sessionDetailSimport { ModernSession } from "@/src/features/sessions/ModernSession";import { ConnectedModernSessionBodyTimeline } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline";import { SessionRedesignBanner } from "@/src/features/sessions/SessionRedesignBanner";+import { ConnectedSessionCustomizationDialog } from "@/src/features/sessions/SessionCustomizationDialog/ConnectedSessionCustomizationDialog";+import { useInternalFeaturesEnabled } from "@/src/features/feature-flags/hooks/useInternalFeaturesEnabled";+import { default as useIsFeatureEnabled } from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";+import { DialogController } from "@/src/components/design-system/DialogController/DialogController";import { HeaderActionMenuRow } from "@/src/components/HeaderActionMenuRow";import { ModernSessionHeaderActionsController } from "@/src/features/sessions/ModernSessionHeaderActionsController";import { ConnectedSessionAddToDropdownMenuController } from "@/src/features/sessions/ConnectedSessionAddToDropdownMenuController";-import { useInternalFeaturesEnabled } from "@/src/features/feature-flags/hooks/useInternalFeaturesEnabled";-import { default as useIsFeatureEnabled } from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";import { useIsMobile } from "@/src/hooks/use-mobile";import { useStore } from "zustand";import { TraceReviewPanelProvider } from "@/src/features/traces/contexts/TraceReviewPanelProvider";@@ -1019,6 +1024,32 @@ export const SessionEventsPage: React.FC<{projectId,},);+ const [traceFilterQuery, setTraceFilterQuery] = useQueryParam(+ "traceFilter",+ StringParam,+ );+ const isInternalFeaturesEnabled = useInternalFeaturesEnabled();+ const traceFilters = React.useMemo(() => {+ if (!isInternalFeaturesEnabled) return [];++ try {+ const parsed = sessionTraceFilterSchema.safeParse(+ decodeFiltersGeneric(traceFilterQuery ?? ""),+ );+ return parsed.success ? parsed.data : [];+ } catch {+ return [];+ }+ }, [traceFilterQuery, isInternalFeaturesEnabled]);+ // Keep shared links and reloads consistent with the applied observation filters.+ const [tracesWithoutMatchesQuery, setTracesWithoutMatchesQuery] =+ useQueryParam("tracesWithoutMatches", StringParam);+ const unmatchedTraces =+ tracesWithoutMatchesQuery === "hide" ? "hide" : "show";+ const setUnmatchedTraces = (value: "show" | "hide") =>+ setTracesWithoutMatchesQuery(value === "hide" ? "hide" : undefined);+ const setTraceFilters = (filters: FilterState) =>+ setTraceFilterQuery(encodeFiltersGeneric(filters) || undefined);const session = api.sessions.byIdWithScoresFromEvents.useQuery({sessionId,@@ -1030,8 +1061,19 @@ export const SessionEventsPage: React.FC<{},);+ const traceListFilters =+ isModernSessionEnabled && isSessionTimelineEnabled+ ? traceFilters.filter((filter) => {+ if (filter.column === "traceName") return true;+ return unmatchedTraces === "hide";+ })+ : [];const tracesQuery = api.sessions.tracesFromEvents.useQuery(- { projectId, sessionId },+ {+ projectId,+ sessionId,+ filter: traceListFilters.length > 0 ? traceListFilters : undefined,+ },{enabled: !!projectId && !!sessionId,retry: shouldRetryResourceQuery,@@ -1089,6 +1131,10 @@ export const SessionEventsPage: React.FC<{session={session.data}traces={tracesQuery.data}isTracesSuccess={tracesQuery.isSuccess}+ traceFilters={traceFilters}+ setTraceFilters={setTraceFilters}+ unmatchedTraces={unmatchedTraces}+ setUnmatchedTraces={setUnmatchedTraces}/>);};@@ -1130,7 +1176,6 @@ function SessionEventsLoadingPage({</div></SessionReviewLeading><ConnectedModernSessionBodyTimeline- transcriptSource="generations"tracesState={{ type: "loading" }}projectId={projectId}sessionId={sessionId}@@ -1149,7 +1194,27 @@ const LoadedSessionEventsPage: React.FC<{session: EventSession;traces: EventSessionTrace[] | undefined;isTracesSuccess: boolean;-}> = ({ sessionId, projectId, session, traces, isTracesSuccess }) => {+ traceFilters: FilterState;+ setTraceFilters: (filters: FilterState) => void;+ unmatchedTraces: React.ComponentProps<+ typeof ConnectedSessionCustomizationDialog+ >["initialUnmatchedTraces"];+ setUnmatchedTraces: (+ value: React.ComponentProps<+ typeof ConnectedSessionCustomizationDialog+ >["initialUnmatchedTraces"],+ ) => void;+}> = ({+ sessionId,+ projectId,+ session,+ traces,+ isTracesSuccess,+ traceFilters,+ setTraceFilters,+ unmatchedTraces,+ setUnmatchedTraces,+}) => {const router = useRouter();const { setDetailPageList, detailPagelists } = useDetailPageLists();const userSession = useSession();@@ -1165,6 +1230,7 @@ const LoadedSessionEventsPage: React.FC<{projectId,},);+ const isInternalFeaturesEnabled = useInternalFeaturesEnabled();const [isRedesignBannerDismissed, setIsRedesignBannerDismissed] =useLocalStorage("sessionRedesignBannerDismissed", false);const showRedesignBanner =@@ -1325,23 +1391,6 @@ const LoadedSessionEventsPage: React.FC<{};}, [positionInTraceColumn, sessionEventsTableName]);const [urlFiltersQuery] = useQueryParam("filter", StringParam);- const [urlTranscriptSource, setUrlTranscriptSource] = useQueryParam(- "transcriptSource",- StringParam,- );- const [storedTranscriptSource, setStoredTranscriptSource] = useLocalStorage<- "root" | "generations"- >("sessionTranscriptSource", "generations");- const internalFeaturesEnabled = useInternalFeaturesEnabled();- const transcriptSource =- internalFeaturesEnabled &&- (urlTranscriptSource ?? storedTranscriptSource) === "root"- ? "root"- : "generations";- const setTranscriptSource = (source: typeof storedTranscriptSource) => {- setStoredTranscriptSource(source);- setUrlTranscriptSource(source);- };const filtersQuery = React.useMemo(() =>urlFiltersQuery ??@@ -1781,64 +1830,275 @@ const LoadedSessionEventsPage: React.FC<{openRef={openAnnotateRef}onDisabledChange={setAnnotateDisabled}/>- <Page- headerProps={{- title: sessionId,- itemType: "SESSION",- divider: false,- breadcrumb: [- {- name: "Sessions",- href: `/project/${projectId}/sessions`,- },- ],- actionButtonsLeft: !isModernSessionEnabled ? (- <div className="flex items-center gap-0">- <PublishSessionSwitch- projectId={projectId}- sessionId={sessionId}- isPublic={session.public}- key="publish"- size="icon-xs"- />- <CopySessionIdButton key="copy-id" sessionId={sessionId} />- </div>- ) : undefined,- actionButtonsRight: (- <>- {webCalloutAction && (- <WebCalloutButton action={webCalloutAction} />- )}- <ConnectedSessionAddToDropdownMenuController- projectId={projectId}- sessionId={sessionId}- analyticsData={{ source: "SessionDetail", isV4: true }}- >- {({ getTriggerProps, totalCount }) => (- <Button- variant="ghost"- size="sm"- className={headerActionClassName}- {...getTriggerProps()}+ <DialogController+ key={`${projectId}:${sessionId}`}+ renderDialog={({ closeDialog, isOpen }) => (+ <ConnectedSessionCustomizationDialog+ isOpen={isOpen}+ projectId={projectId}+ sessionId={sessionId}+ initialFilters={traceFilters}+ initialUnmatchedTraces={unmatchedTraces}+ onApply={(filters, nextUnmatchedTraces) => {+ setTraceFilters(filters);+ setUnmatchedTraces(nextUnmatchedTraces);+ closeDialog();+ }}+ />+ )}+ >+ {({ openDialog }) => (+ <Page+ headerProps={{+ title: sessionId,+ itemType: "SESSION",+ divider: false,+ breadcrumb: [+ {+ name: "Sessions",+ href: `/project/${projectId}/sessions`,+ },+ ],+ actionButtonsLeft: !isModernSessionEnabled ? (+ <div className="flex items-center gap-0">+ <PublishSessionSwitch+ projectId={projectId}+ sessionId={sessionId}+ isPublic={session.public}+ key="publish"+ size="icon-xs"+ />+ <CopySessionIdButton key="copy-id" sessionId={sessionId} />+ </div>+ ) : undefined,+ actionButtonsRight: (+ <>+ {webCalloutAction && (+ <WebCalloutButton action={webCalloutAction} />+ )}+ <ConnectedSessionAddToDropdownMenuController+ projectId={projectId}+ sessionId={sessionId}+ analyticsData={{ source: "SessionDetail", isV4: true }}>- <Plus size="base" color="default" aria-hidden="true" />- Add to- {totalCount > 0 && (- <ActionButtonCountBadge count={totalCount} />+ {({ getTriggerProps, totalCount }) => (+ <Button+ variant="ghost"+ size="sm"+ className={headerActionClassName}+ {...getTriggerProps()}+ >+ <Plus+ size="base"+ color="default"+ aria-hidden="true"+ />+ Add to+ {totalCount > 0 && (+ <ActionButtonCountBadge count={totalCount} />+ )}+ <DropdownIndicator size="sm" nudge />+ </Button>)}- <DropdownIndicator size="sm" nudge />- </Button>- )}- </ConnectedSessionAddToDropdownMenuController>- <AnnotateDrawerController projectId={projectId}>- {({ disabled, openDrawer }) => (- <Button- variant="ghost"- size="sm"- disabled={disabled}- className={headerActionClassName}- onClick={() =>- openDrawer({+ </ConnectedSessionAddToDropdownMenuController>+ <AnnotateDrawerController projectId={projectId}>+ {({ disabled, openDrawer }) => (+ <Button+ variant="ghost"+ size="sm"+ disabled={disabled}+ className={headerActionClassName}+ onClick={() =>+ openDrawer({+ scoreTarget: { type: "session", sessionId },+ scores: session.scores,+ analyticsData: {+ type: "session",+ source: "SessionDetail",+ isV4: true,+ },+ scoreMetadata: {+ projectId,+ environment: session.environment,+ },+ })+ }+ >+ {disabled ? (+ <LockIcon size="base" color="default" />+ ) : (+ <SquarePen size="base" color="default" />+ )}+ Annotate+ {isModernSessionEnabled && annotationCount > 0 ? (+ <ActionButtonCountBadge count={annotationCount} />+ ) : null}+ </Button>+ )}+ </AnnotateDrawerController>+ <CommentDrawerController+ key="comment"+ projectId={projectId}+ count={getNumberFromMap(+ sessionCommentCounts.data,+ sessionId,+ )}+ >+ {({ disabled, openDrawer }) => (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ disabled={disabled}+ className={headerActionClassName}+ onClick={() =>+ openDrawer({+ type: "comments",+ objectId: sessionId,+ objectType: "SESSION",+ })+ }+ >+ {disabled ? (+ <MessageSquareOff size="base" color="default" />+ ) : (+ <MessageSquare size="base" color="default" />+ )}+ {getNumberFromMap(+ sessionCommentCounts.data,+ sessionId,+ )+ ? "Comments"+ : "Comment"}+ {getNumberFromMap(+ sessionCommentCounts.data,+ sessionId,+ ) ? (+ <ActionButtonCountBadge+ count={+ getNumberFromMap(+ sessionCommentCounts.data,+ sessionId,+ ) ?? 0+ }+ />+ ) : null}+ </Button>+ )}+ </CommentDrawerController>+ {!router.query.peek && (+ <DetailPageNav+ key="nav"+ currentId={sessionId}+ path={(entry) =>+ `/project/${projectId}/sessions/${entry.id}`+ }+ listKey="sessions"+ compact+ />+ )}+ {!isModernSessionEnabled ? (+ <label className="flex items-center gap-1.5">+ <Switch+ checked={showCorrections}+ onCheckedChange={setShowCorrectionsForSession}+ size="sm"+ />+ <span className="text-muted-foreground text-xs">+ Show corrections+ </span>+ </label>+ ) : (+ <ModernSessionHeaderActionsController+ projectId={projectId}+ sessionId={sessionId}+ isPublic={session.public}+ {...(!isSessionTimelineEnabled+ ? {+ showCorrections,+ showInlineToolCalls,+ showSystemPrompt,+ onShowCorrectionsChange:+ setShowCorrectionsForSession,+ onShowInlineToolCallsChange:+ setInlineToolCallsForSession,+ onShowSystemPromptChange:+ setShowSystemPromptForSession,+ }+ : {})}+ />+ )}+ </>+ ),+ // Mobile compact header: the same session actions as full-width+ // labeled menu rows for the `⋯` overflow popover, instead of the+ // inline icon toolbar. Session-to-session nav stays desktop-only.+ actionButtonsMenu: ({ closeMenu }) => (+ <>+ <ModernSessionHeaderActionsController+ projectId={projectId}+ sessionId={sessionId}+ isPublic={session.public}+ layout="menu"+ />+ <CommentDrawerController+ projectId={projectId}+ count={getNumberFromMap(+ sessionCommentCounts.data,+ sessionId,+ )}+ >+ {({ disabled, openDrawer }) => {+ const commentCount = getNumberFromMap(+ sessionCommentCounts.data,+ sessionId,+ );+ return (+ <HeaderActionMenuRow+ label={commentCount ? "Comments" : "Comment"}+ icon={+ disabled ? (+ <MessageSquareOff size="base" />+ ) : (+ <MessageSquare size="base" />+ )+ }+ badge={+ !disabled && commentCount ? (+ <ActionButtonCountBadge count={commentCount} />+ ) : null+ }+ disabled={disabled}+ onClick={() => {+ closeMenu({ handoffFocus: true });+ openDrawer({+ type: "comments",+ objectId: sessionId,+ objectType: "SESSION",+ });+ }}+ />+ );+ }}+ </CommentDrawerController>+ <HeaderActionMenuRow+ label="Score"+ icon={+ annotateDisabled ? (+ <LockIcon size="base" />+ ) : (+ <Plus size="base" />+ )+ }+ badge={+ isModernSessionEnabled && annotationCount > 0 ? (+ <ActionButtonCountBadge count={annotationCount} />+ ) : null+ }+ disabled={annotateDisabled}+ onClick={() => {+ closeMenu({ handoffFocus: true });+ openAnnotateRef.current({scoreTarget: { type: "session", sessionId },scores: session.scores,analyticsData: {@@ -1850,428 +2110,262 @@ const LoadedSessionEventsPage: React.FC<{projectId,environment: session.environment,},- })- }- >- {disabled ? (- <LockIcon size="base" color="default" />- ) : (- <SquarePen size="base" color="default" />- )}- Annotate- {isModernSessionEnabled && annotationCount > 0 ? (- <ActionButtonCountBadge count={annotationCount} />- ) : null}- </Button>- )}- </AnnotateDrawerController>- <CommentDrawerController- key="comment"- projectId={projectId}- count={getNumberFromMap(sessionCommentCounts.data, sessionId)}- >- {({ disabled, openDrawer }) => (- <Button- type="button"- variant="ghost"- size="sm"- disabled={disabled}- className={headerActionClassName}- onClick={() =>- openDrawer({- type: "comments",- objectId: sessionId,- objectType: "SESSION",- })- }+ });+ }}+ />+ <ConnectedSessionAddToDropdownMenuController+ projectId={projectId}+ sessionId={sessionId}+ analyticsData={{ source: "SessionDetail", isV4: true }}>- {disabled ? (- <MessageSquareOff size="base" color="default" />- ) : (- <MessageSquare size="base" color="default" />- )}- {getNumberFromMap(sessionCommentCounts.data, sessionId)- ? "Comments"- : "Comment"}- {getNumberFromMap(- sessionCommentCounts.data,- sessionId,- ) ? (- <ActionButtonCountBadge- count={- getNumberFromMap(- sessionCommentCounts.data,- sessionId,- ) ?? 0+ {({ getTriggerProps, totalCount }) => (+ <HeaderActionMenuRow+ label="Add to"+ icon={<Plus size="base" />}+ badge={+ totalCount > 0 ? (+ <ActionButtonCountBadge count={totalCount} />+ ) : null}+ {...getTriggerProps()}/>- ) : null}- </Button>- )}- </CommentDrawerController>- {!router.query.peek && (- <DetailPageNav- key="nav"- currentId={sessionId}- path={(entry) =>- `/project/${projectId}/sessions/${entry.id}`- }- listKey="sessions"- compact- />- )}- {!isModernSessionEnabled ? (- <label className="flex items-center gap-1.5">- <Switch- checked={showCorrections}- onCheckedChange={setShowCorrectionsForSession}- size="sm"- />- <span className="text-muted-foreground text-xs">- Show corrections- </span>- </label>- ) : (- <ModernSessionHeaderActionsController- projectId={projectId}- sessionId={sessionId}- isPublic={session.public}- {...(!isSessionTimelineEnabled- ? {- showCorrections,- showInlineToolCalls,- showSystemPrompt,- onShowCorrectionsChange: setShowCorrectionsForSession,- onShowInlineToolCallsChange:- setInlineToolCallsForSession,- onShowSystemPromptChange:- setShowSystemPromptForSession,- }- : {- useRootIO: transcriptSource === "root",- onUseRootIOChange: (checked: boolean) =>- setTranscriptSource(- checked ? "root" : "generations",- ),- })}- />- )}- </>- ),- // Mobile compact header: the same session actions as full-width- // labeled menu rows for the `⋯` overflow popover, instead of the- // inline icon toolbar. Session-to-session nav stays desktop-only.- actionButtonsMenu: ({ closeMenu }) => (- <>- <ModernSessionHeaderActionsController- projectId={projectId}- sessionId={sessionId}- isPublic={session.public}- layout="menu"- {...(isModernSessionEnabled && isSessionTimelineEnabled- ? {- useRootIO: transcriptSource === "root",- onUseRootIOChange: (checked: boolean) =>- setTranscriptSource(checked ? "root" : "generations"),- }- : {})}- />- <CommentDrawerController- projectId={projectId}- count={getNumberFromMap(sessionCommentCounts.data, sessionId)}- >- {({ disabled, openDrawer }) => {- const commentCount = getNumberFromMap(- sessionCommentCounts.data,- sessionId,- );- return (- <HeaderActionMenuRow- label={commentCount ? "Comments" : "Comment"}- icon={- disabled ? (- <MessageSquareOff size="base" />- ) : (- <MessageSquare size="base" />- )- }- badge={- !disabled && commentCount ? (- <ActionButtonCountBadge count={commentCount} />- ) : null- }- disabled={disabled}- onClick={() => {- closeMenu({ handoffFocus: true });- openDrawer({- type: "comments",- objectId: sessionId,- objectType: "SESSION",- });- }}+ )}+ </ConnectedSessionAddToDropdownMenuController>+ {webCalloutAction && (+ <WebCalloutButton+ action={webCalloutAction}+ layout="menu"/>- );- }}- </CommentDrawerController>- <HeaderActionMenuRow- label="Score"- icon={- annotateDisabled ? (- <LockIcon size="base" />- ) : (- <Plus size="base" />- )- }- badge={- isModernSessionEnabled && annotationCount > 0 ? (- <ActionButtonCountBadge count={annotationCount} />- ) : null- }- disabled={annotateDisabled}- onClick={() => {- closeMenu({ handoffFocus: true });- openAnnotateRef.current({- scoreTarget: { type: "session", sessionId },- scores: session.scores,- analyticsData: {- type: "session",- source: "SessionDetail",- isV4: true,- },- scoreMetadata: {- projectId,- environment: session.environment,- },- });- }}- />- <ConnectedSessionAddToDropdownMenuController- projectId={projectId}- sessionId={sessionId}- analyticsData={{ source: "SessionDetail", isV4: true }}- >- {({ getTriggerProps, totalCount }) => (- <HeaderActionMenuRow- label="Add to"- icon={<Plus size="base" />}- badge={- totalCount > 0 ? (- <ActionButtonCountBadge count={totalCount} />- ) : null- }- {...getTriggerProps()}- />- )}- </ConnectedSessionAddToDropdownMenuController>- {webCalloutAction && (- <WebCalloutButton action={webCalloutAction} layout="menu" />- )}- {!isModernSessionEnabled || !isSessionTimelineEnabled ? (- <label className="hover:bg-accent flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5">- <span className="text-sm">Show corrections</span>- <Switch- checked={showCorrections}- onCheckedChange={setShowCorrectionsForSession}- size="sm"- />- </label>- ) : null}- {isModernSessionEnabled && !isSessionTimelineEnabled ? (- <label className="hover:bg-accent flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5">- <span className="text-sm">Show system prompt</span>- <Switch- checked={showSystemPrompt}- onCheckedChange={setShowSystemPromptForSession}- size="sm"- />- </label>- ) : null}- </>- ),- }}- >- <SessionReviewWorkspace projectId={projectId}>- <div- className={- isModernSessionEnabled- ? "flex h-full min-h-0 flex-col overflow-hidden"- : "flex h-full flex-col overflow-auto"- }+ )}+ {!isModernSessionEnabled || !isSessionTimelineEnabled ? (+ <label className="hover:bg-accent flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5">+ <span className="text-sm">Show corrections</span>+ <Switch+ checked={showCorrections}+ onCheckedChange={setShowCorrectionsForSession}+ size="sm"+ />+ </label>+ ) : null}+ {isModernSessionEnabled && !isSessionTimelineEnabled ? (+ <label className="hover:bg-accent flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5">+ <span className="text-sm">Show system prompt</span>+ <Switch+ checked={showSystemPrompt}+ onCheckedChange={setShowSystemPromptForSession}+ size="sm"+ />+ </label>+ ) : null}+ </>+ ),+ }}>- {showRedesignBanner ? (- <SessionRedesignBanner- onDismiss={() => setIsRedesignBannerDismissed(true)}- />- ) : null}- {!isModernSessionEnabled && hasSessionControls ? (- <SessionControlsBar- isMobile={isMobile && !isModernSessionEnabled}- desktopClassName="bg-background sticky top-0 z-40 flex flex-wrap items-center gap-2 border-b p-4"- summary={- <>- <span className="text-sm font-bold">- Session controls- </span>- <span- className="text-muted-foreground min-w-0 truncate text-xs"- title={`${session.countTraces} traces · ${usdFormatter(- session.totalCost ?? 0,- 2,- )}`}- >- {session.countTraces} traces ·{" "}- {usdFormatter(session.totalCost ?? 0, 2)}- </span>- </>+ <SessionReviewWorkspace projectId={projectId}>+ <div+ className={+ isModernSessionEnabled+ ? "flex h-full min-h-0 flex-col overflow-hidden"+ : "flex h-full flex-col overflow-auto"}>- {/* Saved Views */}- {!isModernSessionEnabled ? (- <TableViewPresetsDrawer- viewConfig={{- tableName: TableViewPresetTableName.SessionDetail,- projectId,- controllers: viewControllers,- }}- currentState={{- orderBy: null,- filters: queryFilter.filterState,- columnOrder,- columnVisibility,- searchQuery: "",- }}- systemFilterPresets={SESSION_DETAIL_SYSTEM_PRESETS}- triggerId={SESSION_DETAIL_VIEW_TRIGGER_ID}+ {showRedesignBanner ? (+ <SessionRedesignBanner+ onDismiss={() => setIsRedesignBannerDismissed(true)}/>) : null}+ {!isModernSessionEnabled && hasSessionControls ? (+ <SessionControlsBar+ isMobile={isMobile && !isModernSessionEnabled}+ desktopClassName="bg-background sticky top-0 z-40 flex flex-wrap items-center gap-2 border-b p-4"+ summary={+ <>+ <span className="text-sm font-bold">+ Session controls+ </span>+ <span+ className="text-muted-foreground min-w-0 truncate text-xs"+ title={`${session.countTraces} traces · ${usdFormatter(+ session.totalCost ?? 0,+ 2,+ )}`}+ >+ {session.countTraces} traces ·{" "}+ {usdFormatter(session.totalCost ?? 0, 2)}+ </span>+ </>+ }+ >+ {/* Saved Views */}+ {!isModernSessionEnabled ? (+ <TableViewPresetsDrawer+ viewConfig={{+ tableName: TableViewPresetTableName.SessionDetail,+ projectId,+ controllers: viewControllers,+ }}+ currentState={{+ orderBy: null,+ filters: queryFilter.filterState,+ columnOrder,+ columnVisibility,+ searchQuery: "",+ }}+ systemFilterPresets={SESSION_DETAIL_SYSTEM_PRESETS}+ triggerId={SESSION_DETAIL_VIEW_TRIGGER_ID}+ />+ ) : null}- {/* Refines the selected view by filtering observations within each+ {/* Refines the selected view by filtering observations within eachtrace (it does not filter the list of traces) — labelled to sayso (LFE-10520). */}- {!isModernSessionEnabled ? (- <PopoverFilterBuilder- key={viewControllers.filterEditorResetKey}- columns={filterColumns}- filterState={visibleFilterState}- onChange={queryFilter.setFilterState}- columnsWithCustomSelect={filterColumnsWithCustomSelect}- label="Filter observations"- // Analytics (LFE-10781): session-detail observation refinement is a- // v3/legacy surface (the v4 events table filters via the grammar bar).- tableName="session-detail"- isV4={false}- />- ) : null}+ {!isModernSessionEnabled ? (+ <PopoverFilterBuilder+ key={viewControllers.filterEditorResetKey}+ columns={filterColumns}+ filterState={visibleFilterState}+ onChange={queryFilter.setFilterState}+ columnsWithCustomSelect={+ filterColumnsWithCustomSelect+ }+ label="Filter observations"+ // Analytics (LFE-10781): session-detail observation refinement is a+ // v3/legacy surface (the v4 events table filters via the grammar bar).+ tableName="session-detail"+ isV4={false}+ />+ ) : null}- {/* Separator */}- {!isModernSessionEnabled ? (- <Separator orientation="vertical" className="h-6" />- ) : null}+ {/* Separator */}+ {!isModernSessionEnabled ? (+ <Separator orientation="vertical" className="h-6" />+ ) : null}- {/* Stats stay in the toolbar for the existing card layout. Modern+ {/* Stats stay in the toolbar for the existing card layout. ModernSession shows trace count and cost in its minimap header. */}- {!isModernSessionEnabled ? (- <>- <Badge- color="primary"- text={`Total traces: ${session.countTraces}`}- />- <Badge- color="primary"- text={`Total cost: ${usdFormatter(session.totalCost ?? 0, 2)}`}- />- </>- ) : null}+ {!isModernSessionEnabled ? (+ <>+ <Badge+ color="primary"+ text={`Total traces: ${session.countTraces}`}+ />+ <Badge+ color="primary"+ text={`Total cost: ${usdFormatter(session.totalCost ?? 0, 2)}`}+ />+ </>+ ) : null}- {/* Users */}- {session.users?.length ? (- <SessionUsers projectId={projectId} users={session.users} />- ) : null}+ {/* Users */}+ {session.users?.length ? (+ <SessionUsers+ projectId={projectId}+ users={session.users}+ />+ ) : null}- {/* Scores */}- <SessionScores scores={session.scores} />- </SessionControlsBar>- ) : null}- {!isModernSessionEnabled ? (- <div ref={parentRef} className="flex-1 overflow-auto p-4">- <div- style={{- height: `${virtualizer.getTotalSize()}px`,- width: "100%",- position: "relative",- }}- >- {virtualItems.map((virtualItem) => {- const trace = traces?.[virtualItem.index];- if (!trace) return null;-- return (- <SessionVirtualizedRow- key={virtualItem.key}- itemKey={String(virtualItem.key)}- measurementKey={`${String(virtualItem.key)}:${showCorrections}:${visibleFilterMeasurementKey}`}- source="events"- virtualItem={virtualItem}- virtualizer={virtualizer}- >- <LazySessionTraceEventsRow- trace={trace}- projectId={projectId}- sessionId={sessionId}- openPeek={openPeek}- traceCommentCounts={asCommentCounts(- traceCommentCounts.data,- )}- index={virtualItem.index}- filterState={visibleFilterState}- viewLabel={viewLabel}- />- </SessionVirtualizedRow>- );- })}- </div>+ {/* Scores */}+ <SessionScores scores={session.scores} />+ </SessionControlsBar>+ ) : null}+ {!isModernSessionEnabled ? (+ <div ref={parentRef} className="flex-1 overflow-auto p-4">+ <div+ style={{+ height: `${virtualizer.getTotalSize()}px`,+ width: "100%",+ position: "relative",+ }}+ >+ {virtualItems.map((virtualItem) => {+ const trace = traces?.[virtualItem.index];+ if (!trace) return null;++ return (+ <SessionVirtualizedRow+ key={virtualItem.key}+ itemKey={String(virtualItem.key)}+ measurementKey={`${String(virtualItem.key)}:${showCorrections}:${visibleFilterMeasurementKey}`}+ source="events"+ virtualItem={virtualItem}+ virtualizer={virtualizer}+ >+ <LazySessionTraceEventsRow+ trace={trace}+ projectId={projectId}+ sessionId={sessionId}+ openPeek={openPeek}+ traceCommentCounts={asCommentCounts(+ traceCommentCounts.data,+ )}+ index={virtualItem.index}+ filterState={visibleFilterState}+ viewLabel={viewLabel}+ />+ </SessionVirtualizedRow>+ );+ })}+ </div>+ </div>+ ) : (+ <ModernSession+ customization={+ isSessionTimelineEnabled && isInternalFeaturesEnabled+ ? {+ activeFilterCount: traceFilters.length,+ onCustomizeView: openDialog,+ onClearFilters: () => setTraceFilters([]),+ }+ : undefined+ }+ headerDividerTone={+ showRedesignBanner ? "orange" : "default"+ }+ isTimelineEnabled={isSessionTimelineEnabled}+ session={session}+ tracesState={+ isTracesSuccess+ ? { type: "loaded", traces: traces ?? [] }+ : { type: "loading" }+ }+ projectId={projectId}+ sessionId={sessionId}+ openPeek={openPeek}+ traceCommentCounts={asCommentCounts(+ traceCommentCounts.data,+ )}+ filterState={+ isSessionTimelineEnabled+ ? traceFilters+ : visibleFilterState+ }+ filterMeasurementKey={visibleFilterMeasurementKey}+ viewLabel={viewLabel}+ showInlineToolCalls={showInlineToolCalls}+ showSystemPrompt={showSystemPrompt}+ filterControlsProps={{+ projectId,+ filterState: visibleFilterState,+ filterColumns,+ filterColumnsWithCustomSelect,+ onChange: queryFilter.setFilterState,+ viewControllers,+ currentViewState: {+ orderBy: null,+ filters: queryFilter.filterState,+ columnOrder,+ columnVisibility,+ searchQuery: "",+ },+ }}+ onFilterObservationByName={filterObservationsByName}+ />+ )}</div>- ) : (- <ModernSession- transcriptSource={transcriptSource}- headerDividerTone={showRedesignBanner ? "orange" : "default"}- isTimelineEnabled={isSessionTimelineEnabled}- session={session}- tracesState={- isTracesSuccess- ? { type: "loaded", traces: traces ?? [] }- : { type: "loading" }- }- projectId={projectId}- sessionId={sessionId}- openPeek={openPeek}- traceCommentCounts={asCommentCounts(traceCommentCounts.data)}- filterState={visibleFilterState}- filterMeasurementKey={visibleFilterMeasurementKey}- viewLabel={viewLabel}- showInlineToolCalls={showInlineToolCalls}- showSystemPrompt={showSystemPrompt}- filterControlsProps={{- projectId,- filterState: visibleFilterState,- filterColumns,- filterColumnsWithCustomSelect,- onChange: queryFilter.setFilterState,- viewControllers,- currentViewState: {- orderBy: null,- filters: queryFilter.filterState,- columnOrder,- columnVisibility,- searchQuery: "",- },- }}- onFilterObservationByName={filterObservationsByName}- />- )}- </div>- </SessionReviewWorkspace>- </Page>+ </SessionReviewWorkspace>+ </Page>+ )}+ </DialogController></TraceReviewPanelProvider><TablePeekViewTraceDetailitemType="TRACE"diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline.tsxindex e1ca392806..20f244998d 100644--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline.tsx@@ -1,4 +1,5 @@-import { useRef, useState } from "react";+import { type ComponentProps, useRef, useState } from "react";+import { type FilterState } from "@langfuse/shared";import {ConnectedSessionConversationTimeline,@@ -20,21 +21,25 @@ const EMPTY_TRACES: EventSessionTrace[] = [];type OpenPeek = (id: string, row: EventSessionTrace) => void;type ConnectedModernSessionBodyTimelineProps = {- transcriptSource: "root" | "generations";+ customization?: ComponentProps<+ typeof ConnectedSessionConversationTimeline+ >["customization"];tracesState:| { type: "loading" }| { type: "loaded"; traces: EventSessionTrace[] };projectId: string;sessionId: string;openPeek: OpenPeek;+ filterState?: FilterState;};export function ConnectedModernSessionBodyTimeline({- transcriptSource,+ customization,tracesState,projectId,sessionId,openPeek,+ filterState,}: ConnectedModernSessionBodyTimelineProps) {const traces =tracesState.type === "loaded" ? tracesState.traces : EMPTY_TRACES;@@ -101,7 +106,7 @@ export function ConnectedModernSessionBodyTimeline({projectId,traces: traces.map((trace, index) => ({ trace, turnNumber: index + 1 })),activeTraceIds: activeTranscriptTraceIds,- transcriptSource,+ filter: filterState,});const allTranscriptsLoaded =tracesState.type === "loaded" &&@@ -112,7 +117,7 @@ export function ConnectedModernSessionBodyTimeline({traceId: trace.id,timestamp: trace.timestamp,fallbackToRootIO: true,- transcriptSource,+ filter: filterState,}) !== undefined,);const searchQuery = allTranscriptsLoaded@@ -232,6 +237,7 @@ export function ConnectedModernSessionBodyTimeline({return (<ConnectedSessionConversationTimeline+ customization={customization}{...(tracesState.type === "loading"? { state: "loading" }: {diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/ConnectedSessionConversationTimeline.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/ConnectedSessionConversationTimeline.tsxindex 815cd8afe0..66610419db 100644--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/ConnectedSessionConversationTimeline.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/ConnectedSessionConversationTimeline.tsx@@ -24,6 +24,9 @@ export function ConnectedSessionConversationTimeline("traces" | "controller">) & {+ customization?: ComponentProps<+ typeof SessionConversationalView+ >["customization"];traces: readonly ConnectedSessionConversationTimelineItem[];projectId: string;openPeek: (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.tsxindex 41b4bc2880..d21e007d57 100644--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.tsx@@ -5,7 +5,8 @@ import {useRef,useState,} from "react";-import { Search } from "@langfuse/icons";+import { Filter, Search } from "@langfuse/icons";+import { Tooltip } from "@/src/components/design-system/Tooltip/Tooltip";import { Input } from "@/src/components/ui/input";import {ResizableHandle,@@ -44,12 +45,16 @@ export function SessionConversationalView(isSearchPending: boolean;})) & {+ customization?: ComponentProps<+ typeof SessionConversationSidebar+ >["customization"];traces: readonly (ComponentProps<typeof SessionConversationTimeline>["traces"][number] & { trace: EventSessionTrace })[];controller: SessionConversationTimelineController;},) {+ const { customization } = props;const transcriptRef = useRef<HTMLDivElement>(null);const [collapsedTraceIds, setCollapsedTraceIds] = useState<Set<string>>(new Set(),@@ -284,7 +289,7 @@ export function SessionConversationalView(className="bg-background relative flex min-h-0 flex-1 flex-col overflow-hidden">{!showSidebar && (- <div className="shrink-0 border-b px-2 py-2.5">+ <div className="flex shrink-0 items-center gap-1 border-b px-2 py-2.5"><DialogControllerrenderDialog={({ closeDialog }) => (<Dialog title="Search session" closeOnInteractionOutside>@@ -354,6 +359,23 @@ export function SessionConversationalView(</DialogTrigger>)}</DialogController>+ {customization && (+ <Tooltip+ label={`Customize view${customization.activeFilterCount > 0 ? ` (${customization.activeFilterCount})` : ""}`}+ >+ {({ getTriggerProps }) => (+ <button+ {...getTriggerProps()}+ type="button"+ className="border-input bg-background hover:bg-accent hover:text-accent-foreground focus-visible:ring-ring inline-flex size-7 shrink-0 items-center justify-center rounded-sm border focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none"+ aria-label="Customize view"+ onClick={customization.onCustomizeView}+ >+ <Filter size="sm" aria-hidden="true" />+ </button>+ )}+ </Tooltip>+ )}</div>)}<ResizablePanelGroup@@ -370,7 +392,10 @@ export function SessionConversationalView(maxSize="50%"className="h-full min-h-0">- <SessionConversationSidebar {...sidebarProps} />+ <SessionConversationSidebar+ {...sidebarProps}+ customization={props.customization}+ /></ResizablePanel>)}{showSidebar && (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.tsxindex 019b910c77..330ec20cde 100644--- 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.tsx@@ -1,6 +1,7 @@import preview from "@/.storybook/preview";import { expect, fn, userEvent, waitFor, within } from "storybook/test";import { type ComponentProps, useState } from "react";+import { Button } from "@/src/components/design-system/Button/Button";import { SessionConversationSidebar } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar";type Props = ComponentProps<typeof SessionConversationSidebar>;@@ -125,6 +126,15 @@ export const DarkMode = meta.story({});export const Empty = meta.story({ args: { ...loadedArgs, traces: [] } });+export const CustomizeView = meta.story({+ args: {+ ...loadedArgs,+ searchActions: (+ <Button variant="ghost" size="sm" text="Customize view" onClick={fn()} />+ ),+ },+});+export const GroupedToolStatuses = meta.story({name: "(Test) Grouped and Individual Tool Status Indicators",args: {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.tsxindex cadf42b6e3..9c8eb53d3c 100644--- 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.tsx@@ -8,7 +8,8 @@ import {type UIEvent,} from "react";import { useVirtualizer } from "@tanstack/react-virtual";-import { ChevronDown, Search } from "@langfuse/icons";+import { ChevronDown, Filter, Search } from "@langfuse/icons";+import { Tooltip } from "@/src/components/design-system/Tooltip/Tooltip";import { type Observation } from "@langfuse/shared";import { Input } from "@/src/components/ui/input";import { SessionToolTooltip } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionToolTooltip/SessionToolTooltip";@@ -73,8 +74,15 @@ export function SessionConversationSidebar(isLoadingTranscripts: boolean;transcriptLoadError: boolean;}- ) & { searchVisibility?: "hidden" },+ ) & {+ searchVisibility?: "hidden";+ customization?: {+ activeFilterCount: number;+ onCustomizeView: () => void;+ };+ },) {+ const { customization } = props;const traces = props.state === "loaded" ? props.traces : EMPTY_TRACES;const activeTraceId =props.state === "loaded" ? props.activeTraceId : undefined;@@ -238,11 +246,11 @@ export function SessionConversationSidebar(><divclassName={cn(- "shrink-0 p-4",+ "flex shrink-0 items-center gap-1 p-4",props.searchVisibility === "hidden" && "hidden",)}>- <div className="relative min-w-0">+ <div className="relative min-w-0 flex-1"><Searchsize="base"color="tertiary"@@ -256,6 +264,23 @@ export function SessionConversationSidebar(className="h-7 rounded-sm bg-transparent pl-7 font-mono text-xs"/></div>+ {customization && (+ <Tooltip+ label={`Customize view${customization.activeFilterCount > 0 ? ` (${customization.activeFilterCount})` : ""}`}+ >+ {({ getTriggerProps }) => (+ <button+ {...getTriggerProps()}+ type="button"+ className="border-input bg-background hover:bg-accent hover:text-accent-foreground focus-visible:ring-ring inline-flex size-7 shrink-0 items-center justify-center rounded-sm border focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none"+ aria-label="Customize view"+ onClick={customization.onCustomizeView}+ >+ <Filter size="sm" aria-hidden="true" />+ </button>+ )}+ </Tooltip>+ )}</div><div className="flex min-h-0 flex-1 flex-col gap-2 px-4 pt-0.5 pb-4">{[0, 1, 2].map((index) => (@@ -288,11 +313,11 @@ export function SessionConversationSidebar(><divclassName={cn(- "relative z-10 shrink-0 p-4",+ "relative z-10 flex shrink-0 items-center gap-1 p-4",props.searchVisibility === "hidden" && "hidden",)}>- <div className="relative min-w-0">+ <div className="relative min-w-0 flex-1"><Searchsize="base"color="tertiary"@@ -309,6 +334,23 @@ export function SessionConversationSidebar(className="h-7 rounded-sm bg-transparent pl-7 font-mono text-xs"/></div>+ {customization && (+ <Tooltip+ label={`Customize view${customization.activeFilterCount > 0 ? ` (${customization.activeFilterCount})` : ""}`}+ >+ {({ getTriggerProps }) => (+ <button+ {...getTriggerProps()}+ type="button"+ className="border-input bg-background hover:bg-accent hover:text-accent-foreground focus-visible:ring-ring inline-flex size-7 shrink-0 items-center justify-center rounded-sm border focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none"+ aria-label="Customize view"+ onClick={customization.onCustomizeView}+ >+ <Filter size="sm" aria-hidden="true" />+ </button>+ )}+ </Tooltip>+ )}{isListScrolled ? (<divaria-hidden="true"diff --git a/web/src/features/sessions/hooks/useSessionTraceTranscripts.clienttest.tsx b/web/src/features/sessions/hooks/useSessionTraceTranscripts.clienttest.tsxindex 765161380d..b1dcd5d4d9 100644--- a/web/src/features/sessions/hooks/useSessionTraceTranscripts.clienttest.tsx+++ b/web/src/features/sessions/hooks/useSessionTraceTranscripts.clienttest.tsx@@ -40,21 +40,18 @@ function setup(client = new QueryClient()) {client,...renderHook(({- transcriptSource,- }: Pick<- Parameters<typeof useSessionTraceTranscripts>[0],- "transcriptSource"- >) =>+ filter,+ }: Pick<Parameters<typeof useSessionTraceTranscripts>[0], "filter">) =>useSessionTraceTranscripts({projectId: "project",- transcriptSource,+ filter,traces,activeTraceIds: new Set(traces.slice(0, 6).map(({ trace }) => trace.id),),}),{- initialProps: { transcriptSource: "generations" },+ initialProps: {},wrapper: ({ children }: { children: ReactNode }) => (<QueryClientProvider client={client}>{children}</QueryClientProvider>),@@ -67,15 +64,21 @@ beforeEach(() => {query.mockReset();});-it("uses separate cached transcripts when switching sources", async () => {+it("keys transcripts by observation filters and restores the unfiltered cache when cleared", async () => {query.mockResolvedValue(output);const { rerender, result, unmount, client } = setup();await waitFor(() =>expect(result.current.get("trace-5")?.state).toBe("loaded"),);- expect(query).toHaveBeenCalledTimes(6);-- rerender({ transcriptSource: "root" });+ const filter = [+ {+ column: "level",+ type: "string" as const,+ operator: "=" as const,+ value: "ERROR",+ },+ ];+ rerender({ filter });await waitFor(() => expect(query).toHaveBeenCalledTimes(12));await waitFor(() =>expect(result.current.get("trace-5")?.state).toBe("loaded"),@@ -83,10 +86,11 @@ it("uses separate cached transcripts when switching sources", async () => {expect(query.mock.calls.slice(6)- .every(([input]) => input.transcriptSource === "root"),+ .every(+ ([input]) => JSON.stringify(input.filter) === JSON.stringify(filter),+ ),).toBe(true);-- rerender({ transcriptSource: "generations" });+ rerender({});await waitFor(() =>expect(result.current.get("trace-5")?.state).toBe("loaded"),);diff --git a/web/src/features/sessions/hooks/useSessionTraceTranscripts.ts b/web/src/features/sessions/hooks/useSessionTraceTranscripts.tsindex 3e326f6e40..b58025bd21 100644--- a/web/src/features/sessions/hooks/useSessionTraceTranscripts.ts+++ b/web/src/features/sessions/hooks/useSessionTraceTranscripts.ts@@ -14,14 +14,12 @@ export function useSessionTraceTranscripts({projectId,traces,activeTraceIds,- transcriptSource,+ filter,}: {projectId: string;traces: readonly { trace: EventSessionTrace; turnNumber: number }[];activeTraceIds: ReadonlySet<string>;- transcriptSource: NonNullable<- RouterInputs["events"]["transcriptByTraceId"]["transcriptSource"]- >;+ filter?: RouterInputs["events"]["transcriptByTraceId"]["filter"];}): Map<string, SessionTraceTranscriptState> {const [queue] = useState(() => new PQueue({ concurrency: 4 }));const utils = api.useUtils();@@ -35,7 +33,7 @@ export function useSessionTraceTranscripts({traceId: trace.id,timestamp: trace.timestamp,fallbackToRootIO: true,- transcriptSource,+ filter,};return {queryKey: getQueryKey(api.events.transcriptByTraceId, input, "query"),diff --git a/web/src/features/sessions/sessionTraceSearchRegistry.clienttest.ts b/web/src/features/sessions/sessionTraceSearchRegistry.clienttest.tsnew file mode 100644index 0000000000..47b2faa262--- /dev/null+++ b/web/src/features/sessions/sessionTraceSearchRegistry.clienttest.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from "vitest";+import { sessionTraceFilterSchema } from "@langfuse/shared";+import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";+import { planCommit } from "@/src/features/search-bar/lib/commit";+import { SESSION_TRACE_FIELD_REGISTRY } from "./sessionTraceSearchRegistry";++describe("session trace search registry", () => {+ it.each(["name", "traceName"])(+ "round-trips exact exclusions for %s",+ (column) => {+ const filters = sessionTraceFilterSchema.parse([+ {+ column,+ type: "stringOptions",+ operator: "none of",+ value: ["agent"],+ },+ ]);+ const query = filterStateToQueryText(+ filters,+ {},+ SESSION_TRACE_FIELD_REGISTRY,+ );+ expect(query.skippedFilters).toEqual([]);+ const restored = planCommit(+ query.text,+ undefined,+ SESSION_TRACE_FIELD_REGISTRY,+ );+ expect(restored.status).toBe("committed");+ if (restored.status !== "committed") return;+ expect(restored.filters).toEqual(filters);+ },+ );++ it("lowers trace and observation syntax into supported filters and round-trips saved views", () => {+ const result = planCommit(+ "traceName:chat name:=agent type:=GENERATION level:=ERROR isRootObservation:true",+ undefined,+ SESSION_TRACE_FIELD_REGISTRY,+ );+ expect(result.status).toBe("committed");+ if (result.status !== "committed") return;+ expect(sessionTraceFilterSchema.safeParse(result.filters).success).toBe(+ true,+ );+ expect(result.filters.map(({ column }) => column)).toEqual([+ "traceName",+ "name",+ "type",+ "level",+ "isRootObservation",+ ]);+ const query = filterStateToQueryText(+ result.filters,+ {},+ SESSION_TRACE_FIELD_REGISTRY,+ );+ expect(query.skippedFilters).toEqual([]);+ const restored = planCommit(+ query.text,+ undefined,+ SESSION_TRACE_FIELD_REGISTRY,+ );+ expect(restored.status).toBe("committed");+ if (restored.status !== "committed") return;+ expect(restored.filters).toEqual(result.filters);+ });+});diff --git a/web/src/features/sessions/sessionTraceSearchRegistry.ts b/web/src/features/sessions/sessionTraceSearchRegistry.tsnew file mode 100644index 0000000000..6e3545d334--- /dev/null+++ b/web/src/features/sessions/sessionTraceSearchRegistry.ts@@ -0,0 +1,47 @@+import { sessionTraceFilterColumns } from "@langfuse/shared";+import { fieldRegistryFromColumns } from "@/src/features/search-bar/lib/fields";++export const SESSION_TRACE_FIELD_REGISTRY = fieldRegistryFromColumns(+ sessionTraceFilterColumns.filter((column) =>+ ["name", "traceName", "type", "level", "isRootObservation"].includes(+ column.id,+ ),+ ),+ {+ id: "sessionTraces",+ allowFreeText: false,+ defaultSearchType: [],+ metadata: false,+ searchPlaceholder: "Filter observations… e.g. level:=ERROR",+ searchExamples: [+ "name:=agent",+ "traceName:=chat",+ "type:=GENERATION",+ "level:=ERROR",+ "isRootObservation:true",+ ],+ fields: {+ name: { aliases: ["observationName"] },+ },+ filterStateErrors: (filters) =>+ filters.every((filter) => {+ if (filter.column === "isRootObservation")+ return filter.type === "boolean" && filter.operator === "=";+ if (+ filter.type === "stringOptions" &&+ (filter.column === "name" || filter.column === "traceName")+ )+ return filter.operator === "none of";+ if (filter.type !== "string") return false;+ if (filter.column === "name" || filter.column === "traceName")+ return ["=", "contains", "does not contain"].includes(+ filter.operator,+ );+ return (+ ["type", "level"].includes(filter.column) && filter.operator === "="+ );+ })+ ? []+ : ["These filters are not supported for session observations."],+ },+);diff --git a/web/src/features/traces/components/VirtualizedTreeNodeWrapper.tsx b/web/src/features/traces/components/VirtualizedTreeNodeWrapper.tsxindex 6f8d7a3f2e..ab18e592dd 100644--- a/web/src/features/traces/components/VirtualizedTreeNodeWrapper.tsx+++ b/web/src/features/traces/components/VirtualizedTreeNodeWrapper.tsx@@ -169,6 +169,7 @@ export function VirtualizedTreeNodeWrapper(<div className="flex w-7 shrink-0 items-start justify-end py-0.5 pr-1">{loaded && hasChildren && (<Button+ aria-label={isCollapsed ? "Expand branch" : "Collapse branch"}aria-expanded={!isCollapsed}data-expand-buttonsize="icon"diff --git a/web/src/hooks/usePrevious.clienttest.ts b/web/src/hooks/usePrevious.clienttest.tsnew file mode 100644index 0000000000..e8f1fb8b49--- /dev/null+++ b/web/src/hooks/usePrevious.clienttest.ts@@ -0,0 +1,33 @@+import { renderHook } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import { usePrevious } from "./usePrevious";++describe("usePrevious", () => {+ it("returns the previous committed value by default", () => {+ const { result, rerender } = renderHook((value) => usePrevious(value), {+ initialProps: "first",+ });+ expect(result.current).toBeUndefined();+ rerender("second");+ expect(result.current).toBe("first");+ rerender("third");+ expect(result.current).toBe("second");+ });++ it("retains the last saved value across consecutive skipped renders", () => {+ const { result, rerender } = renderHook(+ ({ value, valid }) => usePrevious(value, valid),+ { initialProps: { value: "invalid", valid: false } },+ );+ expect(result.current).toBeUndefined();+ rerender({ value: "first valid", valid: true });+ expect(result.current).toBeUndefined();+ rerender({ value: "invalid", valid: false });+ expect(result.current).toBe("first valid");+ rerender({ value: "still invalid", valid: false });+ expect(result.current).toBe("first valid");+ rerender({ value: "second valid", valid: true });+ rerender({ value: "invalid again", valid: false });+ expect(result.current).toBe("second valid");+ });+});diff --git a/web/src/hooks/usePrevious.ts b/web/src/hooks/usePrevious.tsnew file mode 100644index 0000000000..d2c7ba2e12--- /dev/null+++ b/web/src/hooks/usePrevious.ts@@ -0,0 +1,12 @@+import { useEffect, useRef } from "react";++/** Returns the value saved after the previous committed render. */+export function usePrevious<T>(value: T, shouldSave = true): T | undefined {+ const previous = useRef<T | undefined>(undefined);++ useEffect(() => {+ if (shouldSave) previous.current = value;+ }, [value, shouldSave]);++ return previous.current;+}diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.tsindex e524e8422c..60de9d109f 100644--- a/web/src/server/api/routers/sessions.ts+++ b/web/src/server/api/routers/sessions.ts@@ -10,6 +10,7 @@ import {getSessionsTableCountFromEvents,getSessionMetricsFromEvents,getSessionTracesFromEvents,+ getObservationsForTraceFromEventsTable,getObservationsWithModelDataFromEventsTable,getObservationFullIOForSessionFromEventsTable,getTracesGroupedByTags,@@ -50,6 +51,7 @@ import {type SessionOptions,type ScoreDomain,LISTABLE_SCORE_TYPES,+ sessionTraceFilterSchema,} from "@langfuse/shared";import { TRPCError } from "@trpc/server";import Decimal from "decimal.js";@@ -736,6 +738,52 @@ export const sessionRouter = createTRPCRouter({scores: toDomainArrayWithStringifiedMetadata(validatedScores),};}),+ previewTree: protectedGetSessionProcedure+ .input(+ z.object({+ projectId: z.string(),+ sessionId: z.string(),+ }),+ )+ .query(async ({ input }) => {+ const traces = await getSessionTracesFromEvents({+ ...input,+ filter: [],+ limit: 5,+ });+ if (traces.length === 0) return [];+ return Promise.all(+ traces.map(async (trace) => {+ const source = {+ projectId: input.projectId,+ traceId: trace.id,+ timestamp: trace.timestamp,+ };+ const structure = await getObservationsForTraceFromEventsTable({+ ...source,+ limit: 200,+ selectMetadata: true,+ });+ return {+ id: trace.id,+ name: trace.name,+ truncated: structure.totalCount > structure.observations.length,+ observations: structure.observations.map((observation) => ({+ id: observation.id,+ parentObservationId: observation.parentObservationId,+ name: observation.name,+ type: observation.type,+ level: observation.level,+ isRootObservation: observation.isRootObservation,+ userId: observation.userId,+ environment: observation.environment,+ traceTags: observation.traceTags,+ metadata: observation.metadata,+ })),+ };+ }),+ );+ }),byIdWithScoresFromEvents: protectedGetSessionProcedure.input(z.object({@@ -822,12 +870,14 @@ export const sessionRouter = createTRPCRouter({z.object({sessionId: z.string(), // used for security checkprojectId: z.string(), // used for security check+ filter: sessionTraceFilterSchema.optional(),}),).query(async ({ input }) => {const traces = await getSessionTracesFromEvents({projectId: input.projectId,sessionId: input.sessionId,+ filter: input.filter ?? [],});const chunks = chunk(traces, 500);diff --git a/worker/src/features/database-read-stream/observation-stream.ts b/worker/src/features/database-read-stream/observation-stream.tsindex 39282a602e..dc3fd94101 100644--- a/worker/src/features/database-read-stream/observation-stream.ts+++ b/worker/src/features/database-read-stream/observation-stream.ts@@ -658,6 +658,7 @@ const getObservationStreamFromEvents = async (release: _release,bookmarked: _bookmarked,public: _public,+ isRootObservation: _isRootObservation,skillsAvailable: _skillsAvailable,skillsResourceLoaded: _skillsResourceLoaded,userId,