πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(search-bar): suggest matching facet filters for bare typed terms (LFE-10888) (#15053)
Nikita Kabardinedd88136199e
diff --git a/web/src/features/search-bar/lib/completions.clienttest.ts b/web/src/features/search-bar/lib/completions.clienttest.tsindex c3b990ae3f..bdbf653e03 100644--- a/web/src/features/search-bar/lib/completions.clienttest.ts+++ b/web/src/features/search-bar/lib/completions.clienttest.ts@@ -5,6 +5,7 @@ import {SECTION_COMPARE_OPS,SECTION_FIELDS,SECTION_MATCH_OPS,+ SECTION_MATCHING_FILTERS,SECTION_RECENT,SECTION_VALUES,type CompletionOption,@@ -63,6 +64,35 @@ describe("planInputCompletions", () => {expect(first[0]).toMatchObject({ kind: "field", fieldId: "level" });});+ it("always surfaces an exactly-named field first, even when ranking would drop it", () => {+ // `ttft` is an alias of timeToFirstToken but not a substring of it β label+ // ranking alone dropped the field entirely while the exact match armed+ // Enter, which then picked whatever happened to sit first instead of the+ // field the user named.+ const ttft = plan("ttft", 4);+ expect(ttft?.autoHighlight).toBe(true);+ expect(flattenOptions(ttft)[0]).toMatchObject({+ kind: "field",+ fieldId: "timeToFirstToken",+ });+ // `model` resolves to providedModelName; `modelId` merely ranks first by+ // label prefix β Enter must honor the alias, not the label ranking.+ const model = plan("model", 5);+ expect(model?.autoHighlight).toBe(true);+ expect(flattenOptions(model)[0]).toMatchObject({+ kind: "field",+ fieldId: "providedModelName",+ });+ // `has` (the pseudo-field) hoists its own entry above the hasInput/+ // hasParentObservation label matches.+ const has = plan("has", 3);+ expect(has?.autoHighlight).toBe(true);+ expect(flattenOptions(has)[0]).toMatchObject({+ kind: "field",+ fieldId: "has",+ });+ });+it("arms Enter only when a bare word EXACTLY names a field", () => {// Exact field/alias name β arm Enter to start the filter (`level` β `level:`).expect(plan("level", 5)?.autoHighlight).toBe(true);@@ -713,6 +743,144 @@ describe("planInputCompletions", () => {const operators = flattenOptions(p).filter((o) => o.kind === "operator");expect(operators.map((o) => o.label)).not.toContain("OR");});++ describe("matching filters (contextual facet-value suggestions, LFE-10888)", () => {+ // Typing `mcp` must not ONLY offer full-text search: when a loaded facet+ // contains a matching value, the concrete `toolNames:mcp` filter is offered+ // alongside β drawn from LOADED columns only (never fanning out on-demand+ // option fetches).+ const observed: ObservedOptions = {+ ...OBSERVED,+ toolNames: [+ { value: "mcp", count: 42 },+ { value: "mcp-search", count: 7 },+ ],+ calledToolNames: [{ value: "web-mcp" }],+ };++ it("suggests column:value matches for a bare term, exact > prefix > substring", () => {+ const p = plan("mcp", 3, { observed });+ const sec = p?.sections.find((s) => s.title === SECTION_MATCHING_FILTERS);+ expect(sec?.options.map((o) => o.label)).toEqual([+ "toolNames:mcp", // exact value match+ "toolNames:mcp-search", // prefix+ "calledToolNames:web-mcp", // substring+ ]);+ expect(sec?.options[0]).toMatchObject({+ kind: "pattern",+ insert: "toolNames:mcp",+ detail: "Available tool names",+ replaceSpan: { from: 0, to: 3 },+ });+ // Free-text stays the primary path: Enter is unarmed (commits the text)+ // and the default-scope anchor is still offered.+ expect(p?.autoHighlight ?? false).toBe(false);+ expect(flattenOptions(p).map((o) => o.id)).toContain("scope:default");+ // Loaded columns only β no on-demand option fetch is triggered by typing.+ expect(p?.requestColumns).toBeUndefined();+ });++ it("prefers higher observed counts within the same match tier", () => {+ // `er` prefixes both level:ERROR (count 12) and a name value (count 3);+ // the count breaks the tie even though `name` precedes `level` in the+ // registry.+ const p = plan("er", 2, {+ observed: { ...OBSERVED, name: [{ value: "error-handler", count: 3 }] },+ });+ const sec = p?.sections.find((s) => s.title === SECTION_MATCHING_FILTERS);+ expect(sec?.options.map((o) => o.label)).toEqual([+ "level:ERROR",+ "name:error-handler",+ ]);+ });++ it("caps the section at three matches", () => {+ const p = plan("mcp", 3, {+ observed: {+ ...observed,+ name: [{ value: "mcp-router" }, { value: "run-mcp" }],+ },+ });+ const sec = p?.sections.find((s) => s.title === SECTION_MATCHING_FILTERS);+ expect(sec?.options).toHaveLength(3);+ });++ it("matches the whole coalesced run and quotes spaced values", () => {+ // Caret inside a two-word run: the match target is the logical phrase,+ // and the suggestion rewrites the WHOLE run β like the scope switches β+ // serializing the spaced value back to one quoted token.+ const p = plan("codex tu", 4, {+ observed: { ...OBSERVED, traceName: [{ value: "Codex Turn" }] },+ });+ const sec = p?.sections.find((s) => s.title === SECTION_MATCHING_FILTERS);+ expect(sec?.options[0]).toMatchObject({+ insert: 'traceName:"Codex Turn"',+ replaceSpan: { from: 0, to: 8 },+ });+ });++ it("scopes the rewrite to the free-text run, leaving existing filters alone", () => {+ const q = "level:ERROR mcp";+ const p = plan(q, q.length, { observed });+ const sec = p?.sections.find((s) => s.title === SECTION_MATCHING_FILTERS);+ expect(sec?.options[0]).toMatchObject({+ insert: "toolNames:mcp",+ replaceSpan: { from: 12, to: 15 },+ });+ });++ it("offers no matches for 1-char terms, negated terms, or unloaded/absent values", () => {+ // A 1-char term matches half the dataset β stay quiet.+ const short = plan("m", 1, { observed });+ expect(short?.sections.map((s) => s.title) ?? []).not.toContain(+ SECTION_MATCHING_FILTERS,+ );+ // A negated term is not a free-text run (and a positive rewrite would+ // invert the user's intent).+ const negated = plan("-mcp", 4, { observed });+ expect(negated?.sections.map((s) => s.title) ?? []).not.toContain(+ SECTION_MATCHING_FILTERS,+ );+ // toolNames not loaded (lazy column absent) β nothing to match.+ const unloaded = plan("mcp", 3);+ expect(unloaded?.sections.map((s) => s.title) ?? []).not.toContain(+ SECTION_MATCHING_FILTERS,+ );+ // Observed map still on its initial bulk load β no matches, no crash.+ const initial = plan("mcp", 3, { observed: undefined });+ expect(initial?.sections.map((s) => s.title) ?? []).not.toContain(+ SECTION_MATCHING_FILTERS,+ );+ });++ it("stays out of the value stage and of key positions inside existing filters", () => {+ // Caret in a value (`level:ER`) plans the value stage β no run, no section.+ const value = plan("level:ER", 8, { observed });+ expect(value?.stage).toBe("value");+ expect(value?.sections.map((s) => s.title)).not.toContain(+ SECTION_MATCHING_FILTERS,+ );+ // Caret in the key of an existing filter β a switcher, not a run.+ const key = plan("level:ERROR", 3, { observed });+ expect(key?.sections.map((s) => s.title)).not.toContain(+ SECTION_MATCHING_FILTERS,+ );+ });++ it("applyPick replaces the run and completes the filter at the end", () => {+ const p = plan("mcp", 3, { observed });+ const opt = flattenOptions(p).find((o) => o.id === "match:toolNames:mcp");+ expect(opt).toBeDefined();+ const r = applyPick(+ opt as Exclude<CompletionOption, { kind: "recent" }>,+ "mcp",+ p!,+ );+ expect(r.next).toBe("toolNames:mcp ");+ expect(r.caret).toBe("toolNames:mcp ".length);+ expect(r.keepOpen).toBe(true);+ });+ });});describe("applyPick", () => {diff --git a/web/src/features/search-bar/lib/completions.ts b/web/src/features/search-bar/lib/completions.tsindex 6daf87e1d1..35e5a9dbaa 100644--- a/web/src/features/search-bar/lib/completions.ts+++ b/web/src/features/search-bar/lib/completions.ts@@ -103,6 +103,7 @@ export type CompletionPlan = {export const SECTION_SUGGESTIONS = "Suggestions";export const SECTION_FIELDS = "Fields";+export const SECTION_MATCHING_FILTERS = "Matching filters";export const SECTION_VALUES = "Observed values";export const SECTION_OPERATORS = "Operators";export const SECTION_PATTERNS = "Patterns";@@ -234,6 +235,32 @@ function fieldOptions(includeVirtual = true): CompletionOption[] {return opts;}+/**+ * Move the option for `fieldId` to the front of `options`. When it is absent+ * (rank-filtering dropped it) and `pool` is given, prepend it from the pool+ * instead β used to guarantee an exactly-named field is always offered.+ */+function hoistFieldOption(+ options: CompletionOption[],+ fieldId: string,+ pool?: CompletionOption[],+): CompletionOption[] {+ const index = options.findIndex(+ (o) => o.kind === "field" && o.fieldId === fieldId,+ );+ if (index !== -1) {+ return [+ options[index]!,+ ...options.slice(0, index),+ ...options.slice(index + 1),+ ];+ }+ const fromPool = pool?.find(+ (o) => o.kind === "field" && o.fieldId === fieldId,+ );+ return fromPool ? [fromPool, ...options] : options;+}+// Ready-to-run query suggestions for the empty state: the top observed value// of a few showcase fields, inserted as complete filters.const SUGGESTION_FIELDS = ["level", "type", "environment", "name"];@@ -258,6 +285,78 @@ function querySuggestionOptions(return out;}+// ---- contextual facet-value matches for a bare typed term ----+//+// Typing `mcp` should not ONLY offer full-text search: when an already-loaded+// facet contains a matching value (say toolNames has `mcp`), the concrete+// `toolNames:mcp` filter is almost always what the user is reaching for. This+// scans the observed map β LOADED columns only, by design: suggestions mirror+// what the facet sidebar can currently show, and typing must never fan out+// on-demand option fetches (the lazy-column mechanism exists to avoid exactly+// that) β and surfaces the best few as ready-to-run rewrites of the free-text+// run, exactly parallel to the input:/output: scope switches.++/** Fields whose observed values are meaningful bare-term match targets: the+ * option-backed columns plus textSearch fields that keep a value picker+ * (id/name). Booleans/numbers/datetimes never match here β their observed+ * lists are empty or non-enumerated. */+const VALUE_MATCH_FIELDS: FieldDef[] = FIELDS.filter(+ (f) =>+ f.syncMode === "exactOption" ||+ f.syncMode === "arrayOption" ||+ f.suggestObservedValues === true,+);++/** A 1-char term matches half the dataset; require a real prefix. */+const MIN_VALUE_MATCH_LENGTH = 2;+/** Popover budget: the section competes with fields + full-text, keep it tight. */+const MAX_VALUE_MATCHES = 3;++/**+ * Ready-to-run `field:value` rewrites of the free-text run, drawn from loaded+ * observed values. Exact value matches rank above prefix matches above+ * substring matches; ties prefer the higher observed count, then registry+ * order (sort is stable). Replaces the WHOLE run via replaceSpan, like the+ * scope switches β the suggestion converts the visual free-text block the user+ * sees, not one word of it.+ */+function matchingFilterOptions(+ typed: string,+ observed: ObservedOptions | undefined,+ span: { from: number; to: number },+): CompletionOption[] {+ if (observed === undefined || typed.length < MIN_VALUE_MATCH_LENGTH)+ return [];+ const q = typed.toLowerCase();+ const ranked: Array<{+ rank: number;+ count: number;+ option: CompletionOption;+ }> = [];+ for (const f of VALUE_MATCH_FIELDS) {+ for (const o of observedValues(observed, f.id)) {+ const v = o.value.toLowerCase();+ const rank = v === q ? 0 : v.startsWith(q) ? 1 : v.includes(q) ? 2 : null;+ if (rank === null) continue;+ const insert = `${f.id}:${serializeValue(o.value)}`;+ ranked.push({+ rank,+ count: o.count ?? 0,+ option: {+ id: `match:${insert}`,+ kind: "pattern",+ label: insert,+ detail: f.description,+ insert,+ replaceSpan: span,+ },+ });+ }+ }+ ranked.sort((a, b) => a.rank - b.rank || b.count - a.count);+ return ranked.slice(0, MAX_VALUE_MATCHES).map((m) => m.option);+}+/*** Value-stage option list. An empty or exactly-matching typed value means the* caret sits on a COMPLETE value (click-to-edit): offer the full list with@@ -1100,25 +1199,32 @@ export function planInputCompletions(const resolvedKey = colon === -1 ? null : resolveField(keyPart);// The COMPLETE key of an existing filter is a switcher (like a complete// value): offer every field, current one first, and leave Enter unarmed.- // A partial key prefix-filters and arms Enter-to-complete.+ // A partial key prefix-filters and arms Enter-to-complete β and a bare word+ // that EXACTLY names a field (id or alias) always surfaces that field+ // first: an alias need not be a substring of its field id (`ttft` β+ // timeToFirstToken, `model` β providedModelName), so label ranking alone+ // can bury or drop the very field the user named while the exact match+ // arms Enter β which must pick IT, not whatever happened to rank first.const allFields = fieldOptions();const fields =resolvedKey !== null- ? (() => {- const currentId =- resolvedKey.type === "field" ? resolvedKey.field.id : keyPart;- const index = allFields.findIndex(- (o) => o.kind === "field" && o.fieldId === currentId,- );- return index === -1- ? allFields- : [- allFields[index]!,- ...allFields.slice(0, index),- ...allFields.slice(index + 1),- ];- })()- : rankFilter(allFields, keyPart);+ ? hoistFieldOption(+ allFields,+ resolvedKey.type === "field" ? resolvedKey.field.id : keyPart,+ )+ : (() => {+ const ranked = rankFilter(allFields, keyPart);+ const exact = resolveField(keyPart);+ const exactId =+ exact?.type === "field"+ ? exact.field.id+ : exact?.type === "pseudo"+ ? exact.id+ : null;+ return exactId === null+ ? ranked+ : hoistFieldOption(ranked, exactId, allFields);+ })();const operators =colon === -1 ? rankFilter(OPERATOR_OPTIONS, tokenBody) : [];const patterns =@@ -1152,10 +1258,21 @@ export function planInputCompletions({ keepCurrentFirst: true },): [];+ // Contextual facet matches share the run gate (and its span) with the scope+ // switches: both rewrite the whole free-text block the user sees, and the+ // gate already excludes negated terms and existing `key:` tokens.+ const matchingFilters: CompletionOption[] =+ run !== null+ ? matchingFilterOptions(run.text, ctx.observed, {+ from: run.from,+ to: run.to,+ })+ : [];if (fields.length +operators.length +patterns.length ++ matchingFilters.length +searchScopes.length ===0)@@ -1177,7 +1294,12 @@ export function planInputCompletions(? resolveField(keyPart) !== null: resolvedKey === null && fields.length > 0,sections: [+ // Fields stay first: options[0] must remain the field so the+ // exact-alias autoHighlight (Enter β `level:`) keeps picking it.+ // Concrete facet matches beat the generic operator/pattern syntax help+ // and the full-text fallback....section(SECTION_FIELDS, fields),+ ...section(SECTION_MATCHING_FILTERS, matchingFilters),...section(SECTION_OPERATORS, operators),...section(SECTION_PATTERNS, patterns),...section(SECTION_SEARCH_IN, searchScopes),