Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(filters): add the search bar to the sessions table (#16408)

Nikita Kabardin59d92c7cf365
diff --git a/.agents/skills/seed-test-data/SKILL.md b/.agents/skills/seed-test-data/SKILL.md
index 7fb0d45f89..06c2c49a0f 100644
--- a/.agents/skills/seed-test-data/SKILL.md
+++ b/.agents/skills/seed-test-data/SKILL.md
@@ -42,6 +42,7 @@ this.
| An extremely DEEP single-chain trace (tree depth = observation count; layout stress) | `pnpm run seed -- deep-chain --v4` (1401 sequential generations, each the sole child of the previous β€” the mis-parented-instrumentation shape from LFE-10959 that collapses tree/timeline layouts; `--observations N` to change depth) |
| 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 / media) 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 sessions for the sessions TABLE and its filters / search bar (not the detail view) | `pnpm run seed -- session-variety --sessions 120 --days 14` (searchable topic ids, 1-3 userIds and 1-3 tags per session, four environments, session metadata `tier`/`region`/`channel`/`topic`, numeric + categorical + boolean session scores, comments on a quarter; v4 on by default. Widen the time-range picker past the default 1 day.) |
| Session messages carrying Langfuse media references (inline image, several refs in one message, bare refs in a content array, link-only payload) | `pnpm run seed -- session-shapes --shape media` β€” uploads the image/audio/pdf fixtures to MinIO and links them to the observation, so the inline chip and the "Media" strip both resolve (LFE-14815, LFE-9577) |
| Many traces for list/filter performance | `pnpm run seed -- many-traces --count 100000 --days 14` |
| Long-window v4 traffic with cost/latency/token OUTLIERS (outlier chart strip, LFE-14451) | `pnpm run seed -- outlier-traffic --days 90` (diurnal base load + deterministic spikes + hour-long Γ—8-latency incidents; root AGENT + GENERATION carrying cost + TOOL per trace; v4 on by default) |
diff --git a/packages/shared/scripts/seeder/AGENTS.md b/packages/shared/scripts/seeder/AGENTS.md
index 921ec031b8..da391b2e64 100644
--- a/packages/shared/scripts/seeder/AGENTS.md
+++ b/packages/shared/scripts/seeder/AGENTS.md
@@ -23,6 +23,7 @@ pnpm run seed -- support-agent --v4 --id-prefix <hex> # demo-grade handcrafted
pnpm run seed -- long-session --traces 300 --observations-per-trace 8
pnpm run seed -- session-shapes --shape all # chat / coding-agent / mixed / media v4 sessions
pnpm run seed -- session-shapes --shape media # messages carrying @@@langfuseMedia:...@@@ refs (needs MinIO)
+pnpm run seed -- session-variety --sessions 120 --days 14 # many sessions for the sessions TABLE + its filters/search bar (topic ids, multi user/tag, 4 envs, session metadata, numeric+categorical+boolean scores, comments)
pnpm run seed -- many-traces --count 100000 --days 14
pnpm run seed -- outlier-traffic --days 90 # diurnal v4 traffic w/ cost/latency/token outliers (outlier chart strip)
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 98e8562f92..a4526c9bca 100644
--- a/packages/shared/scripts/seeder/scenarios/index.ts
+++ b/packages/shared/scripts/seeder/scenarios/index.ts
@@ -8,6 +8,7 @@ import { manyTracesScenario } from "./many-traces";
import { outlierTrafficScenario } from "./outlier-traffic";
import { scoredTracesScenario } from "./scored-traces";
import { sessionShapesScenario } from "./session-shapes";
+import { sessionVarietyScenario } from "./session-variety";
import { supportAgentScenario } from "./support-agent";
import { timelineAnnotatedScenario } from "./timeline-annotated";
import { timelineShapesScenario } from "./timeline-shapes";
@@ -27,6 +28,7 @@ export const scenarios: Record<string, ScenarioDefinition> = {
"outlier-traffic": outlierTrafficScenario,
"scored-traces": scoredTracesScenario,
"session-shapes": sessionShapesScenario,
+ "session-variety": sessionVarietyScenario,
"annotation-queue": annotationQueueScenario,
"custom-models": customModelsScenario,
"support-agent": supportAgentScenario,
diff --git a/packages/shared/scripts/seeder/scenarios/session-variety.ts b/packages/shared/scripts/seeder/scenarios/session-variety.ts
new file mode 100644
index 0000000000..b4a9af4eb4
--- /dev/null
+++ b/packages/shared/scripts/seeder/scenarios/session-variety.ts
@@ -0,0 +1,540 @@
+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 { generationUsageCost } from "./payload";
+import { jitter, Rng, utcDayStartMs } from "./rng";
+import {
+ chunk,
+ ScenarioContext,
+ ScenarioDefinition,
+ SeedError,
+ SeedSummary,
+} from "./types";
+import { countRows, sessionLink } from "./verify";
+
+/**
+ * Sessions LIST fixtures: many sessions spread across every axis the sessions
+ * table can filter on. The other session scenarios (long-session,
+ * session-shapes) build one or four sessions to exercise the session DETAIL
+ * view; this one exists so the table's filters β€” and the sessions search bar β€”
+ * have something to narrow.
+ */
+
+/** Session id topics, so a bare-word id search matches a meaningful subset. */
+const TOPICS = [
+ "checkout",
+ "refund",
+ "onboarding",
+ "support",
+ "billing-dispute",
+ "password-reset",
+];
+
+const TAG_POOL = [
+ "billing",
+ "urgent",
+ "refund",
+ "vip",
+ "beta",
+ "escalated",
+ "self-serve",
+];
+
+const TRACE_NAMES = [
+ "answer-support-question",
+ "classify-intent",
+ "draft-reply",
+ "lookup-order",
+ "escalate-to-human",
+];
+
+const TIERS = ["enterprise", "pro", "free"];
+const REGIONS = ["eu", "us", "apac"];
+const CHANNELS = ["web", "mobile", "api"];
+
+const SENTIMENTS = ["positive", "neutral", "negative"];
+
+const COMMENT_TEXTS = [
+ "Customer was upset about the duplicate charge, refunded manually.",
+ "Model hallucinated the order id here β€” worth a look.",
+ "Great answer, using this as a golden example.",
+ "Escalated to billing, still waiting on a reply.",
+ "This is the bug we saw last week, reproduced.",
+];
+
+const run = async (
+ ctx: ScenarioContext,
+ params: Record<string, string | number | boolean>,
+): Promise<SeedSummary> => {
+ const startedAt = Date.now();
+ const sessionCount = params["sessions"] as number;
+ const days = params["days"] as number;
+ const withV4 = params["v4"] as boolean;
+
+ if (sessionCount < 1) {
+ throw new SeedError(
+ `--sessions must be >= 1, got ${sessionCount}`,
+ "pass a positive integer, e.g. --sessions 60",
+ );
+ }
+ if (days < 1) {
+ throw new SeedError(
+ `--days must be >= 1, got ${days}`,
+ "negative windows would place sessions in the future, hidden by UI time filters",
+ );
+ }
+
+ // The base environment stays in the pool so --environment still shows up in
+ // the data; the rest give the environment facet something to filter.
+ const environments = Array.from(
+ new Set([ctx.environment, "production", "staging", "dev"]),
+ );
+
+ const sessionIds = Array.from(
+ { length: sessionCount },
+ (_, s) =>
+ `${ctx.idPrefix}-${TOPICS[s % TOPICS.length]}-${String(s).padStart(4, "0")}`,
+ );
+
+ if (ctx.dryRun) {
+ return {
+ scenario: "session-variety",
+ target: "clickhouse",
+ params,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ traceIds: [],
+ sessionIds: sessionIds.slice(0, 5),
+ counts: { sessions: sessionCount },
+ verified: {},
+ links: [`${ctx.baseUrl}/project/${ctx.projectId}/sessions`],
+ dryRun: true,
+ durationMs: Date.now() - startedAt,
+ };
+ }
+
+ const rng = new Rng(ctx.seed);
+ const windowEnd = utcDayStartMs();
+ const windowMs = days * 24 * 60 * 60 * 1000;
+
+ const traces: TraceRecordInsertType[] = [];
+ const observations: ObservationRecordInsertType[] = [];
+ const scores: ScoreRecordInsertType[] = [];
+ const events: EventRecordInsertType[] = [];
+ const pgSessions: {
+ id: string;
+ environment: string;
+ createdAt: Date;
+ }[] = [];
+ const comments: {
+ projectId: string;
+ objectId: string;
+ content: string;
+ }[] = [];
+
+ for (let s = 0; s < sessionCount; s++) {
+ const sessionId = sessionIds[s];
+ const environment = environments[s % environments.length];
+
+ // jitter() not rng for anything landing in a ClickHouse ORDER BY key:
+ // stream-position randomness re-keys rows when an unrelated flag changes
+ // how much rng earlier code consumed.
+ const sessionStart =
+ windowEnd - windowMs + jitter(ctx.seed, s * 7 + 1, windowMs);
+
+ // Durations span seconds to ~1h so numeric range filters have spread.
+ const durationMs =
+ s % 9 === 0
+ ? 4_000 + jitter(ctx.seed, s * 13, 6_000)
+ : 30_000 + jitter(ctx.seed, s * 13, 3_500_000);
+ const traceCount = 1 + (jitter(ctx.seed, s * 17 + 3, 12) as number);
+ const stepMs = traceCount > 1 ? durationMs / (traceCount - 1) : 0;
+
+ // 1–3 users per session, so `any of` and `all of` on userIds both bite.
+ const userCount = 1 + (jitter(ctx.seed, s * 19 + 5, 3) as number);
+ const sessionUsers = Array.from(
+ { length: userCount },
+ (_, u) => `user-${TIERS[(s + u) % TIERS.length]}-${(s * 3 + u) % 24}`,
+ );
+
+ // 1–3 tags, drawn deterministically so the same session keeps its tags.
+ const tagCount = 1 + (jitter(ctx.seed, s * 23 + 7, 3) as number);
+ const sessionTags = Array.from(
+ { length: tagCount },
+ (_, i) => TAG_POOL[(s * 2 + i * 3) % TAG_POOL.length],
+ );
+
+ // v4 session metadata is argMax over (start_time, event_ts, span_id) β€” the
+ // LAST event of the session wins β€” so the same map goes on every row.
+ const sessionMetadata = {
+ tier: TIERS[s % TIERS.length],
+ region: REGIONS[s % REGIONS.length],
+ channel: CHANNELS[s % CHANNELS.length],
+ topic: TOPICS[s % TOPICS.length],
+ };
+
+ pgSessions.push({
+ id: sessionId,
+ environment,
+ createdAt: new Date(sessionStart),
+ });
+
+ for (let t = 0; t < traceCount; t++) {
+ const traceId = `${sessionId}-t${t}`;
+ const timestamp =
+ sessionStart +
+ Math.floor(t * stepMs) +
+ jitter(ctx.seed, s * 31 + t, 400);
+
+ traces.push(
+ createTrace({
+ id: traceId,
+ project_id: ctx.projectId,
+ environment,
+ session_id: sessionId,
+ timestamp,
+ name: TRACE_NAMES[(s + t) % TRACE_NAMES.length],
+ // Cycle users across traces so multi-user sessions really have
+ // several distinct user_ids aggregated into userIds.
+ user_id: sessionUsers[t % sessionUsers.length],
+ release: "v1.2.3",
+ version: "v1.2.3",
+ tags: sessionTags,
+ public: false,
+ bookmarked: false,
+ metadata: sessionMetadata,
+ input: JSON.stringify({ topic: sessionMetadata.topic, turn: t }),
+ output: JSON.stringify({ ok: true }),
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ }),
+ );
+
+ // Two observations per trace: a root span and one generation carrying the
+ // usage/cost that the table's token and cost columns aggregate.
+ const rootStart = timestamp;
+ const genStart = timestamp + 120 + jitter(ctx.seed, s * 37 + t, 200);
+ const genEnd = genStart + 400 + jitter(ctx.seed, s * 41 + t, 2_500);
+
+ observations.push(
+ createObservation({
+ id: `${traceId}-o0`,
+ trace_id: traceId,
+ project_id: ctx.projectId,
+ environment,
+ type: "AGENT",
+ parent_observation_id: null,
+ name: "session-turn",
+ start_time: rootStart,
+ end_time: genEnd + 20,
+ completion_start_time: null,
+ level: "DEFAULT",
+ status_message: null,
+ version: null,
+ input: null,
+ output: null,
+ metadata: sessionMetadata,
+ 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(),
+ }),
+ );
+
+ // Token counts scale with the session index so cost/token filters have a
+ // wide, predictable spread rather than one clump.
+ const usageInput = 150 + (jitter(ctx.seed, s * 43 + t, 6_000) as number);
+ const usageOutput = 60 + (jitter(ctx.seed, s * 47 + t, 2_500) as number);
+
+ observations.push(
+ createObservation({
+ id: `${traceId}-o1`,
+ trace_id: traceId,
+ project_id: ctx.projectId,
+ environment,
+ type: "GENERATION",
+ parent_observation_id: `${traceId}-o0`,
+ name: "gpt-5.4-completion",
+ start_time: genStart,
+ end_time: genEnd,
+ completion_start_time: genStart + 90,
+ level: "DEFAULT",
+ status_message: null,
+ version: null,
+ input: JSON.stringify({
+ messages: [{ role: "user", content: sessionMetadata.topic }],
+ }),
+ output: "Here is what I found.",
+ metadata: sessionMetadata,
+ provided_model_name: "gpt-5.4",
+ internal_model_id: null,
+ model_parameters: JSON.stringify({ temperature: 0.7 }),
+ ...generationUsageCost(usageInput, usageOutput),
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ }),
+ );
+ }
+
+ // Session-level scores: one numeric, plus a categorical and a boolean on a
+ // subset, so `scores.<name>` covers all three lowering shapes.
+ scores.push(
+ createSessionScore({
+ id: `${sessionId}-score-quality`,
+ project_id: ctx.projectId,
+ session_id: sessionId,
+ environment,
+ name: "session-quality",
+ value: Math.round(rng.next() * 100) / 100,
+ data_type: "NUMERIC",
+ source: "API",
+ comment: null,
+ metadata: {},
+ timestamp: sessionStart,
+ }),
+ );
+ if (s % 2 === 0) {
+ scores.push(
+ createSessionScore({
+ id: `${sessionId}-score-sentiment`,
+ project_id: ctx.projectId,
+ session_id: sessionId,
+ environment,
+ name: "sentiment",
+ value: 1,
+ string_value: SENTIMENTS[s % SENTIMENTS.length],
+ data_type: "CATEGORICAL",
+ source: "API",
+ comment: null,
+ metadata: {},
+ timestamp: sessionStart,
+ }),
+ );
+ }
+ if (s % 3 === 0) {
+ scores.push(
+ createSessionScore({
+ id: `${sessionId}-score-resolved`,
+ project_id: ctx.projectId,
+ session_id: sessionId,
+ environment,
+ name: "resolved",
+ value: s % 6 === 0 ? 1 : 0,
+ // `score_booleans` is concat(name, ':', lowerUTF8(string_value)), so a
+ // boolean score without the True/False string can never be filtered.
+ string_value: s % 6 === 0 ? "True" : "False",
+ data_type: "BOOLEAN",
+ source: "API",
+ comment: null,
+ metadata: {},
+ timestamp: sessionStart,
+ }),
+ );
+ }
+
+ // Comments on every 4th session, so commentCount and commentContent are
+ // both non-empty without every row having one.
+ if (s % 4 === 0) {
+ comments.push({
+ projectId: ctx.projectId,
+ objectId: sessionId,
+ content: COMMENT_TEXTS[s % COMMENT_TEXTS.length],
+ });
+ }
+ }
+
+ if (withV4) {
+ const tracesById = new Map(traces.map((tr) => [tr.id, tr]));
+ for (const trace of traces) events.push(traceToEvent(trace));
+ for (const obs of observations) {
+ const trace = obs.trace_id ? tracesById.get(obs.trace_id) : undefined;
+ if (trace) events.push(observationToEvent(obs, trace));
+ }
+ }
+
+ const counts: Record<string, number> = {
+ sessions: sessionIds.length,
+ traces: traces.length,
+ observations: observations.length,
+ scores: scores.length,
+ comments: comments.length,
+ events: events.length,
+ };
+
+ ctx.log(
+ `writing ${sessionIds.length} sessions, ${traces.length} traces, ${observations.length} observations, ${scores.length} scores, ${comments.length} comments${withV4 ? `, ${events.length} events` : ""}`,
+ );
+
+ // Session detail 404s without the Postgres trace_sessions row.
+ for (const batch of chunk(pgSessions, 200)) {
+ await prisma.$transaction(
+ batch.map((session) =>
+ prisma.traceSession.upsert({
+ where: {
+ id_projectId: { id: session.id, projectId: ctx.projectId },
+ },
+ update: {},
+ create: {
+ id: session.id,
+ projectId: ctx.projectId,
+ environment: session.environment,
+ createdAt: session.createdAt,
+ },
+ }),
+ ),
+ );
+ }
+
+ // Re-runs with the same id prefix would otherwise stack duplicate comments;
+ // ClickHouse rows dedupe by id, Postgres comments do not.
+ await prisma.comment.deleteMany({
+ where: {
+ projectId: ctx.projectId,
+ objectType: "SESSION",
+ objectId: { in: comments.map((comment) => comment.objectId) },
+ },
+ });
+ if (comments.length > 0) {
+ await prisma.comment.createMany({
+ data: comments.map((comment) => ({
+ projectId: comment.projectId,
+ objectType: "SESSION" as const,
+ objectId: comment.objectId,
+ content: comment.content,
+ })),
+ });
+ }
+
+ for (const batch of chunk(traces, 1000)) await createTracesCh(batch);
+ for (const batch of chunk(observations, 1000)) {
+ await createObservationsCh(batch);
+ }
+ for (const batch of chunk(scores, 1000)) await createScoresCh(batch);
+ for (const batch of chunk(events, 500)) await createEventsCh(batch);
+
+ // uniqExact(id): count() would see pre-merge ReplacingMergeTree duplicates
+ // after re-runs with the same id prefix.
+ 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)",
+ ),
+ sessions: await countRows(
+ "traces",
+ `project_id = {projectId: String} AND session_id IN {sessionIds: Array(String)}`,
+ { projectId: ctx.projectId, sessionIds },
+ "uniqExact(session_id)",
+ ),
+ scores: await countRows(
+ "scores",
+ `project_id = {projectId: String} AND session_id IN {sessionIds: Array(String)}`,
+ { projectId: ctx.projectId, sessionIds },
+ "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.sessions < sessionIds.length) {
+ throw new SeedError(
+ `Readback mismatch: expected ${sessionIds.length} sessions, found ${verified.sessions}`,
+ );
+ }
+ if (verified.traces < traces.length) {
+ throw new SeedError(
+ `Readback mismatch: expected ${traces.length} traces, found ${verified.traces}`,
+ );
+ }
+ if (verified.scores < scores.length) {
+ throw new SeedError(
+ `Readback mismatch: expected ${scores.length} scores, found ${verified.scores}`,
+ );
+ }
+ if (withV4 && verified.events < events.length) {
+ throw new SeedError(
+ `Readback mismatch: expected ${events.length} events_full rows, found ${verified.events}`,
+ );
+ }
+
+ return {
+ scenario: "session-variety",
+ target: "clickhouse",
+ params,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ traceIds: traces.slice(0, 5).map((trace) => trace.id),
+ sessionIds,
+ counts,
+ verified,
+ links: [
+ `${ctx.baseUrl}/project/${ctx.projectId}/sessions`,
+ sessionLink(ctx, sessionIds[0]),
+ ],
+ dryRun: false,
+ durationMs: Date.now() - startedAt,
+ };
+};
+
+export const sessionVarietyScenario: ScenarioDefinition = {
+ name: "session-variety",
+ description:
+ "Many sessions spread across every axis the sessions TABLE filters on β€” searchable topic ids, 1-3 userIds and 1-3 tags per session, four environments, session metadata (tier/region/channel/topic), numeric + categorical + boolean session scores, comments on a quarter of them, and durations/trace counts/costs/tokens with real spread. The other session scenarios build one or four sessions for the DETAIL view; this one gives the list and its filters something to narrow.",
+ flags: [
+ {
+ flag: "sessions",
+ type: "number",
+ default: 60,
+ description: "number of sessions to write",
+ },
+ {
+ flag: "days",
+ type: "number",
+ default: 7,
+ description: "spread the sessions over this many days back from today",
+ },
+ {
+ flag: "v4",
+ type: "boolean",
+ default: true,
+ description:
+ "mirror into v4 events tables (on by default: the sessions bar is v4-only)",
+ },
+ ],
+ supportsV4: true,
+ run,
+};
diff --git a/web/src/__tests__/server/organization-feature-flags.servertest.ts b/web/src/__tests__/server/organization-feature-flags.servertest.ts
index 06af6722f2..bc6a7dedc3 100644
--- a/web/src/__tests__/server/organization-feature-flags.servertest.ts
+++ b/web/src/__tests__/server/organization-feature-flags.servertest.ts
@@ -203,6 +203,7 @@ describe("organization feature preview defaults", () => {
).toEqual({
modernSession: false,
compactTimeline: true,
+ sessionsSearchBar: false,
});
});
@@ -434,6 +435,7 @@ describe("organization member feature preview overrides", () => {
expect(row?.featurePreviews).toEqual({
modernSession: false,
compactTimeline: true,
+ sessionsSearchBar: false,
});
expect(row?.user).not.toHaveProperty("featureFlags");
expect(row).not.toHaveProperty("organizationIds");
diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsx
index 62a2a4fcec..d98b19777e 100644
--- a/web/src/components/table/use-cases/sessions.tsx
+++ b/web/src/components/table/use-cases/sessions.tsx
@@ -64,6 +64,12 @@ import { TableSelectionManager } from "@/src/features/table/components/TableSele
import { useScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";
import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";
import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";
+import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";
+import { SESSIONS_FIELD_REGISTRY } from "@/src/features/filters/config/sessionsSearchRegistry";
+import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";
+import { DEFAULT_SEARCH_TYPE } from "@/src/features/search-bar/lib/commit";
+import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSearchBar";
+import { EventsSearchBarRow } from "@/src/features/search-bar/components/EventsSearchBarRow";
export type SessionTableRow = {
id: string;
@@ -292,6 +298,40 @@ export default function SessionsTable({
[],
);
+ // Grammar search bar (Feature Preview): an ADDITIONAL editor over the same
+ // FilterState the facet sidebar edits β€” the sidebar stays and the two reflect
+ // each other with no explicit sync. Off on the user-detail mount, which is
+ // page-scoped by a userId filter the bar must not fight (same embedded
+ // opt-out as EventsTable).
+ const sessionsSearchBarEnabled =
+ useIsFeatureEnabled("sessionsSearchBar", { enableForAdmins: false }) &&
+ isBetaEnabled &&
+ !userId;
+ const observedOptions = useMemo(
+ () => toObservedOptions(newFilterOptions, isSidebarFilterLoading),
+ [newFilterOptions, isSidebarFilterLoading],
+ );
+ // Sessions has no full-text lane (`sessions.all*` takes no searchQuery), so
+ // the registry rejects free text and these stay inert.
+ const noSearchLane = useCallback(() => {}, []);
+ const {
+ store: searchBarStore,
+ commit: searchBarCommit,
+ applyFilters: searchBarApplyFilters,
+ } = useEventsSearchBar({
+ projectId,
+ tableName: sessionsFilterConfig.tableName,
+ enabled: sessionsSearchBarEnabled,
+ filterState: queryFilter.explicitFilterState,
+ searchQuery: null,
+ searchType: DEFAULT_SEARCH_TYPE,
+ observed: observedOptions,
+ setFilterState: setFiltersWrapper,
+ setSearchQuery: noSearchLane,
+ setSearchType: noSearchLane,
+ registry: SESSIONS_FIELD_REGISTRY,
+ });
+
const combinedFilterState = queryFilter.effectiveFilterState.concat(
userIdFilter,
dateRangeFilter,
@@ -757,57 +797,80 @@ export default function SessionsTable({
setTimeRange={setTimeRange}
/>
)}
- {/* Toolbar spanning full width */}
- <DataTableToolbar
- filterState={queryFilter.explicitFilterState}
- actionButtons={[
- selectedSessionIds.length > 0 || selectAll ? (
- <TableActionMenu
- key="sessions-multi-select-actions"
- projectId={projectId}
- actions={tableActions}
- tableName={BatchExportTableName.Sessions}
- selectedCount={selectedSessionCount}
- onClearSelection={() => {
- setSelectedRows({});
- setSelectAll(false);
+ {/* In bar mode the composer and the toolbar stick together as one band
+ (matching EventsTable) so the toolbar cannot scroll under the
+ composer and render half-clipped; pb-1.5 gives the band the same
+ breathing room above the table that the events tables have. */}
+ <div
+ className={cn(
+ sessionsSearchBarEnabled &&
+ "bg-background sticky top-0 z-30 pb-1.5",
+ )}
+ >
+ {sessionsSearchBarEnabled && (
+ <EventsSearchBarRow
+ projectId={projectId}
+ tableName={sessionsFilterConfig.tableName}
+ store={searchBarStore}
+ commit={searchBarCommit}
+ observed={observedOptions}
+ onApplyFilters={searchBarApplyFilters}
+ registry={SESSIONS_FIELD_REGISTRY}
+ />
+ )}
+ {/* Toolbar spanning full width */}
+ <DataTableToolbar
+ rowClassName={sessionsSearchBarEnabled ? "my-1" : undefined}
+ filterState={queryFilter.explicitFilterState}
+ actionButtons={[
+ selectedSessionIds.length > 0 || selectAll ? (
+ <TableActionMenu
+ key="sessions-multi-select-actions"
+ projectId={projectId}
+ actions={tableActions}
+ tableName={BatchExportTableName.Sessions}
+ selectedCount={selectedSessionCount}
+ onClearSelection={() => {
+ setSelectedRows({});
+ setSelectAll(false);
+ }}
+ />
+ ) : null,
+ <BatchExportTableButton
+ {...{
+ projectId,
+ filterState: backendFilterState,
+ orderByState,
}}
- />
- ) : null,
- <BatchExportTableButton
- {...{
- projectId,
- filterState: backendFilterState,
- orderByState,
- }}
- tableName={BatchExportTableName.Sessions}
- key="batchExport"
- />,
- ]}
- columns={columns}
- columnVisibility={columnVisibility}
- setColumnVisibility={setColumnVisibility}
- columnOrder={columnOrder}
- setColumnOrder={setColumnOrder}
- viewConfig={{
- tableName: TableViewPresetTableName.Sessions,
- projectId,
- controllers: viewControllers,
- }}
- timeRange={showControlsInPageHeader ? undefined : timeRange}
- setTimeRange={showControlsInPageHeader ? undefined : setTimeRange}
- columnsWithCustomSelect={["userIds"]}
- rowHeight={rowHeight}
- setRowHeight={setRowHeight}
- multiSelect={{
- selectAll,
- setSelectAll,
- selectedRowIds: selectedSessionIds,
- setRowSelection: setSelectedRows,
- totalCount,
- ...paginationState,
- }}
- />
+ tableName={BatchExportTableName.Sessions}
+ key="batchExport"
+ />,
+ ]}
+ columns={columns}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibility}
+ columnOrder={columnOrder}
+ setColumnOrder={setColumnOrder}
+ viewConfig={{
+ tableName: TableViewPresetTableName.Sessions,
+ projectId,
+ controllers: viewControllers,
+ }}
+ timeRange={showControlsInPageHeader ? undefined : timeRange}
+ setTimeRange={showControlsInPageHeader ? undefined : setTimeRange}
+ columnsWithCustomSelect={["userIds"]}
+ rowHeight={rowHeight}
+ setRowHeight={setRowHeight}
+ multiSelect={{
+ selectAll,
+ setSelectAll,
+ selectedRowIds: selectedSessionIds,
+ setRowSelection: setSelectedRows,
+ totalCount,
+ ...paginationState,
+ }}
+ />
+ </div>
{/* Content area with sidebar and table */}
<ResizableFilterLayout>
diff --git a/web/src/features/evals/v2/constants/ruleSearchRegistry.ts b/web/src/features/evals/v2/constants/ruleSearchRegistry.ts
index 012c9e5721..a3129a8b0c 100644
--- a/web/src/features/evals/v2/constants/ruleSearchRegistry.ts
+++ b/web/src/features/evals/v2/constants/ruleSearchRegistry.ts
@@ -11,6 +11,13 @@ export const RULE_FIELD_REGISTRY = fieldRegistryFromColumns(
{
id: "evaluationRules",
allowFreeText: false,
+ aiFilterPrompt: true,
+ searchExamples: [
+ "level:ERROR",
+ "-env:dev",
+ "tags:billing",
+ "type:GENERATION",
+ ],
metadata: true,
aiContextFields: [
{ observedOptionsKey: "type", promptLabel: "type" },
diff --git a/web/src/features/feature-flags/available-flags.ts b/web/src/features/feature-flags/available-flags.ts
index d88ec0063b..6d210d1e4a 100644
--- a/web/src/features/feature-flags/available-flags.ts
+++ b/web/src/features/feature-flags/available-flags.ts
@@ -3,6 +3,7 @@ import { assertUnreachable } from "@langfuse/shared";
export const featurePreviewFlags = [
"modernSession",
"compactTimeline",
+ "sessionsSearchBar",
] as const;
export type FeaturePreviewFlag = (typeof featurePreviewFlags)[number];
@@ -19,6 +20,7 @@ export const filterFeaturePreviewFlags = (
export const featurePreviewLabels = {
modernSession: "Compact Session View",
compactTimeline: "Compact Timeline",
+ sessionsSearchBar: "Sessions Search Bar",
} satisfies Record<FeaturePreviewFlag, string>;
export type FeaturePreviewAvailabilityContext = {
@@ -37,6 +39,13 @@ export const isFeaturePreviewAvailable = (
return true;
}
+ if (flag === "sessionsSearchBar") {
+ // Reads the events-backed sessions table, so it depends on v4 exactly as
+ // modernSession does β€” without this, staff who get previews by default
+ // would see the tile checked but disabled.
+ return context.v4BetaEnabled;
+ }
+
return assertUnreachable(flag);
};
diff --git a/web/src/features/feature-flags/components/OrganizationFeaturePreviewsSettings.clienttest.tsx b/web/src/features/feature-flags/components/OrganizationFeaturePreviewsSettings.clienttest.tsx
index 5ee5f76282..3a9afc8d4f 100644
--- a/web/src/features/feature-flags/components/OrganizationFeaturePreviewsSettings.clienttest.tsx
+++ b/web/src/features/feature-flags/components/OrganizationFeaturePreviewsSettings.clienttest.tsx
@@ -2,6 +2,7 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { ButtonHTMLAttributes, ReactNode } from "react";
import { OrganizationFeaturePreviewsSettings } from "./OrganizationFeaturePreviewsSettings";
+import { featurePreviewFlags } from "../available-flags";
const mocks = vi.hoisted(() => ({
capture: vi.fn(),
@@ -161,7 +162,9 @@ describe("OrganizationFeaturePreviewsSettings", () => {
const switches = screen.getAllByRole("checkbox", {
name: /organization default/i,
});
- expect(switches).toHaveLength(2);
+ // Derived, not hardcoded: the page renders one switch per registered
+ // preview, so a new preview must not fail this test.
+ expect(switches).toHaveLength(featurePreviewFlags.length);
switches.forEach((featureSwitch) => {
expect(featureSwitch).toBeChecked();
expect(featureSwitch).toBeDisabled();
diff --git a/web/src/features/feature-flags/components/UserFeaturePreviewsPopover.clienttest.tsx b/web/src/features/feature-flags/components/UserFeaturePreviewsPopover.clienttest.tsx
index 2b45d79d1a..da9b773d5b 100644
--- a/web/src/features/feature-flags/components/UserFeaturePreviewsPopover.clienttest.tsx
+++ b/web/src/features/feature-flags/components/UserFeaturePreviewsPopover.clienttest.tsx
@@ -2,6 +2,7 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { ComponentProps, ReactNode } from "react";
import { UserFeaturePreviewsControl } from "./UserFeaturePreviewsPopover";
+import { featurePreviewFlags } from "../available-flags";
const mocks = vi.hoisted(() => ({
capture: vi.fn(),
@@ -123,6 +124,7 @@ describe("UserFeaturePreviewsControl", () => {
featurePreviews: {
modernSession: false,
compactTimeline: false,
+ sessionsSearchBar: false,
},
management: {
allowed: false,
@@ -135,7 +137,11 @@ describe("UserFeaturePreviewsControl", () => {
),
).toBeInTheDocument();
expect(
- screen.getByRole("button", { name: /0\/2 enabled/i }),
+ screen.getByRole("button", {
+ // Derived: the counter's denominator is the number of registered
+ // previews, so a new preview must not fail this test.
+ name: new RegExp(`0/${featurePreviewFlags.length} enabled`, "i"),
+ }),
).toBeDisabled();
});
@@ -146,6 +152,7 @@ describe("UserFeaturePreviewsControl", () => {
featurePreviews: {
modernSession: false,
compactTimeline: false,
+ sessionsSearchBar: false,
},
management: { allowed: true },
});
@@ -182,6 +189,7 @@ describe("UserFeaturePreviewsControl", () => {
featurePreviews: {
modernSession: false,
compactTimeline: false,
+ sessionsSearchBar: false,
},
management: { allowed: true },
});
@@ -209,6 +217,7 @@ describe("UserFeaturePreviewsControl", () => {
featurePreviews: {
modernSession: false,
compactTimeline: false,
+ sessionsSearchBar: false,
},
management: { allowed: true },
});
diff --git a/web/src/features/feature-flags/types.ts b/web/src/features/feature-flags/types.ts
index 32c0ab9fa1..20a33fb04d 100644
--- a/web/src/features/feature-flags/types.ts
+++ b/web/src/features/feature-flags/types.ts
@@ -2,9 +2,13 @@ import { type availableFlags } from "./available-flags";
export type Flag = (typeof availableFlags)[number];
export type Flags = {
- [key in Exclude<Flag, "modernSession" | "compactTimeline">]: boolean;
+ [key in Exclude<
+ Flag,
+ "modernSession" | "compactTimeline" | "sessionsSearchBar"
+ >]: boolean;
} & {
// Optional while older sessions and test fixtures roll across new flags.
modernSession?: boolean;
compactTimeline?: boolean;
+ sessionsSearchBar?: boolean;
};
diff --git a/web/src/features/feature-previews/assets/sessions-search-bar-dark.svg b/web/src/features/feature-previews/assets/sessions-search-bar-dark.svg
new file mode 100644
index 0000000000..6cdf952ade
--- /dev/null
+++ b/web/src/features/feature-previews/assets/sessions-search-bar-dark.svg
@@ -0,0 +1,107 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="650" height="300" viewBox="0 0 650 300">
+ <defs>
+ <linearGradient id="barGlow" x1="62" y1="52" x2="595" y2="104" gradientUnits="userSpaceOnUse">
+ <stop offset="0" stop-color="hsl(246, 55%, 70%)" stop-opacity="0.14"/>
+ <stop offset="0.58" stop-color="hsl(217.2, 32.6%, 18%)" stop-opacity="0.72"/>
+ <stop offset="1" stop-color="hsl(188, 53%, 63%)" stop-opacity="0.08"/>
+ </linearGradient>
+ <linearGradient id="rowGlow" x1="255" y1="173" x2="574" y2="196" gradientUnits="userSpaceOnUse">
+ <stop offset="0" stop-color="hsl(246, 55%, 70%)" stop-opacity="0.2"/>
+ <stop offset="1" stop-color="hsl(217.2, 32.6%, 16%)" stop-opacity="0.74"/>
+ </linearGradient>
+ </defs>
+
+ <rect width="650" height="300" fill="hsl(222.2, 84%, 4.9%)"/>
+
+ <g stroke="hsl(210, 40%, 83%)" stroke-width="1.5" fill="none" opacity="0.4">
+ <path d="M14 32 V14 H32"/>
+ <path d="M636 32 V14 H618"/>
+ <path d="M14 268 V286 H32"/>
+ <path d="M636 268 V286 H618"/>
+ </g>
+
+ <g opacity="0.22" fill="none" stroke="hsl(217.2, 32.6%, 36%)" stroke-width="1">
+ <path d="M83 41 L584 40 L610 77 L560 118 L118 110 L55 76 Z"/>
+ <path d="M153 41 L124 111"/>
+ <path d="M321 41 L304 109"/>
+ <path d="M476 40 L514 113"/>
+ </g>
+
+ <rect x="48" y="54" width="554" height="54" rx="10" fill="url(#barGlow)" stroke="hsl(217.2, 32.6%, 30%)"/>
+ <polygon points="87,60 158,54 133,108 63,104" fill="hsl(246, 55%, 70%)" fill-opacity="0.06"/>
+ <polygon points="420,54 589,54 559,108 455,108" fill="hsl(188, 53%, 63%)" fill-opacity="0.05"/>
+
+ <circle cx="77" cy="78" r="7" fill="none" stroke="hsl(210, 40%, 83%)" stroke-width="2.2"/>
+ <path d="M82 83 L90 91" stroke="hsl(210, 40%, 83%)" stroke-width="2.2" stroke-linecap="round"/>
+
+ <g font-family="'Geist Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace" font-size="12" font-weight="600" letter-spacing="0.01em" text-anchor="middle">
+ <rect x="112" y="69" width="108" height="25" rx="6" fill="hsl(246, 55%, 70%)" fill-opacity="0.16" stroke="hsl(246, 55%, 70%)" stroke-opacity="0.8"/>
+ <text x="166" y="86" fill="hsl(246, 72%, 85%)">tags<tspan fill-opacity="0.5">:</tspan>urgent</text>
+
+ <rect x="230" y="69" width="86" height="25" rx="6" fill="hsl(217.2, 32.6%, 17.5%)" stroke="hsl(217.2, 32.6%, 36%)"/>
+ <text x="273" y="86" fill="hsl(210, 40%, 86%)">env<tspan fill-opacity="0.5">:</tspan>prod</text>
+
+ <rect x="326" y="69" width="100" height="25" rx="6" fill="hsl(217.2, 32.6%, 17.5%)" stroke="hsl(217.2, 32.6%, 36%)"/>
+ <text x="376" y="86" fill="hsl(210, 40%, 86%)">duration<tspan fill-opacity="0.5">&gt;</tspan>30</text>
+
+ <rect x="436" y="69" width="86" height="25" rx="6" fill="hsl(217.2, 32.6%, 17.5%)" stroke="hsl(217.2, 32.6%, 36%)"/>
+ <text x="479" y="86" fill="hsl(210, 40%, 86%)">score<tspan fill-opacity="0.5">&gt;</tspan>.8</text>
+
+ <rect x="534" y="75" width="3" height="18" rx="1.5" fill="hsl(210, 40%, 83%)" opacity="0.85"/>
+ </g>
+
+ <g stroke="hsl(210, 40%, 83%)" stroke-width="1" stroke-dasharray="3 6" opacity="0.28" fill="none">
+ <path d="M166 108 C 156 124, 139 135, 122 151"/>
+ <path d="M273 108 C 277 129, 269 145, 274 165"/>
+ <path d="M376 108 C 393 133, 411 149, 452 167"/>
+ <path d="M479 108 C 487 131, 506 148, 540 168"/>
+ </g>
+
+ <g font-family="'Geist Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace">
+ <rect x="54" y="135" width="160" height="115" rx="8" fill="hsl(222.2, 84%, 4.9%)" stroke="hsl(217.2, 32.6%, 29%)"/>
+ <polygon points="54,135 214,135 183,169 72,176" fill="hsl(217.2, 32.6%, 15%)" fill-opacity="0.4"/>
+ <path d="M86 135 L122 250" stroke="hsl(217.2, 32.6%, 28%)" opacity="0.6"/>
+ <path d="M183 135 L154 250" stroke="hsl(217.2, 32.6%, 24%)" opacity="0.6"/>
+
+ <text x="72" y="156" font-size="9.5" font-weight="600" letter-spacing="0.16em" fill="hsl(215, 20.2%, 62%)">FILTER FIELD</text>
+ <line x1="72" y1="168" x2="194" y2="168" stroke="hsl(217.2, 32.6%, 27.5%)"/>
+
+ <circle cx="82" cy="194" r="4" fill="hsl(246, 55%, 70%)"/>
+ <text x="100" y="198" font-size="12" font-weight="500" fill="hsl(210, 40%, 86%)">tags</text>
+ <polygon points="150,184 190,184 198,204 155,204" fill="hsl(246, 55%, 70%)" fill-opacity="0.16" stroke="hsl(246, 55%, 70%)" stroke-opacity="0.68"/>
+ <text x="173" y="198" font-size="10" font-weight="600" letter-spacing="0.04em" text-anchor="middle" fill="hsl(246, 72%, 85%)">VIP</text>
+
+ <circle cx="82" cy="228" r="4" fill="hsl(215, 20.2%, 55%)"/>
+ <text x="100" y="232" font-size="12" font-weight="500" fill="hsl(215, 20.2%, 66%)">environment</text>
+ </g>
+
+ <g font-family="'Geist Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace">
+ <rect x="244" y="135" width="352" height="115" rx="8" fill="hsl(222.2, 84%, 4.9%)" stroke="hsl(217.2, 32.6%, 29%)"/>
+ <polygon points="244,135 596,135 574,167 256,171" fill="hsl(217.2, 32.6%, 15%)" fill-opacity="0.34"/>
+ <path d="M430 135 L406 250" stroke="hsl(217.2, 32.6%, 25%)" opacity="0.6"/>
+ <path d="M550 135 L525 250" stroke="hsl(217.2, 32.6%, 24%)" opacity="0.6"/>
+
+ <text x="266" y="156" font-size="9.5" font-weight="600" letter-spacing="0.16em" fill="hsl(215, 20.2%, 62%)">MATCHED SESSION</text>
+ <line x1="266" y1="168" x2="574" y2="168" stroke="hsl(217.2, 32.6%, 27.5%)"/>
+
+ <path d="M262 180 H574 L566 208 H262 Z" fill="url(#rowGlow)" stroke="hsl(246, 55%, 70%)" stroke-opacity="0.7"/>
+ <rect x="262" y="217" width="304" height="22" rx="5" fill="hsl(222.2, 84%, 4.9%)" stroke="hsl(217.2, 32.6%, 28%)"/>
+
+ <circle cx="282" cy="194" r="4" fill="hsl(246, 55%, 70%)"/>
+ <text x="302" y="198" font-size="12" font-weight="500" fill="hsl(210, 40%, 87%)">checkout-0012</text>
+ <text x="434" y="198" font-size="12" font-weight="600" fill="hsl(246, 72%, 85%)">alice</text>
+ <text x="502" y="198" font-size="12" font-weight="500" fill="hsl(210, 40%, 80%)">2.4s</text>
+ <polygon points="544,187 572,187 568,203 540,203" fill="hsl(246, 55%, 70%)" fill-opacity="0.22"/>
+ <text x="556" y="198" font-size="10.5" font-weight="600" letter-spacing="0.02em" text-anchor="middle" fill="hsl(246, 72%, 85%)">.91</text>
+
+ <circle cx="282" cy="228" r="3.5" fill="hsl(215, 20.2%, 55%)"/>
+ <text x="302" y="232" font-size="12" font-weight="500" fill="hsl(215, 20.2%, 66%)">refund-0007</text>
+ <text x="434" y="232" font-size="12" font-weight="500" fill="hsl(215, 20.2%, 62%)">bob</text>
+ <text x="502" y="232" font-size="12" font-weight="500" fill="hsl(215, 20.2%, 62%)">1.7s</text>
+ </g>
+
+ <g opacity="0.72">
+ <path d="M214 195 C 226 194, 234 192, 244 190" stroke="hsl(246, 55%, 70%)" stroke-dasharray="3 5" fill="none"/>
+ <circle cx="214" cy="195" r="3.5" fill="hsl(246, 55%, 70%)"/>
+ </g>
+</svg>
diff --git a/web/src/features/feature-previews/assets/sessions-search-bar-light.svg b/web/src/features/feature-previews/assets/sessions-search-bar-light.svg
new file mode 100644
index 0000000000..e130794031
--- /dev/null
+++ b/web/src/features/feature-previews/assets/sessions-search-bar-light.svg
@@ -0,0 +1,107 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="650" height="300" viewBox="0 0 650 300">
+ <defs>
+ <linearGradient id="barGlow" x1="62" y1="52" x2="595" y2="104" gradientUnits="userSpaceOnUse">
+ <stop offset="0" stop-color="hsl(243, 75.4%, 58.6%)" stop-opacity="0.14"/>
+ <stop offset="0.58" stop-color="hsl(210, 40%, 94%)" stop-opacity="0.72"/>
+ <stop offset="1" stop-color="hsl(188, 60%, 42%)" stop-opacity="0.08"/>
+ </linearGradient>
+ <linearGradient id="rowGlow" x1="255" y1="173" x2="574" y2="196" gradientUnits="userSpaceOnUse">
+ <stop offset="0" stop-color="hsl(243, 75.4%, 58.6%)" stop-opacity="0.2"/>
+ <stop offset="1" stop-color="hsl(210, 40%, 95%)" stop-opacity="0.74"/>
+ </linearGradient>
+ </defs>
+
+ <rect width="650" height="300" fill="hsl(0, 0%, 100%)"/>
+
+ <g stroke="hsl(222.2, 47.4%, 11.2%)" stroke-width="1.5" fill="none" opacity="0.4">
+ <path d="M14 32 V14 H32"/>
+ <path d="M636 32 V14 H618"/>
+ <path d="M14 268 V286 H32"/>
+ <path d="M636 268 V286 H618"/>
+ </g>
+
+ <g opacity="0.22" fill="none" stroke="hsl(214.3, 31.8%, 82%)" stroke-width="1">
+ <path d="M83 41 L584 40 L610 77 L560 118 L118 110 L55 76 Z"/>
+ <path d="M153 41 L124 111"/>
+ <path d="M321 41 L304 109"/>
+ <path d="M476 40 L514 113"/>
+ </g>
+
+ <rect x="48" y="54" width="554" height="54" rx="10" fill="url(#barGlow)" stroke="hsl(214.3, 31.8%, 86%)"/>
+ <polygon points="87,60 158,54 133,108 63,104" fill="hsl(243, 75.4%, 58.6%)" fill-opacity="0.06"/>
+ <polygon points="420,54 589,54 559,108 455,108" fill="hsl(188, 60%, 42%)" fill-opacity="0.05"/>
+
+ <circle cx="77" cy="78" r="7" fill="none" stroke="hsl(222.2, 47.4%, 11.2%)" stroke-width="2.2"/>
+ <path d="M82 83 L90 91" stroke="hsl(222.2, 47.4%, 11.2%)" stroke-width="2.2" stroke-linecap="round"/>
+
+ <g font-family="'Geist Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace" font-size="12" font-weight="600" letter-spacing="0.01em" text-anchor="middle">
+ <rect x="112" y="69" width="108" height="25" rx="6" fill="hsl(243, 75.4%, 58.6%)" fill-opacity="0.16" stroke="hsl(243, 75.4%, 58.6%)" stroke-opacity="0.8"/>
+ <text x="166" y="86" fill="hsl(243, 75.4%, 45%)">tags<tspan fill-opacity="0.5">:</tspan>urgent</text>
+
+ <rect x="230" y="69" width="86" height="25" rx="6" fill="hsl(210, 40%, 96.1%)" stroke="hsl(214.3, 31.8%, 82%)"/>
+ <text x="273" y="86" fill="hsl(222.2, 47.4%, 11.2%)">env<tspan fill-opacity="0.5">:</tspan>prod</text>
+
+ <rect x="326" y="69" width="100" height="25" rx="6" fill="hsl(210, 40%, 96.1%)" stroke="hsl(214.3, 31.8%, 82%)"/>
+ <text x="376" y="86" fill="hsl(222.2, 47.4%, 11.2%)">duration<tspan fill-opacity="0.5">&gt;</tspan>30</text>
+
+ <rect x="436" y="69" width="86" height="25" rx="6" fill="hsl(210, 40%, 96.1%)" stroke="hsl(214.3, 31.8%, 82%)"/>
+ <text x="479" y="86" fill="hsl(222.2, 47.4%, 11.2%)">score<tspan fill-opacity="0.5">&gt;</tspan>.8</text>
+
+ <rect x="534" y="75" width="3" height="18" rx="1.5" fill="hsl(222.2, 47.4%, 11.2%)" opacity="0.85"/>
+ </g>
+
+ <g stroke="hsl(222.2, 47.4%, 11.2%)" stroke-width="1" stroke-dasharray="3 6" opacity="0.28" fill="none">
+ <path d="M166 108 C 156 124, 139 135, 122 151"/>
+ <path d="M273 108 C 277 129, 269 145, 274 165"/>
+ <path d="M376 108 C 393 133, 411 149, 452 167"/>
+ <path d="M479 108 C 487 131, 506 148, 540 168"/>
+ </g>
+
+ <g font-family="'Geist Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace">
+ <rect x="54" y="135" width="160" height="115" rx="8" fill="hsl(0, 0%, 100%)" stroke="hsl(214.3, 31.8%, 88%)"/>
+ <polygon points="54,135 214,135 183,169 72,176" fill="hsl(210, 40%, 96.1%)" fill-opacity="0.4"/>
+ <path d="M86 135 L122 250" stroke="hsl(214.3, 31.8%, 91.4%)" opacity="0.6"/>
+ <path d="M183 135 L154 250" stroke="hsl(214.3, 31.8%, 88%)" opacity="0.6"/>
+
+ <text x="72" y="156" font-size="9.5" font-weight="600" letter-spacing="0.16em" fill="hsl(215.4, 16.3%, 46.9%)">FILTER FIELD</text>
+ <line x1="72" y1="168" x2="194" y2="168" stroke="hsl(214.3, 31.8%, 91.4%)"/>
+
+ <circle cx="82" cy="194" r="4" fill="hsl(243, 75.4%, 58.6%)"/>
+ <text x="100" y="198" font-size="12" font-weight="500" fill="hsl(222.2, 47.4%, 11.2%)">tags</text>
+ <polygon points="150,184 190,184 198,204 155,204" fill="hsl(243, 75.4%, 58.6%)" fill-opacity="0.16" stroke="hsl(243, 75.4%, 58.6%)" stroke-opacity="0.68"/>
+ <text x="173" y="198" font-size="10" font-weight="600" letter-spacing="0.04em" text-anchor="middle" fill="hsl(243, 75.4%, 45%)">VIP</text>
+
+ <circle cx="82" cy="228" r="4" fill="hsl(215.4, 16.3%, 55%)"/>
+ <text x="100" y="232" font-size="12" font-weight="500" fill="hsl(215.4, 16.3%, 46.9%)">environment</text>
+ </g>
+
+ <g font-family="'Geist Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace">
+ <rect x="244" y="135" width="352" height="115" rx="8" fill="hsl(0, 0%, 100%)" stroke="hsl(214.3, 31.8%, 88%)"/>
+ <polygon points="244,135 596,135 574,167 256,171" fill="hsl(210, 40%, 96.1%)" fill-opacity="0.34"/>
+ <path d="M430 135 L406 250" stroke="hsl(214.3, 31.8%, 88%)" opacity="0.6"/>
+ <path d="M550 135 L525 250" stroke="hsl(214.3, 31.8%, 88%)" opacity="0.6"/>
+
+ <text x="266" y="156" font-size="9.5" font-weight="600" letter-spacing="0.16em" fill="hsl(215.4, 16.3%, 46.9%)">MATCHED SESSION</text>
+ <line x1="266" y1="168" x2="574" y2="168" stroke="hsl(214.3, 31.8%, 91.4%)"/>
+
+ <path d="M262 180 H574 L566 208 H262 Z" fill="url(#rowGlow)" stroke="hsl(243, 75.4%, 58.6%)" stroke-opacity="0.7"/>
+ <rect x="262" y="217" width="304" height="22" rx="5" fill="hsl(0, 0%, 100%)" stroke="hsl(214.3, 31.8%, 91.4%)"/>
+
+ <circle cx="282" cy="194" r="4" fill="hsl(243, 75.4%, 58.6%)"/>
+ <text x="302" y="198" font-size="12" font-weight="500" fill="hsl(222.2, 84%, 4.9%)">checkout-0012</text>
+ <text x="434" y="198" font-size="12" font-weight="600" fill="hsl(243, 75.4%, 45%)">alice</text>
+ <text x="502" y="198" font-size="12" font-weight="500" fill="hsl(215.4, 16.3%, 35%)">2.4s</text>
+ <polygon points="544,187 572,187 568,203 540,203" fill="hsl(243, 75.4%, 58.6%)" fill-opacity="0.22"/>
+ <text x="556" y="198" font-size="10.5" font-weight="600" letter-spacing="0.02em" text-anchor="middle" fill="hsl(243, 75.4%, 45%)">.91</text>
+
+ <circle cx="282" cy="228" r="3.5" fill="hsl(215.4, 16.3%, 55%)"/>
+ <text x="302" y="232" font-size="12" font-weight="500" fill="hsl(215.4, 16.3%, 46.9%)">refund-0007</text>
+ <text x="434" y="232" font-size="12" font-weight="500" fill="hsl(215.4, 16.3%, 46.9%)">bob</text>
+ <text x="502" y="232" font-size="12" font-weight="500" fill="hsl(215.4, 16.3%, 46.9%)">1.7s</text>
+ </g>
+
+ <g opacity="0.72">
+ <path d="M214 195 C 226 194, 234 192, 244 190" stroke="hsl(243, 75.4%, 58.6%)" stroke-dasharray="3 5" fill="none"/>
+ <circle cx="214" cy="195" r="3.5" fill="hsl(243, 75.4%, 58.6%)"/>
+ </g>
+</svg>
diff --git a/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx b/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx
index e7c1f4e3c7..17120d239c 100644
--- a/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx
+++ b/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx
@@ -62,6 +62,21 @@ export function ControlledFeaturePreviewModal({
onToggle: onToggle("modernSession"),
isToggling: setFeaturePreviewEnabled.isPending,
},
+ sessionsSearchBar: {
+ enabled:
+ authSession.data?.user?.featureFlags.sessionsSearchBar === true ||
+ authSession.data?.environment.enableExperimentalFeatures === true,
+ disabled:
+ !isBetaEnabled ||
+ authSession.data?.environment.enableExperimentalFeatures === true,
+ warningReason: !isBetaEnabled
+ ? `The sessions search bar reads the events-backed sessions table. Turn on ${V4_PREVIEW_LABEL} to enable it.`
+ : authSession.data?.environment.enableExperimentalFeatures === true
+ ? "This preview is enabled by LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES, so a per-user opt-out does not disable it."
+ : undefined,
+ onToggle: onToggle("sessionsSearchBar"),
+ isToggling: setFeaturePreviewEnabled.isPending,
+ },
compactTimeline: {
enabled:
authSession.data?.user?.featureFlags.compactTimeline === true ||
diff --git a/web/src/features/feature-previews/components/FeaturePreviewModal.tsx b/web/src/features/feature-previews/components/FeaturePreviewModal.tsx
index 8a3945dfb2..4583cccbe6 100644
--- a/web/src/features/feature-previews/components/FeaturePreviewModal.tsx
+++ b/web/src/features/feature-previews/components/FeaturePreviewModal.tsx
@@ -18,6 +18,8 @@ import {
} from "@/src/features/feature-flags/available-flags";
import compactTimelineDarkIllustration from "../assets/compact-timeline-dark.svg";
+import sessionsSearchBarDarkIllustration from "../assets/sessions-search-bar-dark.svg";
+import sessionsSearchBarLightIllustration from "../assets/sessions-search-bar-light.svg";
import compactTimelineLightIllustration from "../assets/compact-timeline-light.svg";
import modernSessionDarkIllustration from "../assets/modern-session-dark.svg";
import modernSessionLightIllustration from "../assets/modern-session-light.svg";
@@ -81,6 +83,19 @@ const PREVIEW_REGISTRY: PreviewRegistryItem[] = [
alt: "A whole trace as dense coloured lines, one per observation, cascading across a time axis.",
},
},
+ {
+ flag: "sessionsSearchBar",
+ description:
+ "Filter sessions by typing instead of clicking β€” the same query bar the observations table uses, now over the sessions table.",
+ details:
+ "One keyboard-driven bar over the sessions table: type `userIds:alice`, `tags:(billing AND urgent)`, `duration:>30`, `metadata.region:eu`, or `scores.helpfulness:>0.8` and press Enter. Autocomplete suggests fields and the values your project has actually recorded. The facet sidebar stays and stays in sync β€” the bar is an additional editor over the same filters, so saved views keep working from either side.",
+ feedbackUrl: "https://github.com/orgs/langfuse/discussions",
+ illustration: {
+ light: sessionsSearchBarLightIllustration,
+ dark: sessionsSearchBarDarkIllustration,
+ alt: "A query bar above the sessions table with typed filter pills and an autocomplete list.",
+ },
+ },
];
const FEATURE_PREVIEW_MODAL_TITLE = "Feature Preview";
diff --git a/web/src/features/filters/config/sessionsSearchRegistry.ts b/web/src/features/filters/config/sessionsSearchRegistry.ts
new file mode 100644
index 0000000000..2fbb974033
--- /dev/null
+++ b/web/src/features/filters/config/sessionsSearchRegistry.ts
@@ -0,0 +1,128 @@
+import {
+ fieldRegistryFromColumns,
+ SCORE_COLUMNS,
+ type FieldRegistry,
+} from "@/src/features/search-bar/lib/fields";
+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";
+
+import { sessionEventsFilterConfig } from "./sessions-config";
+
+/**
+ * The bar's field list is derived from the sidebar's FACETS, not from the raw
+ * `ColumnDefinition[]`. The facet list is the view's curated filter surface;
+ * the column list also carries internals the sidebar never offers (`usage`
+ * duplicates `totalTokens`, `createdAt` is owned by the time-range picker,
+ * `bookmarked` was retired from the UI). Deriving from facets keeps the bar a
+ * subset of the sidebar by construction β€” the invariant that makes saved views
+ * round-trip and stops the bar from writing filters the sidebar cannot show or
+ * remove. Adding a facet gives the bar the field for free.
+ */
+function facetColumns(config: FilterConfig) {
+ const exposed = new Set(config.facets.map((facet) => facet.column));
+ return config.columnDefinitions.filter((column) => exposed.has(column.id));
+}
+
+/**
+ * Sessions filter columns whose sidebar values come from
+ * `sessions.filterOptions*` β€” the AI prompt's vocabulary for this view.
+ */
+const AI_CONTEXT_FIELDS = [
+ { observedOptionsKey: "environment", promptLabel: "environment" },
+ { observedOptionsKey: "userIds", promptLabel: "userIds (user)" },
+ { observedOptionsKey: "tags", promptLabel: "tags" },
+ {
+ observedOptionsKey: SCORE_COLUMNS.observation.numeric,
+ promptLabel: "scores.<name> (numeric)",
+ },
+ {
+ observedOptionsKey: SCORE_COLUMNS.observation.categorical,
+ promptLabel: "scores.<name> (categorical)",
+ },
+ {
+ observedOptionsKey: SCORE_COLUMNS.observation.boolean,
+ promptLabel: "scores.<name> (boolean)",
+ },
+] as const;
+
+/**
+ * Grammar overlay: only what `ColumnDefinition` deliberately does not carry β€”
+ * user-facing aliases, display units, and prose labels. Units matter here
+ * because every sessions number column is a magnitude someone types with an
+ * implied unit (`duration:>30`, `cost:>0.5`).
+ */
+const SESSION_FIELD_OVERLAY = {
+ id: {
+ aliases: ["sessionid", "session_id", "session"],
+ label: "Session ID",
+ description: "Session identifier",
+ },
+ environment: { aliases: ["env"] },
+ userIds: {
+ aliases: ["userid", "user_id", "user", "users", "userids"],
+ label: "User IDs",
+ description: "User ids seen in the session",
+ },
+ tags: {
+ aliases: ["tag", "tracetags", "trace_tags"],
+ label: "Trace tags",
+ description: "Tags on the session's traces",
+ },
+ sessionDuration: {
+ aliases: ["duration", "sessionduration", "session_duration"],
+ label: "Session duration",
+ description: "Session duration in seconds",
+ unit: "s",
+ },
+ countTraces: {
+ aliases: ["traces", "tracecount", "trace_count", "counttraces"],
+ label: "Trace count",
+ description: "Number of traces in the session",
+ },
+ inputTokens: { aliases: ["inputtokens", "input_tokens"] },
+ outputTokens: { aliases: ["outputtokens", "output_tokens"] },
+ totalTokens: { aliases: ["totaltokens", "total_tokens", "tokens"] },
+ inputCost: { aliases: ["inputcost", "input_cost"], unit: "$" },
+ outputCost: { aliases: ["outputcost", "output_cost"], unit: "$" },
+ totalCost: { aliases: ["totalcost", "total_cost", "cost"], unit: "$" },
+ commentCount: { aliases: ["commentcount", "comment_count"] },
+ commentContent: {
+ aliases: ["commentcontent", "comment_content", "comment"],
+ label: "Comment text",
+ description: "Text of comments on the session",
+ },
+};
+
+function sessionsRegistry(config: FilterConfig, metadata: boolean) {
+ return fieldRegistryFromColumns(facetColumns(config), {
+ id: "sessions",
+ metadata,
+ scores: true,
+ // Sessions aggregate scores at session level; the backend has no
+ // `trace_scores_*` columns, so the legacy trace namespace stays closed.
+ traceScores: false,
+ // Sessions has no full-text lane. `id contains` is its most-applied filter
+ // by a wide margin, so a bare word means that rather than an error.
+ allowFreeText: false,
+ defaultTextField: "id",
+ recentSearches: true,
+ searchExamples: [
+ "userIds:alice",
+ "tags:(billing AND urgent)",
+ "duration:>30",
+ "scores.helpfulness:>0.8",
+ ],
+ aiContextFields: AI_CONTEXT_FIELDS,
+ fields: SESSION_FIELD_OVERLAY,
+ });
+}
+
+/**
+ * v4 (events-backed) sessions. The v3 config differs by exactly one column β€” v4
+ * adds `metadata` β€” so one derivation parameterised by the metadata flag would
+ * cover both. Only the v4 registry exists because the bar is gated on v4; a v3
+ * variant would be unreachable, and the recipe forbids speculative registries.
+ */
+export const SESSIONS_FIELD_REGISTRY: FieldRegistry = sessionsRegistry(
+ sessionEventsFilterConfig,
+ true,
+);
diff --git a/web/src/features/search-bar/README.md b/web/src/features/search-bar/README.md
index 8f7308ca56..5d00cb0257 100644
--- a/web/src/features/search-bar/README.md
+++ b/web/src/features/search-bar/README.md
@@ -1,7 +1,8 @@
# Search Bar
-Grammar-based query bar shared by the observations (v4 events) table and
-evaluation-rule observation filters. On the events table it does NOT replace
+Grammar-based query bar shared by the observations (v4 events) table,
+evaluation-rule observation filters, and the sessions table (Feature Preview,
+`sessionsSearchBar`). On the events table it does NOT replace
the facet sidebar β€” it is an ADDITIONAL keyboard-driven editor that coexists
with the sidebar and stays in sync with it. The facet sidebar's `FilterState`
(+ the table's full-text search) remains the single source of truth; the bar
@@ -396,22 +397,51 @@ registry + grammar + value validation. Keep it that way.
adapter, serializer, completion planner, token projection, store, and AI prompt
all take an injected `FieldRegistry`. `EVENTS_FIELD_REGISTRY` remains the default
for existing call sites; evaluation rules pass `RULE_FIELD_REGISTRY`, which is
-derived from the same `eventsEvalFilterColumns` used by backend validation.
+derived from the same `eventsEvalFilterColumns` used by backend validation, and
+the sessions table passes `SESSIONS_FIELD_REGISTRY`
+(`features/filters/config/sessionsSearchRegistry.ts`).
+
+**Pass the registry to BOTH halves.** `registry` is an optional prop defaulting
+to `EVENTS_FIELD_REGISTRY` on `useEventsSearchBar` AND on `EventsSearchBarRow`.
+Give it to the hook only and the view still _works_: commits validate against
+the right fields while the autocomplete offers the events list. Nothing throws β€”
+so a new view must check the field dropdown, not just that Enter applies.
**Recipe to add the bar to a view:**
-1. **Derive the field registry from that view's `ColumnDefinition[]`** β€” do NOT
- hand-author a second 47-entry list. ~70% is mechanical: `type β†’ kind`
- (`number`/`datetime`/`boolean` map directly, everything else β†’ `text`),
- `nullable`, `options β†’ observed values`, `unit`. Use the existing
- `fieldRegistryFromColumns(cols, overlay)` helper.
+1. **Derive the field registry from the view's FACETS, not its raw columns.** Use
+ `fieldRegistryFromColumns(cols, overlay)` β€” never hand-author a second
+ 47-entry list; ~70% is mechanical (`type β†’ kind`, `nullable`,
+ `options β†’ observed values`, `unit`). But feed it the columns the _facet
+ sidebar_ exposes, as `sessionsSearchRegistry.ts` does, not the whole
+ `ColumnDefinition[]`. A view's column list also carries internals the sidebar
+ deliberately never offers β€” a duplicate (`usage` = `totalTokens`), a column
+ owned by another control (`createdAt`, the time-range picker), a retired one
+ (`bookmarked`). Deriving from facets keeps the bar a strict SUBSET of the
+ sidebar by construction: no bar-authored filter the sidebar cannot display or
+ clear, and adding a facet gives the bar the field for free. Anything outside
+ that set resolves to null, so an old saved view's filter on it lands in
+ `skippedFilters` (preserved) instead of becoming an unparsable token.
2. **Add a thin per-view grammar overlay** for what `ColumnDefinition`
deliberately does not carry (it is a UI/SQL contract, not a grammar):
user-facing **field aliases** (`env`, `tags`, `ttft`), **inline filter
aliases/macros**, **AI context fields**, **dot-path roots**
(`metadata.`, `scores.`/`traceScores.` and their score columns), and
**value-parse hints** (datetime ISO, numeric, boolean). Keep it small and
- declarative.
+ declarative. Three flags are per-view capabilities, not cosmetics:
+ - `metadata` / `scores` / `traceScores` β€” the keyed dot-path roots. Set them
+ from the columns the view's BACKEND has, not from what reads well: sessions
+ aggregates scores at session level and has no `trace_scores_*` columns, so
+ it keeps `scores.` and closes `traceScores.`. A dot path the backend cannot
+ answer is worse than an unknown-field diagnostic. `fieldRegistryFromColumns`
+ drops the keyed score columns from the field list when `scores` is on
+ (`score_categories` is `categoryOptions`, not `*Object`, so the `*Object`
+ filter alone would leave a bogus keyless `score_categories:` field).
+ - `allowFreeText` + `defaultTextField` β€” see "Bare text on a view with no
+ full-text lane" below.
+ - `searchExamples` β€” the placeholder, **written per view, never derived from
+ field ids**. The events examples (`level:ERROR`, `latency:>2`) advertised
+ fields that do not exist on either of the other two surfaces.
3. **Reuse the view's `filterOptions` tRPC** for observed values β€”
`observed-options.ts` already maps that payload to per-column observed
values; point it at the new view's procedure (do not invent a parallel one).
@@ -426,6 +456,27 @@ derived from the same `eventsEvalFilterColumns` used by backend validation.
6. **Add the round-trip property test for the new registry** (see Hardening) β€”
run it per registry. This is the universal safety net across views.
+**Bare text on a view with no full-text lane.** Sessions has no `searchQuery`
+at all β€” `sessions.all*` takes none. Two registry options cover that:
+
+- `allowFreeText: false` alone β€” bare words are a commit-blocking diagnostic
+ (evaluation rules).
+- `allowFreeText: false` + `defaultTextField: "<field>"` β€” bare words become a
+ `contains` filter on that field (sessions uses `id`: it is that view's
+ most-applied filter by an order of magnitude, and every application of it is
+ `contains`). Two properties make this safe rather than magic: the rewrite is
+ **offered before Enter** (it joins the matching-filter suggestions, so the user
+ sees `id:"…"` while typing), and it is **visible and terminal after** β€” the bar
+ re-renders the word as an `id:` pill which commits to the identical filter. It
+ lowers through the normal field path; there is no second lowering path.
+- A multi-word run is ONE phrase, coalesced exactly like `searchQuery` is. Per
+ word it would AND `id contains test` with `id contains 123` β€” matching neither
+ the input nor the suggestion.
+
+**`createFieldRegistry` stays unexported.** Both derived views (rules, sessions)
+are fully expressed by `fieldRegistryFromColumns` + overlay; nothing has yet
+needed to hand-assemble a registry. Do not export it speculatively.
+
**What stays grammar-global β€” do not make per-view:** tokenizing, quoting
(`serializeValue` ↔ `reservedTokenIssue` is a **mirror invariant**: add a
reserved token to one, add it to the other, or the round-trip test fails),
@@ -459,7 +510,10 @@ real consumer and validate it against that view's backend filter contract.
The harness is **pure and registry-shaped**: it generates the matrix from the
passed `view.registry`, so it auto-covers added/changed fields. Each
filterable view gets the same coverage by adding one block to the
- `.clienttest.ts` with its registry β€” see "Extending to other views".
+ `.clienttest.ts` with its registry β€” see "Extending to other views". It only
+ exercises free text through `freeTextValues` (INV-3, serialize↔parse), so a
+ `defaultTextField` view must also pin its phrase/round-trip behaviour
+ explicitly, as the sessions block does.
- **`SearchComposer` (~1.3k LOC) has no unit tests** β€” the contenteditable
controller is browser-reviewed only. Extracting the selection/`beforeinput`
diff --git a/web/src/features/search-bar/components/EventsSearchBarRow.tsx b/web/src/features/search-bar/components/EventsSearchBarRow.tsx
index 1a6e64948b..13fc77fdb5 100644
--- a/web/src/features/search-bar/components/EventsSearchBarRow.tsx
+++ b/web/src/features/search-bar/components/EventsSearchBarRow.tsx
@@ -101,7 +101,11 @@ export function EventsSearchBarRow({
const { organization } = useQueryProject();
// Mirror the legacy wand gate: org-level AI features. The server
// enforces it too, so this only governs whether the affordance is offered.
- const aiAvailable = Boolean(organization?.aiFeaturesEnabled);
+ // Org entitlement AND a prompt written for this view β€” see
+ // FieldRegistry.aiFilterPrompt. Without the second half a new surface silently
+ // inherits the events prompt.
+ const aiAvailable =
+ Boolean(organization?.aiFeaturesEnabled) && registry.aiFilterPrompt;
const activateAi = React.useCallback(() => {
// Ground the model on real project values: lazily request the AI columns so
diff --git a/web/src/features/search-bar/components/SearchBarAiPrompt.tsx b/web/src/features/search-bar/components/SearchBarAiPrompt.tsx
index 44f3f7c0d4..aa89f79f4e 100644
--- a/web/src/features/search-bar/components/SearchBarAiPrompt.tsx
+++ b/web/src/features/search-bar/components/SearchBarAiPrompt.tsx
@@ -19,6 +19,7 @@ import { ArrowLeft, ArrowRight, Loader2 } from "lucide-react";
import { useStore } from "zustand";
import { type FilterState } from "@langfuse/shared";
+import type { FieldRegistry } from "@/src/features/search-bar/lib/fields";
import { KeyboardShortcut } from "@/src/components/design-system/KeyboardShortcut/KeyboardShortcut";
import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import type { ObservedScoreNames } from "@/src/features/search-bar/lib/observed-options";
@@ -58,7 +59,7 @@ export function SearchBarAiPrompt({
* model's returned score keys against these (a misspelled name would
* otherwise apply as a dead filter that silently matches nothing). */
scoreNames?: ObservedScoreNames;
- registryId?: "events" | "evaluationRules";
+ registryId?: FieldRegistry["id"];
/** Apply generated filters via the bar's setFilterState (apply-immediately). */
onApply: (filters: FilterState) => void;
/** Leave AI mode and restore the grammar composer. */
diff --git a/web/src/features/search-bar/components/SearchComposer.tsx b/web/src/features/search-bar/components/SearchComposer.tsx
index 054cf363f4..1f699ba3bc 100644
--- a/web/src/features/search-bar/components/SearchComposer.tsx
+++ b/web/src/features/search-bar/components/SearchComposer.tsx
@@ -55,7 +55,7 @@ import {
WORD_JOINER,
} from "@/src/features/search-bar/components/ComposerTokens";
import {
- COMPOSER_PLACEHOLDER,
+ composerPlaceholder,
deactivationReason,
optionDomId,
} from "@/src/features/search-bar/components/presentation";
@@ -1201,6 +1201,7 @@ export function SearchComposer({
setHoveredTokenId(token?.getAttribute("data-segment-id") ?? null);
};
+ const placeholder = composerPlaceholder(registry);
const segments = deriveComposerSegments(draft, scoreTypes, registry);
// The token holding a collapsed caret β€” the keyboard counterpart to hover.
// Not at the trailing insertion point, where the user is appending, not
@@ -1397,9 +1398,9 @@ export function SearchComposer({
? "right-20"
: "right-8",
)}
- title={COMPOSER_PLACEHOLDER}
+ title={placeholder}
>
- {COMPOSER_PLACEHOLDER}
+ {placeholder}
</div>
)}
<div
diff --git a/web/src/features/search-bar/components/presentation.ts b/web/src/features/search-bar/components/presentation.ts
index c5ea61635d..33661202c6 100644
--- a/web/src/features/search-bar/components/presentation.ts
+++ b/web/src/features/search-bar/components/presentation.ts
@@ -3,10 +3,14 @@
// component files keep Fast Refresh eligibility.
import type { ComposerSegment } from "@/src/features/search-bar/lib/composer-segments";
+import type { FieldRegistry } from "@/src/features/search-bar/lib/fields";
-// Page-neutral: the bar mounts on both the Observations and Traces tables.
-export const COMPOSER_PLACEHOLDER =
- "Search β€” e.g. level:ERROR, -env:dev, latency:>2, scores.accuracy:>0.8";
+/** Per-view: the examples have to name fields the view actually has. */
+export function composerPlaceholder(registry: FieldRegistry): string {
+ return registry.searchExamples.length > 0
+ ? `Search β€” e.g. ${registry.searchExamples.join(", ")}`
+ : "Search";
+}
/** DOM id for an option row β€” referenced by aria-activedescendant. Option ids
* embed observed values (`value:My Test Trace`) and recent queries, which can
diff --git a/web/src/features/search-bar/lib/adapter.ts b/web/src/features/search-bar/lib/adapter.ts
index 5fc5606763..920beed337 100644
--- a/web/src/features/search-bar/lib/adapter.ts
+++ b/web/src/features/search-bar/lib/adapter.ts
@@ -160,15 +160,45 @@ export function astToFilterState(
lowerTopLevel(ast, false, ctx);
}
+ const defaultTextFilter = lowerDefaultTextField(ctx);
+
return {
filters: ctx.filters,
- searchQuery: ctx.searchTerms.length > 0 ? ctx.searchTerms.join(" ") : null,
+ searchQuery:
+ defaultTextFilter || ctx.searchTerms.length === 0
+ ? null
+ : ctx.searchTerms.join(" "),
// The bar has no scope tokens; the caller (commit.ts) applies the default.
searchType: null,
errors: ctx.errors,
};
}
+/**
+ * On a view with no full-text lane, the collected free-text words are ONE
+ * phrase on the view's default text field β€” the same coalescing the events
+ * table applies before writing `searchQuery`, and the same thing the bar's own
+ * `id:"test 123"` suggestion promises. Lowering per word instead would AND
+ * `id contains test` with `id contains 123`, which matches neither.
+ * Returns whether it consumed the terms.
+ */
+function lowerDefaultTextField(ctx: LowerContext): boolean {
+ const field = ctx.registry.defaultTextField;
+ if (ctx.registry.allowFreeText || field === null) return false;
+ if (ctx.searchTerms.length === 0) return false;
+ lowerFilterNode(
+ {
+ kind: "filter",
+ key: field,
+ op: "=",
+ values: [ctx.searchTerms.join(" ")],
+ },
+ false,
+ ctx,
+ );
+ return true;
+}
+
// AND chains (top-level or parenthesized β€” semantically identical in the
// flat contract) accept free text (-> searchQuery; the default scope searches
// ids, names, input, and output) and lower everything else into single filters.
@@ -186,19 +216,27 @@ function lowerTopLevel(
return;
}
// A bare dot-prefix (`metadata.`, `scores.`, …) parses as free text, so
- // committing it would silently set searchQuery to the prefix. Reject it
- // here so every commit path (typed Enter and structured pick) is gated.
- // Quoted text is an explicit literal search and is allowed.
- if (!ctx.registry.allowFreeText) {
- ctx.errors.push("Free-text search is not supported by this view");
- return;
- }
+ // committing it would silently search for the prefix itself. Gated ahead
+ // of the free-text branches below so every view reports the same accurate
+ // reason β€” a view whose bare words are rewritten (or rejected outright)
+ // still supports `metadata.<key>`, so "free text is not supported" would
+ // be the wrong message. Quoted text is an explicit literal and is allowed.
if (!node.quoted && isDanglingDotPrefix(node.value, ctx.registry)) {
ctx.errors.push(
`Incomplete field "${node.value}" β€” add a key after the dot (e.g. metadata.region:eu)`,
);
return;
}
+ if (
+ !ctx.registry.allowFreeText &&
+ ctx.registry.defaultTextField === null
+ ) {
+ ctx.errors.push("Free-text search is not supported by this view");
+ return;
+ }
+ // Collected, not lowered: on a `defaultTextField` view a multi-word run is
+ // ONE phrase, so it becomes a single filter (see lowerDefaultTextField),
+ // never one AND-ed filter per word.
ctx.searchTerms.push(node.value);
return;
case "not":
diff --git a/web/src/features/search-bar/lib/completions.ts b/web/src/features/search-bar/lib/completions.ts
index 23df4f59d9..779c5cb207 100644
--- a/web/src/features/search-bar/lib/completions.ts
+++ b/web/src/features/search-bar/lib/completions.ts
@@ -27,6 +27,7 @@ import {
type FieldRef,
} from "./fields";
import { quoteIfNeeded } from "./quoting";
+import { validateQuery } from "./validate";
import { rankFilter } from "./rank";
import type { ObservedOptions } from "./observed-options";
@@ -228,11 +229,16 @@ function fieldOptions(
);
}
if (includeVirtual) {
+ // The example names one of THIS view's nullable fields; `has:endTime` on a
+ // view without endTime advertises a filter that cannot resolve.
+ const example = registry.nullableFields()[0]?.id;
opts.push({
id: "field:has",
kind: "field",
label: "has",
- detail: "field has a value, e.g. has:endTime (-has: for missing)",
+ detail: example
+ ? `field has a value, e.g. has:${example} (-has: for missing)`
+ : "field has a value (-has: for missing)",
fieldId: "has",
});
}
@@ -389,16 +395,24 @@ function valueOptions(
function recentOptions(
recents: string[],
currentQueryText: string,
+ registry: FieldRegistry,
): CompletionOption[] {
- return recents
- .filter((q) => q !== currentQueryText.trim())
- .slice(0, MAX_RECENTS_SHOWN)
- .map((q, i) => ({
- id: `recent:${i}:${q}`,
- kind: "recent" as const,
- label: q,
- query: q,
- }));
+ return (
+ recents
+ .filter((q) => q !== currentQueryText.trim())
+ // Recents are stored per PROJECT, not per view, so a query typed on another
+ // table can be offered here. Picking one that names a field this view does
+ // not have would insert a query that cannot commit, so offer only the ones
+ // that are valid against THIS registry.
+ .filter((q) => validateQuery(q, undefined, registry).valid)
+ .slice(0, MAX_RECENTS_SHOWN)
+ .map((q, i) => ({
+ id: `recent:${i}:${q}`,
+ kind: "recent" as const,
+ label: q,
+ query: q,
+ }))
+ );
}
function queryPresetSections(
@@ -570,7 +584,8 @@ function pathKindOf(
const lower = keyPart.toLowerCase();
for (const kind of PATH_PREFIXES) {
if (kind.canonical === "metadata." && !registry.metadata) continue;
- if (kind.canonical !== "metadata." && !registry.scores) continue;
+ if (kind.canonical === "scores." && !registry.scores) continue;
+ if (kind.canonical === "traceScores." && !registry.traceScores) continue;
if (lower.startsWith(kind.prefix)) {
return { kind, typedKey: keyPart.slice(kind.prefix.length) };
}
@@ -1198,8 +1213,8 @@ export function planInputCompletions(
...section(SECTION_FIELDS, fieldOptions(registry)),
...section(
SECTION_RECENT,
- registry.allowFreeText
- ? recentOptions(ctx.recents, ctx.currentQueryText)
+ registry.recentSearches
+ ? recentOptions(ctx.recents, ctx.currentQueryText, registry)
: [],
),
],
@@ -1315,6 +1330,26 @@ export function planInputCompletions(
colon === -1 && !negated
? freeTextRun(ctx.currentQueryText, caret)
: null;
+ // A view with no full-text lane offers the one rewrite it does support, so
+ // the bare-word canonicalization is visible BEFORE Enter, not after it.
+ const defaultTextRewrite: CompletionOption[] =
+ run !== null && !registry.allowFreeText && registry.defaultTextField
+ ? (() => {
+ const ref = registry.resolveField(registry.defaultTextField);
+ if (ref?.type !== "field") return [];
+ const insert = `${ref.field.id}:${serializeValue(run.text)}`;
+ return [
+ {
+ id: "scope:defaultTextField",
+ kind: "pattern" as const,
+ label: insert,
+ detail: `${ref.field.label.toLowerCase()} contains "${run.text}"`,
+ insert,
+ replaceSpan: { from: run.from, to: run.to },
+ },
+ ];
+ })()
+ : [];
const searchScopes: CompletionOption[] =
run !== null && registry.allowFreeText
? scopeSwitchOptions(
@@ -1331,14 +1366,19 @@ export function planInputCompletions(
// Contextual facet matches share the run gate (and its span) with the scope
// switches: both rewrite the whole free-text block the user sees, and the
// gate already excludes negated terms and existing `key:` tokens.
+ // The default-text rewrite IS a matching filter (`id:chat`), not a full-text
+ // scope, so it joins that section after the observed-value matches.
const matchingFilters: CompletionOption[] =
run !== null
- ? matchingFilterOptions(
- run.text,
- ctx.observed,
- { from: run.from, to: run.to },
- registry,
- )
+ ? [
+ ...matchingFilterOptions(
+ run.text,
+ ctx.observed,
+ { from: run.from, to: run.to },
+ registry,
+ ),
+ ...defaultTextRewrite,
+ ]
: [];
if (
fields.length +
diff --git a/web/src/features/search-bar/lib/fields.ts b/web/src/features/search-bar/lib/fields.ts
index 9b3f647424..80b5226f80 100644
--- a/web/src/features/search-bar/lib/fields.ts
+++ b/web/src/features/search-bar/lib/fields.ts
@@ -57,12 +57,36 @@ export type FieldDef = {
};
export type FieldRegistry = {
- id: "events" | "evaluationRules";
+ id: "events" | "evaluationRules" | "sessions";
fields: readonly FieldDef[];
columns: readonly ColumnDefinition[];
allowFreeText: boolean;
metadata: boolean;
scores: boolean;
+ /** Trace-level `traceScores.<name>` paths. Views whose backend has no
+ * trace-score columns (sessions) keep observation scores without them. */
+ traceScores: boolean;
+ /** Field a bare word searches on a view with no full-text lane. Sessions has
+ * no searchQuery, but `id contains` is its most-applied filter by far, so a
+ * bare word means that instead of being rejected. Null = reject. */
+ defaultTextField: string | null;
+ /** 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[];
+ /**
+ * Offer the project's recent searches on the empty bar. Off by default: the
+ * store is per PROJECT, not per view, so a view opts in and only the recents
+ * that are valid against its own registry are offered.
+ */
+ recentSearches: boolean;
+ /**
+ * Whether this view has its OWN branch in `buildFilterSystemPrompt`. False
+ * hides Ask AI: the fallback prompt is the events one β€” events prose, events
+ * worked examples β€” so a view without its own branch would be handed a
+ * correct field catalog wrapped in instructions steering the model at columns
+ * it does not have. Write the branch, then flip this.
+ */
+ aiFilterPrompt: boolean;
aiContextFields: readonly AIContextField[];
resolveField: (name: string) => FieldRef | null;
nullableFields: () => readonly FieldDef[];
@@ -93,12 +117,28 @@ export function fieldRegistryFromColumns(
fields?: Readonly<Record<string, FieldOverlay>>;
metadata?: boolean;
scores?: boolean;
+ /** Defaults to `scores`. */
+ traceScores?: boolean;
allowFreeText?: boolean;
+ defaultTextField?: string;
+ searchExamples?: readonly string[];
+ recentSearches?: boolean;
+ aiFilterPrompt?: boolean;
aiContextFields?: readonly AIContextField[];
},
): FieldRegistry {
+ const scores = overlay.scores ?? false;
const fields = columns
- .filter((column) => !column.type.endsWith("Object"))
+ // `*Object` columns and the categorical score column are keyed dot-paths
+ // (`metadata.<key>`, `scores.<name>`), never plain fields β€” a derived
+ // `score_categories` field would lower to a keyless categoryOptions filter
+ // the backend cannot answer. They stay in `columns` so the reverse adapter
+ // still resolves them.
+ .filter(
+ (column) =>
+ !column.type.endsWith("Object") &&
+ !(scores && isKeyedScoreColumn(column.id)),
+ )
.map((column): FieldDef => {
const fieldOverlay = overlay.fields?.[column.id];
const kind: FieldKind =
@@ -133,8 +173,13 @@ export function fieldRegistryFromColumns(
fields,
columns,
metadata: overlay.metadata ?? false,
- scores: overlay.scores ?? false,
+ scores,
+ traceScores: overlay.traceScores ?? scores,
allowFreeText: overlay.allowFreeText ?? true,
+ defaultTextField: overlay.defaultTextField ?? null,
+ searchExamples: overlay.searchExamples ?? [],
+ recentSearches: overlay.recentSearches ?? false,
+ aiFilterPrompt: overlay.aiFilterPrompt ?? false,
aiContextFields: overlay.aiContextFields ?? [],
});
}
@@ -217,6 +262,15 @@ export const SCORE_COLUMNS = {
},
} as const;
+const KEYED_SCORE_COLUMNS: ReadonlySet<string> = new Set([
+ ...Object.values(SCORE_COLUMNS.observation),
+ ...Object.values(SCORE_COLUMNS.trace),
+]);
+
+function isKeyedScoreColumn(column: string): boolean {
+ return KEYED_SCORE_COLUMNS.has(column);
+}
+
export type FieldRef =
| { type: "field"; field: FieldDef }
| { type: "metadata"; key: string }
@@ -229,7 +283,12 @@ function createFieldRegistry({
columns,
metadata,
scores,
+ traceScores,
allowFreeText,
+ defaultTextField,
+ searchExamples,
+ recentSearches,
+ aiFilterPrompt,
aiContextFields,
}: {
id: FieldRegistry["id"];
@@ -237,7 +296,12 @@ function createFieldRegistry({
columns: readonly ColumnDefinition[];
metadata: boolean;
scores: boolean;
+ traceScores: boolean;
allowFreeText: boolean;
+ defaultTextField: string | null;
+ searchExamples: readonly string[];
+ recentSearches: boolean;
+ aiFilterPrompt: boolean;
aiContextFields: readonly AIContextField[];
}): FieldRegistry {
const byName = new Map<string, FieldDef>();
@@ -262,6 +326,11 @@ function createFieldRegistry({
allowFreeText,
metadata,
scores,
+ traceScores,
+ defaultTextField,
+ searchExamples,
+ recentSearches,
+ aiFilterPrompt,
aiContextFields,
resolveField: (name) => resolveFromRegistry(name, registry, byName),
nullableFields: () => nullable,
@@ -270,9 +339,8 @@ function createFieldRegistry({
const lower = value.toLowerCase();
return (
(metadata && lower === METADATA_PREFIX) ||
- (scores &&
- (SCORE_PREFIXES.includes(lower) ||
- TRACE_SCORE_PREFIXES.includes(lower)))
+ (scores && SCORE_PREFIXES.includes(lower)) ||
+ (traceScores && TRACE_SCORE_PREFIXES.includes(lower))
);
},
columnIdOf: (column) => columnIds.get(column.toLowerCase()) ?? null,
@@ -286,7 +354,17 @@ export const EVENTS_FIELD_REGISTRY = createFieldRegistry({
columns: eventsTableCols,
metadata: true,
scores: true,
+ traceScores: true,
allowFreeText: true,
+ defaultTextField: null,
+ searchExamples: [
+ "level:ERROR",
+ "-env:dev",
+ "latency:>2",
+ "scores.accuracy:>0.8",
+ ],
+ recentSearches: true,
+ aiFilterPrompt: true,
aiContextFields: [
{ observedOptionsKey: "type", promptLabel: "type" },
{ observedOptionsKey: "level", promptLabel: "level" },
@@ -336,13 +414,15 @@ function resolveFromRegistry(
const key = unquote(name.slice(METADATA_PREFIX.length)).value;
return key.length > 0 ? { type: "metadata", key } : null;
}
- if (registry.scores) {
+ if (registry.traceScores) {
for (const prefix of TRACE_SCORE_PREFIXES) {
if (lower.startsWith(prefix)) {
const key = unquote(name.slice(prefix.length)).value;
return key.length > 0 ? { type: "scores", key, level: "trace" } : null;
}
}
+ }
+ if (registry.scores) {
for (const prefix of SCORE_PREFIXES) {
if (lower.startsWith(prefix)) {
const key = unquote(name.slice(prefix.length)).value;
diff --git a/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts b/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts
index 57c87d47e8..118d93bb6e 100644
--- a/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts
+++ b/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts
@@ -4,8 +4,10 @@ import { describe, expect, it } from "vitest";
import { EVENTS_FIELD_REGISTRY } from "./fields";
import { RULE_FIELD_REGISTRY } from "@/src/features/evals/v2/constants/ruleSearchRegistry";
+import { SESSIONS_FIELD_REGISTRY } from "@/src/features/filters/config/sessionsSearchRegistry";
import { validateQuery } from "./validate";
import { planCommit } from "./commit";
+import { filterStateToQueryText } from "./filter-state-to-query";
import { planInputCompletions } from "./completions";
import {
generateQueryCases,
@@ -278,3 +280,258 @@ describe("search bar invariants β€” evaluation rules registry", () => {
expect(runSearchBarInvariants(evaluationRulesView)).toEqual([]);
});
});
+
+const sessionsView: RegistryUnderTest = {
+ name: "sessions v4",
+ registry: SESSIONS_FIELD_REGISTRY,
+ extraKeys: [
+ "metadata.region",
+ 'metadata."my key"',
+ "scores.accuracy",
+ 'scores."Rouge Score"',
+ "has:environment",
+ "has:userIds",
+ ],
+ scoreContexts: [
+ {
+ numericScoreNames: new Set(["accuracy"]),
+ categoricalScoreNames: new Set(),
+ },
+ {
+ numericScoreNames: new Set(),
+ categoricalScoreNames: new Set(["accuracy"]),
+ },
+ {
+ numericScoreNames: new Set(),
+ categoricalScoreNames: new Set(),
+ booleanScoreNames: new Set(["accuracy"]),
+ },
+ ],
+ fieldValues: ["x", "default", "5", "0.8", "true", "a b", "user-1"],
+ // Free text is rewritten onto `id`, not dropped, so the quoting/reserved-word
+ // mirror still has to hold on this registry.
+ freeTextValues: ["hello", "refund policy", "or", "and", "!important", "-foo"],
+};
+
+describe("search bar invariants β€” sessions registry", () => {
+ it("holds all three invariants (parity, round-trip, serialize symmetry)", () => {
+ const failures = runSearchBarInvariants(sessionsView);
+ expect(
+ failures,
+ failures.length === 0
+ ? "ok"
+ : `\n${failures
+ .slice(0, 25)
+ .map((f) => ` [${f.invariant}] ${f.case} β€” ${f.detail}`)
+ .join(
+ "\n",
+ )}${failures.length > 25 ? `\n …and ${failures.length - 25} more` : ""}`,
+ ).toEqual([]);
+ });
+
+ it("exposes the sidebar's facets and nothing else", () => {
+ expect(SESSIONS_FIELD_REGISTRY.fields.map((f) => f.id).sort()).toEqual([
+ "commentContent",
+ "commentCount",
+ "countTraces",
+ "environment",
+ "id",
+ "inputCost",
+ "inputTokens",
+ "outputCost",
+ "outputTokens",
+ "sessionDuration",
+ "tags",
+ "totalCost",
+ "totalTokens",
+ "userIds",
+ ]);
+ // Events-only fields and columns the sidebar never offers stay unresolvable,
+ // so a stray token is a diagnostic rather than a filter the sidebar cannot
+ // show or remove.
+ for (const key of ["latency", "createdAt", "usage", "bookmarked"]) {
+ expect(SESSIONS_FIELD_REGISTRY.resolveField(key)).toBeNull();
+ }
+ });
+
+ it("keeps the trace-score namespace closed but observation scores open", () => {
+ expect(SESSIONS_FIELD_REGISTRY.resolveField("scores.accuracy")).toEqual({
+ type: "scores",
+ key: "accuracy",
+ level: "observation",
+ });
+ expect(
+ SESSIONS_FIELD_REGISTRY.resolveField("traceScores.accuracy"),
+ ).toBeNull();
+ });
+
+ it("round-trips the all-of array filters sessions users actually apply", () => {
+ // `tags all of` (1.2k applies/56d) and `userIds all of` are the two shapes
+ // the sessions sidebar produces that no other bar surface exercises.
+ for (const column of ["tags", "userIds"]) {
+ expect(
+ planCommit(`${column}:(a AND b)`, undefined, SESSIONS_FIELD_REGISTRY),
+ ).toMatchObject({
+ status: "committed",
+ filters: [
+ {
+ column,
+ type: "arrayOptions",
+ operator: "all of",
+ value: ["a", "b"],
+ },
+ ],
+ });
+ }
+ });
+
+ it("lowers metadata and session id the way the sidebar does", () => {
+ expect(
+ planCommit("metadata.region:eu", undefined, SESSIONS_FIELD_REGISTRY),
+ ).toMatchObject({
+ status: "committed",
+ filters: [
+ {
+ column: "metadata",
+ type: "stringObject",
+ key: "region",
+ value: "eu",
+ },
+ ],
+ });
+ // `id contains` is how every one of the 13.6k session-id filters is applied.
+ expect(
+ planCommit("id:checkout", undefined, SESSIONS_FIELD_REGISTRY),
+ ).toMatchObject({
+ status: "committed",
+ filters: [
+ {
+ column: "id",
+ type: "string",
+ operator: "contains",
+ value: "checkout",
+ },
+ ],
+ });
+ });
+
+ it("rewrites a bare word onto the session id and settles there", () => {
+ const first = planCommit("refund", undefined, SESSIONS_FIELD_REGISTRY);
+ if (first.status !== "committed") throw new Error(first.status);
+ expect(first).toMatchObject({
+ status: "committed",
+ searchQuery: null,
+ filters: [
+ { column: "id", type: "string", operator: "contains", value: "refund" },
+ ],
+ });
+ // The canonicalization is visible AND terminal: the echo renders `id:refund`
+ // and committing that again produces the identical filter, so the bar does
+ // not keep rewriting itself.
+ expect(
+ filterStateToQueryText(first.filters, undefined, SESSIONS_FIELD_REGISTRY)
+ .text,
+ ).toBe("id:refund");
+ expect(
+ planCommit("id:refund", undefined, SESSIONS_FIELD_REGISTRY),
+ ).toMatchObject({ status: "committed", filters: first.filters });
+
+ // A dangling dot-prefix must stay an error rather than becoming an id search
+ // for the literal text "metadata." β€” and the message has to name the real
+ // problem, since this view does support `metadata.<key>`.
+ const dangling = planCommit(
+ "metadata.",
+ undefined,
+ SESSIONS_FIELD_REGISTRY,
+ );
+ expect(dangling.status).toBe("invalid");
+ if (dangling.status !== "invalid") throw new Error("expected invalid");
+ expect(
+ dangling.diagnostics.some((d) =>
+ /add a key after the dot/.test(d.message),
+ ),
+ ).toBe(true);
+
+ // Quoting it makes it an explicit literal, so it searches ids like any word.
+ expect(
+ planCommit('"metadata."', undefined, SESSIONS_FIELD_REGISTRY),
+ ).toMatchObject({
+ status: "committed",
+ filters: [
+ {
+ column: "id",
+ type: "string",
+ operator: "contains",
+ value: "metadata.",
+ },
+ ],
+ });
+ });
+
+ it("treats a multi-word run as one phrase, not one filter per word", () => {
+ // The suggestion offers `id:"test 123"`, so Enter must agree with it. Per
+ // word it would AND `id contains test` with `id contains 123` β€” a query
+ // matching neither what was typed nor what was offered.
+ const multi = planCommit("test 123", undefined, SESSIONS_FIELD_REGISTRY);
+ if (multi.status !== "committed") throw new Error(multi.status);
+ expect(multi.filters).toEqual([
+ { column: "id", type: "string", operator: "contains", value: "test 123" },
+ ]);
+ expect(multi.searchQuery).toBeNull();
+ // …and it round-trips through the quoting as the same single filter.
+ const text = filterStateToQueryText(
+ multi.filters,
+ undefined,
+ SESSIONS_FIELD_REGISTRY,
+ ).text;
+ expect(text).toBe('id:"test 123"');
+ expect(planCommit(text, undefined, SESSIONS_FIELD_REGISTRY)).toMatchObject({
+ filters: multi.filters,
+ });
+
+ // Words split around a real filter token still coalesce into one phrase.
+ const mixed = planCommit(
+ "test countTraces:8 123",
+ undefined,
+ SESSIONS_FIELD_REGISTRY,
+ );
+ if (mixed.status !== "committed") throw new Error(mixed.status);
+ expect(mixed.filters.filter((f) => f.column === "id")).toEqual([
+ { column: "id", type: "string", operator: "contains", value: "test 123" },
+ ]);
+ });
+
+ it("does not offer Ask AI until the view has its own prompt", () => {
+ // buildFilterSystemPrompt branches on registry.id and falls back to the
+ // EVENTS prompt β€” events prose, events worked examples. A view without its
+ // own branch must not offer AI generation, or the model gets a correct field
+ // catalog wrapped in instructions aimed at columns the view lacks.
+ expect(SESSIONS_FIELD_REGISTRY.aiFilterPrompt).toBe(false);
+ expect(EVENTS_FIELD_REGISTRY.aiFilterPrompt).toBe(true);
+ expect(RULE_FIELD_REGISTRY.aiFilterPrompt).toBe(true);
+ });
+
+ it("offers only the recent searches that are valid on this view", () => {
+ // Recents live in one per-PROJECT store shared with the events bar, so a
+ // query typed there can surface here. An events-only one must not be
+ // offered: picking it would insert a query that cannot commit.
+ const plan = planInputCompletions(
+ {
+ input: "",
+ caret: 0,
+ observed: {},
+ recents: ["latency:>2", "tags:billing", "level:ERROR", "countTraces:8"],
+ currentQueryText: "",
+ },
+ SESSIONS_FIELD_REGISTRY,
+ );
+ const offered = (plan?.sections ?? [])
+ .flatMap((section) => section.options)
+ .filter((option) => option.kind === "recent")
+ .map((option) => option.label);
+ expect(offered).toEqual(["tags:billing", "countTraces:8"]);
+
+ // Opt-in: a view that has not asked for recents gets none, valid or not.
+ expect(RULE_FIELD_REGISTRY.recentSearches).toBe(false);
+ });
+});
diff --git a/web/src/features/search-bar/server/router.ts b/web/src/features/search-bar/server/router.ts
index 0459b0bb53..b6304aa854 100644
--- a/web/src/features/search-bar/server/router.ts
+++ b/web/src/features/search-bar/server/router.ts
@@ -50,6 +50,7 @@ import {
} from "./parseOutcomeScoring";
import { getProductBaseUrl } from "@/src/utils/base-url";
import { RULE_FIELD_REGISTRY } from "@/src/features/evals/v2/constants/ruleSearchRegistry";
+import { SESSIONS_FIELD_REGISTRY } from "@/src/features/filters/config/sessionsSearchRegistry";
import { EVENTS_FIELD_REGISTRY } from "../lib/fields";
// Caps shared with `observedScoreNamesFromOptions` (the client-side builder),
@@ -61,7 +62,9 @@ const scoreNameList = z
const GenerateFilterInput = z.object({
projectId: z.string(),
prompt: z.string().min(1).max(2048),
- registryId: z.enum(["events", "evaluationRules"]).default("events"),
+ registryId: z
+ .enum(["events", "evaluationRules", "sessions"])
+ .default("events"),
/** Existing bar query text, so the model refines the current filters. */
currentQuery: z.string().max(4096).optional(),
/** Project data context (observed values, metadata keys, result count) built
@@ -90,7 +93,18 @@ export const searchBarRouter = createTRPCRouter({
const registry =
input.registryId === "evaluationRules"
? RULE_FIELD_REGISTRY
- : EVENTS_FIELD_REGISTRY;
+ : input.registryId === "sessions"
+ ? SESSIONS_FIELD_REGISTRY
+ : EVENTS_FIELD_REGISTRY;
+ // Defence in depth for the client gate above: generating against the
+ // fallback (events) prompt for a view that has no branch of its own
+ // produces filters for columns that view does not have.
+ if (!registry.aiFilterPrompt) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "AI filter generation is not available for this view",
+ });
+ }
// Generating a filter reads nothing a project member cannot already
// read by hand, so membership is the right bar; whether the org uses
// AI at all is governed by `aiFeaturesEnabled` below.