Skip to content

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

feat(session): show real v4 sessions with a View model + visible filters (LFE-10520) (#14727)

Nikita Kabardin6bc10674d51a
diff --git a/.agents/skills/seed-test-data/SKILL.md b/.agents/skills/seed-test-data/SKILL.md
index 70d720a783..8d800862f2 100644
--- a/.agents/skills/seed-test-data/SKILL.md
+++ b/.agents/skills/seed-test-data/SKILL.md
@@ -36,6 +36,7 @@ this.
| Async parents whose subtree outlives their own span (subtree wall-clock duration badge) | add `--async-parents` to `trace-tree` (root + hub end immediately while children keep running) |
| A realistic agent flow over a timeline (graph view + scrubbable timeline) | `pnpm run seed -- agent-timeline --turns 6 --v4` (LangGraph refine loop planner→retriever→generator→critic→loop, staggered in time; add `--timing-only` for the pure timing fallback) |
| A super tough session (v3 legacy session view) | `pnpm run seed -- long-session --traces 300 --observations-per-trace 8` |
+| Diverse v4 session shapes (chat / coding-agent / mixed) for the session-detail view | `pnpm run seed -- session-shapes --shape all` (the `agent` shape has I/O on AGENT/TOOL with no GENERATION — pre-LFE-10520 the "first generation" default rendered empty cards for it; the current "All observations with I/O" default renders it correctly; v4 on by default) |
| Many traces for list/filter performance | `pnpm run seed -- many-traces --count 100000 --days 14` |
| Scores with spaces in the name (filter/grammar testing) | `pnpm run seed -- scored-traces --traces 24 --v4` |
| Lots of scores on every node (dense score badges, tree-row overflow testing) | add `--scores-per-node 12` to `trace-tree` (N distinct scores per observation; try `--depth 2 --breadth 44` for many tall sibling rows) |
diff --git a/packages/shared/scripts/seeder/AGENTS.md b/packages/shared/scripts/seeder/AGENTS.md
index fa24131d25..030fecefef 100644
--- a/packages/shared/scripts/seeder/AGENTS.md
+++ b/packages/shared/scripts/seeder/AGENTS.md
@@ -11,6 +11,7 @@ pnpm run seed -- list # scenarios and flags (--json for machines)
pnpm run seed -- trace-tree --observations 5000 --breadth 500 --v4
pnpm run seed -- agent-timeline --turns 6 --v4 # realistic agent flow-with-loop over a timeline (graph view)
pnpm run seed -- long-session --traces 300 --observations-per-trace 8
+pnpm run seed -- session-shapes --shape all # chat / coding-agent / mixed v4 sessions
pnpm run seed -- many-traces --count 100000 --days 14
pnpm run seed -- scored-traces --traces 24 --v4 # scores w/ spaces in the name
```
diff --git a/packages/shared/scripts/seeder/scenarios/index.ts b/packages/shared/scripts/seeder/scenarios/index.ts
index 0f6df41901..1e5096b8cf 100644
--- a/packages/shared/scripts/seeder/scenarios/index.ts
+++ b/packages/shared/scripts/seeder/scenarios/index.ts
@@ -3,6 +3,7 @@ import { annotationQueueScenario } from "./annotation-queue";
import { longSessionScenario } from "./long-session";
import { manyTracesScenario } from "./many-traces";
import { scoredTracesScenario } from "./scored-traces";
+import { sessionShapesScenario } from "./session-shapes";
import { traceTreeScenario } from "./trace-tree";
import { ScenarioDefinition } from "./types";
@@ -15,6 +16,7 @@ export const scenarios: Record<string, ScenarioDefinition> = {
"long-session": longSessionScenario,
"many-traces": manyTracesScenario,
"scored-traces": scoredTracesScenario,
+ "session-shapes": sessionShapesScenario,
"annotation-queue": annotationQueueScenario,
};
diff --git a/packages/shared/scripts/seeder/scenarios/session-shapes.ts b/packages/shared/scripts/seeder/scenarios/session-shapes.ts
new file mode 100644
index 0000000000..fe84cad86d
--- /dev/null
+++ b/packages/shared/scripts/seeder/scenarios/session-shapes.ts
@@ -0,0 +1,692 @@
+import { prisma } from "../../../src/db";
+import {
+ createTrace,
+ createObservation,
+ createSessionScore,
+ createTracesCh,
+ createObservationsCh,
+ createScoresCh,
+ createEventsCh,
+ EventRecordInsertType,
+ ObservationRecordInsertType,
+ ScoreRecordInsertType,
+ TraceRecordInsertType,
+} from "../../../src/server";
+import { observationToEvent, traceToEvent } from "./event-mirror";
+import { jitter, Rng, utcDayStartMs } from "./rng";
+import {
+ chunk,
+ ScenarioContext,
+ ScenarioDefinition,
+ SeedError,
+ SeedSummary,
+} from "./types";
+import { countRows, sessionLink } from "./verify";
+
+/**
+ * Diverse v4 session shapes for the session-detail view (LFE-10520).
+ *
+ * The v4 session view renders one card per trace. Pre-LFE-10520 it defaulted to
+ * a "First Generation in Trace" preset that surfaced only the first
+ * `type=GENERATION` observation per trace — which broke agentic sessions whose
+ * I/O lives on AGENT/TOOL observations with no GENERATION at all (every card
+ * rendered "No observations match the current filter."). The default is now
+ * "All observations with I/O", which renders those correctly. This scenario
+ * seeds the shapes to see both the fix and the shapes it targets:
+ *
+ * - chat one GENERATION per turn carrying accumulating ChatML messages;
+ * renders as a chat.
+ * - agent a coding/agent session: I/O on the root AGENT + TOOL children,
+ * NO GENERATION — the shape the old default rendered empty.
+ * - mixed alternating chat/agent turns.
+ *
+ * Each shape is written as its own session (id `<prefix>-<shape>`) so a single
+ * `--shape all` run hands back one session link per shape.
+ */
+
+type Shape = "chat" | "agent" | "mixed";
+
+const SHAPES: readonly Shape[] = ["chat", "agent", "mixed"];
+
+const CHAT_TURNS: ReadonlyArray<{ user: string; assistant: string }> = [
+ {
+ user: "Hi! How do I get a refund for order #4821? It arrived damaged.",
+ assistant:
+ "I'm sorry to hear that. I can start a refund for order #4821 right away — refunds for damaged items are processed within 5 business days to your original payment method. Would you like a replacement shipped instead?",
+ },
+ {
+ user: "A refund is fine. Do I need to send the damaged item back?",
+ assistant:
+ "No need to return it for a damaged-on-arrival item. I've issued the refund and emailed you the confirmation. Is there anything else I can help with?",
+ },
+ {
+ user: "Can you also update the shipping address on my account?",
+ assistant:
+ "Of course. I've opened the address form — please share the new street, city, and postal code and I'll update it on your profile.",
+ },
+ {
+ user: "It's 14 Rue de la Paix, Paris, 75002.",
+ assistant:
+ "Done — your default shipping address is now 14 Rue de la Paix, Paris, 75002. Future orders will ship there unless you choose otherwise.",
+ },
+];
+
+const CODING_TASKS: ReadonlyArray<{
+ request: string;
+ read: { path: string; content: string };
+ patch: { diff: string; result: string };
+ test: { command: string; result: string };
+ summary: string;
+}> = [
+ {
+ request:
+ "The test `validateToken` in src/auth.test.ts is failing after the latest refactor. Find the bug, fix it, and make sure the auth tests pass.",
+ read: {
+ path: "src/auth.ts",
+ content:
+ "export function validateToken(token) {\n const payload = decode(token);\n return payload.exp > Date.now() / 1000;\n}",
+ },
+ patch: {
+ diff: "@@ -1,4 +1,5 @@\n export function validateToken(token) {\n const payload = decode(token);\n- return payload.exp > Date.now() / 1000;\n+ if (!payload) return false;\n+ return payload.exp > Date.now() / 1000;\n }",
+ result: "Patch applied to src/auth.ts (1 hunk, +2 -1).",
+ },
+ test: {
+ command: "pnpm vitest run src/auth.test.ts",
+ result:
+ "✓ src/auth.test.ts (14 tests) 312ms\n ✓ validateToken rejects a null payload\n\nTest Files 1 passed (1)\n Tests 14 passed (14)",
+ },
+ summary:
+ "Fixed a missing null-check in validateToken(): a malformed token made decode() return null and threw on `.exp`. Added an early `return false`. All 14 auth tests pass and lint is clean.",
+ },
+ {
+ request:
+ "Add a `--dry-run` flag to the export script in scripts/export.ts so it prints the plan without writing files.",
+ read: {
+ path: "scripts/export.ts",
+ content:
+ "async function main() {\n const rows = await load();\n await writeFiles(rows);\n}",
+ },
+ patch: {
+ diff: "@@ -1,4 +1,7 @@\n async function main() {\n+ const dryRun = process.argv.includes('--dry-run');\n const rows = await load();\n- await writeFiles(rows);\n+ if (dryRun) { console.log(`would write ${rows.length} files`); return; }\n+ await writeFiles(rows);\n }",
+ result: "Patch applied to scripts/export.ts (1 hunk, +3 -1).",
+ },
+ test: {
+ command: "pnpm tsx scripts/export.ts --dry-run",
+ result: "would write 128 files",
+ },
+ summary:
+ "Added a `--dry-run` flag: when present, the export script logs the file count it would write and exits before touching disk. Verified it prints the plan and writes nothing.",
+ },
+];
+
+const buildChatMessages = (turnIdx: number): string => {
+ const messages: Array<{ role: string; content: string }> = [
+ {
+ role: "system",
+ content:
+ "You are a friendly customer-support assistant for an e-commerce store. Be concise and helpful.",
+ },
+ ];
+ for (let i = 0; i <= turnIdx; i++) {
+ const turn = CHAT_TURNS[i % CHAT_TURNS.length];
+ messages.push({ role: "user", content: turn.user });
+ if (i < turnIdx) {
+ messages.push({ role: "assistant", content: turn.assistant });
+ }
+ }
+ return JSON.stringify({ messages });
+};
+
+const microPrice = (tokens: number, rate: number) => tokens * rate;
+
+/**
+ * Builds the rows for one chat trace: a root AGENT turn (no I/O) plus a
+ * GENERATION carrying the accumulating ChatML conversation. The default
+ * "first generation" preset surfaces the GENERATION, so the card renders as a
+ * chat.
+ */
+const buildChatTrace = (
+ ctx: ScenarioContext,
+ rng: Rng,
+ sessionId: string,
+ traceId: string,
+ turnIdx: number,
+ timestamp: number,
+): {
+ trace: TraceRecordInsertType;
+ observations: ObservationRecordInsertType[];
+} => {
+ const turn = CHAT_TURNS[turnIdx % CHAT_TURNS.length];
+ const trace = createTrace({
+ id: traceId,
+ project_id: ctx.projectId,
+ environment: ctx.environment,
+ session_id: sessionId,
+ timestamp,
+ name: "chat-turn",
+ user_id: `user-${ctx.idPrefix}`,
+ release: "v2.0.0",
+ version: "v2.0.0",
+ tags: ["seed", "session-shapes", "chat"],
+ public: false,
+ bookmarked: false,
+ metadata: {
+ scenario: "session-shapes",
+ shape: "chat",
+ turn: String(turnIdx),
+ },
+ input: turn.user,
+ output: turn.assistant,
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ });
+
+ const rootStart = timestamp + jitter(ctx.seed, turnIdx * 7, 60);
+ const genStart = rootStart + 40 + jitter(ctx.seed, turnIdx * 7 + 1, 80);
+ const genEnd = genStart + rng.int(700, 2600);
+ const usageInput = rng.int(200, 1800);
+ const usageOutput = rng.int(60, 500);
+
+ const observations: ObservationRecordInsertType[] = [
+ createObservation({
+ id: `${traceId}-o0`,
+ trace_id: traceId,
+ project_id: ctx.projectId,
+ environment: ctx.environment,
+ type: "AGENT",
+ parent_observation_id: null,
+ name: "assistant-turn",
+ start_time: rootStart,
+ end_time: genEnd + 20,
+ completion_start_time: null,
+ level: "DEFAULT",
+ status_message: null,
+ version: null,
+ input: null,
+ output: null,
+ metadata: { scenario: "session-shapes", shape: "chat" },
+ provided_model_name: null,
+ internal_model_id: null,
+ model_parameters: "{}",
+ provided_usage_details: {},
+ usage_details: {},
+ provided_cost_details: {},
+ cost_details: {},
+ total_cost: null,
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ }),
+ createObservation({
+ id: `${traceId}-o1`,
+ trace_id: traceId,
+ project_id: ctx.projectId,
+ environment: ctx.environment,
+ type: "GENERATION",
+ parent_observation_id: `${traceId}-o0`,
+ name: "gpt-4o-completion",
+ start_time: genStart,
+ end_time: genEnd,
+ completion_start_time: genStart + rng.int(90, 320),
+ level: "DEFAULT",
+ status_message: null,
+ version: null,
+ input: buildChatMessages(turnIdx),
+ output: turn.assistant,
+ metadata: { scenario: "session-shapes", shape: "chat" },
+ provided_model_name: "gpt-4o",
+ internal_model_id: null,
+ model_parameters: JSON.stringify({ temperature: 0.4 }),
+ provided_usage_details: {
+ input: usageInput,
+ output: usageOutput,
+ total: usageInput + usageOutput,
+ },
+ usage_details: {
+ input: usageInput,
+ output: usageOutput,
+ total: usageInput + usageOutput,
+ },
+ provided_cost_details: {
+ input: microPrice(usageInput, 2e-6),
+ output: microPrice(usageOutput, 6e-6),
+ },
+ cost_details: {
+ input: microPrice(usageInput, 2e-6),
+ output: microPrice(usageOutput, 6e-6),
+ total: microPrice(usageInput, 2e-6) + microPrice(usageOutput, 6e-6),
+ },
+ total_cost: microPrice(usageInput, 2e-6) + microPrice(usageOutput, 6e-6),
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ }),
+ ];
+
+ return { trace, observations };
+};
+
+/**
+ * Builds the rows for one coding/agent trace: a root AGENT carrying the user's
+ * request and the agent's final answer, plus TOOL children with real I/O and
+ * an empty SPAN. There is NO GENERATION, so the default "first generation"
+ * preset selects nothing and the card renders empty — the LFE-10520 bug.
+ */
+const buildAgentTrace = (
+ ctx: ScenarioContext,
+ rng: Rng,
+ sessionId: string,
+ traceId: string,
+ turnIdx: number,
+ timestamp: number,
+): {
+ trace: TraceRecordInsertType;
+ observations: ObservationRecordInsertType[];
+} => {
+ const task = CODING_TASKS[turnIdx % CODING_TASKS.length];
+ const trace = createTrace({
+ id: traceId,
+ project_id: ctx.projectId,
+ environment: ctx.environment,
+ session_id: sessionId,
+ timestamp,
+ name: "coding-agent",
+ user_id: `user-${ctx.idPrefix}`,
+ release: "v2.0.0",
+ version: "v2.0.0",
+ tags: ["seed", "session-shapes", "agent"],
+ public: false,
+ bookmarked: false,
+ metadata: {
+ scenario: "session-shapes",
+ shape: "agent",
+ turn: String(turnIdx),
+ },
+ input: task.request,
+ output: task.summary,
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ });
+
+ const base = timestamp + jitter(ctx.seed, turnIdx * 13, 60);
+ const mkTime = (slot: number) =>
+ base + slot * 400 + jitter(ctx.seed, turnIdx * 13 + slot + 1, 120);
+
+ const observations: ObservationRecordInsertType[] = [];
+
+ const mkChild = (
+ slot: number,
+ id: string,
+ type: "TOOL" | "SPAN",
+ name: string,
+ input: string | null,
+ output: string | null,
+ ) => {
+ const start = mkTime(slot);
+ observations.push(
+ createObservation({
+ id,
+ trace_id: traceId,
+ project_id: ctx.projectId,
+ environment: ctx.environment,
+ type,
+ parent_observation_id: `${traceId}-o0`,
+ name,
+ start_time: start,
+ end_time: start + rng.int(20, 400),
+ completion_start_time: null,
+ level: "DEFAULT",
+ status_message: null,
+ version: null,
+ input,
+ output,
+ metadata: { scenario: "session-shapes", shape: "agent" },
+ provided_model_name: null,
+ internal_model_id: null,
+ model_parameters: "{}",
+ provided_usage_details: {},
+ usage_details: {},
+ provided_cost_details: {},
+ cost_details: {},
+ total_cost: null,
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ }),
+ );
+ };
+
+ // Root AGENT carries the request + final answer (generation-like I/O, but
+ // NOT a GENERATION type — this is exactly what the default preset misses).
+ const rootStart = base;
+ observations.push(
+ createObservation({
+ id: `${traceId}-o0`,
+ trace_id: traceId,
+ project_id: ctx.projectId,
+ environment: ctx.environment,
+ type: "AGENT",
+ parent_observation_id: null,
+ name: "coding-agent",
+ start_time: rootStart,
+ end_time: mkTime(5) + 50,
+ completion_start_time: null,
+ level: "DEFAULT",
+ status_message: null,
+ version: null,
+ input: task.request,
+ output: task.summary,
+ metadata: { scenario: "session-shapes", shape: "agent" },
+ provided_model_name: null,
+ internal_model_id: null,
+ model_parameters: "{}",
+ provided_usage_details: {},
+ usage_details: {},
+ provided_cost_details: {},
+ cost_details: {},
+ total_cost: null,
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ }),
+ );
+
+ mkChild(1, `${traceId}-o1`, "SPAN", "plan", null, null);
+ mkChild(
+ 2,
+ `${traceId}-o2`,
+ "TOOL",
+ "read_file",
+ JSON.stringify({ path: task.read.path }),
+ task.read.content,
+ );
+ mkChild(
+ 3,
+ `${traceId}-o3`,
+ "TOOL",
+ "apply_patch",
+ JSON.stringify({ path: task.read.path, diff: task.patch.diff }),
+ task.patch.result,
+ );
+ mkChild(
+ 4,
+ `${traceId}-o4`,
+ "TOOL",
+ "run_tests",
+ JSON.stringify({ command: task.test.command }),
+ task.test.result,
+ );
+
+ return { trace, observations };
+};
+
+const buildSession = (
+ ctx: ScenarioContext,
+ rng: Rng,
+ shape: Shape,
+ turns: number,
+): {
+ sessionId: string;
+ sessionStart: number;
+ traces: TraceRecordInsertType[];
+ observations: ObservationRecordInsertType[];
+} => {
+ const sessionId = `${ctx.idPrefix}-${shape}`;
+ // Anchor each session in a recent, distinct hour so UI time windows show
+ // them and the three sessions don't overlap their timestamps.
+ const shapeOffsetMin = (SHAPES.indexOf(shape) + 1) * 90;
+ const sessionStart = utcDayStartMs() - shapeOffsetMin * 60 * 1000;
+ const stepMs = (45 * 60 * 1000) / Math.max(turns, 1);
+
+ const traces: TraceRecordInsertType[] = [];
+ const observations: ObservationRecordInsertType[] = [];
+
+ for (let t = 0; t < turns; t++) {
+ const traceId = `${ctx.idPrefix}-${shape}-t${t}`;
+ const timestamp =
+ sessionStart + Math.floor(t * stepMs) + jitter(ctx.seed, t, 400);
+
+ // mixed alternates chat/agent turns; chat/agent are uniform.
+ const turnShape: Exclude<Shape, "mixed"> =
+ shape === "mixed" ? (t % 2 === 0 ? "chat" : "agent") : shape;
+
+ const built =
+ turnShape === "chat"
+ ? buildChatTrace(ctx, rng, sessionId, traceId, t, timestamp)
+ : buildAgentTrace(ctx, rng, sessionId, traceId, t, timestamp);
+
+ traces.push(built.trace);
+ observations.push(...built.observations);
+ }
+
+ return { sessionId, sessionStart, traces, observations };
+};
+
+const run = async (
+ ctx: ScenarioContext,
+ params: Record<string, string | number | boolean>,
+): Promise<SeedSummary> => {
+ const startedAt = Date.now();
+ const shapeParam = String(params["shape"]);
+ const turns = params["turns"] as number;
+ const withV4 = params["v4"] as boolean;
+
+ if (shapeParam !== "all" && !SHAPES.includes(shapeParam as Shape)) {
+ throw new SeedError(
+ `--shape must be one of ${SHAPES.join(", ")}, all — got "${shapeParam}"`,
+ "e.g. --shape agent (the empty-cards repro) or --shape all",
+ );
+ }
+ if (turns < 1) {
+ throw new SeedError(
+ `--turns must be >= 1, got ${turns}`,
+ "pass a positive integer, e.g. --turns 8",
+ );
+ }
+
+ const shapesToSeed: Shape[] =
+ shapeParam === "all" ? [...SHAPES] : [shapeParam as Shape];
+
+ const rng = new Rng(ctx.seed);
+
+ if (ctx.dryRun) {
+ return {
+ scenario: "session-shapes",
+ target: "clickhouse",
+ params,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ traceIds: shapesToSeed.map((shape) => `${ctx.idPrefix}-${shape}-t0`),
+ sessionIds: shapesToSeed.map((shape) => `${ctx.idPrefix}-${shape}`),
+ counts: {
+ sessions: shapesToSeed.length,
+ traces: shapesToSeed.length * turns,
+ },
+ verified: {},
+ links: shapesToSeed.map((shape) =>
+ sessionLink(ctx, `${ctx.idPrefix}-${shape}`),
+ ),
+ dryRun: true,
+ durationMs: Date.now() - startedAt,
+ };
+ }
+
+ const allTraces: TraceRecordInsertType[] = [];
+ const allObservations: ObservationRecordInsertType[] = [];
+ const allScores: ScoreRecordInsertType[] = [];
+ const allEvents: EventRecordInsertType[] = [];
+ const sessionIds: string[] = [];
+ const links: string[] = [];
+
+ for (const shape of shapesToSeed) {
+ const { sessionId, sessionStart, traces, observations } = buildSession(
+ ctx,
+ rng,
+ shape,
+ turns,
+ );
+ sessionIds.push(sessionId);
+ links.push(sessionLink(ctx, sessionId));
+ allTraces.push(...traces);
+ allObservations.push(...observations);
+
+ allScores.push(
+ createSessionScore({
+ id: `${sessionId}-quality`,
+ project_id: ctx.projectId,
+ session_id: sessionId,
+ environment: ctx.environment,
+ name: "session-quality",
+ value: Math.round(rng.next() * 100) / 100,
+ data_type: "NUMERIC",
+ source: "API",
+ comment: null,
+ metadata: {},
+ timestamp: sessionStart,
+ }),
+ );
+
+ // The session detail page 404s without the Postgres trace_sessions row.
+ await prisma.traceSession.upsert({
+ where: { id_projectId: { id: sessionId, projectId: ctx.projectId } },
+ update: {},
+ create: {
+ id: sessionId,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ createdAt: new Date(sessionStart),
+ },
+ });
+ }
+
+ if (withV4) {
+ const tracesById = new Map(allTraces.map((tr) => [tr.id, tr]));
+ for (const trace of allTraces) {
+ allEvents.push(traceToEvent(trace));
+ }
+ for (const obs of allObservations) {
+ const trace = obs.trace_id ? tracesById.get(obs.trace_id) : undefined;
+ if (trace) allEvents.push(observationToEvent(obs, trace));
+ }
+ }
+
+ ctx.log(
+ `writing ${sessionIds.length} sessions, ${allTraces.length} traces, ${allObservations.length} observations, ${allScores.length} scores${
+ withV4 ? `, ${allEvents.length} events` : ""
+ }`,
+ );
+ for (const batch of chunk(allTraces, 1000)) {
+ await createTracesCh(batch);
+ }
+ for (const batch of chunk(allObservations, 1000)) {
+ await createObservationsCh(batch);
+ }
+ await createScoresCh(allScores);
+ for (const batch of chunk(allEvents, 500)) {
+ await createEventsCh(batch);
+ }
+
+ const traceIds = allTraces.map((tr) => tr.id);
+ const verified: Record<string, number> = {
+ traces: await countRows(
+ "traces",
+ `project_id = {projectId: String} AND session_id IN {sessionIds: Array(String)}`,
+ { projectId: ctx.projectId, sessionIds },
+ "uniqExact(id)",
+ ),
+ observations: await countRows(
+ "observations",
+ `project_id = {projectId: String} AND trace_id IN {traceIds: Array(String)}`,
+ { projectId: ctx.projectId, traceIds },
+ "uniqExact(id)",
+ ),
+ };
+ if (withV4) {
+ verified.events = await countRows(
+ "events_full",
+ `project_id = {projectId: String} AND session_id IN {sessionIds: Array(String)}`,
+ { projectId: ctx.projectId, sessionIds },
+ "uniqExact(span_id)",
+ );
+ }
+
+ if (verified.traces < allTraces.length) {
+ throw new SeedError(
+ `Readback mismatch: expected ${allTraces.length} session traces, found ${verified.traces}`,
+ );
+ }
+ if (verified.observations < allObservations.length) {
+ throw new SeedError(
+ `Readback mismatch: expected ${allObservations.length} observations, found ${verified.observations}`,
+ );
+ }
+ if (withV4 && verified.events < allEvents.length) {
+ throw new SeedError(
+ `Readback mismatch: expected ${allEvents.length} events_full rows, found ${verified.events}`,
+ );
+ }
+
+ return {
+ scenario: "session-shapes",
+ target: "clickhouse",
+ params,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ traceIds: traceIds.slice(0, 5),
+ sessionIds,
+ counts: {
+ sessions: sessionIds.length,
+ traces: allTraces.length,
+ observations: allObservations.length,
+ scores: allScores.length,
+ events: allEvents.length,
+ },
+ verified,
+ links,
+ dryRun: false,
+ durationMs: Date.now() - startedAt,
+ };
+};
+
+export const sessionShapesScenario: ScenarioDefinition = {
+ name: "session-shapes",
+ description:
+ "Diverse v4 session shapes for the session-detail view: a clean multi-turn CHAT session (renders as chat), a coding/AGENT session whose I/O lives on AGENT/TOOL observations with NO GENERATION (the default 'first generation' preset yields empty cards — LFE-10520), and a MIXED session. Creates the Postgres trace_sessions rows.",
+ supportsV4: true,
+ flags: [
+ {
+ flag: "shape",
+ type: "string",
+ default: "all",
+ description: "session shape: chat | agent | mixed | all",
+ },
+ {
+ flag: "turns",
+ type: "number",
+ default: 8,
+ description: "traces (turns) per session",
+ },
+ {
+ flag: "v4",
+ type: "boolean",
+ default: true,
+ description:
+ "mirror into v4 events tables (on by default: v4-only surface)",
+ },
+ ],
+ run,
+};
diff --git a/packages/shared/src/eventsTable.ts b/packages/shared/src/eventsTable.ts
index 500c960032..27912485c6 100644
--- a/packages/shared/src/eventsTable.ts
+++ b/packages/shared/src/eventsTable.ts
@@ -3,6 +3,10 @@ import { type ColumnDefinition } from "./tableDefinitions";
export const eventsTableHasParentObservationSql = "e.parent_span_id != ''";
export const eventsTableIsRootObservationSql =
"(e.parent_span_id = '' OR e.is_app_root = true)";
+// True when the observation carries input / output. NULL/'' both count as
+// absent (NULL != '' is NULL, i.e. not true), so only real payloads match.
+export const eventsTableHasInputSql = "e.input != ''";
+export const eventsTableHasOutputSql = "e.output != ''";
type MutableDeep<T> = T extends readonly (infer U)[]
? MutableDeep<U>[]
@@ -286,6 +290,18 @@ const eventsTableColsDefinition = [
type: "boolean",
internal: eventsTableIsRootObservationSql,
},
+ {
+ name: "Has Input",
+ id: "hasInput",
+ type: "boolean",
+ internal: eventsTableHasInputSql,
+ },
+ {
+ name: "Has Output",
+ id: "hasOutput",
+ type: "boolean",
+ internal: eventsTableHasOutputSql,
+ },
{
name: "Experiment Dataset ID",
id: "experimentDatasetId",
diff --git a/packages/shared/src/server/tableMappings/mapEventsTable.ts b/packages/shared/src/server/tableMappings/mapEventsTable.ts
index f9089bcb71..b6e8c43e1f 100644
--- a/packages/shared/src/server/tableMappings/mapEventsTable.ts
+++ b/packages/shared/src/server/tableMappings/mapEventsTable.ts
@@ -5,6 +5,8 @@ import { UiColumnMappings } from "../../tableDefinitions";
import {
eventsTableHasParentObservationSql,
eventsTableIsRootObservationSql,
+ eventsTableHasInputSql,
+ eventsTableHasOutputSql,
} from "../../eventsTable";
export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [
@@ -244,6 +246,18 @@ export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "events_proto",
clickhouseSelect: eventsTableIsRootObservationSql,
},
+ {
+ uiTableName: "Has Input",
+ uiTableId: "hasInput",
+ clickhouseTableName: "events_proto",
+ clickhouseSelect: eventsTableHasInputSql,
+ },
+ {
+ uiTableName: "Has Output",
+ uiTableId: "hasOutput",
+ clickhouseTableName: "events_proto",
+ clickhouseSelect: eventsTableHasOutputSql,
+ },
{
uiTableName: "Parent Observation ID",
uiTableId: "parentObservationId",
diff --git a/web/src/components/session/LazySessionTraceEventsRow.tsx b/web/src/components/session/LazySessionTraceEventsRow.tsx
index c7b7af4331..312a78f41a 100644
--- a/web/src/components/session/LazySessionTraceEventsRow.tsx
+++ b/web/src/components/session/LazySessionTraceEventsRow.tsx
@@ -15,6 +15,7 @@ type LazySessionTraceEventsRowProps = {
index: number;
traceCommentCounts: Map<string, number> | undefined;
filterState: FilterState;
+ viewLabel: string | null;
hideTracePanel?: boolean;
};
diff --git a/web/src/components/session/TraceEventsRow.tsx b/web/src/components/session/TraceEventsRow.tsx
index 3dade37077..01e638470c 100644
--- a/web/src/components/session/TraceEventsRow.tsx
+++ b/web/src/components/session/TraceEventsRow.tsx
@@ -13,6 +13,56 @@ import { type FilterState } from "@langfuse/shared";
import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";
import { IOPreview } from "@/src/components/trace/components/IOPreview/IOPreview";
import { api } from "@/src/utils/api";
+import { FilterX } from "lucide-react";
+import isEqual from "lodash/isEqual";
+import { SESSION_DETAIL_VIEW_TRIGGER_ID } from "@/src/components/session/session-detail-presets";
+
+const hasContent = (value: unknown): boolean =>
+ value !== null &&
+ value !== undefined &&
+ !(typeof value === "string" && value.trim() === "");
+
+const observationHasIO = (observation: {
+ input?: unknown;
+ output?: unknown;
+}): boolean => hasContent(observation.input) || hasContent(observation.output);
+
+// Opens the session-detail "View" drawer by activating its trigger — the empty
+// notice's action routes through the one shared View control (no per-card state).
+const openSessionViewMenu = () => {
+ if (typeof document === "undefined") return;
+ const trigger = document.getElementById(SESSION_DETAIL_VIEW_TRIGGER_ID);
+ if (trigger instanceof HTMLElement) trigger.click();
+};
+
+/**
+ * LFE-10520 — replaces the silent "No observations match the current filter."
+ * empty state. When the selected view (the single source of truth) matches
+ * nothing in a trace, this says so explicitly instead of rendering a blank
+ * card. It is purely informational: to see the trace's content the user
+ * switches the view above — there is no per-card state.
+ */
+const ViewMismatchNotice = ({ viewLabel }: { viewLabel: string | null }) => (
+ <div className="flex flex-col items-start gap-1.5 rounded-md border border-dashed border-amber-500/50 bg-amber-500/5 p-3">
+ <div className="flex items-center gap-2 text-xs font-medium text-amber-700 dark:text-amber-500">
+ <FilterX className="h-3.5 w-3.5 shrink-0" />
+ {viewLabel
+ ? `No observation matches the "${viewLabel}" view in this trace`
+ : "No observation matches the current filter in this trace"}
+ </div>
+ <p className="text-muted-foreground text-xs">
+ Its content is hidden by the current view, not missing.{" "}
+ <button
+ type="button"
+ onClick={openSessionViewMenu}
+ className="text-primary underline underline-offset-2 hover:no-underline"
+ >
+ Switch the view
+ </button>{" "}
+ to see it.
+ </p>
+ </div>
+);
export const TraceEventsSkeleton = () => {
return (
@@ -33,6 +83,8 @@ type LazyTraceEventsRowProps = {
traceCommentCounts: Map<string, number> | undefined;
showCorrections: boolean;
filterState: FilterState;
+ /** Selected view's display name, for the empty-state notice (null = custom). */
+ viewLabel: string | null;
hideTracePanel?: boolean;
};
@@ -48,6 +100,7 @@ const areLazyTraceEventsRowPropsEqual = (
previous.traceCommentCounts === next.traceCommentCounts &&
previous.showCorrections === next.showCorrections &&
previous.filterState === next.filterState &&
+ previous.viewLabel === next.viewLabel &&
previous.hideTracePanel === next.hideTracePanel;
export const TraceEventsRow = React.memo(
@@ -59,6 +112,7 @@ export const TraceEventsRow = React.memo(
traceCommentCounts,
showCorrections,
filterState,
+ viewLabel,
hideTracePanel = false,
}: {
trace: RouterOutputs["sessions"]["tracesFromEvents"][number];
@@ -68,6 +122,7 @@ export const TraceEventsRow = React.memo(
traceCommentCounts: Map<string, number> | undefined;
showCorrections: boolean;
filterState: FilterState;
+ viewLabel: string | null;
hideTracePanel?: boolean;
}) => {
const observationsQuery =
@@ -85,6 +140,43 @@ export const TraceEventsRow = React.memo(
},
);
+ // What each card shows is determined by the selected view (LFE-10520): the
+ // server applies the view's FilterState (incl. the "with I/O" view's
+ // Has-Input-or-Output filter). The only client-side shaping is dropping the
+ // synthetic trace-level row (id `t-<traceId>`, the canonical synthetic-span
+ // id — see handleEventPropagationJob). It is identified by id, NOT an empty
+ // parent: OTel/internal-tracing roots also have an empty parent but are real
+ // observations. It is dropped when redundant — empty, or a real observation
+ // already shows its (non-empty) input OR output — so a chat turn (the
+ // GENERATION carries the same assistant output) and the common auto-derived
+ // case render one card, not two. It is KEPT only when it carries
+ // trace-level I/O that no observation shows (a v3-migrated trace can set
+ // trace I/O apart from any observation; dropping it would lose content and
+ // blind the annotation queue, which hides the trace panel).
+ const observations = observationsQuery.data;
+ const visibleObservations = React.useMemo(() => {
+ if (!observations) return undefined;
+ const syntheticTraceRowId = `t-${trace.id}`;
+ const syntheticRow = observations.find(
+ (observation) => observation.id === syntheticTraceRowId,
+ );
+ const realObservations = observations.filter(
+ (observation) => observation.id !== syntheticTraceRowId,
+ );
+ const syntheticRowIsRedundant =
+ !syntheticRow ||
+ !observationHasIO(syntheticRow) ||
+ realObservations.some(
+ (observation) =>
+ (hasContent(syntheticRow.input) &&
+ isEqual(observation.input, syntheticRow.input)) ||
+ (hasContent(syntheticRow.output) &&
+ isEqual(observation.output, syntheticRow.output)),
+ );
+ if (!syntheticRowIsRedundant) return observations;
+ return realObservations.length > 0 ? realObservations : observations;
+ }, [observations, trace.id]);
+
return (
<Card className="border-border shadow-none">
<div
@@ -101,9 +193,9 @@ export const TraceEventsRow = React.memo(
<div className="text-destructive p-2 text-xs">
Failed to load observations.
</div>
- ) : observationsQuery.data && observationsQuery.data.length > 0 ? (
+ ) : visibleObservations && visibleObservations.length > 0 ? (
<div className="flex flex-col gap-4">
- {observationsQuery.data.map((observation) => (
+ {visibleObservations.map((observation) => (
<div key={observation.id} className="flex flex-col gap-2">
<div className="text-muted-foreground flex flex-wrap items-center gap-2 text-xs">
<span>{observation.name ?? "Observation"}</span>
@@ -142,10 +234,17 @@ export const TraceEventsRow = React.memo(
</div>
))}
</div>
- ) : (
+ ) : observations &&
+ observations.length === 0 &&
+ filterState.length === 0 ? (
+ // No filter and the trace genuinely has no observations.
<div className="text-muted-foreground p-2 text-xs">
- No observations match the current filter.
+ This trace has no observations.
</div>
+ ) : (
+ // The selected view/filter matched nothing (or hid the only
+ // observations, e.g. "with I/O" on a trace with none) — say so.
+ <ViewMismatchNotice viewLabel={viewLabel} />
)}
</div>
{!hideTracePanel && (
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index d000a2e0a2..4efc769c59 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -68,6 +68,8 @@ import {
SESSION_DETAIL_SYSTEM_PRESETS,
type SessionDetailSystemPreset,
getSessionDetailPresetToApply,
+ findSessionDetailViewByFilters,
+ SESSION_DETAIL_VIEW_TRIGGER_ID,
} from "@/src/components/session/session-detail-presets";
import { downloadSessionAsJson } from "@/src/components/session/actions/downloadSessionAsJson";
import { SessionDetailStoreProvider } from "@/src/components/session/SessionDetailStoreProvider";
@@ -924,26 +926,82 @@ const LoadedSessionEventsPage: React.FC<{
[queryFilter, viewControllers],
);
+ // The URL's viewId captured on first render, before the table view manager
+ // strips frontend system-preset ids — lets us restore a reloaded system view
+ // (incl. the empty-filter "All observations", otherwise indistinguishable
+ // from a fresh load) instead of silently replacing its FilterState. Read from
+ // window.location synchronously (not useQueryParam, which can lag a render on
+ // mount and miss the value before the strip).
+ const readUrlViewId = (): string | null =>
+ typeof window === "undefined"
+ ? null
+ : new URLSearchParams(window.location.search).get("viewId");
+ const initialViewIdRef = useRef<string | null>(readUrlViewId());
+ // Navigating between sessions (DetailPageNav prev/next) can reuse this mounted
+ // component when the destination is already in the react-query cache — the
+ // useRef initializer wouldn't re-run, leaving a stale viewId that blocks the
+ // default-view effect on the new session. Re-read the URL during render (not
+ // an effect, which would race the view manager's strip on reload) whenever the
+ // sessionId changes, mirroring the defaultPresetAppliedRef reset above.
+ const initialViewIdSessionRef = useRef(sessionId);
+ if (initialViewIdSessionRef.current !== sessionId) {
+ initialViewIdSessionRef.current = sessionId;
+ initialViewIdRef.current = readUrlViewId();
+ }
+
+ const selectedViewId = viewControllers.selectedViewId;
+
+ // Which named view drives the empty-state notice. Derived from the applied
+ // FilterState (the single source of truth) so the label survives the manager
+ // stripping the viewId on reload, and drops to null the moment the filter is
+ // edited. Mirrors the drawer trigger's rule: only name a view when it also
+ // matches the selected view id — so a selected saved view, or a filter
+ // hand-edited into another preset's exact shape, doesn't make the notice and
+ // the drawer trigger disagree.
+ const filterMatchedView = findSessionDetailViewByFilters(visibleFilterState);
+ const matchedView =
+ filterMatchedView &&
+ (!selectedViewId || filterMatchedView.id === selectedViewId)
+ ? filterMatchedView
+ : null;
+ const viewLabel = matchedView?.name ?? null;
+
+ // Recover the system-preset viewId the view manager strips from the URL on
+ // reload/shared-link (frontend presets aren't backend-fetchable). Idempotent
+ // (no one-shot guard) so it runs *after* the async strip, not before. Recovers
+ // when the surviving filter matches a preset AND either that preset was the
+ // URL's provenance viewId (captured before the strip — covers the empty-filter
+ // "All observations", otherwise indistinguishable from a fresh load) or the
+ // filter is non-empty (unambiguous). The filter itself is never changed.
+ useEffect(() => {
+ if (isViewLoading) return;
+ if (selectedViewId) return;
+ const filterMatchedView =
+ findSessionDetailViewByFilters(visibleFilterState);
+ if (!filterMatchedView) return;
+ const shouldRecover =
+ filterMatchedView.id === initialViewIdRef.current ||
+ visibleFilterState.length > 0;
+ if (shouldRecover) viewControllers.handleSetViewId(filterMatchedView.id);
+ }, [isViewLoading, selectedViewId, visibleFilterState, viewControllers]);
+
+ // Fresh load with nothing in the URL → apply the default view. Skipped on
+ // reload/shared-link (a viewId was in the URL) so the recovery effect above,
+ // not the default, decides the view — otherwise "All observations" would be
+ // silently replaced by the default on every reload.
useEffect(() => {
if (defaultPresetAppliedRef.current) return;
if (isViewLoading) return; // Wait for view manager to initialize
-
+ if (selectedViewId) return;
+ if (initialViewIdRef.current) return;
const presetToApply = getSessionDetailPresetToApply({
- selectedViewId: viewControllers.selectedViewId,
- hasFilters: queryFilter.filterState.length > 0,
+ selectedViewId: null,
+ hasFilters: visibleFilterState.length > 0,
});
if (!presetToApply) return;
-
defaultPresetAppliedRef.current = true;
- // Sessions intentionally default to the first generation in each trace
- // when opened without explicit filters or a saved view.
applySystemPreset(presetToApply);
- }, [
- applySystemPreset,
- queryFilter.filterState.length,
- isViewLoading,
- viewControllers.selectedViewId,
- ]);
+ }, [applySystemPreset, isViewLoading, selectedViewId, visibleFilterState]);
const virtualizer = useVirtualizer({
count: traces?.length ?? 0,
@@ -1064,14 +1122,18 @@ const LoadedSessionEventsPage: React.FC<{
searchQuery: "",
}}
systemFilterPresets={SESSION_DETAIL_SYSTEM_PRESETS}
+ triggerId={SESSION_DETAIL_VIEW_TRIGGER_ID}
/>
- {/* Filter Builder */}
+ {/* Refines the selected view by filtering observations within each
+ trace (it does not filter the list of traces) — labelled to say
+ so (LFE-10520). */}
<PopoverFilterBuilder
columns={filterColumns}
filterState={visibleFilterState}
onChange={queryFilter.setFilterState}
columnsWithCustomSelect={filterColumnsWithCustomSelect}
+ label="Filter observations"
/>
{/* Separator */}
@@ -1122,6 +1184,7 @@ const LoadedSessionEventsPage: React.FC<{
)}
index={virtualItem.index}
filterState={visibleFilterState}
+ viewLabel={viewLabel}
/>
</SessionVirtualizedRow>
);
diff --git a/web/src/components/session/session-detail-presets.ts b/web/src/components/session/session-detail-presets.ts
index 694d9b234c..1db512b8dd 100644
--- a/web/src/components/session/session-detail-presets.ts
+++ b/web/src/components/session/session-detail-presets.ts
@@ -1,7 +1,15 @@
import { type FilterState } from "@langfuse/shared";
+import isEqual from "lodash/isEqual";
const SYSTEM_PRESET_ID_PREFIX = "__langfuse_";
+/**
+ * DOM id of the session-detail "View" drawer trigger. The empty-state notice
+ * (TraceEventsRow) uses it to open the View menu, so switching view from a
+ * card routes through the same single control — no per-card state.
+ */
+export const SESSION_DETAIL_VIEW_TRIGGER_ID = "session-detail-view-trigger";
+
export interface SessionDetailSystemPreset {
id: string;
name: string;
@@ -10,6 +18,39 @@ export interface SessionDetailSystemPreset {
}
export const SESSION_DETAIL_SYSTEM_PRESETS: SessionDetailSystemPreset[] = [
+ {
+ id: `${SYSTEM_PRESET_ID_PREFIX}with_io__`,
+ name: "All observations with I/O",
+ description:
+ "Every observation that has input or output — a chat renders as a chat, an agent run shows its tool calls",
+ // Expressed as real, renderable filters (the "Has Input" / "Has Output"
+ // boolean columns lower to `input != ''` / `output != ''`), so the view
+ // shows up in the "Filter observations" UI like any other filter — no
+ // hidden view rule. Two AND-joined filters (the flat filter contract can't
+ // express a cross-column OR); observations carry both or neither in
+ // practice, so this matches the intent of "surface observations with I/O".
+ filters: [
+ {
+ column: "hasInput",
+ type: "boolean",
+ operator: "=",
+ value: true,
+ },
+ {
+ column: "hasOutput",
+ type: "boolean",
+ operator: "=",
+ value: true,
+ },
+ ] satisfies FilterState,
+ },
+ {
+ id: `${SYSTEM_PRESET_ID_PREFIX}all__`,
+ name: "All observations",
+ description:
+ "Every observation in each trace, including ones without input/output",
+ filters: [],
+ },
{
id: `${SYSTEM_PRESET_ID_PREFIX}first_generation__`,
name: "First Generation in Trace",
@@ -50,9 +91,20 @@ export const SESSION_DETAIL_SYSTEM_PRESETS: SessionDetailSystemPreset[] = [
},
];
+/**
+ * The default view: "All observations with I/O". Shows the real session out of
+ * the box (chat looks like chat, an agent run shows its tool calls) without the
+ * old "first generation" default that rendered empty cards for agentic sessions
+ * with no GENERATION (LFE-10520).
+ */
export const getSessionDetailDefaultPreset = () =>
SESSION_DETAIL_SYSTEM_PRESETS[0];
+/**
+ * Which system preset to auto-apply on load. A selected system preset (deep
+ * link / saved view) is re-applied; a user's own filters win; otherwise the
+ * default "All observations with I/O" view is applied.
+ */
export const getSessionDetailPresetToApply = ({
selectedViewId,
hasFilters,
@@ -74,3 +126,29 @@ export const getSessionDetailPresetToApply = ({
return selectedSystemPreset ?? getSessionDetailDefaultPreset();
};
+
+/** Strip `undefined` values so two filter states compare structurally equal. */
+const normalizeFilterState = (filters: FilterState): FilterState =>
+ filters.map(
+ (filter) =>
+ Object.fromEntries(
+ Object.entries(filter).filter(([, value]) => value !== undefined),
+ ) as FilterState[number],
+ );
+
+/**
+ * The system view whose filters exactly match `filterState`, or null. Matched
+ * by **filters**, not by the URL `viewId`: the label stays correct after the
+ * table view manager strips the frontend system-preset id from the URL on a
+ * reload/shared-link, and it drops to null the moment the user edits the filter
+ * away from the preset (so the notice never names a stale view).
+ */
+export const findSessionDetailViewByFilters = (
+ filterState: FilterState,
+): SessionDetailSystemPreset | null =>
+ SESSION_DETAIL_SYSTEM_PRESETS.find((preset) =>
+ isEqual(
+ normalizeFilterState(preset.filters),
+ normalizeFilterState(filterState),
+ ),
+ ) ?? null;
diff --git a/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx b/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx
index 049a433b7c..88c0c15bca 100644
--- a/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx
+++ b/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx
@@ -156,6 +156,8 @@ interface TableViewPresetsDrawerProps {
};
/** Page-specific system filter presets (e.g. "Last Generation in Trace") */
systemFilterPresets?: SystemFilterPreset[];
+ /** Optional DOM id on the trigger button so other UI can open the drawer. */
+ triggerId?: string;
}
function formatOrderBy(orderBy?: OrderByState) {
@@ -178,6 +180,7 @@ export function TableViewPresetsDrawer({
viewConfig,
currentState,
systemFilterPresets,
+ triggerId,
}: TableViewPresetsDrawerProps) {
const [searchQuery, setSearchQueryLocal] = useState("");
const { tableName, projectId, controllers } = viewConfig;
@@ -444,6 +447,7 @@ export function TableViewPresetsDrawer({
<DrawerTrigger asChild>
<Button
variant="outline"
+ id={triggerId}
title={selectedViewName ? `View: ${selectedViewName}` : "Views"}
>
<span>
diff --git a/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx b/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
index 8d1bb70484..f222e73fce 100644
--- a/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
+++ b/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
@@ -187,6 +187,7 @@ export const SessionAnnotationProcessor: React.FC<
traceCommentCounts={asCommentCounts(traceCommentCounts.data)}
showCorrections
filterState={EMPTY_FILTER_STATE}
+ viewLabel={null}
hideTracePanel
index={index}
/>
diff --git a/web/src/features/filters/components/filter-builder.tsx b/web/src/features/filters/components/filter-builder.tsx
index 50582f48ba..1ed7733f89 100644
--- a/web/src/features/filters/components/filter-builder.tsx
+++ b/web/src/features/filters/components/filter-builder.tsx
@@ -87,6 +87,7 @@ export function PopoverFilterBuilder({
columnsWithCustomSelect = [],
filterWithAI = false,
buttonType = "default",
+ label = "Filters",
}: {
/** Which column field to persist in filter.column: 'id' for stable refs, 'name' for legacy compatibility */
columns: ColumnDefinitionWithAlert[];
@@ -98,6 +99,8 @@ export function PopoverFilterBuilder({
columnsWithCustomSelect?: string[];
filterWithAI?: boolean;
buttonType?: "default" | "icon";
+ /** Trigger button label. Defaults to "Filters"; override to clarify scope. */
+ label?: string;
}) {
const capture = usePostHogClientCapture();
const [wipFilterState, _setWipFilterState] =
@@ -174,7 +177,7 @@ export function PopoverFilterBuilder({
<PopoverTrigger asChild>
{buttonType === "default" ? (
<Button variant="outline" type="button">
- <span>Filters</span>
+ <span>{label}</span>
{filterState.length > 0 && filterState.length < 3 ? (
<InlineFilterState
filterState={filterState}
diff --git a/web/src/features/filters/filter-integration.clienttest.ts b/web/src/features/filters/filter-integration.clienttest.ts
index ef7ac1bd34..2308fa1091 100644
--- a/web/src/features/filters/filter-integration.clienttest.ts
+++ b/web/src/features/filters/filter-integration.clienttest.ts
@@ -798,16 +798,48 @@ describe("Saved view validation", () => {
internal: "positionInTrace",
},
];
+ // LFE-10520: the default view is "All observations with I/O", expressed as
+ // a real, renderable boolean filter (not a hidden flag). Selecting a
+ // generation preset still applies its positionInTrace filters.
const defaultPreset = getSessionDetailPresetToApply({
selectedViewId: null,
hasFilters: false,
});
+ expect(defaultPreset).toEqual(SESSION_DETAIL_SYSTEM_PRESETS[0]);
+ expect(defaultPreset?.name).toBe("All observations with I/O");
+ expect(defaultPreset?.filters).toEqual([
+ {
+ column: "hasInput",
+ type: "boolean",
+ operator: "=",
+ value: true,
+ },
+ {
+ column: "hasOutput",
+ type: "boolean",
+ operator: "=",
+ value: true,
+ },
+ ]);
+ // The view filter must validate against the session columns so it renders
+ // in the "Filter observations" UI like any other filter.
+ expect(
+ validateFilters(defaultPreset?.filters ?? [], sessionEventColumns),
+ ).toEqual(defaultPreset?.filters ?? []);
+
+ const firstGenerationPreset = SESSION_DETAIL_SYSTEM_PRESETS.find(
+ (preset) => preset.name === "First Generation in Trace",
+ );
+ const appliedFirstGeneration = getSessionDetailPresetToApply({
+ selectedViewId: firstGenerationPreset?.id ?? null,
+ hasFilters: false,
+ });
const lastPreset = SESSION_DETAIL_SYSTEM_PRESETS.find(
(preset) => preset.name === "Last Generation in Trace",
);
- expect(defaultPreset).toEqual(SESSION_DETAIL_SYSTEM_PRESETS[0]);
- expect(defaultPreset?.filters).toEqual([
+ expect(appliedFirstGeneration).toEqual(firstGenerationPreset);
+ expect(firstGenerationPreset?.filters).toEqual([
{
column: "type",
type: "stringOptions",
@@ -822,8 +854,11 @@ describe("Saved view validation", () => {
},
]);
expect(
- validateFilters(defaultPreset?.filters ?? [], sessionEventColumns),
- ).toEqual(defaultPreset?.filters ?? []);
+ validateFilters(
+ firstGenerationPreset?.filters ?? [],
+ sessionEventColumns,
+ ),
+ ).toEqual(firstGenerationPreset?.filters ?? []);
expect(lastPreset?.filters).toEqual([
{
column: "type",
diff --git a/web/src/features/search-bar/lib/fields.ts b/web/src/features/search-bar/lib/fields.ts
index b907d16887..8033af8707 100644
--- a/web/src/features/search-bar/lib/fields.ts
+++ b/web/src/features/search-bar/lib/fields.ts
@@ -74,6 +74,8 @@ export const FIELDS: FieldDef[] = [
{ id: "traceTags", aliases: ["tracetags", "trace_tags", "tags", "tag"], kind: "text", syncMode: "arrayOption", description: "Trace tags" },
{ id: "isRootObservation", aliases: ["isrootobservation", "is_root_observation", "root"], kind: "boolean", syncMode: "textSearch", description: "Whether the observation is a trace root" },
{ id: "hasParentObservation", aliases: ["hasparentobservation", "has_parent_observation"], kind: "boolean", syncMode: "textSearch", description: "Whether the observation has a parent (inverse of root)" },
+ { id: "hasInput", aliases: ["hasinput", "has_input"], kind: "boolean", syncMode: "textSearch", description: "Whether the observation has input" },
+ { id: "hasOutput", aliases: ["hasoutput", "has_output"], kind: "boolean", syncMode: "textSearch", description: "Whether the observation has output" },
{ id: "toolNames", aliases: ["toolnames", "tool_names"], kind: "text", syncMode: "arrayOption", description: "Available tool names", nullable: true },
{ id: "calledToolNames", aliases: ["calledtoolnames", "called_tool_names", "calledtools", "called_tools"], kind: "text", syncMode: "arrayOption", description: "Called tool names", nullable: true },
{ id: "toolDefinitions", aliases: ["tooldefinitions", "tool_definitions"], kind: "number", syncMode: "textSearch", description: "Available tool count", nullable: true },