Skip to content

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

feat(evals): reuse rule filters in search bar (#16554)

Tobias Wochinger27807e9c241b
diff --git a/web/src/__tests__/server/evaluation-rule-v2-repository.servertest.ts b/web/src/__tests__/server/evaluation-rule-v2-repository.servertest.ts
index 9d4466442d..4a9cc5dfa5 100644
--- a/web/src/__tests__/server/evaluation-rule-v2-repository.servertest.ts
+++ b/web/src/__tests__/server/evaluation-rule-v2-repository.servertest.ts
@@ -1,9 +1,11 @@
import { randomUUID } from "node:crypto";
-import { EvalTargetObject } from "@langfuse/shared";
-import { prisma } from "@langfuse/shared/src/db";
+import { EvalTargetObject, type FilterState } from "@langfuse/shared";
+import { Prisma, prisma } from "@langfuse/shared/src/db";
import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import * as ruleRepository from "@/src/features/evals/v2/server/rules/ruleRepository";
+import { filtersMatch } from "@/src/features/evals/v2/server/rules/ruleFilterMatching";
+import { RuleService } from "@/src/features/evals/v2/server/rules/ruleService";
const orgIds: string[] = [];
let projectId = "";
@@ -65,13 +67,19 @@ async function createRule({
targetProjectId = projectId,
name = `rule-${randomUUID()}`,
evaluatorId,
+ evaluatorIds,
+ filter = [],
createdByUserId = null,
}: {
targetProjectId?: string;
name?: string;
evaluatorId?: string;
+ evaluatorIds?: string[];
+ filter?: Parameters<typeof ruleRepository.createRule>[0]["input"]["filter"];
createdByUserId?: string | null;
} = {}) {
+ const assignedEvaluatorIds =
+ evaluatorIds ?? (evaluatorId ? [evaluatorId] : []);
return ruleRepository.createRule({
prisma,
input: {
@@ -79,11 +87,12 @@ async function createRule({
name,
targetObject: EvalTargetObject.EVENT,
enabled: true,
- filter: [],
+ filter,
sampling: 1,
- evaluatorAssignments: evaluatorId
- ? [{ evaluatorId, variableMapping: null }]
- : [],
+ evaluatorAssignments: assignedEvaluatorIds.map((assignedEvaluatorId) => ({
+ evaluatorId: assignedEvaluatorId,
+ variableMapping: null,
+ })),
},
createdByUserId,
});
@@ -530,6 +539,189 @@ describe("evaluation rule v2 repository", () => {
});
});
+ describe("listReusableFilterCandidates", () => {
+ it("returns at most the 20 newest candidate rules", async () => {
+ const oldestRuleId = randomUUID();
+ await prisma.evaluationRule.createMany({
+ data: Array.from({ length: 21 }, (_, index) => ({
+ id: index === 0 ? oldestRuleId : randomUUID(),
+ projectId,
+ name: `candidate-${index}`,
+ status: "ACTIVE" as const,
+ targetObject: EvalTargetObject.EVENT,
+ filter: [],
+ sampling: 1,
+ delay: 0,
+ timeScope: ["NEW"],
+ updatedAt: new Date(Date.UTC(2026, 0, 1, 0, 0, 0, index)),
+ })),
+ });
+
+ const candidates = await ruleRepository.listReusableFilterCandidates({
+ prisma,
+ projectId,
+ });
+
+ expect(candidates).toHaveLength(20);
+ expect(candidates.map(({ id }) => id)).not.toContain(oldestRuleId);
+ });
+ });
+
+ describe("RuleService.listReusableFilters", () => {
+ it("groups equivalent modern rule filters and ranks only by distinct evaluator count, then updated time", async () => {
+ const [
+ firstEvaluator,
+ secondEvaluator,
+ thirdEvaluator,
+ legacyEvaluator,
+ foreignEvaluator,
+ ] = await Promise.all([
+ createEvaluator(),
+ createEvaluator(),
+ createEvaluator(),
+ createEvaluator(),
+ createEvaluator(otherProjectId),
+ ]);
+ const popularFilter = [
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["production", "staging"],
+ },
+ ] satisfies FilterState;
+ const newerFilter = [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["GENERATION"],
+ },
+ ] satisfies FilterState;
+ const olderFilter = [
+ {
+ column: "level",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["ERROR"],
+ },
+ ] satisfies FilterState;
+
+ const [popularFirst, popularSecond, newer, older] = await Promise.all([
+ createRule({
+ evaluatorIds: [firstEvaluator.id, secondEvaluator.id],
+ filter: [...popularFilter],
+ }),
+ // Same conditions and values in a different order. The repeated
+ // evaluator counts once across the grouped filter preset.
+ createRule({
+ evaluatorIds: [
+ secondEvaluator.id,
+ thirdEvaluator.id,
+ legacyEvaluator.id,
+ ],
+ filter: [
+ {
+ ...popularFilter[0],
+ value: ["staging", "production"],
+ },
+ ],
+ }),
+ createRule({
+ evaluatorId: firstEvaluator.id,
+ filter: [...newerFilter],
+ }),
+ createRule({
+ evaluatorId: secondEvaluator.id,
+ filter: [...olderFilter],
+ }),
+ ]);
+ const oldDate = new Date("2026-01-01T00:00:00.000Z");
+ const newDate = new Date("2026-02-01T00:00:00.000Z");
+ await Promise.all([
+ prisma.evaluationRule.updateMany({
+ where: { id: { in: [popularFirst.id, popularSecond.id, older.id] } },
+ data: { updatedAt: oldDate },
+ }),
+ prisma.evaluationRule.update({
+ where: { id: newer.id },
+ data: { updatedAt: newDate },
+ }),
+ // Denormalized assignment ids are scoped explicitly: a foreign-project
+ // evaluator attached to a current-project rule does not affect usage.
+ prisma.evaluationRuleEvaluatorAssignment.create({
+ data: {
+ projectId,
+ evaluationRuleId: popularFirst.id,
+ evaluatorId: foreignEvaluator.id,
+ variableMapping: Prisma.DbNull,
+ },
+ }),
+ // An evaluator with a legacy trace/dataset assignment is excluded from
+ // usage counts, and the legacy rule never becomes a reusable preset.
+ prisma.evaluationRule.create({
+ data: {
+ projectId,
+ name: "Legacy trace rule",
+ status: "ACTIVE",
+ targetObject: EvalTargetObject.TRACE,
+ filter: olderFilter,
+ sampling: 1,
+ delay: 0,
+ timeScope: ["NEW"],
+ assignments: {
+ create: {
+ projectId,
+ evaluatorId: legacyEvaluator.id,
+ variableMapping: Prisma.DbNull,
+ },
+ },
+ },
+ }),
+ createRule({
+ targetProjectId: otherProjectId,
+ evaluatorId: foreignEvaluator.id,
+ filter: [...newerFilter],
+ }),
+ ]);
+ await Promise.all(
+ Array.from({ length: 8 }, (_, index) =>
+ createRule({
+ filter: [
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: [`extra-${index}`],
+ },
+ ],
+ }),
+ ),
+ );
+
+ const result = await new RuleService(
+ prisma,
+ async () => undefined,
+ ).listReusableFilters(projectId);
+
+ expect(result).toHaveLength(10);
+ expect(
+ result.slice(0, 3).map(({ evaluatorCount }) => evaluatorCount),
+ ).toEqual([3, 1, 1]);
+ expect(filtersMatch(result[0]?.filter ?? [], [...popularFilter])).toBe(
+ true,
+ );
+ expect(result[1]).toMatchObject({
+ filter: [...newerFilter],
+ updatedAt: newDate,
+ });
+ expect(result[2]).toMatchObject({
+ filter: [...olderFilter],
+ updatedAt: oldDate,
+ });
+ });
+ });
+
describe("countRulesForEvaluators", () => {
it("returns project-scoped counts and omits evaluators without rules", async () => {
const [firstEvaluator, secondEvaluator] = await Promise.all([
diff --git a/web/src/features/evals/v2/components/Evaluators/Testing/components/SampleObservationSelectorBase/SampleObservationSelectorBase.tsx b/web/src/features/evals/v2/components/Evaluators/Testing/components/SampleObservationSelectorBase/SampleObservationSelectorBase.tsx
index 580f92aa55..f91b316ff5 100644
--- a/web/src/features/evals/v2/components/Evaluators/Testing/components/SampleObservationSelectorBase/SampleObservationSelectorBase.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/Testing/components/SampleObservationSelectorBase/SampleObservationSelectorBase.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useState, type UIEvent } from "react";
+import { useCallback, useMemo, useState, type UIEvent } from "react";
import { EyeOff, FlaskConical, ListTree, Sparkles, Wrench } from "lucide-react";
import {
type FilterState,
@@ -32,6 +32,8 @@ import { SectionHeader } from "@/src/features/evals/v2/components/Evaluators/Tes
import { EXPERIMENTS_AND_EVALS_EXCLUSION_FILTERS } from "@/src/features/evals/v2/constants/experimentAndEvalFilters";
import { dedupeObservationPages } from "@/src/features/evals/v2/components/Evaluators/Testing/components/SampleObservationSelectorBase/fns/dedupeObservations";
import { toggleExampleFilters } from "@/src/features/evals/v2/components/Evaluators/Testing/components/SampleObservationSelectorBase/fns/toggleExampleFilters";
+import { useReusableRuleFilterPresets } from "@/src/features/evals/v2/hooks/useReusableRuleFilterPresets";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export type SampleObservation =
RouterOutputs["events"]["all"]["observations"][number];
@@ -167,6 +169,28 @@ export function SampleObservationSelectorBase(
formatCount,
mapObservedOptions,
} = props;
+ const activeRegistry = registry ?? EVENTS_FIELD_REGISTRY;
+ const reusableRuleFilters = useReusableRuleFilterPresets(
+ projectId,
+ activeRegistry,
+ );
+ const capture = usePostHogClientCapture();
+ const onQueryPresetPick = useCallback(
+ (presetId: string) => {
+ const preset = reusableRuleFilters.presets.find(
+ (candidate) => candidate.id === presetId,
+ );
+ if (!preset) return;
+ capture("evaluation_rules:filter_reused", {
+ tableName,
+ evaluatorCount: preset.evaluatorCount,
+ filterCount: preset.filterCount,
+ replacedFilterCount: filterState.length,
+ isV4: true,
+ });
+ },
+ [capture, filterState.length, reusableRuleFilters.presets, tableName],
+ );
const setFilters = (
next: FilterState | ((current: FilterState) => FilterState),
) => {
@@ -304,16 +328,21 @@ export function SampleObservationSelectorBase(
resultCount: observationQuery.isSuccess
? matchingObservations.length
: null,
- registry: registry ?? EVENTS_FIELD_REGISTRY,
+ registry: activeRegistry,
}),
- [matchingObservations, observationQuery.isSuccess, observed, registry],
+ [
+ activeRegistry,
+ matchingObservations,
+ observationQuery.isSuccess,
+ observed,
+ ],
);
const aiScoreNames = useMemo(
() =>
- (registry ?? EVENTS_FIELD_REGISTRY).scores
+ activeRegistry.scores
? observedScoreNamesFromOptions(observed)
: undefined,
- [observed, registry],
+ [activeRegistry, observed],
);
const selectionToReconcile = observationQuery.isSuccess
? resolveSelection(matchingObservations, selectedObservationId)
@@ -460,6 +489,8 @@ export function SampleObservationSelectorBase(
{...(registry ? { registry } : {})}
onApplyFilters={search.applyFilters}
onRequestColumns={options.requestColumns}
+ presetSections={reusableRuleFilters.sections}
+ onQueryPresetPick={onQueryPresetPick}
aiDataContext={aiDataContext}
aiScoreNames={aiScoreNames}
className="p-0"
diff --git a/web/src/features/evals/v2/hooks/useReusableRuleFilterPresets.clienttest.ts b/web/src/features/evals/v2/hooks/useReusableRuleFilterPresets.clienttest.ts
new file mode 100644
index 0000000000..35dd9c2072
--- /dev/null
+++ b/web/src/features/evals/v2/hooks/useReusableRuleFilterPresets.clienttest.ts
@@ -0,0 +1,90 @@
+// @vitest-environment node
+
+import { describe, expect, it } from "vitest";
+import type { FilterState } from "@langfuse/shared";
+
+import { RULE_FIELD_REGISTRY } from "@/src/features/evals/v2/constants/ruleSearchRegistry";
+import { prepareReusableRuleFilterPresets } from "@/src/features/evals/v2/hooks/useReusableRuleFilterPresets";
+import { EVENTS_FIELD_REGISTRY } from "@/src/features/search-bar/lib/fields";
+
+const reusableFilters = [
+ {
+ latestRuleId: "rule-1",
+ filter: [
+ {
+ column: "tags",
+ type: "arrayOptions",
+ operator: "any of",
+ value: ["production"],
+ },
+ ] satisfies FilterState,
+ evaluatorCount: 3,
+ updatedAt: new Date("2026-02-01T00:00:00.000Z"),
+ },
+];
+
+describe("prepareReusableRuleFilterPresets", () => {
+ it.each([
+ [
+ "evaluator sample observations",
+ EVENTS_FIELD_REGISTRY,
+ "traceTags:production",
+ ],
+ ["rule filters", RULE_FIELD_REGISTRY, "tags:production"],
+ ])("builds reusable queries for %s", (_surface, registry, expectedQuery) => {
+ expect(prepareReusableRuleFilterPresets(reusableFilters, registry)).toEqual(
+ {
+ sections: [
+ {
+ title: "Reuse rule filters",
+ options: [
+ {
+ id: "rule-filter:rule-1",
+ label: expectedQuery,
+ detail: "Used by 3 evaluators",
+ query: expectedQuery,
+ },
+ ],
+ },
+ ],
+ presets: [
+ {
+ id: "rule-filter:rule-1",
+ evaluatorCount: 3,
+ filterCount: 1,
+ },
+ ],
+ },
+ );
+ });
+
+ it("preserves exact name matching when adapting to the events registry", () => {
+ const exactNameFilter = [
+ {
+ latestRuleId: "rule-exact-name",
+ filter: [
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["checkout"],
+ },
+ ] satisfies FilterState,
+ evaluatorCount: 1,
+ updatedAt: new Date("2026-02-01T00:00:00.000Z"),
+ },
+ ];
+
+ const events = prepareReusableRuleFilterPresets(
+ exactNameFilter,
+ EVENTS_FIELD_REGISTRY,
+ );
+ const rules = prepareReusableRuleFilterPresets(
+ exactNameFilter,
+ RULE_FIELD_REGISTRY,
+ );
+
+ expect(events.sections[0]?.options[0]?.query).toBe("name:=checkout");
+ expect(rules.sections[0]?.options[0]?.query).toBe("name:checkout");
+ });
+});
diff --git a/web/src/features/evals/v2/hooks/useReusableRuleFilterPresets.ts b/web/src/features/evals/v2/hooks/useReusableRuleFilterPresets.ts
new file mode 100644
index 0000000000..a10fbab04a
--- /dev/null
+++ b/web/src/features/evals/v2/hooks/useReusableRuleFilterPresets.ts
@@ -0,0 +1,94 @@
+import { useMemo } from "react";
+
+import type { FilterState } from "@langfuse/shared";
+
+import { RULE_FIELD_REGISTRY } from "@/src/features/evals/v2/constants/ruleSearchRegistry";
+import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";
+import type { FieldRegistry } from "@/src/features/search-bar/lib/fields";
+import type { QueryPresetSection } from "@/src/features/search-bar/lib/completions";
+import { validateQuery } from "@/src/features/search-bar/lib/validate";
+import { api, type RouterOutputs } from "@/src/utils/api";
+
+const SECTION_TITLE = "Reuse rule filters";
+
+type ReusableFilter =
+ RouterOutputs["evalsV2"]["rules"]["reusableFilters"][number];
+
+export type ReusableRuleFilterPreset = {
+ id: string;
+ evaluatorCount: number;
+ filterCount: number;
+};
+
+function projectRuleFilterToRegistry(
+ filter: FilterState,
+ registry: FieldRegistry,
+): FilterState {
+ return filter.map((condition) => {
+ const source = RULE_FIELD_REGISTRY.resolveField(condition.column);
+ if (source?.type !== "field") return condition;
+ const target = registry.resolveField(source.field.id);
+ return target?.type === "field"
+ ? { ...condition, column: target.field.id }
+ : condition;
+ }) as FilterState;
+}
+
+export function prepareReusableRuleFilterPresets(
+ reusableFilters: ReusableFilter[],
+ registry: FieldRegistry,
+): {
+ sections: QueryPresetSection[];
+ presets: ReusableRuleFilterPreset[];
+} {
+ const presets: ReusableRuleFilterPreset[] = [];
+ const options = reusableFilters.flatMap((reusableFilter) => {
+ const filter = projectRuleFilterToRegistry(
+ reusableFilter.filter as FilterState,
+ registry,
+ );
+ const query = filterStateToQueryText(filter, {}, registry);
+ if (
+ query.text.length === 0 ||
+ query.skippedFilters.length > 0 ||
+ !validateQuery(query.text, undefined, registry).valid
+ ) {
+ return [];
+ }
+
+ const id = `rule-filter:${reusableFilter.latestRuleId}`;
+ presets.push({
+ id,
+ evaluatorCount: reusableFilter.evaluatorCount,
+ filterCount: reusableFilter.filter.length,
+ });
+ return [
+ {
+ id,
+ label: query.text,
+ detail: `Used by ${reusableFilter.evaluatorCount} ${reusableFilter.evaluatorCount === 1 ? "evaluator" : "evaluators"}`,
+ query: query.text,
+ },
+ ];
+ });
+
+ return {
+ sections: options.length > 0 ? [{ title: SECTION_TITLE, options }] : [],
+ presets,
+ };
+}
+
+export function useReusableRuleFilterPresets(
+ projectId: string,
+ registry: FieldRegistry,
+) {
+ const reusableFilters = api.evalsV2.rules.reusableFilters.useQuery({
+ projectId,
+ });
+
+ return useMemo(
+ () =>
+ prepareReusableRuleFilterPresets(reusableFilters.data ?? [], registry),
+ [registry, reusableFilters.data],
+ );
+}
diff --git a/web/src/features/evals/v2/server/rules/ruleFilterMatching.ts b/web/src/features/evals/v2/server/rules/ruleFilterMatching.ts
index 22695d7200..721286d131 100644
--- a/web/src/features/evals/v2/server/rules/ruleFilterMatching.ts
+++ b/web/src/features/evals/v2/server/rules/ruleFilterMatching.ts
@@ -10,12 +10,12 @@ function conditionKey(condition: FilterState[number]) {
return stableJsonStringify({ ...condition, value });
}
-export function filtersMatch(left: FilterState, right: FilterState) {
- if (left.length !== right.length) return false;
+export function filterStateKey(filter: FilterState) {
+ return stableJsonStringify(filter.map(conditionKey).sort());
+}
- const leftKeys = left.map(conditionKey).sort();
- const rightKeys = right.map(conditionKey).sort();
- return leftKeys.every((key, index) => key === rightKeys[index]);
+export function filtersMatch(left: FilterState, right: FilterState) {
+ return filterStateKey(left) === filterStateKey(right);
}
export function fallbackRuleName(filter: FilterState) {
diff --git a/web/src/features/evals/v2/server/rules/ruleRepository.ts b/web/src/features/evals/v2/server/rules/ruleRepository.ts
index 680da21a80..2d3ffc9280 100644
--- a/web/src/features/evals/v2/server/rules/ruleRepository.ts
+++ b/web/src/features/evals/v2/server/rules/ruleRepository.ts
@@ -22,10 +22,13 @@ import type {
UpdateRuleInput,
} from "./ruleTypes";
import { creatorOptionsWhere, creatorWhere } from "../creatorFilterPrisma";
+import { batchEligibleEvaluatorWhere } from "../evaluators/evaluatorRepository";
import { filtersMatch } from "./ruleFilterMatching";
export type RulePrisma = PrismaClient | Prisma.TransactionClient;
+const MAX_REUSABLE_FILTER_CANDIDATES = 20;
+
const latestVersion = {
orderBy: { version: "desc" as const },
take: 1,
@@ -144,6 +147,39 @@ export async function listRules(params: {
return { rules, totalItems };
}
+export async function listReusableFilterCandidates(params: {
+ prisma: PrismaClient;
+ projectId: string;
+}) {
+ const rules = await params.prisma.evaluationRule.findMany({
+ where: {
+ projectId: params.projectId,
+ targetObject: {
+ in: [EvalTargetObject.EVENT, EvalTargetObject.EXPERIMENT],
+ },
+ },
+ orderBy: [{ updatedAt: "desc" }, { id: "desc" }],
+ take: MAX_REUSABLE_FILTER_CANDIDATES,
+ select: {
+ id: true,
+ filter: true,
+ updatedAt: true,
+ assignments: {
+ where: {
+ projectId: params.projectId,
+ evaluator: {
+ projectId: params.projectId,
+ ...batchEligibleEvaluatorWhere,
+ },
+ },
+ select: { evaluatorId: true },
+ },
+ },
+ });
+
+ return rules;
+}
+
export async function listRuleFilterOptions(params: {
prisma: PrismaClient;
projectId: string;
diff --git a/web/src/features/evals/v2/server/rules/ruleRouter.ts b/web/src/features/evals/v2/server/rules/ruleRouter.ts
index 87aeb297ff..2086258f2a 100644
--- a/web/src/features/evals/v2/server/rules/ruleRouter.ts
+++ b/web/src/features/evals/v2/server/rules/ruleRouter.ts
@@ -60,6 +60,17 @@ export const ruleRouter = createTRPCRouter({
return serviceForContext(ctx).listFilterOptions(ctx.session.projectId);
}),
+ reusableFilters: protectedProjectProcedure
+ .input(ListRulesSchema.pick({ projectId: true }))
+ .query(({ ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: ctx.session.projectId,
+ scope: "evalJob:read",
+ });
+ return serviceForContext(ctx).listReusableFilters(ctx.session.projectId);
+ }),
+
get: protectedProjectProcedure.input(RuleIdSchema).query(({ input, ctx }) => {
throwIfNoProjectAccess({
session: ctx.session,
diff --git a/web/src/features/evals/v2/server/rules/ruleService.ts b/web/src/features/evals/v2/server/rules/ruleService.ts
index a640599f10..9dc0912003 100644
--- a/web/src/features/evals/v2/server/rules/ruleService.ts
+++ b/web/src/features/evals/v2/server/rules/ruleService.ts
@@ -40,7 +40,9 @@ import * as repository from "./ruleRepository";
import { isLegacyEvalTarget } from "@/src/features/evals/utils/typeHelpers";
import { prepareModernRuleVariableMapping } from "@/src/features/evals/v2/fns/variableMapping/prepareModernRuleVariableMapping";
import { assertCompleteEvaluatorVariableMapping } from "../evaluators/evaluatorValidation";
-import { fallbackRuleName } from "./ruleFilterMatching";
+import { fallbackRuleName, filterStateKey } from "./ruleFilterMatching";
+
+const MAX_REUSABLE_FILTERS = 10;
export type RuleAuditEvent = {
action: "create" | "update" | "delete";
@@ -107,6 +109,58 @@ export class RuleService {
);
}
+ async listReusableFilters(projectId: string) {
+ const candidates = await repository.listReusableFilterCandidates({
+ prisma: this.prisma,
+ projectId,
+ });
+ // FilterState equality ignores condition order and multi-value order. A SQL
+ // JSONB GROUP BY would need to canonicalize both array levels first, so the
+ // service owns semantic deduplication and ranking over repository rows.
+ const grouped = new Map<
+ string,
+ {
+ latestRuleId: string;
+ filter: FilterState;
+ updatedAt: Date;
+ evaluatorIds: Set<string>;
+ }
+ >();
+
+ for (const candidate of candidates) {
+ const filter = candidate.filter as FilterState;
+ if (filter.length === 0) continue;
+ const key = filterStateKey(filter);
+ const group = grouped.get(key) ?? {
+ latestRuleId: candidate.id,
+ filter,
+ updatedAt: candidate.updatedAt,
+ evaluatorIds: new Set<string>(),
+ };
+ if (candidate.updatedAt > group.updatedAt) {
+ group.latestRuleId = candidate.id;
+ group.filter = filter;
+ group.updatedAt = candidate.updatedAt;
+ }
+ for (const { evaluatorId } of candidate.assignments) {
+ group.evaluatorIds.add(evaluatorId);
+ }
+ grouped.set(key, group);
+ }
+
+ return [...grouped.values()]
+ .map(({ evaluatorIds, ...group }) => ({
+ ...group,
+ evaluatorCount: evaluatorIds.size,
+ }))
+ .sort(
+ (left, right) =>
+ right.evaluatorCount - left.evaluatorCount ||
+ right.updatedAt.getTime() - left.updatedAt.getTime(),
+ )
+ .slice(0, MAX_REUSABLE_FILTERS);
+ }
+
async listRulesForEvaluator(projectId: string, evaluatorId: string) {
const exists = await evaluatorRepository.countProjectEvaluators({
prisma: this.prisma,
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index d777cee67c..27480d1eea 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -191,6 +191,7 @@ export const events = {
"status_change",
"attach_evaluator",
"detach_evaluator",
+ "filter_reused",
],
integrations: [
"posthog_form_submitted",
diff --git a/web/src/features/search-bar/README.md b/web/src/features/search-bar/README.md
index b7ac466e96..8f7308ca56 100644
--- a/web/src/features/search-bar/README.md
+++ b/web/src/features/search-bar/README.md
@@ -258,6 +258,21 @@ encode/decode round-trip. The flat URL contract (`FilterState` + `searchQuery`
interleave is preserved only in the recent-searches entry (`planCommit`'s
`canonical`), not in the live bar.
+## Host-provided query presets
+
+Views can inject complete-query sections through `EventsSearchBarRow`'s
+`presetSections` prop. These are data, not grammar: the shared planner renders
+them at every blank top-level term, including after existing filters, and a pick
+replaces and commits the complete draft. The host owns fetching, ranking,
+registry compatibility, labels, and optional pick analytics.
+
+Evaluation setup uses this seam for **Reuse rule filters**. It groups equivalent
+modern event/experiment rule filters, ranks them only by distinct attached
+evaluator count (latest rule update breaks ties), and excludes legacy
+trace/dataset rules. Rule `FilterState` is serialized with the rule registry and
+validated against the receiving registry before it is offered, so aliases such
+as rule `tags` can safely lower to the events table's `traceTags` column.
+
## AI filter mode (the "Ask AI" button)
The bar is also the home of AI-assisted filtering on v4 (it replaces the legacy
diff --git a/web/src/features/search-bar/components/AutocompleteListbox.stories.tsx b/web/src/features/search-bar/components/AutocompleteListbox.stories.tsx
index 2f7fd85ee2..a7b4460db1 100644
--- a/web/src/features/search-bar/components/AutocompleteListbox.stories.tsx
+++ b/web/src/features/search-bar/components/AutocompleteListbox.stories.tsx
@@ -52,6 +52,27 @@ const fieldPlan: CompletionPlan = {
],
};
+const presetPlan: CompletionPlan = {
+ stage: "empty",
+ from: 0,
+ to: 0,
+ loading: false,
+ sections: [
+ {
+ title: "Reuse rule filters",
+ options: [
+ {
+ id: "rule-filter:production-generations",
+ kind: "preset",
+ label: "environment:production type:GENERATION",
+ detail: "Used by 8 evaluators",
+ query: "environment:production type:GENERATION",
+ },
+ ],
+ },
+ ],
+};
+
const valuePlan: CompletionPlan = {
stage: "value",
from: 6,
@@ -97,6 +118,10 @@ export const Fields = meta.story({
args: { plan: fieldPlan, highlightedId: "field:level" },
});
+export const Presets = meta.story({
+ args: { plan: presetPlan },
+});
+
export const ObservedValues = meta.story({
args: { plan: valuePlan },
});
diff --git a/web/src/features/search-bar/components/AutocompleteListbox.tsx b/web/src/features/search-bar/components/AutocompleteListbox.tsx
index 33a2dca41f..a84130a63b 100644
--- a/web/src/features/search-bar/components/AutocompleteListbox.tsx
+++ b/web/src/features/search-bar/components/AutocompleteListbox.tsx
@@ -4,7 +4,7 @@
// AutocompletePopover (positioning); Storybook renders it directly.
import * as React from "react";
-import { Check, Clock, Parentheses, Search } from "lucide-react";
+import { Bookmark, Check, Clock, Parentheses, Search } from "lucide-react";
import { cn } from "@/src/utils/tailwind";
import { ScoreTag } from "@/src/components/score-tag";
@@ -17,6 +17,7 @@ import { optionDomId } from "@/src/features/search-bar/components/presentation";
function OptionIcon({ kind }: { kind: CompletionOption["kind"] }) {
const cls = "h-3.5 w-3.5 flex-none opacity-55";
if (kind === "recent") return <Clock className={cls} aria-hidden />;
+ if (kind === "preset") return <Bookmark className={cls} aria-hidden />;
if (kind === "operator" || kind === "pattern")
return <Parentheses className={cls} aria-hidden />;
return <Search className={cls} aria-hidden />;
diff --git a/web/src/features/search-bar/components/EventsSearchBarRow.tsx b/web/src/features/search-bar/components/EventsSearchBarRow.tsx
index 6dbdf187f7..1a6e64948b 100644
--- a/web/src/features/search-bar/components/EventsSearchBarRow.tsx
+++ b/web/src/features/search-bar/components/EventsSearchBarRow.tsx
@@ -32,7 +32,8 @@ import { ComposerWithPreview } from "@/src/features/search-bar/components/Compos
import { SearchBarAiPrompt } from "@/src/features/search-bar/components/SearchBarAiPrompt";
import { SearchBarStoreProvider } from "@/src/features/search-bar/store/SearchBarStoreProvider";
import type { SearchBarStore } from "@/src/features/search-bar/store/searchBarStore";
-import type { SearchCommitTrigger } from "@/src/features/search-bar/hooks/useEventsSearchBar";
+import type { SearchCommit } from "@/src/features/search-bar/hooks/useEventsSearchBar";
+import type { QueryPresetSection } from "@/src/features/search-bar/lib/completions";
export function EventsSearchBarRow({
projectId,
@@ -45,6 +46,8 @@ export function EventsSearchBarRow({
freeTextReason,
onApplyFilters,
onRequestColumns,
+ presetSections,
+ onQueryPresetPick,
aiDataContext,
aiScoreNames,
className,
@@ -54,7 +57,7 @@ export function EventsSearchBarRow({
/** Table this bar filters — threaded to AI-prompt analytics (LFE-10781). */
tableName: string;
store: SearchBarStore;
- commit: (trigger?: SearchCommitTrigger) => string | null;
+ commit: SearchCommit;
observed: ObservedOptions | undefined;
/** Columns whose lazy fetch terminally errored — value-stage loading settles to
* empty (per column) instead of pinning, matching the sidebar's settled-error
@@ -78,6 +81,9 @@ export function EventsSearchBarRow({
* (request the observed-options keys so the prompt sees real values).
*/
onRequestColumns?: (columns: readonly string[]) => void;
+ /** Complete queries supplied by the host view. */
+ presetSections?: QueryPresetSection[];
+ onQueryPresetPick?: (presetId: string) => void;
/** Project data context (observed values + metadata keys + result count) for
* the AI prompt — built by EventsTable from filterOptions + visible rows. */
aiDataContext?: string;
@@ -127,6 +133,8 @@ export function EventsSearchBarRow({
freeTextReason={freeTextReason}
onActivateAi={aiAvailable ? activateAi : undefined}
onRequestColumns={onRequestColumns}
+ presetSections={presetSections}
+ onQueryPresetPick={onQueryPresetPick}
registry={registry}
/>
</SearchBarStoreProvider>
diff --git a/web/src/features/search-bar/components/SearchComposer.tsx b/web/src/features/search-bar/components/SearchComposer.tsx
index 9b51f51eb4..3874fa5920 100644
--- a/web/src/features/search-bar/components/SearchComposer.tsx
+++ b/web/src/features/search-bar/components/SearchComposer.tsx
@@ -41,6 +41,7 @@ import {
planInputCompletions,
type CompletionOption,
type CompletionPlan,
+ type QueryPresetSection,
} from "@/src/features/search-bar/lib/completions";
import {
useSearchBarStore,
@@ -304,6 +305,8 @@ export function SearchComposer({
erroredColumns,
onActivateAi,
onRequestColumns,
+ onQueryPresetPick,
+ presetSections,
fieldReason,
freeTextReason,
registry = EVENTS_FIELD_REGISTRY,
@@ -323,6 +326,10 @@ export function SearchComposer({
* loading is wired by the host table.
*/
onRequestColumns?: (columns: readonly string[]) => void;
+ /** Complete-query sections supplied by the host view. Presets remain visible
+ * at every blank top-level term and replace the full query when picked. */
+ presetSections?: QueryPresetSection[];
+ onQueryPresetPick?: (presetId: string) => void;
/** Given a filter token's field, the reason it is not applied on the current
* surface (dims the pill + hover), or null. Undefined leaves all active. */
fieldReason?: (field: string) => string | null;
@@ -392,6 +399,7 @@ export function SearchComposer({
observed,
erroredColumns,
recents,
+ presetSections,
currentQueryText: draft,
},
registry,
@@ -796,21 +804,23 @@ export function SearchComposer({
(option: CompletionOption) => {
const currentPlan = planRef.current;
if (currentPlan === null) return;
- if (option.kind === "recent") {
- // Land in the RESTING (trailing-space) form like every other commit
- // landing, so a later click past the text doesn't have to mutate the
- // draft (= the caret flicker this PR removed). A recent is stored
- // canonical/trimmed, so one space never doubles.
+ if (option.kind === "recent" || option.kind === "preset") {
+ // Complete-query picks replace the full draft and land in the RESTING
+ // trailing-space form like every other commit landing.
const resting =
option.query.length === 0 ? option.query : `${option.query} `;
setDraftWithSelection(resting, resting.length);
- // A recent is a COMPLETE query the user explicitly picked, so it gets
- // the same Enter/blur reveal semantics: commit if valid, otherwise
- // reveal the red invalid state instead of silently no-op'ing (e.g. a
- // recent stored before a grammar tightening, or a since-retyped score).
+ // Explicit complete-query picks commit when valid and otherwise reveal
+ // the invalid state instead of silently no-op'ing.
const state = storeApi.getState();
- if (state.draftValid) commitToFilterState("pick");
- else state.actions.revealInvalid();
+ if (state.draftValid) {
+ const committed = commitToFilterState(
+ "pick",
+ option.kind === "preset" ? { replaceHidden: true } : undefined,
+ );
+ if (option.kind === "preset" && committed !== null)
+ onQueryPresetPick?.(option.id);
+ } else state.actions.revealInvalid();
setAutocompleteOpen(false);
return;
}
@@ -845,6 +855,7 @@ export function SearchComposer({
setDraftWithSelection,
commitStructuredEdit,
commitToFilterState,
+ onQueryPresetPick,
storeApi,
],
);
diff --git a/web/src/features/search-bar/hooks/useEventsSearchBar.clienttest.tsx b/web/src/features/search-bar/hooks/useEventsSearchBar.clienttest.tsx
index 208e6aac26..3400c7e269 100644
--- a/web/src/features/search-bar/hooks/useEventsSearchBar.clienttest.tsx
+++ b/web/src/features/search-bar/hooks/useEventsSearchBar.clienttest.tsx
@@ -34,6 +34,35 @@ function setup(
return { result, setFilterState, setSearchQuery, setSearchType };
}
+describe("useEventsSearchBar.commit", () => {
+ it("fully replaces hidden filters when a query preset is picked", () => {
+ const hiddenFilter: FilterState = [
+ {
+ column: "traceTags",
+ type: "arrayOptions",
+ operator: "all of",
+ value: ["legacy-scope"],
+ },
+ ];
+ const { result, setFilterState } = setup({
+ filterState: hiddenFilter,
+ searchQuery: null,
+ });
+
+ act(() => result.current.store.getState().actions.setDraft("level:ERROR"));
+ act(() => result.current.commit("pick", { replaceHidden: true }));
+
+ expect(setFilterState).toHaveBeenCalledWith([
+ {
+ column: "level",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["ERROR"],
+ },
+ ]);
+ });
+});
+
describe("useEventsSearchBar.applyFilters", () => {
it("clears the free-text lane so refine actually drops it", () => {
// The model gets the full bar text (with `refund` rendered inline) as
diff --git a/web/src/features/search-bar/hooks/useEventsSearchBar.ts b/web/src/features/search-bar/hooks/useEventsSearchBar.ts
index dee8d8ad13..7f0ce4cb7a 100644
--- a/web/src/features/search-bar/hooks/useEventsSearchBar.ts
+++ b/web/src/features/search-bar/hooks/useEventsSearchBar.ts
@@ -40,6 +40,11 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePos
/** How a search-bar commit was triggered — the `trigger` analytics dimension. */
export type SearchCommitTrigger = "enter" | "blur" | "pick";
+export type SearchCommitOptions = { replaceHidden?: boolean };
+export type SearchCommit = (
+ trigger?: SearchCommitTrigger,
+ options?: SearchCommitOptions,
+) => string | null;
/** Order-independent scope-set equality (scopes are unique). */
function sameScopes(a: TracingSearchType[], b: TracingSearchType[]): boolean {
@@ -97,7 +102,7 @@ export function useEventsSearchBar({
registry?: FieldRegistry;
}): {
store: SearchBarStore;
- commit: (trigger?: SearchCommitTrigger) => string | null;
+ commit: SearchCommit;
applyFilters: (filters: FilterState) => void;
} {
const capture = usePostHogClientCapture();
@@ -204,7 +209,10 @@ export function useEventsSearchBar({
const lastErrorTextRef = useRef<string | null>(null);
const commit = useCallback(
- (trigger: SearchCommitTrigger = "enter"): string | null => {
+ (
+ trigger: SearchCommitTrigger = "enter",
+ options: SearchCommitOptions = {},
+ ): string | null => {
const draftText = store.getState().draft;
const result = planCommit(
draftText,
@@ -245,9 +253,12 @@ export function useEventsSearchBar({
lastErrorTextRef.current = null;
const { setFilterState, setSearchQuery, setSearchType } =
applyRef.current;
- // Re-attach the filters the grammar can't represent so the commit never
- // drops them (no-silent-drop contract; shared with the AI apply path).
- const committedFilters = mergeWithSkipped(result.filters);
+ // Ordinary grammar edits preserve filters the grammar cannot represent.
+ // Complete-query replacements can explicitly clear those hidden filters
+ // instead of silently carrying old scope.
+ const committedFilters = options.replaceHidden
+ ? result.filters
+ : mergeWithSkipped(result.filters);
setFilterState(committedFilters);
setSearchQuery(result.searchQuery);
// Only write searchType when it actually changed. planCommit coerces a
diff --git a/web/src/features/search-bar/lib/completions.clienttest.ts b/web/src/features/search-bar/lib/completions.clienttest.ts
index 38354768b1..5999d373e1 100644
--- a/web/src/features/search-bar/lib/completions.clienttest.ts
+++ b/web/src/features/search-bar/lib/completions.clienttest.ts
@@ -55,6 +55,128 @@ describe("planInputCompletions", () => {
expect(titles).toContain(SECTION_RECENT);
});
+ it("always includes injected query presets at a blank top-level term", () => {
+ const presetSections = [
+ {
+ title: "Reuse rule filters",
+ options: [
+ {
+ id: "rule-filter:popular",
+ label: "environment:production",
+ detail: "Used by 8 evaluators",
+ query: "environment:production",
+ },
+ ],
+ },
+ ];
+
+ const empty = plan("", 0, { presetSections });
+ const afterExistingFilters = plan("level:ERROR ", 12, {
+ presetSections,
+ });
+
+ for (const result of [empty, afterExistingFilters]) {
+ expect(result?.sections[0]).toMatchObject({
+ title: "Reuse rule filters",
+ options: [
+ {
+ kind: "preset",
+ id: "rule-filter:popular",
+ query: "environment:production",
+ },
+ ],
+ });
+ expect(result?.autoHighlight).not.toBe(true);
+ }
+ });
+
+ it("caps all preset sections at ten and hides the current query", () => {
+ const presetSections = [
+ {
+ title: "Primary presets",
+ options: Array.from({ length: 6 }, (_, index) => ({
+ id: `rule-filter:${index}`,
+ label: `environment:env-${index}`,
+ query: `environment:env-${index}`,
+ })),
+ },
+ {
+ title: "Secondary presets",
+ options: Array.from({ length: 7 }, (_, index) => ({
+ id: `rule-filter:${index + 6}`,
+ label: `environment:env-${index + 6}`,
+ query: `environment:env-${index + 6}`,
+ })),
+ },
+ ];
+ const currentQuery = "environment:env-2";
+ const result = plan(`${currentQuery} `, currentQuery.length + 1, {
+ presetSections,
+ });
+ const presets =
+ result?.sections.filter((section) => section.title.endsWith("presets")) ??
+ [];
+ const presetIds = presets.flatMap((section) =>
+ section.options.map((option) => option.id),
+ );
+
+ expect(presets.map((section) => section.options.length)).toEqual([5, 5]);
+ expect(presetIds).not.toContain("rule-filter:2");
+ expect(presetIds).toEqual([
+ "rule-filter:0",
+ "rule-filter:1",
+ "rule-filter:3",
+ "rule-filter:4",
+ "rule-filter:5",
+ "rule-filter:6",
+ "rule-filter:7",
+ "rule-filter:8",
+ "rule-filter:9",
+ "rule-filter:10",
+ ]);
+ });
+
+ it("keeps only the first host preset when ids are duplicated", () => {
+ const result = plan("", 0, {
+ presetSections: [
+ {
+ title: "Reuse rule filters",
+ options: [
+ {
+ id: "rule-filter:duplicate",
+ label: "environment:first",
+ query: "environment:first",
+ },
+ {
+ id: "rule-filter:duplicate",
+ label: "environment:second",
+ query: "environment:second",
+ },
+ {
+ id: "rule-filter:unique",
+ label: "environment:third",
+ query: "environment:third",
+ },
+ ],
+ },
+ ],
+ });
+ const presets = result?.sections.find(
+ (section) => section.title === "Reuse rule filters",
+ );
+
+ expect(presets?.options).toMatchObject([
+ {
+ id: "rule-filter:duplicate",
+ query: "environment:first",
+ },
+ {
+ id: "rule-filter:unique",
+ query: "environment:third",
+ },
+ ]);
+ });
+
it("ranks fields against the typed key prefix but does NOT arm Enter (free-text-first)", () => {
// A bare prefix lists the field but must not hijack Enter — the user may be
// typing a free-text search. Enter commits the text; the field is one
@@ -874,7 +996,7 @@ describe("planInputCompletions", () => {
const opt = flattenOptions(p).find((o) => o.id === "match:toolNames:mcp");
expect(opt).toBeDefined();
const r = applyPick(
- opt as Exclude<CompletionOption, { kind: "recent" }>,
+ opt as Exclude<CompletionOption, { kind: "recent" | "preset" }>,
"mcp",
p!,
);
@@ -886,9 +1008,9 @@ describe("planInputCompletions", () => {
});
describe("applyPick", () => {
- // Narrowing helper: the popover only picks non-recent options here.
- const nonRecent = (o: CompletionOption | undefined) =>
- o as Exclude<CompletionOption, { kind: "recent" }>;
+ // Narrowing helper: applyPick only handles span-local options here.
+ const spanLocal = (o: CompletionOption | undefined) =>
+ o as Exclude<CompletionOption, { kind: "recent" | "preset" }>;
it("keeps the caret INSIDE the block after picking a numeric operator", () => {
// LFE-10501 BUG A. Picking `>` for a numeric field must not append a
@@ -900,7 +1022,7 @@ describe("applyPick", () => {
(o) => o.kind === "operator" && o.label === ">",
);
expect(gt).toBeDefined();
- const result = applyPick(nonRecent(gt), "latency:", p!);
+ const result = applyPick(spanLocal(gt), "latency:", p!);
expect(result.next).toBe("latency:>"); // no trailing space appended
expect(result.caret).toBe(9); // caret sits right after `>`, inside the block
});
@@ -911,7 +1033,7 @@ describe("applyPick", () => {
(o) => o.kind === "operator" && o.label === ">=",
);
expect(gte).toBeDefined();
- const result = applyPick(nonRecent(gte), "startTime:", p!);
+ const result = applyPick(spanLocal(gte), "startTime:", p!);
expect(result.next).toBe("startTime:>=");
expect(result.caret).toBe(12);
});
@@ -923,7 +1045,7 @@ describe("applyPick", () => {
(o) => o.kind === "operator" && o.label === "<",
);
expect(lt).toBeDefined();
- const result = applyPick(nonRecent(lt), q, p!);
+ const result = applyPick(spanLocal(lt), q, p!);
expect(result.next).toBe(`${q}<`);
expect(result.caret).toBe(q.length + 1);
});
@@ -937,7 +1059,7 @@ describe("applyPick", () => {
(o) => o.kind === "value" && o.value === "ERROR",
);
expect(err).toBeDefined();
- const result = applyPick(nonRecent(err), "level:", p!);
+ const result = applyPick(spanLocal(err), "level:", p!);
expect(result.next).toBe("level:ERROR ");
expect(result.caret).toBe(12);
expect(result.keepOpen).toBe(true);
@@ -951,7 +1073,7 @@ describe("applyPick", () => {
(o) => o.kind === "operator" && o.label === "NOT",
);
expect(not).toBeDefined();
- const result = applyPick(nonRecent(not), "level:ERROR N", p!);
+ const result = applyPick(spanLocal(not), "level:ERROR N", p!);
expect(result.next).toBe("level:ERROR NOT ");
expect(result.caret).toBe("level:ERROR NOT ".length);
});
diff --git a/web/src/features/search-bar/lib/completions.ts b/web/src/features/search-bar/lib/completions.ts
index ea98545db1..2063e3e5d6 100644
--- a/web/src/features/search-bar/lib/completions.ts
+++ b/web/src/features/search-bar/lib/completions.ts
@@ -74,10 +74,27 @@ export type CompletionOption =
* the token under the caret. */
replaceSpan?: { from: number; to: number };
}
- | { id: string; kind: "recent"; label: string; query: string };
+ | { id: string; kind: "recent"; label: string; query: string }
+ | {
+ id: string;
+ kind: "preset";
+ label: string;
+ detail?: string;
+ query: string;
+ };
export type CompletionSection = { title: string; options: CompletionOption[] };
+export type QueryPresetSection = {
+ title: string;
+ options: Array<{
+ id: string;
+ label: string;
+ detail?: string;
+ query: string;
+ }>;
+};
+
export type CompletionPlan = {
stage: CompletionStage;
/** Span in the active INPUT text that an accepted option replaces. */
@@ -118,6 +135,7 @@ export const SECTION_SCORE_NAMES = "Score names";
export const SECTION_SEARCH_IN = "Full-text search";
const MAX_RECENTS_SHOWN = 5;
+const MAX_PRESETS_SHOWN = 10;
// Operators insert with a trailing space so they tokenize out of the input
// immediately; patterns are complete expressions and merge on accept.
@@ -388,6 +406,27 @@ function recentOptions(
}));
}
+function queryPresetSections(
+ presetSections: QueryPresetSection[],
+ currentQueryText: string,
+): CompletionSection[] {
+ const current = currentQueryText.trim();
+ const seenIds = new Set<string>();
+ let remaining = MAX_PRESETS_SHOWN;
+ return presetSections.flatMap((presetSection) => {
+ if (remaining === 0) return [];
+ const options: CompletionOption[] = [];
+ for (const option of presetSection.options) {
+ if (option.query === current || seenIds.has(option.id)) continue;
+ seenIds.add(option.id);
+ options.push({ ...option, kind: "preset" });
+ remaining--;
+ if (remaining === 0) break;
+ }
+ return section(presetSection.title, options);
+ });
+}
+
function section(
title: string,
options: CompletionOption[],
@@ -1000,6 +1039,9 @@ export type InputCompletionContext = {
*/
erroredColumns?: ReadonlySet<string>;
recents: string[];
+ /** Complete queries supplied by a host view, shown at every blank top-level
+ * term. Picking one replaces the full draft. */
+ presetSections?: QueryPresetSection[];
/** Full committed/draft query text (recents identical to it are hidden). */
currentQueryText: string;
};
@@ -1150,6 +1192,10 @@ export function planInputCompletions(
to,
loading: false,
sections: [
+ ...queryPresetSections(
+ ctx.presetSections ?? [],
+ ctx.currentQueryText,
+ ),
...section(
SECTION_SUGGESTIONS,
querySuggestionOptions(ctx.observed, registry),
@@ -1436,8 +1482,8 @@ export function planInputCompletions(
/**
* Apply a picked completion option to the draft — the pure text/caret half of
* the composer's `pickOption` (the composer keeps the DOM/selection side
- * effects and the whole-query `recent` replacement, which is why `recent` is
- * excluded here). Returns the rewritten draft, the caret offset to place inside
+ * effects and whole-query `recent`/`preset` replacements, which is why those
+ * are excluded here). Returns the rewritten draft, the caret offset to place inside
* it, and whether the popover should stay open.
*
* The classification is the crux: an option that INVITES MORE INPUT leaves the
@@ -1448,7 +1494,7 @@ export function planInputCompletions(
* field suggestions for the next filter.
*/
export function applyPick(
- option: Exclude<CompletionOption, { kind: "recent" }>,
+ option: Exclude<CompletionOption, { kind: "recent" | "preset" }>,
current: string,
plan: CompletionPlan,
): { next: string; caret: number; keepOpen: boolean } {
diff --git a/web/src/features/search-bar/store/SearchBarStoreProvider.tsx b/web/src/features/search-bar/store/SearchBarStoreProvider.tsx
index f719f71354..140eb33338 100644
--- a/web/src/features/search-bar/store/SearchBarStoreProvider.tsx
+++ b/web/src/features/search-bar/store/SearchBarStoreProvider.tsx
@@ -5,7 +5,7 @@ import {
type SearchBarStore,
type SearchBarStoreState,
} from "@/src/features/search-bar/store/searchBarStore";
-import { type SearchCommitTrigger } from "@/src/features/search-bar/hooks/useEventsSearchBar";
+import { type SearchCommit } from "@/src/features/search-bar/hooks/useEventsSearchBar";
type SearchBarContextValue = {
store: SearchBarStore;
@@ -13,7 +13,7 @@ type SearchBarContextValue = {
* truth). Returns the canonical committed text on success, or null (and
* reveals diagnostics) when the draft is invalid. `trigger` records how the
* commit was initiated for analytics. */
- commit: (trigger?: SearchCommitTrigger) => string | null;
+ commit: SearchCommit;
};
const SearchBarContext = createContext<SearchBarContextValue | null>(null);
@@ -25,7 +25,7 @@ export function SearchBarStoreProvider({
}: {
children: ReactNode;
store: SearchBarStore;
- commit: (trigger?: SearchCommitTrigger) => string | null;
+ commit: SearchCommit;
}) {
const value = useMemo(() => ({ store, commit }), [store, commit]);
return (
@@ -53,8 +53,6 @@ export function useSearchBarStore<TValue>(
return useStore(useSearchBarContext().store, selector);
}
-export function useSearchBarCommit(): (
- trigger?: SearchCommitTrigger,
-) => string | null {
+export function useSearchBarCommit(): SearchCommit {
return useSearchBarContext().commit;
}