Skip to content

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

feat(web): unify the Users filter experience with Traces (#17241)

Nikita Kabardin0de1d9c2fb04
diff --git a/web/src/__tests__/server/users-facet-coverage.servertest.ts b/web/src/__tests__/server/users-facet-coverage.servertest.ts
new file mode 100644
index 0000000000..a44658670a
--- /dev/null
+++ b/web/src/__tests__/server/users-facet-coverage.servertest.ts
@@ -0,0 +1,263 @@
+/**
+ * The Users sidebar inherits its facets from the Traces and Observations
+ * configs, and both Users read paths scan a single table with no observation,
+ * score, or comment join. So a facet that is perfectly valid on Traces can be
+ * a 400 on Users, and nothing in the type system says so β€” the failure is a
+ * ClickHouse "unknown identifier s.value" at request time, or an
+ * `InvalidRequestError` out of the filter factory.
+ *
+ * This pins the deny-lists in `users-config.ts` to the queries they describe:
+ * every facet the sidebar offers is run through the real Users query on its
+ * own read path, so inheriting a new join-dependent facet fails here instead
+ * of in a user's browser.
+ */
+import { randomUUID } from "crypto";
+
+import { observationEventsFilterConfig } from "@/src/features/events/config/filter-config";
+import { traceFilterConfig } from "@/src/features/filters/config/traces-config";
+import {
+ usersEventsFilterConfig,
+ usersFilterConfig,
+} from "@/src/features/filters/config/users-config";
+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";
+import { type ColumnDefinition, type FilterState } from "@langfuse/shared";
+import {
+ createEvent,
+ createEventsCh,
+ createObservation,
+ createObservationsCh,
+ createTrace,
+ createTracesCh,
+ getTotalUserCount,
+ getTracesGroupedByUsers,
+ getUserMetrics,
+ getUserMetricsFromEventsTable,
+ getUsersCountFromEventsTable,
+ getUsersFromEventsTable,
+} from "@langfuse/shared/src/server";
+
+const projectId = randomUUID();
+const userId = `facet-coverage-${randomUUID()}`;
+const traceId = randomUUID();
+
+const PROBE_KEY = "__facet_probe_key__";
+
+type Facet = FilterConfig["facets"][number];
+
+/**
+ * The FilterState the sidebar persists for this facet, matching the
+ * type/operator pairs `sidebar-filter-actions.ts` writes. Values are chosen to
+ * match the seeded row where possible: a filter that compiles but excludes
+ * everything still proves the SQL is legal, but matching keeps the assertion
+ * honest about the join actually resolving.
+ */
+function buildFilter(
+ facet: Facet,
+ columnDefinitions: ColumnDefinition[],
+): FilterState {
+ const column = facet.column;
+ const colType = columnDefinitions.find(
+ (c) => c.id === column || c.name === column,
+ )?.type;
+
+ switch (facet.type) {
+ case "categorical":
+ return [
+ {
+ column,
+ type: colType === "arrayOptions" ? "arrayOptions" : "stringOptions",
+ operator: "any of",
+ value: ["default"],
+ },
+ ] as FilterState;
+ case "string":
+ return [
+ { column, type: "string", operator: "contains", value: "" },
+ ] as FilterState;
+ case "numeric":
+ // ">= 0" matches every seeded row and stays inside the narrow
+ // Decimal64(12) range the cost columns cast to.
+ return [
+ { column, type: "number", operator: ">=", value: 0 },
+ ] as FilterState;
+ case "boolean":
+ return [
+ { column, type: "boolean", operator: "=", value: true },
+ ] as FilterState;
+ case "stringKeyValue":
+ return [
+ {
+ column,
+ type: "stringObject",
+ operator: "=",
+ key: PROBE_KEY,
+ value: "",
+ },
+ ] as FilterState;
+ case "keyValue":
+ return [
+ {
+ column,
+ type: "categoryOptions",
+ operator: "any of",
+ key: PROBE_KEY,
+ value: ["probe"],
+ },
+ ] as FilterState;
+ case "numericKeyValue":
+ return [
+ {
+ column,
+ type: "numberObject",
+ operator: ">=",
+ key: PROBE_KEY,
+ value: 0,
+ },
+ ] as FilterState;
+ case "booleanKeyValue":
+ return [
+ {
+ column,
+ type: "booleanObject",
+ operator: "=",
+ key: PROBE_KEY,
+ value: true,
+ },
+ ] as FilterState;
+ }
+}
+
+const runV3 = async (filter: FilterState) => {
+ // The router passes no `columns`/`columnDefinitions`, so the defaults
+ // (tracesTableUiColumnDefinitions + tracesTableCols) apply here too.
+ await getTracesGroupedByUsers(projectId, filter, undefined, 50, 0, undefined);
+ await getTotalUserCount(projectId, filter, undefined);
+ await getUserMetrics(projectId, [userId], filter);
+};
+
+const runV4 = async (filter: FilterState) => {
+ await getUsersFromEventsTable(projectId, filter, undefined, 50, 0);
+ await getUsersCountFromEventsTable(projectId, filter, undefined);
+ await getUserMetricsFromEventsTable(projectId, [userId], filter);
+};
+
+describe("users sidebar facet coverage", () => {
+ beforeAll(async () => {
+ await createTracesCh([
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ user_id: userId,
+ session_id: `facet-coverage-session-${randomUUID()}`,
+ environment: "default",
+ name: "facet-coverage-trace",
+ tags: ["facet-coverage-tag"],
+ version: "v1",
+ release: "r1",
+ }),
+ ]);
+
+ await createObservationsCh([
+ createObservation({
+ id: randomUUID(),
+ trace_id: traceId,
+ project_id: projectId,
+ type: "GENERATION",
+ usage_details: { input: 10, output: 20, total: 30 },
+ total_cost: 5,
+ }),
+ ]);
+
+ await createEventsCh([
+ createEvent({
+ id: randomUUID(),
+ span_id: randomUUID(),
+ parent_span_id: "",
+ type: "SPAN",
+ project_id: projectId,
+ trace_id: traceId,
+ user_id: userId,
+ session_id: `facet-coverage-session-${randomUUID()}`,
+ environment: "default",
+ name: "facet-coverage-event",
+ trace_name: "facet-coverage-trace",
+ tags: ["facet-coverage-tag"],
+ version: "v1",
+ release: "r1",
+ }),
+ ]);
+ });
+
+ it("seeds a user reachable on both read paths", async () => {
+ const v3 = await getTracesGroupedByUsers(
+ projectId,
+ [],
+ undefined,
+ 50,
+ 0,
+ undefined,
+ );
+ const v4 = await getUsersFromEventsTable(projectId, [], undefined, 50, 0);
+ expect(v3.map((u) => u.user)).toContain(userId);
+ expect(v4.map((u) => u.user)).toContain(userId);
+ });
+
+ it.each(usersFilterConfig.facets.map((f) => [f.column, f] as const))(
+ "v3 users query answers the %s facet",
+ async (_column, facet) => {
+ await expect(
+ runV3(buildFilter(facet, usersFilterConfig.columnDefinitions)),
+ ).resolves.toBeUndefined();
+ },
+ );
+
+ it.each(usersEventsFilterConfig.facets.map((f) => [f.column, f] as const))(
+ "v4 users query answers the %s facet",
+ async (_column, facet) => {
+ await expect(
+ runV4(buildFilter(facet, usersEventsFilterConfig.columnDefinitions)),
+ ).resolves.toBeUndefined();
+ },
+ );
+
+ // Without this the suite passes just as happily if every facet were removed
+ // from the config, or if the queries had quietly stopped rejecting anything.
+ it("rejects the score facet both configs exclude", async () => {
+ const scoreFilter = [
+ {
+ column: "scores_avg",
+ type: "numberObject",
+ operator: ">=",
+ key: "quality",
+ value: 0,
+ },
+ ] as FilterState;
+
+ await expect(runV3(scoreFilter)).rejects.toThrow();
+ await expect(runV4(scoreFilter)).rejects.toThrow();
+ });
+
+ // Dropping a facet only hides it from the sidebar. `columnDefinitions` stays
+ // whole on both paths, so a filter on a dropped column that arrives by URL or
+ // saved view still decodes and still reaches the query that rejects it above.
+ // `omittedFilterColumns` is what drops it, which makes the two lists one
+ // decision: a facet this page removes is a filter this page never applies.
+ it.each([
+ ["v3", traceFilterConfig, usersFilterConfig],
+ ["v4", observationEventsFilterConfig, usersEventsFilterConfig],
+ ] as const)(
+ "%s users config never applies a facet it drops",
+ (_, base, config) => {
+ const dropped = base.facets
+ .map((facet) => facet.column)
+ .filter(
+ (column) => !config.facets.some((facet) => facet.column === column),
+ );
+
+ expect(dropped.length).toBeGreaterThan(0);
+ expect(config.omittedFilterColumns ?? []).toEqual(
+ expect.arrayContaining(dropped),
+ );
+ },
+ );
+});
diff --git a/web/src/features/events/hooks/useEventsFilterOptions.ts b/web/src/features/events/hooks/useEventsFilterOptions.ts
index 906c8aa498..051f21add2 100644
--- a/web/src/features/events/hooks/useEventsFilterOptions.ts
+++ b/web/src/features/events/hooks/useEventsFilterOptions.ts
@@ -142,6 +142,14 @@ type UseEventsFilterOptionsParams = {
* typed into.
*/
lazy?: boolean;
+ /**
+ * Off keeps every query unmounted and reports "settled with nothing". For a
+ * surface that exists on both read paths (Users) and picks its option source
+ * per path: a v3 project must not scan `events_core`, and a disabled query is
+ * `pending` forever in react-query, which would skeleton the sidebar for good
+ * if that flag were passed through unchanged.
+ */
+ enabled?: boolean;
};
export function useEventsFilterOptions({
@@ -152,6 +160,7 @@ export function useEventsFilterOptions({
isRootObservation,
columns,
lazy = false,
+ enabled = true,
}: UseEventsFilterOptionsParams) {
// User-authored start-time conditions (search-bar `startTime:>…`) merge into
// the authoritative startTimeFilter channel β€” the server ignores them in
@@ -236,6 +245,7 @@ export function useEventsFilterOptions({
includeApproxCount,
},
{
+ enabled,
trpc: { context: { skipBatch: true } },
...FILTER_OPTION_QUERY_OPTIONS,
},
@@ -285,7 +295,7 @@ export function useEventsFilterOptions({
perColumnPlan.map(({ column, filter }) =>
t.events.filterOptions(
{ ...baseInput, filter, columns: [column] },
- FILTER_OPTION_QUERY_OPTIONS,
+ { enabled, ...FILTER_OPTION_QUERY_OPTIONS },
),
),
{ combine: combineLazy },
@@ -380,6 +390,9 @@ export function useEventsFilterOptions({
// Each entry is gated on an in-flight fetch: a skeleton means "loading", not
// "no data". On a terminal error the column is dropped (no auto-retry, so the
// facet renders its empty state instead of skeletoning forever).
+ // A disabled query never leaves `pending`, so report it as settled-empty
+ // rather than letting consumers skeleton forever.
+ const isEagerPending = enabled && eagerQuery.isPending;
const isEagerFetching = eagerQuery.isFetching;
const bulkColumns = plan.bulk.columns;
const loadingColumns = useMemo<ReadonlySet<string> | undefined>(() => {
@@ -427,7 +440,7 @@ export function useEventsFilterOptions({
return {
filterOptions: newFilterOptions,
- isFilterOptionsPending: eagerQuery.isPending,
+ isFilterOptionsPending: isEagerPending,
/** Approximate total observation count matching the refined filter, or null. */
approxTotalCount,
/** True while the first approximate-count value is still loading. */
diff --git a/web/src/features/filters/config/users-config.ts b/web/src/features/filters/config/users-config.ts
new file mode 100644
index 0000000000..be9730e360
--- /dev/null
+++ b/web/src/features/filters/config/users-config.ts
@@ -0,0 +1,92 @@
+import { observationEventsFilterConfig } from "@/src/features/events/config/filter-config";
+import { traceFilterConfig } from "@/src/features/filters/config/traces-config";
+import {
+ omitFilterFacets,
+ type FilterConfig,
+} from "@/src/features/filters/lib/filter-config";
+
+/**
+ * The Users list is the traces/events population grouped by `user_id`, so its
+ * sidebar is the Traces sidebar: same facets, same labels, same lowering. The
+ * facet sets below are therefore derived from the trace and observation
+ * configs rather than restated, so a facet added there reaches Users too.
+ *
+ * What Users cannot inherit is anything that needs a join. Both read paths
+ * scan a single table β€” v3 `from traces t`, v4 `from events_core e` β€” with no
+ * observation, score, or comment join. A score facet lowers to an `s.` alias
+ * that does not exist and fails in ClickHouse; the comment facets fail earlier,
+ * in `createFilterFromFilterState`, though for different reasons per path (v3
+ * has no `commentCount` mapping at all, v4 maps it to a `comments` table the
+ * filter factory refuses to lower against this query). Those are excluded per
+ * path below.
+ *
+ * Exclusions go through `omitFilterFacets` rather than a local facet filter, so
+ * a dropped column is also dropped from the filter state. `columnDefinitions`
+ * stays whole on both paths, so a filter on an excluded column that arrives by
+ * URL or saved view still decodes; without the omission it would reach the
+ * query and fail there.
+ *
+ * `users-facet-coverage.servertest.ts` runs every facet declared here through
+ * the real query, so a newly inherited facet that needs a join fails there
+ * rather than in a user's browser.
+ */
+
+/**
+ * v3 filters `traces t` alone. Only trace-table columns resolve: the trace
+ * config's `level`, `latency`, token and cost facets all map to an
+ * `observations` alias the users query never joins.
+ */
+const TRACE_FACET_COLUMNS_UNAVAILABLE_ON_USERS = [
+ "level",
+ "latency",
+ "inputTokens",
+ "outputTokens",
+ "totalTokens",
+ "inputCost",
+ "outputCost",
+ "totalCost",
+ "scores_avg",
+ "score_categories",
+ "score_booleans",
+ "commentCount",
+ "commentContent",
+];
+
+/**
+ * v4 filters `events_core e` alone. Every native event column resolves β€”
+ * including the `level`, `latency`, token and cost columns v3 has to drop β€”
+ * so only the score aggregates (an `s.` join) and the comment facets (which
+ * lower against the `comments` table this query never reaches) fall out.
+ */
+const EVENT_FACET_COLUMNS_UNAVAILABLE_ON_USERS = [
+ "scores_avg",
+ "score_categories",
+ "score_booleans",
+ "commentCount",
+ "commentContent",
+];
+
+export const usersFilterConfig: FilterConfig = {
+ ...omitFilterFacets(
+ traceFilterConfig,
+ TRACE_FACET_COLUMNS_UNAVAILABLE_ON_USERS,
+ ),
+ // v3 and v4 expose different facet sets, so they persist under different
+ // table names. Sharing one would let a v4-only filter (`level`) rehydrate on
+ // a v3 project, where it is a 400 rather than a narrowed table.
+ tableName: "users",
+ defaultExpanded: ["environment", "traceName"],
+};
+
+export const usersEventsFilterConfig: FilterConfig = {
+ ...omitFilterFacets(
+ observationEventsFilterConfig,
+ EVENT_FACET_COLUMNS_UNAVAILABLE_ON_USERS,
+ ),
+ tableName: "users-events",
+ defaultExpanded: ["environment", "name"],
+};
+
+export function getUsersFilterConfig(fromEvents: boolean): FilterConfig {
+ return fromEvents ? usersEventsFilterConfig : usersFilterConfig;
+}
diff --git a/web/src/features/filters/config/usersSearchRegistry.ts b/web/src/features/filters/config/usersSearchRegistry.ts
new file mode 100644
index 0000000000..1782102d81
--- /dev/null
+++ b/web/src/features/filters/config/usersSearchRegistry.ts
@@ -0,0 +1,72 @@
+import {
+ createFieldRegistry,
+ EVENTS_FIELD_REGISTRY,
+ type FieldRegistry,
+} from "@/src/features/search-bar/lib/fields";
+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";
+
+import { usersEventsFilterConfig } from "./users-config";
+
+/**
+ * The Users bar is the Events bar with the facets the Users query cannot answer
+ * removed β€” the same relationship the Users sidebar has to the Traces sidebar.
+ * So its fields are taken from `EVENTS_FIELD_REGISTRY` rather than re-derived
+ * from the column definitions: the events defs carry hand-tuned sync modes
+ * (`name` searches as a substring even though its column is option-backed), and
+ * re-deriving them would give the same token two different meanings depending on
+ * which page you typed it into.
+ *
+ * The subset is keyed on the SIDEBAR's facets, which keeps the bar a subset of
+ * the sidebar by construction: every field the bar can write, the sidebar can
+ * show and remove.
+ */
+function usersFields(config: FilterConfig) {
+ const exposed = new Set(config.facets.map((facet) => facet.column));
+ return EVENTS_FIELD_REGISTRY.fields.filter((field) =>
+ exposed.has(field.filterColumn ?? field.id),
+ );
+}
+
+function usersColumns(config: FilterConfig) {
+ const exposed = new Set(config.facets.map((facet) => facet.column));
+ return config.columnDefinitions.filter((column) => exposed.has(column.id));
+}
+
+/**
+ * v4 (events-backed) Users. Only the v4 registry exists because the bar is
+ * gated on v4 β€” a v3 variant would be unreachable.
+ */
+export const USERS_FIELD_REGISTRY: FieldRegistry = createFieldRegistry({
+ id: "users",
+ fields: usersFields(usersEventsFilterConfig),
+ columns: usersColumns(usersEventsFilterConfig),
+ metadata: true,
+ // The users queries group `events_core` alone with no score join, so the
+ // sidebar offers no score facet and the `scores.` namespace stays closed at
+ // both levels. Leaving it open would let the bar write a filter that 500s.
+ scores: false,
+ traceScores: false,
+ // A bare word is the user-id search the page has always had: `searchQuery`
+ // lowers to `user_id ILIKE %q%` on this read path, so free text keeps its
+ // own lane rather than being rewritten onto a column.
+ allowFreeText: true,
+ defaultTextField: null,
+ freeTextScopeLabel: "user IDs",
+ // Leads with a bare word: the substring user-id lookup is what this page is
+ // searched for, and it is the one lane the `key:value` examples cannot show.
+ searchExamples: ["alice", "level:ERROR", "-env:dev", "traceTags:billing"],
+ hasExample: "sessionId",
+ recentSearches: true,
+ // No `buildFilterSystemPrompt` branch for this view yet, so Ask AI stays
+ // hidden β€” the fallback prompt is the events one and would steer the model at
+ // score columns this page cannot filter on. Write the branch, then flip this.
+ aiFilterPrompt: false,
+ aiContextFields: [
+ { observedOptionsKey: "environment", promptLabel: "environment" },
+ { observedOptionsKey: "userId", promptLabel: "userId (user)" },
+ { observedOptionsKey: "traceName", promptLabel: "traceName" },
+ { observedOptionsKey: "name", promptLabel: "name" },
+ { observedOptionsKey: "traceTags", promptLabel: "traceTags (tags)" },
+ { observedOptionsKey: "level", promptLabel: "level" },
+ ],
+});
diff --git a/web/src/features/search-bar/lib/completions.ts b/web/src/features/search-bar/lib/completions.ts
index 8d3665ebb5..554b4c3885 100644
--- a/web/src/features/search-bar/lib/completions.ts
+++ b/web/src/features/search-bar/lib/completions.ts
@@ -983,7 +983,7 @@ function valueStageSections(input: ValueStageInput): {
// complement (mirrors the free-text β†’ scope path, gated on !negated).
const scopeSwitches =
!negated && (f.id === "input" || f.id === "output")
- ? scopeSwitchOptions(f.id, typed, tokenSpan)
+ ? scopeSwitchOptions(f.id, typed, tokenSpan, registry)
: [];
return {
sections: [
@@ -1188,14 +1188,21 @@ type FullTextScope = "default" | "input" | "output";
// explicit "this is the default-scope search" option (the anchor) ahead of the
// input:/output: rewrites. Value-stage switches leave it off, so an `input:`
// value never offers a no-op switch back to `input:`.
+//
+// The scoped forms are offered only where the registry actually resolves them.
+// Users narrows the events catalog to what its grouped query can answer, and
+// `input:` is not in it β€” offering the rewrite there would hand the user a
+// token the parser rejects. With nothing left to switch to, the anchor alone is
+// noise, so the section drops out entirely.
function scopeSwitchOptions(
current: FullTextScope,
value: string,
span: { from: number; to: number },
+ registry: FieldRegistry,
opts?: { keepCurrentFirst?: boolean },
): CompletionOption[] {
const v = serializeValue(value);
- const defs: { scope: FullTextScope; insert: string; detail: string }[] = [
+ const allDefs: { scope: FullTextScope; insert: string; detail: string }[] = [
{
scope: "input",
insert: `input:${v}`,
@@ -1209,15 +1216,20 @@ function scopeSwitchOptions(
{
scope: "default",
insert: v,
- detail: "default: ids, names, input & output",
+ detail: registry.freeTextScopeLabel
+ ? `default: ${registry.freeTextScopeLabel}`
+ : "default full-text search",
},
];
+ const defs = allDefs.filter(
+ (d) =>
+ d.scope === "default" || registry.resolveField(d.scope)?.type === "field",
+ );
+ const alternatives = defs.filter((d) => d.scope !== current);
+ if (alternatives.length === 0) return [];
const ordered = opts?.keepCurrentFirst
- ? [
- ...defs.filter((d) => d.scope === current),
- ...defs.filter((d) => d.scope !== current),
- ]
- : defs.filter((d) => d.scope !== current);
+ ? [...defs.filter((d) => d.scope === current), ...alternatives]
+ : alternatives;
return ordered.map((d) => ({
id: `scope:${d.scope}`,
kind: "pattern" as const,
@@ -1422,6 +1434,7 @@ export function planInputCompletions(
// re-quotes it once.
run.text,
{ from: run.from, to: run.to },
+ registry,
// Surface the typed text itself (default scope) as the first option,
// ahead of the input:/output: rewrites.
{ keepCurrentFirst: true },
diff --git a/web/src/features/search-bar/lib/explain.clienttest.ts b/web/src/features/search-bar/lib/explain.clienttest.ts
index feb7c7ec66..28d986d410 100644
--- a/web/src/features/search-bar/lib/explain.clienttest.ts
+++ b/web/src/features/search-bar/lib/explain.clienttest.ts
@@ -72,7 +72,7 @@ describe("explainSegment", () => {
// The label already says "per second" β€” don't spell the unit out twice.
expect(explain("tps:>=50")).toBe("Tokens per second is 50 or more.");
expect(explain("refund policy")).toBe(
- 'Full-text search for "refund policy" β€” matches id, name, input and output.',
+ 'Full-text search for "refund policy" β€” matches ids, names, input & output.',
);
expect(explain("level:ERROR AND latency:>2", 1)).toBe(
"AND β€” every filter has to match.",
diff --git a/web/src/features/search-bar/lib/explain.ts b/web/src/features/search-bar/lib/explain.ts
index 391d495697..746e7ff789 100644
--- a/web/src/features/search-bar/lib/explain.ts
+++ b/web/src/features/search-bar/lib/explain.ts
@@ -236,7 +236,9 @@ export function explainSegment(
case "freeText":
return {
subject: "Full-text search",
- predicate: `for ${quote(seg.raw.trim())} β€” matches id, name, input and output.`,
+ predicate: registry.freeTextScopeLabel
+ ? `for ${quote(seg.raw.trim())} β€” matches ${registry.freeTextScopeLabel}.`
+ : `for ${quote(seg.raw.trim())}.`,
};
case "operator":
return KEYWORDS[seg.raw.toUpperCase()] ?? null;
diff --git a/web/src/features/search-bar/lib/fields.ts b/web/src/features/search-bar/lib/fields.ts
index c89b0e8263..37800934d1 100644
--- a/web/src/features/search-bar/lib/fields.ts
+++ b/web/src/features/search-bar/lib/fields.ts
@@ -74,7 +74,8 @@ export type FieldRegistry = {
| "evaluatorSamples"
| "ruleSamples"
| "sessions"
- | "experiments";
+ | "experiments"
+ | "users";
fields: readonly FieldDef[];
columns: readonly ColumnDefinition[];
allowFreeText: boolean;
@@ -87,6 +88,15 @@ export type FieldRegistry = {
* 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;
+ /**
+ * What a bare word matches, phrased for the hint and the scope list
+ * ("ids, names, input & output"). Written per view because the registry
+ * cannot see it: `searchQuery` lowers to a column list the BACKEND picks,
+ * and the users query narrows that list to `user_id` while keeping the same
+ * field catalog. Null drops the clause rather than guessing β€” vague beats
+ * naming columns a view does not search.
+ */
+ freeTextScopeLabel: 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[];
@@ -144,6 +154,7 @@ export function fieldRegistryFromColumns(
traceScores?: boolean;
allowFreeText?: boolean;
defaultTextField?: string;
+ freeTextScopeLabel?: string;
searchExamples?: readonly string[];
hasExample?: string;
recentSearches?: boolean;
@@ -205,6 +216,7 @@ export function fieldRegistryFromColumns(
traceScores: overlay.traceScores ?? scores,
allowFreeText: overlay.allowFreeText ?? true,
defaultTextField: overlay.defaultTextField ?? null,
+ freeTextScopeLabel: overlay.freeTextScopeLabel ?? null,
searchExamples: overlay.searchExamples ?? [],
hasExample: overlay.hasExample ?? null,
recentSearches: overlay.recentSearches ?? false,
@@ -232,6 +244,7 @@ export function extendFieldRegistryWithColumns(
traceScores: registry.traceScores,
allowFreeText: registry.allowFreeText,
defaultTextField: registry.defaultTextField,
+ freeTextScopeLabel: registry.freeTextScopeLabel,
searchExamples: registry.searchExamples,
hasExample: registry.hasExample,
recentSearches: registry.recentSearches,
@@ -274,6 +287,7 @@ export function withFieldOptions(
traceScores: registry.traceScores,
allowFreeText: registry.allowFreeText,
defaultTextField: registry.defaultTextField,
+ freeTextScopeLabel: registry.freeTextScopeLabel,
searchExamples: registry.searchExamples,
hasExample: registry.hasExample,
recentSearches: registry.recentSearches,
@@ -377,7 +391,15 @@ export type FieldRef =
| { type: "scores"; key: string; level: "observation" | "trace" }
| { type: "pseudo"; id: typeof HAS_KEY };
-function createFieldRegistry({
+/**
+ * Assembles a registry from field defs that already exist. `fieldRegistryFromColumns`
+ * derives its defs from `ColumnDefinition.type`, which is right for a view with no
+ * grammar of its own β€” but a view that narrows ANOTHER view's grammar must reuse that
+ * view's defs verbatim. Deriving them again would silently re-decide `syncMode` from
+ * the column type and give the same field a different meaning on the two bars
+ * (`name:checkout` an exact match on one, a substring on the other).
+ */
+export function createFieldRegistry({
id,
fields,
columns,
@@ -386,6 +408,7 @@ function createFieldRegistry({
traceScores,
allowFreeText,
defaultTextField,
+ freeTextScopeLabel,
searchExamples,
hasExample,
recentSearches,
@@ -400,6 +423,7 @@ function createFieldRegistry({
traceScores: boolean;
allowFreeText: boolean;
defaultTextField: string | null;
+ freeTextScopeLabel: string | null;
searchExamples: readonly string[];
hasExample: string | null;
recentSearches: boolean;
@@ -435,6 +459,7 @@ function createFieldRegistry({
scores,
traceScores,
defaultTextField,
+ freeTextScopeLabel,
searchExamples,
hasExample,
recentSearches,
@@ -465,6 +490,7 @@ export const EVENTS_FIELD_REGISTRY = createFieldRegistry({
traceScores: true,
allowFreeText: true,
defaultTextField: null,
+ freeTextScopeLabel: "ids, names, input & output",
searchExamples: [
"level:ERROR",
"-env:dev",
diff --git a/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts b/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts
index 4290ed1bda..0a52a78532 100644
--- a/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts
+++ b/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts
@@ -13,9 +13,11 @@ import {
RULE_SAMPLE_FIELD_REGISTRY,
} from "@/src/features/evals/v2/constants/evaluatorSearchRegistry";
import { SESSIONS_FIELD_REGISTRY } from "@/src/features/filters";
+import { usersEventsFilterConfig } from "@/src/features/filters/config/users-config";
+import { USERS_FIELD_REGISTRY } from "@/src/features/filters/config/usersSearchRegistry";
import { EXPERIMENTS_FIELD_REGISTRY } from "@/src/features/experiments/constants/experimentsSearchRegistry";
import { validateQuery } from "./validate";
-import { planCommit } from "./commit";
+import { DEFAULT_SEARCH_TYPE, planCommit } from "./commit";
import { filterStateToQueryText } from "./filter-state-to-query";
import {
applyPick,
@@ -756,6 +758,158 @@ describe("search bar invariants β€” sessions registry", () => {
});
});
+const usersView: RegistryUnderTest = {
+ name: "users v4",
+ registry: USERS_FIELD_REGISTRY,
+ extraKeys: [
+ "metadata.region",
+ 'metadata."my key"',
+ "has:latency",
+ "has:sessionId",
+ ],
+ // The users queries group `events_core` with no score join, so `scores.` is
+ // closed at both levels and there is no context to vary.
+ scoreContexts: [],
+ fieldValues: ["x", "ERROR", "5", "0.8", "true", "a b", "gpt-4"],
+ // Free text is its own lane here (it lowers to `user_id ILIKE`), so the same
+ // reserved-token quoting the events bar needs has to hold.
+ freeTextValues: [
+ "hello",
+ "alice smith",
+ "or",
+ "and",
+ "NOT",
+ "!important",
+ "-foo",
+ "key:value",
+ ],
+ sidebarFilters: [
+ // Trace-score columns reach this page only from an older saved view. The
+ // bar does not own them, so it must skip rather than emit a token that
+ // renders as an unknown field.
+ [
+ {
+ type: "numberObject",
+ column: "trace_scores_avg",
+ key: "nps",
+ operator: ">",
+ value: 5,
+ },
+ ],
+ ],
+};
+
+describe("search bar invariants β€” users registry", () => {
+ it("holds all three invariants (parity, round-trip, serialize symmetry)", () => {
+ const failures = runSearchBarInvariants(usersView);
+ 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("is the events grammar minus what the users query cannot answer", () => {
+ // Users groups `events_core` alone: no score join, no comments join. Those
+ // facets are excluded from the sidebar, so the bar must not resolve them
+ // either β€” a `scores.` token here would commit a filter that 500s.
+ expect(USERS_FIELD_REGISTRY.resolveField("scores.accuracy")).toBeNull();
+ expect(USERS_FIELD_REGISTRY.resolveField("traceScores.nps")).toBeNull();
+ for (const key of ["comment", "commentCount", "commentContent"]) {
+ expect(USERS_FIELD_REGISTRY.resolveField(key)).toBeNull();
+ }
+ // Everything else the events bar offers survives, and is exactly the
+ // sidebar's facet set (metadata excepted β€” it resolves by dot-path, not as
+ // a plain field).
+ const facetColumns = new Set(
+ usersEventsFilterConfig.facets.map((f) => f.column),
+ );
+ for (const field of USERS_FIELD_REGISTRY.fields) {
+ expect(facetColumns.has(field.filterColumn ?? field.id)).toBe(true);
+ }
+ expect(USERS_FIELD_REGISTRY.resolveField("metadata.region")).toEqual({
+ type: "metadata",
+ key: "region",
+ });
+ // The two aliases that make the events grammar worth reusing rather than
+ // re-deriving: `env:` and `tag:` are overlay-only, absent from the columns.
+ expect(USERS_FIELD_REGISTRY.resolveField("env")).toMatchObject({
+ type: "field",
+ field: { id: "environment" },
+ });
+ expect(USERS_FIELD_REGISTRY.resolveField("user")).toMatchObject({
+ type: "field",
+ field: { id: "userId" },
+ });
+ });
+
+ it("keeps a bare word in the free-text lane rather than rewriting it", () => {
+ // Unlike sessions (`id contains`), the users backend already has a search
+ // lane: `searchQuery` lowers to `user_id ILIKE %q%`. Rewriting a bare word
+ // onto the userId column would turn a substring search into an exact
+ // any-of match against the facet list.
+ const committed = planCommit("alice", undefined, USERS_FIELD_REGISTRY);
+ expect(committed).toMatchObject({
+ status: "committed",
+ searchQuery: "alice",
+ filters: [],
+ });
+ // …and it renders back as the same bare word, so the bar does not churn.
+ expect(
+ filterStateToQueryText(
+ [],
+ { searchQuery: "alice", searchType: DEFAULT_SEARCH_TYPE },
+ USERS_FIELD_REGISTRY,
+ ).text,
+ ).toBe("alice");
+ });
+
+ it("describes the free-text lane as user ids, and offers no other scope", () => {
+ // The generic copy claims a bare word matches "ids, names, input and
+ // output". On this page it matches user ids and nothing else, and there is
+ // no `input:`/`output:` field to switch into β€” offering the rewrite would
+ // hand the user a token the parser rejects.
+ expect(USERS_FIELD_REGISTRY.freeTextScopeLabel).toBe("user IDs");
+ expect(USERS_FIELD_REGISTRY.resolveField("input")).toBeNull();
+ expect(USERS_FIELD_REGISTRY.resolveField("output")).toBeNull();
+
+ const scopeOptionIds = (registry: FieldRegistry) =>
+ (
+ planInputCompletions(
+ {
+ input: "alice",
+ caret: 5,
+ observed: {},
+ recents: [],
+ currentQueryText: "alice",
+ },
+ registry,
+ )?.sections ?? []
+ )
+ .flatMap((section) => section.options)
+ .map((option) => option.id)
+ .filter((id) => id.startsWith("scope:"));
+
+ expect(scopeOptionIds(USERS_FIELD_REGISTRY)).toEqual([]);
+ // The same input on a registry that does have the columns still offers them.
+ expect(scopeOptionIds(EVENTS_FIELD_REGISTRY)).toEqual(
+ expect.arrayContaining(["scope:input", "scope:output"]),
+ );
+ });
+
+ it("does not offer Ask AI until the view has its own prompt", () => {
+ // buildFilterSystemPrompt falls back to the EVENTS prompt, whose worked
+ // examples filter on score columns this page cannot reach.
+ expect(USERS_FIELD_REGISTRY.aiFilterPrompt).toBe(false);
+ });
+});
+
const experimentsView: RegistryUnderTest = {
name: "experiments",
registry: EXPERIMENTS_FIELD_REGISTRY,
diff --git a/web/src/features/search-bar/server/router.ts b/web/src/features/search-bar/server/router.ts
index d91b65cca3..66d2043005 100644
--- a/web/src/features/search-bar/server/router.ts
+++ b/web/src/features/search-bar/server/router.ts
@@ -55,6 +55,7 @@ import {
} from "@/src/features/evals/v2/constants/evaluatorSearchRegistry";
import { DATASET_NAME_COLUMN } from "@/src/features/evals/v2/utils/datasetNameFilter";
import { SESSIONS_FIELD_REGISTRY } from "@/src/features/filters/config/sessionsSearchRegistry";
+import { USERS_FIELD_REGISTRY } from "@/src/features/filters/config/usersSearchRegistry";
import { EXPERIMENTS_FIELD_REGISTRY } from "@/src/features/experiments/constants/experimentsSearchRegistry";
import {
EVENTS_FIELD_REGISTRY,
@@ -75,6 +76,7 @@ const REGISTRY_IDS = [
"ruleSamples",
"sessions",
"experiments",
+ "users",
] as const;
/**
@@ -90,6 +92,7 @@ const REGISTRIES_BY_ID: Record<(typeof REGISTRY_IDS)[number], FieldRegistry> = {
ruleSamples: RULE_SAMPLE_FIELD_REGISTRY,
sessions: SESSIONS_FIELD_REGISTRY,
experiments: EXPERIMENTS_FIELD_REGISTRY,
+ users: USERS_FIELD_REGISTRY,
};
const GenerateFilterInput = z.object({
diff --git a/web/src/pages/project/[projectId]/users/index.tsx b/web/src/pages/project/[projectId]/users/index.tsx
index ada702aa55..d425704090 100644
--- a/web/src/pages/project/[projectId]/users/index.tsx
+++ b/web/src/pages/project/[projectId]/users/index.tsx
@@ -1,5 +1,5 @@
import { useRouter } from "next/router";
-import { useEffect, useMemo } from "react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
import {
NumberParam,
StringParam,
@@ -9,28 +9,47 @@ import {
} from "use-query-params";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
import { DataTable } from "@/src/components/table/data-table";
+import {
+ DataTableControls,
+ DataTableControlsProvider,
+} from "@/src/components/table/data-table-controls";
+import { ResizableFilterLayout } from "@/src/components/table/resizable-filter-layout";
import { createBadgeTableColumn } from "@/src/components/design-system/table/columns/createBadgeTableColumn";
import { createLinkTableColumn } from "@/src/components/design-system/table/columns/createLinkTableColumn";
import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";
import { type LangfuseColumnDef } from "@/src/components/table/types";
-import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { getUsersFilterConfig } from "@/src/features/filters/config/users-config";
+import { USERS_FIELD_REGISTRY } from "@/src/features/filters/config/usersSearchRegistry";
+import {
+ useSidebarFilterPresentation,
+ useSidebarFilterStateCore,
+ type FacetOptions,
+ type UseSidebarFilterStateOptions,
+} from "@/src/features/filters/hooks/useSidebarFilterState";
+import { buildSidebarFilterSessionContextId } from "@/src/features/filters/lib/persistedSidebarFilterQuery";
+import { sortOptionValues } from "@/src/features/filters";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
+import { useEventsFilterOptions } from "@/src/features/events/hooks/useEventsFilterOptions";
import { useReadPath } from "@/src/features/events/hooks/useReadPath";
+import { EventsSearchBarRow } from "@/src/features/search-bar/components/EventsSearchBarRow";
+import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSearchBar";
+import { DEFAULT_SEARCH_TYPE } from "@/src/features/search-bar/lib/commit";
+import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";
import { api } from "@/src/utils/api";
import { compactNumberFormatter, usdFormatter } from "@/src/utils/numbers";
+import { cn } from "@/src/utils/tailwind";
import { type RouterOutput } from "@/src/utils/types";
-import { type FilterState, usersTableCols } from "@langfuse/shared";
+import {
+ DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,
+ type FilterState,
+ type TimeFilter,
+} from "@langfuse/shared";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
-import { useDebounce } from "@/src/hooks/useDebounce";
import Page from "@/src/components/layouts/page";
import { TableHeaderControls } from "@/src/components/table/table-header-controls";
import { UsersOnboarding } from "@/src/components/onboarding/UsersOnboarding";
-import {
- useEnvironmentFilter,
- convertSelectedEnvironmentsToFilter,
-} from "@/src/hooks/useEnvironmentFilter";
type RowData = {
userId: string;
@@ -125,11 +144,10 @@ const UsersTable = ({
const router = useRouter();
const projectId = router.query.projectId as string;
- const [userFilterState, setUserFilterState] = useQueryFilterState(
- [],
- "users",
- projectId,
- );
+ // The two read paths answer different facet sets from different tables, so
+ // they get different configs β€” and different persistence keys, or a v4-only
+ // filter would rehydrate on a v3 project as a failed query.
+ const usersFilterConfig = useMemo(() => getUsersFilterConfig(isV4), [isV4]);
const { setDetailPageList } = useDetailPageLists();
@@ -147,22 +165,68 @@ const UsersTable = ({
return toAbsoluteTimeRange(timeRange) ?? undefined;
}, [timeRange]);
- const dateRangeFilter: FilterState = dateRange
- ? [
- {
- column: "Timestamp",
- type: "datetime",
- operator: ">=",
- value: dateRange.from,
- },
- {
- column: "Timestamp",
- type: "datetime",
- operator: "<=",
- value: dateRange.to,
- },
- ]
- : [];
+ // Both users queries map "Timestamp" onto their own time column
+ // (`t.timestamp` on v3, `e.start_time` on v4), so one filter serves both.
+ const dateRangeFilter = useMemo<FilterState>(
+ () =>
+ dateRange
+ ? [
+ {
+ column: "Timestamp",
+ type: "datetime",
+ operator: ">=",
+ value: dateRange.from,
+ },
+ {
+ column: "Timestamp",
+ type: "datetime",
+ operator: "<=",
+ value: dateRange.to,
+ },
+ ]
+ : [],
+ [dateRange],
+ );
+
+ const filterStateOptions: UseSidebarFilterStateOptions = useMemo(
+ () => ({
+ stateLocation: "urlAndSessionStorage",
+ sessionFilterContextId: buildSidebarFilterSessionContextId(projectId),
+ // Environment is a sidebar facet here, like every other filter β€” the page
+ // no longer keeps its own environment selection beside the filter state.
+ implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,
+ isV4,
+ }),
+ [isV4, projectId],
+ );
+
+ // Split core/presentation so the v4 facet scan can refine its counts against
+ // the filters already applied β€” the presentation half needs the options the
+ // scan produces, so it cannot also be the thing that supplies the filters.
+ const filterCore = useSidebarFilterStateCore(
+ usersFilterConfig,
+ filterStateOptions,
+ );
+
+ // v3 facet options: the trace facets this page inherits, from the traces
+ // endpoint that already answers them.
+ const traceFilterOptionsResponse = api.traces.filterOptions.useQuery(
+ {
+ projectId,
+ timestampFilter:
+ dateRangeFilter.length > 0
+ ? (dateRangeFilter as TimeFilter[])
+ : undefined,
+ },
+ {
+ enabled: !isV4,
+ trpc: { context: { skipBatch: true } },
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ staleTime: Infinity,
+ },
+ );
const environmentFilterOptions =
api.projects.environmentFilterOptions.useQuery(
@@ -171,6 +235,7 @@ const UsersTable = ({
fromTimestamp: dateRange?.from,
},
{
+ enabled: !isV4,
trpc: { context: { skipBatch: true } },
refetchOnMount: false,
refetchOnWindowFocus: false,
@@ -179,27 +244,142 @@ const UsersTable = ({
},
);
- const environmentOptions =
- environmentFilterOptions.data?.map((value) => value.environment) || [];
-
- const { selectedEnvironments, setSelectedEnvironments } =
- useEnvironmentFilter(environmentOptions, projectId);
+ const v3FacetOptions = useMemo<FacetOptions>(
+ () => ({
+ environment:
+ environmentFilterOptions.data?.map((value) => value.environment) ??
+ undefined,
+ traceName:
+ traceFilterOptionsResponse.data?.name?.map((n) => ({
+ value: n.value,
+ count: Number(n.count),
+ })) ?? undefined,
+ // tags don't have counts; they read A→Z
+ traceTags: sortOptionValues(
+ traceFilterOptionsResponse.data?.tags?.map((t) => t.value),
+ ),
+ userId:
+ traceFilterOptionsResponse.data?.users?.map((u) => ({
+ value: u.value,
+ count: Number(u.count),
+ })) ?? undefined,
+ sessionId:
+ traceFilterOptionsResponse.data?.sessions?.map((s) => ({
+ value: s.value,
+ count: Number(s.count),
+ })) ?? undefined,
+ }),
+ [environmentFilterOptions.data, traceFilterOptionsResponse.data],
+ );
- const environmentFilter = convertSelectedEnvironmentsToFilter(
- ["environment"],
- selectedEnvironments,
+ // v4 facet options: the events facet scan, lazily per column, refined by the
+ // filters already applied.
+ const facetStartTimeFilter = useMemo<TimeFilter[]>(
+ () =>
+ dateRange
+ ? [
+ {
+ column: "startTime",
+ type: "datetime",
+ operator: ">=",
+ value: dateRange.from,
+ },
+ {
+ column: "startTime",
+ type: "datetime",
+ operator: "<=",
+ value: dateRange.to,
+ },
+ ]
+ : [],
+ [dateRange],
);
- const filterState = userFilterState.concat(
- dateRangeFilter,
- environmentFilter,
+ const {
+ filterOptions: v4FacetOptions,
+ isFilterOptionsPending: isV4FacetOptionsPending,
+ erroredColumns,
+ loadingColumns,
+ requestColumns,
+ } = useEventsFilterOptions({
+ projectId,
+ startTimeFilter: facetStartTimeFilter,
+ refiningFilter: filterCore.filterState,
+ lazy: true,
+ enabled: isV4,
+ });
+
+ const isSidebarFilterLoading = isV4
+ ? isV4FacetOptionsPending
+ : traceFilterOptionsResponse.isPending ||
+ environmentFilterOptions.isPending;
+
+ const queryFilter = useSidebarFilterPresentation(
+ filterCore,
+ usersFilterConfig,
+ isV4 ? v4FacetOptions : v3FacetOptions,
+ {
+ loading: isSidebarFilterLoading,
+ loadingColumns,
+ isV4,
+ },
);
+ // Lazy filter-options: load a facet's values when its sidebar section is
+ // expanded (also covers active filters, which auto-expand on mount).
+ const expandedFacets = queryFilter.expanded;
+ useEffect(() => {
+ requestColumns(expandedFacets);
+ }, [expandedFacets, requestColumns]);
+
const [searchQuery, setSearchQuery] = useQueryParam(
"search",
withDefault(StringParam, null),
);
+ // The grammar bar is v4-only: it writes the events facet grammar, which the
+ // trace-backed v3 query cannot answer. v3 keeps the toolbar's search field.
+ const searchBarEnabled = isV4;
+
+ const queryFilterRef = useRef(queryFilter);
+ queryFilterRef.current = queryFilter;
+
+ const setFiltersWrapper = useCallback(
+ (filters: FilterState) =>
+ queryFilterRef.current?.setFilterState(filters, { origin: "user" }),
+ [],
+ );
+
+ const observedOptions = useMemo(
+ () => toObservedOptions(v4FacetOptions, isV4FacetOptionsPending),
+ [v4FacetOptions, isV4FacetOptionsPending],
+ );
+
+ // Both users queries take a `searchQuery` but no search type β€” free text
+ // always lowers to `user_id ILIKE`. The bar reports the default lane; there
+ // is nothing on this page for a write to it to change.
+ const setSearchTypeNoop = useCallback(() => {}, []);
+
+ const {
+ store: searchBarStore,
+ commit: searchBarCommit,
+ applyFilters: searchBarApplyFilters,
+ } = useEventsSearchBar({
+ projectId,
+ tableName: usersFilterConfig.tableName,
+ enabled: searchBarEnabled,
+ filterState: queryFilter.searchBarFilterState,
+ searchQuery,
+ searchType: DEFAULT_SEARCH_TYPE,
+ observed: observedOptions,
+ setFilterState: setFiltersWrapper,
+ setSearchQuery,
+ setSearchType: setSearchTypeNoop,
+ registry: USERS_FIELD_REGISTRY,
+ });
+
+ const filterState = queryFilter.effectiveFilterState.concat(dateRangeFilter);
+
const usersV3 = api.users.all.useQuery(
{
filter: filterState,
@@ -376,81 +556,111 @@ const UsersTable = ({
];
return (
- <>
- {showControlsInPageHeader && (
- <TableHeaderControls
- timeRange={timeRange}
- setTimeRange={setTimeRange}
- />
- )}
- <DataTableToolbar
- tableName="users"
- filterColumnDefinition={usersTableCols}
- filterState={userFilterState}
- setFilterState={useDebounce(setUserFilterState)}
- columns={columns}
- timeRange={showControlsInPageHeader ? undefined : timeRange}
- setTimeRange={showControlsInPageHeader ? undefined : setTimeRange}
- searchConfig={{
- metadataSearchFields: ["User ID"],
- updateQuery: setSearchQuery,
- currentQuery: searchQuery ?? undefined,
- tableAllowsFullTextSearch: false,
- setSearchType: undefined,
- searchType: undefined,
- }}
- environmentFilter={{
- values: selectedEnvironments,
- onValueChange: setSelectedEnvironments,
- options: environmentOptions.map((env) => ({ value: env })),
- }}
- />
- <DataTable
- tableName="users"
- columns={columns}
- data={
- users.isLoading
- ? { isLoading: true, isError: false }
- : users.isError
- ? {
- isLoading: false,
- isError: true,
- error: users.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: userRowData.rows?.map((t) => {
- return {
- userId: t.id,
- environment: t.environment ?? undefined,
- firstEvent:
- t.firstTrace?.toLocaleString() ?? "No event yet",
- lastEvent:
- t.lastTrace?.toLocaleString() ?? "No event yet",
- totalEvents: compactNumberFormatter(
- isV4
- ? Number(t.totalObservations ?? 0)
- : Number(t.totalTraces ?? 0) +
- Number(t.totalObservations ?? 0),
- ),
- totalTokens: compactNumberFormatter(t.totalTokens ?? 0),
- totalCost: usdFormatter(
- t.sumCalculatedTotalCost ?? 0,
- 2,
- 2,
- ),
- };
- }),
- }
- }
- pagination={{
- totalCount,
- onChange: setPaginationState,
- state: paginationState,
- }}
- cellPadding="comfortable"
- />
- </>
+ <DataTableControlsProvider tableName={usersFilterConfig.tableName}>
+ <div className="flex h-full w-full flex-col">
+ {showControlsInPageHeader && (
+ <TableHeaderControls
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
+ />
+ )}
+ {/* In bar mode the composer and the toolbar stick together as one band
+ so the toolbar cannot scroll under the composer and render
+ half-clipped. */}
+ <div
+ className={cn(
+ searchBarEnabled && "bg-background sticky top-0 z-30 pb-1.5",
+ )}
+ >
+ {searchBarEnabled && (
+ <EventsSearchBarRow
+ projectId={projectId}
+ tableName={usersFilterConfig.tableName}
+ store={searchBarStore}
+ commit={searchBarCommit}
+ observed={observedOptions}
+ erroredColumns={erroredColumns}
+ onApplyFilters={searchBarApplyFilters}
+ onRequestColumns={requestColumns}
+ registry={USERS_FIELD_REGISTRY}
+ />
+ )}
+ <DataTableToolbar
+ tableName={usersFilterConfig.tableName}
+ isV4={isV4}
+ rowClassName={searchBarEnabled ? "my-1" : undefined}
+ filterState={queryFilter.explicitFilterState}
+ columns={columns}
+ timeRange={showControlsInPageHeader ? undefined : timeRange}
+ setTimeRange={showControlsInPageHeader ? undefined : setTimeRange}
+ searchConfig={
+ searchBarEnabled
+ ? undefined
+ : {
+ metadataSearchFields: ["User ID"],
+ updateQuery: setSearchQuery,
+ currentQuery: searchQuery ?? undefined,
+ tableAllowsFullTextSearch: false,
+ setSearchType: undefined,
+ searchType: undefined,
+ }
+ }
+ />
+ </div>
+ <ResizableFilterLayout>
+ <DataTableControls queryFilter={queryFilter} />
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <DataTable
+ tableName="users"
+ columns={columns}
+ data={
+ users.isLoading
+ ? { isLoading: true, isError: false }
+ : users.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: users.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: userRowData.rows?.map((t) => {
+ return {
+ userId: t.id,
+ environment: t.environment ?? undefined,
+ firstEvent:
+ t.firstTrace?.toLocaleString() ?? "No event yet",
+ lastEvent:
+ t.lastTrace?.toLocaleString() ?? "No event yet",
+ totalEvents: compactNumberFormatter(
+ isV4
+ ? Number(t.totalObservations ?? 0)
+ : Number(t.totalTraces ?? 0) +
+ Number(t.totalObservations ?? 0),
+ ),
+ totalTokens: compactNumberFormatter(
+ t.totalTokens ?? 0,
+ ),
+ totalCost: usdFormatter(
+ t.sumCalculatedTotalCost ?? 0,
+ 2,
+ 2,
+ ),
+ };
+ }),
+ }
+ }
+ pagination={{
+ totalCount,
+ onChange: setPaginationState,
+ state: paginationState,
+ }}
+ cellPadding="comfortable"
+ />
+ </div>
+ </ResizableFilterLayout>
+ </div>
+ </DataTableControlsProvider>
);
};