Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

paletteSearch.ts

1,260 lines49.1 KB

1/**
2 * Word-aware fuzzy ranking for the command palettes (web, desktop, mobile) and
3 * the MCP thread search, so every surface puts the same thread first.
4 *
5 * A match scores by quality: a whole word beats a word prefix, which beats
6 * words typed together, a one-typo prefix, and then a mid-word substring.
7 * Word starts include camelCase, kebab, path, and letter/digit boundaries.
8 * Thread scores then multiply quality by how recently and often the thread
9 * was used, within limits.
10 */
11​
12import type { OrchestrationV2ThreadOpens } from "@t3tools/contracts";
13​
14import { WORKTREE_BRANCH_PREFIX } from "./git.ts";
15​
16const ALPHANUMERIC = /[\p{L}\p{N}]/u;
17const LOWERCASE = /\p{Ll}/u;
18const UPPERCASE = /\p{Lu}/u;
19const DIGIT = /\p{N}/u;
20const LETTER = /\p{L}/u;
21const COMBINING_MARKS = /\p{M}/gu;
22// Emoji and other symbols can be searched for, so they start words too.
23const SYMBOL = /\p{So}/u;
24const APOSTROPHE = /['’]/;
25const CURLY_APOSTROPHES = /[\u2018\u2019]/g;
26​
27interface SearchField {
28 /** Case- and accent-folded text, one UTF-16 unit per source unit. */
29 readonly text: string;
30 /** 1 where a word starts in `text`. */
31 readonly wordStarts: Uint8Array;
33​
34export interface SearchRange {
35 readonly start: number;
36 readonly end: number;
38​
39// Thread titles, branches, and project names repeat across keystrokes; folding
40// them once keeps a keystroke to plain string scans. Each keystroke reads every
41// field, so the limit must hold all of them or the cache clears every time; a
42// field is a few bytes per character.
43const fieldCache = new Map<string, SearchField>();
44const FIELD_CACHE_LIMIT = 100_000;
45​
46function foldCharacter(character: string): string {
47 // A typed straight apostrophe finds a curly one: iOS keyboards type "’".
48 return character
49 .normalize("NFKD")
50 .replace(COMBINING_MARKS, "")
51 .toLowerCase()
52 .replace("ς", "σ")
53 .replace(/[‘’]/, "'");
55​
56/**
57 * `text` with case and accents folded one UTF-16 unit at a time, so offsets
58 * and word starts still read from `text` and highlights need no mapping. A
59 * letter that folds to more or less than one unit ("ß", "fi") stays as it is.
60 */
61function foldInPlace(text: string): string {
62 return text
63 .replace(/[\u0080-\uffff]/g, (character) => {
64 const folded = foldCharacter(character);
65 return folded.length === 1 ? folded : character;
66 })
67 .toLowerCase();
69​
70// Chinese and Japanese text has no spaces, so each ideograph or kana starts a word.
71function isCjk(character: string): boolean {
72 const code = character.codePointAt(0)!;
73 return (
74 (code >= 0x3040 && code <= 0x30ff) ||
75 (code >= 0x3400 && code <= 0x4dbf) ||
76 (code >= 0x4e00 && code <= 0x9fff) ||
77 (code >= 0xf900 && code <= 0xfaff)
78 );
80​
81// Two Chinese, Japanese, or Korean characters already make a common word.
82function hasCjkWord(token: string): boolean {
83 return Array.from(token).some((character) => {
84 const code = character.codePointAt(0)!;
85 return isCjk(character) || (code >= 0xac00 && code <= 0xd7af);
86 });
88​
89/**
90 * Whether `character` starts a word after `previous` and `beforePrevious`
91 * ("" at the start): after a non-letter, at a camelCase or digit boundary, or
92 * at any Chinese or Japanese character. The one rule for titles and messages.
93 */
94function isWordStart(
95 beforePrevious: string,
96 previous: string,
97 character: string,
98 next: string,
99): boolean {
100 // "Julius’s": a possessive or contraction does not start a word.
101 const afterApostrophe = APOSTROPHE.test(previous) && ALPHANUMERIC.test(beforePrevious);
102 return (
103 (ALPHANUMERIC.test(character) || SYMBOL.test(character)) &&
104 !afterApostrophe &&
105 (previous === "" ||
106 !ALPHANUMERIC.test(previous) ||
107 (LOWERCASE.test(previous) && UPPERCASE.test(character)) ||
108 // The last capital of an acronym starts the next word: "JSONSchema".
109 (UPPERCASE.test(previous) && UPPERCASE.test(character) && LOWERCASE.test(next)) ||
110 DIGIT.test(previous) !== DIGIT.test(character) ||
111 isCjk(character))
112 );
114​
115function foldSearchField(source: string): SearchField {
116 const wordStarts = new Uint8Array(source.length);
117 const characters = Array.from(source);
118 let index = 0;
119 for (const [position, character] of characters.entries()) {
120 const previous = characters[position - 1] ?? "";
121 const next = characters[position + 1] ?? "";
122 if (isWordStart(characters[position - 2] ?? "", previous, character, next)) {
123 wordStarts[index] = 1;
124 }
125 index += character.length;
126 }
127 return { text: foldInPlace(source), wordStarts };
129​
130function prepareSearchField(source: string): SearchField {
131 const cached = fieldCache.get(source);
132 if (cached) return cached;
133 // Oldest first out. A read does not re-insert: that would cost more than the
134 // fold it saves, and the limit holds far more fields than a keystroke reads.
135 if (fieldCache.size >= FIELD_CACHE_LIMIT) {
136 fieldCache.delete(fieldCache.keys().next().value!);
137 }
138 const field = foldSearchField(source);
139 fieldCache.set(source, field);
140 return field;
142​
143// Quotes around a pasted query: "fix sidebar".
144const WRAPPING_QUOTES = /^\s*["'`“”‘’]+|["'`“”‘’]+\s*$/g;
145​
146/** Folded, whitespace-collapsed query; empty when there is nothing to match. */
147export function foldSearchQuery(query: string): string {
148 return foldInPlace(query.replace(WRAPPING_QUOTES, "").normalize("NFC"))
149 .split(/\s+/)
150 .filter((token) => token.length > 0)
151 .join(" ");
153​
154function wordEnd(field: SearchField, index: number): number {
155 let end = index + 1;
156 while (end < field.text.length && !field.wordStarts[end] && ALPHANUMERIC.test(field.text[end]!)) {
157 end++;
158 }
159 return end;
161​
162// One substitution, insertion, deletion, or swap of neighbours; with
163// `swapOnly`, only a swap.
164function withinOneEdit(left: string, right: string, swapOnly: boolean): boolean {
165 if (Math.abs(left.length - right.length) > (swapOnly ? 0 : 1)) return false;
166 let index = 0;
167 while (index < left.length && index < right.length && left[index] === right[index]) index++;
168 const restLeft = left.slice(index);
169 const restRight = right.slice(index);
170 const swapped =
171 restLeft.length > 1 &&
172 restLeft[0] === restRight[1] &&
173 restLeft[1] === restRight[0] &&
174 restLeft.slice(2) === restRight.slice(2);
175 if (swapOnly) return swapped;
176 return (
177 swapped ||
178 restLeft === restRight ||
179 restLeft.slice(1) === restRight.slice(1) ||
180 restLeft.slice(1) === restRight ||
181 restLeft === restRight.slice(1)
182 );
184​
185const WHOLE_WORD = 1;
186// The bonus for a field equal to the whole query lifts a whole word to this.
187const WHOLE_NAME = 1.5;
188const MID_WORD = 0.3;
189const TYPO = 0.45;
190// Whole words typed together are exact, so they rank with typos and above
191// mid-word hits, though below a match at a word start.
192const JOINED_WORDS = 0.6;
193​
194interface TokenMatch extends SearchRange {
195 readonly score: number;
196 /** Separate ranges, for words typed together. */
197 readonly letters?: ReadonlyArray<SearchRange>;
199​
200/**
201 * Best match of one folded query token in a field. Tokens shorter than four
202 * characters only match at a word start ("del" should not find "model"), and
203 * longer ones only inside a word where `midWord` allows it. With
204 * `typos`, a three-character token may swap a pair and a longer one may carry
205 * one typo in a word prefix that keeps its first letter. Numbers never match
206 * with a typo: 22889 is not pull request 22189. In the primary field (the
207 * name), the token may also be whole words typed together (see
208 * `matchJoinedWords`).
209 */
210function matchToken(
211 field: SearchField,
212 token: string,
213 typos: boolean,
214 isPrimary: boolean,
215 midWord: boolean,
216): TokenMatch | null {
217 if (token.length === 0) return null;
218 let best: TokenMatch | null = null;
219 const ownBoundary = !ALPHANUMERIC.test(token[0]!) && !SYMBOL.test(token[0]!);
220 for (
221 let index = field.text.indexOf(token);
222 index !== -1;
223 index = field.text.indexOf(token, index + 1)
224 ) {
225 // A token that opens with punctuation (".ts") brings its own boundary, as in messages.
226 if (field.wordStarts[index] || ownBoundary) {
227 // Whole when the match ends where a word ends: "t3c" is a prefix of
228 // "t3code", ".ts" whole in "index.ts" but a prefix in "parser.tsx".
229 const end = index + token.length;
230 const whole =
231 end >= field.text.length ||
232 field.wordStarts[end] === 1 ||
233 !ALPHANUMERIC.test(field.text[end]!);
234 let runEnd = end;
235 while (runEnd < field.text.length && ALPHANUMERIC.test(field.text[runEnd]!)) runEnd++;
236 const score = whole ? WHOLE_WORD : 0.7 + (0.2 * token.length) / (runEnd - index);
237 if (best === null || score > best.score) {
238 best = { score, start: index, end: index + token.length };
239 }
240 if (score === WHOLE_WORD) return best;
241 } else if (midWord && token.length >= 4 && best === null) {
242 best = { score: MID_WORD, start: index, end: index + token.length };
243 }
244 }
245 // Joined words are exact, so they count without the typo pass: a strong
246 // match elsewhere must not hide "VS Code" for "vscode".
247 if ((best === null || best.score <= MID_WORD) && isPrimary) {
248 const joined = matchJoinedWords(field, token);
249 if (joined) return joined;
250 }
251 if ((best !== null && best.score > MID_WORD) || !typos || token.length < 3) return best;
252 // Numbers skip typos: #22889 is not #22189. Words with digits ("t3code") do not.
253 if (LETTER.test(token)) {
254 for (let index = 0; index < field.text.length; index++) {
255 if (!field.wordStarts[index]) continue;
256 // People rarely mistype the first letter, so a typo keeps it, unless it
257 // swaps the first two of a longer word ("ing" is not "nig…").
258 const first = field.text[index];
259 const firstLetterKept =
260 first === token[0] ||
261 (token.length > 3 && first === token[1] && field.text[index + 1] === token[0]);
262 if (!firstLetterKept) continue;
263 // The whole run, across camelCase joins: "githbu" is "GitHub".
264 let runEnd = index + 1;
265 while (runEnd < field.text.length && ALPHANUMERIC.test(field.text[runEnd]!)) runEnd++;
266 const word = field.text.slice(index, runEnd);
267 // Short tokens forgive a swapped pair or one missing letter ("srv" for
268 // "serv…"); any other edit of a three- or four-letter word matches too
269 // much ("cron" would find every "con…").
270 const short = token.length <= 4;
271 // The same length first, so "githbu" highlights all of "GitHub".
272 const lengths = short
273 ? [token.length, token.length + 1]
274 : [token.length, token.length - 1, token.length + 1];
275 for (const length of lengths) {
276 if (length > word.length) continue;
277 const prefix = word.slice(0, length);
278 if (withinOneEdit(token, prefix, short && length === token.length)) {
279 return { score: TYPO, start: index, end: index + length };
280 }
281 }
282 }
283 }
284 return best;
286​
287/**
288 * Whole words typed together: "vscode" is "VS Code", "fixsid" is "Fix
289 * sid(ebar)". Every part is a whole word but the last. Short words before a
290 * short prefix are a coincidence inside a title ("inth" is not "in th(read)"),
291 * but not at its start ("t3co" is "T3 Co(de)"), before three letters
292 * ("gomod"), or a whole word ("vscode").
293 */
294function matchJoinedWords(field: SearchField, token: string): TokenMatch | null {
295 const firstWord = field.wordStarts.indexOf(1);
296 for (let start = 0; start < field.text.length; start++) {
297 if (!field.wordStarts[start] || field.text[start] !== token[0]) continue;
298 const runs: SearchRange[] = [];
299 let at = start;
300 let rest = token;
301 while (rest.length > 0 && at < field.text.length) {
302 const end = wordEnd(field, at);
303 if (rest.length <= end - at && field.text.startsWith(rest, at)) {
304 runs.push({ start: at, end: at + rest.length });
305 rest = "";
306 } else if (rest.startsWith(field.text.slice(at, end))) {
307 runs.push({ start: at, end });
308 rest = rest.slice(end - at);
309 at = end;
310 while (at < field.text.length && !field.wordStarts[at]) at++;
311 } else {
312 break;
313 }
314 }
315 const last = runs.at(-1);
316 if (rest.length > 0 || last === undefined || runs.length < 2) continue;
317 if (
318 last.end === wordEnd(field, last.start) ||
319 last.end - last.start >= 3 ||
320 start === firstWord ||
321 runs.slice(0, -1).every((run) => run.end - run.start >= 3)
322 ) {
323 return { score: JOINED_WORDS, start, end: last.end, letters: runs };
324 }
325 }
326 return null;
328​
329interface WeightedSearchField {
330 readonly value: string;
331 readonly weight: number;
332 /** Only a whole-word match counts, as for a short query against keywords. */
333 readonly wholeWords?: boolean;
334 /**
335 * Only a match at a word start counts, without typos: hidden keywords that
336 * matched loosely would list results the user cannot see why for.
337 */
338 readonly keyword?: boolean;
339 /**
340 * Where the thread lives (project, environment): it helps a match, but a
341 * word start there does not make the match strong, so it never turns off
342 * joined words or typos for the titles.
343 */
344 readonly context?: boolean;
345 /**
346 * A token of four or more letters may match inside a word here. Only thread
347 * titles allow it: inside a command name or a branch it reads as junk
348 * ("arch" in "Search").
349 */
350 readonly midWord?: boolean;
352​
353interface SearchFieldsMatch {
354 /** Roughly 0.3 (inside a word) to 1.5 (exact title). */
355 readonly quality: number;
356 /** Every token matched at a word start, without a typo. */
357 readonly strong: boolean;
358 /** Source ranges matched in the first field, for highlighting. */
359 readonly primaryRanges: ReadonlyArray<SearchRange>;
361​
362const FILLER_WORDS = new Set(["a", "an", "and", "for", "in", "of", "on", "the", "to", "with"]);
363​
364// Sorted, with overlapping ranges joined.
365function mergeRanges(ranges: ReadonlyArray<SearchRange>): SearchRange[] {
366 const merged: SearchRange[] = [];
367 for (const range of [...ranges].sort((left, right) => left.start - right.start)) {
368 const last = merged.at(-1);
369 if (last && range.start <= last.end) {
370 merged[merged.length - 1] = { start: last.start, end: Math.max(last.end, range.end) };
371 } else {
372 merged.push({ start: range.start, end: range.end });
373 }
374 }
375 return merged;
377​
378/**
379 * Every query token must match some field. Quality is the mean of each token's
380 * best weighted match, plus a bonus when the first field holds the whole query
381 * as a phrase or equals it.
382 */
383function matchSearchFields(
384 normalizedQuery: string,
385 fields: ReadonlyArray<WeightedSearchField>,
386 options?: { readonly typos?: boolean },
387): SearchFieldsMatch | null {
388 if (normalizedQuery.length === 0) return null;
389 const prepared = fields
390 .filter((field) => field.value.length > 0)
391 .map((field) => ({
392 field: prepareSearchField(field.value),
393 weight: field.weight,
394 wholeWords: field.wholeWords ?? false,
395 keyword: field.keyword ?? false,
396 context: field.context ?? false,
397 allowMidWord: field.midWord ?? false,
398 }));
399 const primary = fields[0]?.value ? prepared[0]?.field : undefined;
400 // An empty token would match everywhere, and loop forever in `matchToken`.
401 const tokens = normalizedQuery.split(" ").filter((token) => token.length > 0);
402 if (tokens.length === 0) return null;
403 // A phrase-style query ("fix the sidebar") carries filler words a name may
404 // leave out; they count where they match but are not required.
405 const fillerOptional = tokens.some((token) => !FILLER_WORDS.has(token));
406 const primaryRanges: SearchRange[] = [];
407 let total = 0;
408 let counted = 0;
409 let strong = true;
410 for (const token of tokens) {
411 let best = 0;
412 let bestPrimary: TokenMatch | null = null;
413 let atWordStart = false;
414 for (const { field, weight, wholeWords, keyword, context, allowMidWord } of prepared) {
415 if (best >= weight && field !== primary && atWordStart) continue;
416 const typos = (options?.typos ?? false) && !keyword;
417 // Joined words only count in the name.
418 const match = matchToken(field, token, typos, field === primary, allowMidWord);
419 if (match === null || match.score < (wholeWords ? WHOLE_WORD : keyword ? 0.7 : 0)) continue;
420 if (field === primary) bestPrimary = match;
421 if (match.score >= 0.7 && !context) atWordStart = true;
422 if (match.score * weight > best) best = match.score * weight;
423 }
424 if (best === 0) {
425 if (fillerOptional && FILLER_WORDS.has(token)) continue;
426 return null;
427 }
428 strong &&= atWordStart;
429 if (bestPrimary) primaryRanges.push(...(bestPrimary.letters ?? [bestPrimary]));
430 total += best;
431 counted += 1;
432 }
433 let quality = total / counted;
434 if (primary) {
435 if (primary.text === normalizedQuery) quality += WHOLE_NAME - WHOLE_WORD;
436 else if (tokens.length > 1 && primary.text.includes(normalizedQuery)) quality += 0.25;
437 }
438 return {
439 quality,
440 strong,
441 primaryRanges: mergeRanges(primaryRanges),
442 };
444​
445// A two-letter Latin substring of a message is noise rather than a match.
446const MESSAGE_TOKEN_MIN_LENGTH = 3;
447​
448/**
449 * Message search tokens, lowercased and NFC-composed but not stripped of
450 * accents: the server's index folds Latin accents itself, and stripping marks
451 * would break Korean and Japanese text. Every `long` token must appear in a
452 * message; `short` ones only narrow those hits ("pnpm 12"). A query with no
453 * long token searches no messages. Two CJK characters count as long.
454 */
455export function messageSearchTokens(query: string): {
456 readonly long: ReadonlyArray<string>;
457 readonly short: ReadonlyArray<string>;
458 /** Every token, in the order typed. */
459 readonly words: ReadonlyArray<string>;
460} {
461 const tokens = query
462 .replace(WRAPPING_QUOTES, "")
463 // The index stores apostrophes straight, as `indexedMessageText` writes them.
464 .replace(CURLY_APOSTROPHES, "'")
465 .normalize("NFC")
466 .toLowerCase()
467 .split(/\s+/)
468 .filter((token) => token.length > 0);
469 const searchable = (token: string) => {
470 const length = Array.from(token).length;
471 return length >= MESSAGE_TOKEN_MIN_LENGTH || (length === 2 && hasCjkWord(token));
472 };
473 return {
474 long: tokens.filter(searchable),
475 short: tokens.filter((token) => !searchable(token)),
476 words: tokens,
477 };
479​
480/**
481 * Matches the query's words side by side as whole words, as typed, whatever
482 * whitespace is between them and ignoring case; null for a single word.
483 */
484export function messagePhrase(query: string): RegExp | null {
485 const { words } = messageSearchTokens(query);
486 return words.length > 1
487 ? new RegExp(
488 `(?<![\\p{L}\\p{N}])${words
489 .map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
490 .join("\\s+")}(?![\\p{L}\\p{N}])`,
491 "iu",
492 )
493 : null;
495​
496// Words written together, as typed, rank above the same words apart, as in
497// titles; words near each other rank above words far apart.
498const MESSAGE_PHRASE_BONUS = 0.25;
499const MESSAGE_NEAR_BONUS = 0.1;
500// About what a result row shows.
501const MESSAGE_NEAR_SPAN = 60;
502​
503const NON_ASCII = /[\u0080-\uffff]/;
504// A message token shorter than this must start a word: "fts" is not in "drafts".
505const MESSAGE_WORD_START_LENGTH = 4;
506const MESSAGE_PREFIX = 0.8;
507​
508function startsWordAt(text: string, index: number): boolean {
509 const character = text[index]!;
510 // A token that opens with punctuation (".ts", "#22889") brings its own boundary.
511 if (!ALPHANUMERIC.test(character) && !SYMBOL.test(character)) return true;
512 return isWordStart(
513 text[index - 2] ?? "",
514 text[index - 1] ?? "",
515 character,
516 text[index + 1] ?? "",
517 );
519​
520// Whether a word ends right before `end` in `text`.
521function endsWordAt(text: string, end: number): boolean {
522 return end >= text.length || !ALPHANUMERIC.test(text[end]!) || startsWordAt(text, end);
524​
525// A commit SHA or UUID part: seven or more hex characters with a digit.
526const HEX_ID = /^(?=[a-f]*\d)[0-9a-f]{7,}$/i;
527​
528// Where `token` best sits in `folded`, a fold of `text`: every place it is a
529// whole word, else a word start, else inside a word. Hits past the start of a
530// hex ID do not count ("cafe" in "7cafe52bb8"), though a pasted SHA prefix
531// does.
532function findMessageToken(
533 text: string,
534 folded: string,
535 token: string,
536): { readonly at: ReadonlyArray<number>; readonly quality: number } | null {
537 let quality = 0;
538 let at: number[] = [];
539 // The letters-and-digits run around the hit, kept for later hits in the
540 // same run: rescanning it per hit is quadratic in a long run ("0000" in a
541 // hex dump).
542 let run = { start: 0, end: -1, hex: false };
543 for (let index = folded.indexOf(token); index !== -1; index = folded.indexOf(token, index + 1)) {
544 if (index + token.length > run.end) {
545 let start = index;
546 while (start > 0 && ALPHANUMERIC.test(text[start - 1]!)) start--;
547 let end = index + token.length;
548 while (end < text.length && ALPHANUMERIC.test(text[end]!)) end++;
549 run = { start, end, hex: HEX_ID.test(text.slice(start, end)) };
550 }
551 if (run.hex && run.start < index) continue;
552 const found = !startsWordAt(text, index)
553 ? MID_WORD
554 : endsWordAt(text, index + token.length)
555 ? 1
556 : MESSAGE_PREFIX;
557 if (found > quality) {
558 quality = found;
559 at = [index];
560 } else if (found === quality) {
561 at.push(index);
562 }
563 }
564 return at.length === 0 ? null : { at, quality };
566​
567export interface MessageMatch {
568 /**
569 * 1 when every searched word is a whole word, MESSAGE_PREFIX when one only
570 * starts a word ("mode" in "model"), MID_WORD when one only appears inside
571 * words, plus MESSAGE_PHRASE_BONUS when the words are written together as
572 * typed, else MESSAGE_NEAR_BONUS when they sit within a row's width.
573 */
574 readonly quality: number;
575 /** Where a snippet should start to show the match. */
576 readonly offset: number;
578​
579/**
580 * Grades messages against a query, so message hits rank like titles: null
581 * when a token is missing or a short one never starts a word ("fts" in
582 * "drafts"). Case and accents are ignored, as in the server's index. The
583 * query is prepared once, since the server grades thousands of hits for it.
584 */
585export function messageMatcher(query: string): (text: string) => MessageMatch | null {
586 const { long, short, words } = messageSearchTokens(query);
587 const tokens = [...long, ...short].map((token) => ({
588 token,
589 // Marks go from the folded token: lowercasing "İ" adds one.
590 folded: foldInPlace(token).replace(COMBINING_MARKS, ""),
591 nonAscii: NON_ASCII.test(token),
592 mustStartWord: Array.from(token).length < MESSAGE_WORD_START_LENGTH,
593 // Too short to search, so it only narrows: grading by it would reorder
594 // results on each keystroke while the next word is typed ("nvme s").
595 grades: long.includes(token),
596 }));
597 const phrase = messagePhrase(query);
598 // Accents typed or left out still read as written together: "cafe open"
599 // in "Café open".
600 const foldedPhrase = messagePhrase(
601 words.map((word) => foldInPlace(word).replace(COMBINING_MARKS, "")).join(" "),
602 );
603 const queryNonAscii = NON_ASCII.test(query);
604 return (text) => {
605 const lower = text.toLowerCase();
606 // "İ" lowercases to two units, which would shift every offset after it.
607 const plain = lower.length === text.length ? lower : foldInPlace(text);
608 let folded: string | null = null;
609 let quality = 1;
610 const positions: Array<ReadonlyArray<number>> = [];
611 for (const { token, folded: foldedToken, nonAscii, mustStartWord, grades } of tokens) {
612 let found = findMessageToken(text, plain, token);
613 // Accents typed or left out: "cafe" finds "Café", also after "cafeteria".
614 if (found?.quality !== 1 && foldedToken.length > 0 && (nonAscii || NON_ASCII.test(text))) {
615 found = findMessageToken(text, (folded ??= foldInPlace(text)), foldedToken);
616 }
617 if (found === null) return null;
618 if (found.quality === MID_WORD && mustStartWord) return null;
619 if (grades) quality = Math.min(quality, found.quality);
620 positions.push(found.at);
621 }
622 // Written together as typed: the snippet starts there. Apostrophes are
623 // straight in the query, and straightening keeps offsets.
624 const straight = (value: string) => value.replace(CURLY_APOSTROPHES, "'");
625 const together =
626 phrase?.exec(straight(plain)) ??
627 (queryNonAscii || NON_ASCII.test(text)
628 ? foldedPhrase?.exec(straight((folded ??= foldInPlace(text))))
629 : null);
630 if (together) return { quality: quality + MESSAGE_PHRASE_BONUS, offset: together.index };
631 // Else the shortest stretch that holds every word: the snippet starts
632 // there, so it shows them all, and words close together rank above words
633 // far apart ("lakebed perf").
634 const near = shortestSpan(positions);
635 return {
636 quality:
637 long.length > 1 && near.length <= MESSAGE_NEAR_SPAN
638 ? quality + MESSAGE_NEAR_BONUS
639 : quality,
640 offset: near.start,
641 };
642 };
644​
645// The shortest stretch of text holding one place of each word, from each
646// word's places in order.
647function shortestSpan(places: ReadonlyArray<ReadonlyArray<number>>): {
648 readonly start: number;
649 readonly length: number;
650} {
651 const hits = places
652 .flatMap((at, word) => at.map((index) => ({ index, word })))
653 .sort((left, right) => left.index - right.index);
654 const counts = places.map(() => 0);
655 let covered = 0;
656 let best = { start: hits[0]?.index ?? 0, length: Number.POSITIVE_INFINITY };
657 let left = 0;
658 for (const hit of hits) {
659 counts[hit.word] = (counts[hit.word] ?? 0) + 1;
660 if (counts[hit.word] === 1) covered++;
661 while (covered === places.length) {
662 const first = hits[left]!;
663 if (hit.index - first.index < best.length) {
664 best = { start: first.index, length: hit.index - first.index };
665 }
666 counts[first.word] = (counts[first.word] ?? 1) - 1;
667 if (counts[first.word] === 0) covered--;
668 left++;
669 }
670 }
671 return best;
673​
674/**
675 * Ranges of `text` that contain a long message search token, for message
676 * snippets, ignoring case and accents. Shorter tokens would light up half the
677 * snippet, and a short long token only counts where it starts a word.
678 * Snippets vary per query, so they skip the field cache.
679 */
680export function findSearchTokenRanges(text: string, query: string): SearchRange[] {
681 const tokens = new Map(
682 messageSearchTokens(query)
683 .long.map(
684 (token) =>
685 [foldSearchQuery(token), Array.from(token).length < MESSAGE_WORD_START_LENGTH] as const,
686 )
687 // Some tokens fold to nothing ("´´´"), which would match everywhere.
688 .filter(([token]) => token.length > 0),
689 );
690 if (tokens.size === 0) return [];
691 const field = foldSearchField(text);
692 const ranges: SearchRange[] = [];
693 for (const [token, needsWordStart] of tokens) {
694 // A token that opens with punctuation brings its own boundary, as in scoring.
695 const ownBoundary = !ALPHANUMERIC.test(token[0]!) && !SYMBOL.test(token[0]!);
696 for (let index = field.text.indexOf(token); index !== -1;) {
697 if (needsWordStart && !ownBoundary && !field.wordStarts[index]) {
698 index = field.text.indexOf(token, index + 1);
699 continue;
700 }
701 ranges.push({ start: index, end: index + token.length });
702 index = field.text.indexOf(token, index + token.length);
703 }
704 }
705 return mergeRanges(ranges);
707​
708export interface SearchTextPart {
709 readonly text: string;
710 readonly highlighted: boolean;
711 readonly start: number;
713​
714/** `text` cut into plain and highlighted parts at sorted, non-overlapping `ranges`. */
715export function splitSearchText(
716 text: string,
717 ranges: ReadonlyArray<SearchRange>,
718): SearchTextPart[] {
719 const parts: SearchTextPart[] = [];
720 let cursor = 0;
721 for (const range of ranges) {
722 if (range.start > cursor) {
723 parts.push({ text: text.slice(cursor, range.start), highlighted: false, start: cursor });
724 }
725 parts.push({ text: text.slice(range.start, range.end), highlighted: true, start: range.start });
726 cursor = range.end;
727 }
728 if (cursor < text.length || parts.length === 0) {
729 parts.push({ text: text.slice(cursor), highlighted: false, start: cursor });
730 }
731 return parts;
733​
734const DAY_MS = 24 * 60 * 60 * 1000;
735/** Both activity recency and open counts halve every two weeks. */
736export const SEARCH_RECENCY_HALF_LIFE_MS = 14 * DAY_MS;
737/**
738 * Opens closer together than this count once, so flipping between threads is
739 * not frequency. Clients skip sending them.
740 */
741export const THREAD_OPEN_DEDUPE_MS = 10 * 60 * 1000;
742const THREAD_SEARCH_PICK_LIMIT = 3;
743/** Picked queries are stored this long; clients send no more. */
744const THREAD_SEARCH_PICK_MAX_LENGTH = 32;
745​
746/**
747 * `query` as a pick is stored and compared: folded, then cut to the stored
748 * length without splitting an emoji in two. Clients and the server both use
749 * it, so a long pick matches its query again.
750 */
751export function pickedQuery(query: string): string {
752 const cut = foldSearchQuery(query).slice(0, THREAD_SEARCH_PICK_MAX_LENGTH);
753 return (/[\ud800-\udbff]$/.test(cut) ? cut.slice(0, -1) : cut).trim();
755​
756function decay(ageMs: number): number {
757 return 2 ** (-Math.max(0, ageMs) / SEARCH_RECENCY_HALF_LIFE_MS);
759​
760/** Server-stored open history; see `OrchestrationV2ThreadOpens`. */
761export type ThreadOpenStats = OrchestrationV2ThreadOpens;
762​
763/**
764 * Next open stats after an open at `at`. `query` is the palette query that
765 * picked the thread, when it was opened from search.
766 */
767export function recordThreadOpen(
768 previous: ThreadOpenStats | null,
769 at: number,
770 query: string | undefined,
771): ThreadOpenStats {
772 const pick = pickedQuery(query ?? "");
773 // Picks that no longer count are not kept or synced.
774 const earlier = (previous?.picks ?? []).filter((entry) => at - entry.at <= PICK_WINDOW_MS);
775 const picks = pick
776 ? [{ query: pick, at }, ...earlier.filter((entry) => entry.query !== pick)].slice(
777 0,
778 THREAD_SEARCH_PICK_LIMIT,
779 )
780 : earlier;
781 if (previous !== null && at - previous.openedAt < THREAD_OPEN_DEDUPE_MS) {
782 return { ...previous, picks };
783 }
784 const score = previous === null ? 1 : previous.score * decay(at - previous.openedAt) + 1;
785 return { openedAt: at, score, picks };
787​
788export interface ThreadSearchSubject {
789 /** Matched only by the whole query, like references. */
790 readonly id?: string;
791 readonly title: string;
792 readonly branch?: string | null;
793 readonly projectTitle?: string | null;
794 /** Only set with two or more environments; it tells same-named threads apart. */
795 readonly environmentLabel?: string | null;
796 readonly pullRequests?: ReadonlyArray<{
797 readonly number: number;
798 readonly title?: string | null;
799 /** Values such as URLs, matched only by the whole query. */
800 readonly references?: ReadonlyArray<string>;
801 }>;
802 /** Latest user activity, in epoch ms. */
803 readonly activityAt: number | null;
804 readonly opens?: ThreadOpenStats | null;
806​
807// Use reorders matches of about the same quality but never turns a mid-word
808// hit on a busy thread into a better result than a whole word on a quiet one.
809const USE_BOOST_LIMIT = 2.5;
810​
811/**
812 * How much use lifts a thread: 1 for a stale, never-opened thread, about 2 for
813 * one active today, and up to 2.5 for threads opened often.
814 */
815function threadUsageBoost(thread: ThreadSearchSubject, now: number): number {
816 const recency = thread.activityAt === null ? 0 : decay(now - thread.activityAt);
817 const opens = thread.opens ? thread.opens.score * decay(now - thread.opens.openedAt) : 0;
818 return Math.min(USE_BOOST_LIMIT, 1 + recency + 0.5 * Math.log2(1 + opens));
820​
821const REFERENCE_PREFIX_MIN = 8;
822​
823// IDs and URLs split into many word starts, so matching them as fields would
824// let a two-letter query hit every thread. Only a long piece of one matches: a
825// prefix, or, when it holds a digit like an ID or pull request number, any
826// part ("t3code#22889", a URL without its scheme). Both are ASCII, so
827// lowercasing is enough.
828function matchReference(
829 normalizedQuery: string,
830 thread: ThreadSearchSubject,
831): SearchFieldsMatch | null {
832 if (normalizedQuery.length < REFERENCE_PREFIX_MIN) return null;
833 const references = [
834 ...(thread.id ? [thread.id] : []),
835 ...(thread.pullRequests ?? []).flatMap((pullRequest) => pullRequest.references ?? []),
836 ];
837 const anywhere = DIGIT.test(normalizedQuery);
838 // A number is never cut short: ".../pull/2288" is not pull request 22889.
839 const notCut = (text: string, end: number) => !DIGIT.test(text[end] ?? "");
840 return references.some((reference) => {
841 const folded = reference.toLowerCase();
842 const at = folded.indexOf(normalizedQuery);
843 // A pasted link may go on past the reference: ".../pull/22889/files".
844 return anywhere
845 ? (at !== -1 && notCut(folded, at + normalizedQuery.length)) ||
846 (normalizedQuery.startsWith(folded) && notCut(normalizedQuery, folded.length))
847 : at === 0;
848 })
849 ? { quality: 0.6, strong: true, primaryRanges: [] }
850 : null;
852​
853// How long a pick lasts. While it does, typing the query again (or the start of
854// it) puts the thread first among its group's word matches, the exact query's
855// pick and then the latest first. A pick never moves the group itself, so a
856// thread picked once for "new" does not pass the command of that name. It runs
857// from the pick, so an old pick lets go even if the thread is opened in other
858// ways.
859const PICK_WINDOW_MS = 21 * DAY_MS;
860// The start of a picked query counts from three letters: "n" is too little to
861// go on.
862const PICK_PREFIX_MIN_LENGTH = 3;
863​
864/** The latest pick of the thread for this query, while it lasts. */
865function activePick(
866 thread: ThreadSearchSubject,
867 normalizedQuery: string,
868 now: number,
869): ThreadOpenStats["picks"][number] | undefined {
870 // Stored picks are cut to a length, so compare the query cut the same way.
871 const query = pickedQuery(normalizedQuery);
872 const prefix = query.length >= PICK_PREFIX_MIN_LENGTH;
873 // The latest exact pick, else the latest pick the query starts.
874 let exact: ThreadOpenStats["picks"][number] | undefined;
875 let latest: ThreadOpenStats["picks"][number] | undefined;
876 for (const pick of thread.opens?.picks ?? []) {
877 if (now - pick.at > PICK_WINDOW_MS) continue;
878 if (pick.query === query && (exact === undefined || pick.at > exact.at)) exact = pick;
879 const matches = pick.query === query || (prefix && pick.query.startsWith(query));
880 if (matches && (latest === undefined || pick.at > latest.at)) latest = pick;
881 }
882 return exact ?? latest;
884​
885export interface ThreadSearchMatch {
886 /** Match quality times use; what results sort by. */
887 readonly score: number;
888 /** Match quality alone; see `rankSearchGroups`. */
889 readonly quality: number;
890 /** Every token matched at a word start; see `rankSearchGroups`. */
891 readonly strong: boolean;
892 /** Matched ranges in the title. */
893 readonly ranges: ReadonlyArray<SearchRange>;
894 /**
895 * Why the thread matched when its title shows no match, for the result row.
896 * Built on demand, so only the rows shown pay for it.
897 */
898 readonly explain?: () => SearchMatchHint | undefined;
899 /** When the thread was picked for this query, while that pick lasts; see `rankSearchGroups`. */
900 readonly pickedAt?: number;
901 /** Picked for exactly this query, before newer picks for longer ones; see `rankSearchGroups`. */
902 readonly pickedExactly?: boolean;
903 /** Below the whole-name class; see `scoreThreadSearch`. */
904 readonly groupQuality: number;
906​
907export interface SearchMatchHint {
908 readonly label: string;
909 readonly text: string;
910 readonly ranges: ReadonlyArray<SearchRange>;
912​
913// Most threads' branches start with the app's own worktree prefix ("t3/", and
914// "t3code/" before it), so "t3 connect" would match nearly every thread.
915// Only before more text, so typing "t3/" does not empty the list for a keystroke.
916const WORKTREE_BRANCH_PREFIX_PATTERN = new RegExp(`^(?:${WORKTREE_BRANCH_PREFIX}|t3code)/(?=\\S)`);
917​
918function searchableBranch(branch: string | null | undefined): string | null {
919 return branch ? branch.replace(WORKTREE_BRANCH_PREFIX_PATTERN, "") : null;
921​
922/**
923 * The field that explains a match whose title shows none: the first that holds
924 * the whole query, else, past the words the project or environment holds, the
925 * first that holds the rest ("lakebed perf" in project "lakebed" with the PR
926 * title "perf: …").
927 */
928function matchHint(
929 normalizedQuery: string,
930 thread: ThreadSearchSubject,
931 typos: boolean,
932): SearchMatchHint | undefined {
933 const candidates: Array<{ readonly label: string; readonly text: string | null | undefined }> = [
934 ...(thread.pullRequests ?? []).map((pullRequest) => ({
935 label: "PR",
936 text: `#${pullRequest.number}${pullRequest.title ? ` ${pullRequest.title}` : ""}`,
937 })),
938 { label: "Branch", text: searchableBranch(thread.branch) },
939 { label: "Project", text: thread.projectTitle },
940 { label: "Environment", text: thread.environmentLabel },
941 ];
942 const holds = (text: string, query: string) =>
943 matchSearchFields(query, [{ value: text, weight: 1 }], { typos })?.primaryRanges;
944 const hintFor = (query: string) => {
945 for (const { label, text } of candidates) {
946 const ranges = text ? holds(text, query) : undefined;
947 if (text && ranges) return { label, text, ranges };
948 }
949 return undefined;
950 };
951 const whole = hintFor(normalizedQuery);
952 if (whole) return whole;
953 const contexts = [thread.projectTitle, thread.environmentLabel].filter(
954 (text): text is string => !!text,
955 );
956 const rest = normalizedQuery
957 .split(" ")
958 .filter((token) => !contexts.some((text) => holds(text, token)))
959 .join(" ");
960 return rest && rest !== normalizedQuery ? hintFor(rest) : undefined;
962​
963/**
964 * Scores a thread for a normalized query, or null when it does not match.
965 * Titles and pull request numbers count fully, pull request titles and
966 * branches less, project and environment names least.
967 */
968export function scoreThreadSearch(
969 normalizedQuery: string,
970 thread: ThreadSearchSubject,
971 now: number,
972 options?: {
973 readonly typos?: boolean;
974 /**
975 * Palette picks; off where a pick would show up unexplained, such as a
976 * sidebar filter or an agent's search.
977 */
978 readonly picks?: boolean;
979 },
980): ThreadSearchMatch | null {
981 const fields: WeightedSearchField[] = [{ value: thread.title, weight: 1, midWord: true }];
982 for (const pullRequest of thread.pullRequests ?? []) {
983 fields.push({ value: `#${pullRequest.number}`, weight: 1 });
984 if (pullRequest.title) fields.push({ value: pullRequest.title, weight: 0.5 });
985 }
986 const branch = searchableBranch(thread.branch);
987 if (branch) fields.push({ value: branch, weight: 0.6 });
988 if (thread.projectTitle) {
989 fields.push({ value: thread.projectTitle, weight: 0.25, context: true });
990 }
991 if (thread.environmentLabel) {
992 fields.push({ value: thread.environmentLabel, weight: 0.25, context: true });
993 }
994 // "#22889", "pr 22889", and a pasted "t3/branch" search without their
995 // prefixes, as the branch field is stored without the app's worktree prefix.
996 const fieldQuery = normalizedQuery
997 .replace(/^(?:pr|pull request|pull)\s*(?=#?\d)/, "")
998 .replace(/^#\s*/, "")
999 .replace(WORKTREE_BRANCH_PREFIX_PATTERN, "");
1000 const fieldMatch = matchSearchFields(fieldQuery, fields, options);
1001 const referenceMatch = fieldMatch ? null : matchReference(normalizedQuery, thread);
1002 const match = fieldMatch ?? referenceMatch;
1003 if (match === null) return null;
1004 // A row whose title shows no match must say why. With several words, one
1005 // that cannot (its words spread over unrelated fields) is a coincidence and
1006 // is left out; a single word always sits in the field that matched it, so
1007 // its hint waits until the row is shown.
1008 const typos = options?.typos ?? false;
1009 const titleShowsMatch = match.primaryRanges.length > 0;
1010 const checkHint = !titleShowsMatch && referenceMatch === null && fieldQuery.includes(" ");
1011 const checkedHint = checkHint ? matchHint(fieldQuery, thread, typos) : undefined;
1012 if (checkHint && checkedHint === undefined) return null;
1013 const explain = titleShowsMatch
1014 ? undefined
1015 : (): SearchMatchHint | undefined =>
1016 referenceMatch
1017 ? { label: "ID or link", text: normalizedQuery, ranges: [] }
1018 : (checkedHint ?? matchHint(fieldQuery, thread, typos));
1019 const pick = options?.picks === false ? undefined : activePick(thread, normalizedQuery, now);
1020 return {
1021 score: match.quality * threadUsageBoost(thread, now),
1022 quality: match.quality,
1023 // A thread's whole title never lifts its group over a command or project
1024 // of that name: every new thread is titled "New thread" for a while.
1025 groupQuality: Math.min(match.quality, WHOLE_NAME - 0.01),
1026 strong: match.strong,
1027 ranges: match.primaryRanges,
1028 ...(explain ? { explain } : {}),
1029 ...(pick ? { pickedAt: pick.at } : {}),
1030 ...(pick?.query === pickedQuery(normalizedQuery) ? { pickedExactly: true } : {}),
1031 };
1033​
1034/** When the user last used a thread: their last message or their last open. */
1035export function threadRecentUse(thread: ThreadSearchSubject): number {
1036 return Math.max(thread.activityAt ?? 0, thread.opens?.openedAt ?? 0);
1038​
1039/**
1040 * How strongly a thread's messages match among matches of one quality: a
1041 * thread that keeps using the word outweighs a recent passing mention, as
1042 * hits count for more than recency or use (21 hits about 5.5, one hit 2).
1043 */
1044function messageMatchWeight(hits: number): number {
1045 return 1 + Math.log2(1 + hits);
1047​
1048/**
1049 * Orders message matches from the server, from any number of environments:
1050 * word matches before matches inside words, then threads picked for the
1051 * query, then match quality, then hit count times use, then the newest
1052 * message. With `withoutTitleMatches`, threads that match by title are left
1053 * out: a palette lists them above, so they must not use up message rows.
1054 */
1055export function rankMessageMatches<
1056 T extends {
1057 readonly quality?: number;
1058 readonly hits?: number;
1059 readonly messageCreatedAt?: string | null;
1060 },
1062 matches: ReadonlyArray<T>,
1063 subjectOf: (match: T) => ThreadSearchSubject | undefined,
1064 normalizedQuery: string,
1065 now: number,
1066 options?: { readonly picks?: boolean; readonly withoutTitleMatches?: boolean },
1067): T[] {
1068 return matches
1069 .flatMap((match) => {
1070 const subject = subjectOf(match);
1071 if (!subject) return [];
1072 if (
1073 options?.withoutTitleMatches &&
1074 scoreThreadSearch(normalizedQuery, subject, now, { picks: false }) !== null
1075 ) {
1076 return [];
1078 // Older servers send no quality; their matches count as words.
1079 const quality = match.quality ?? 1;
1080 return [
1082 match,
1083 quality,
1084 pickedAt:
1085 options?.picks === false ? 0 : (activePick(subject, normalizedQuery, now)?.at ?? 0),
1086 score: messageMatchWeight(match.hits ?? 1) * threadUsageBoost(subject, now),
1087 },
1088 ];
1089 })
1090 .sort(
1091 (left, right) =>
1092 // Word matches first; among them a pick, then the closer match.
1093 Number(right.quality >= MESSAGE_PREFIX) - Number(left.quality >= MESSAGE_PREFIX) ||
1094 right.pickedAt - left.pickedAt ||
1095 right.quality - left.quality ||
1096 right.score - left.score ||
1097 (right.match.messageCreatedAt ?? "").localeCompare(left.match.messageCreatedAt ?? ""),
1099 .map(({ match }) => match);
1101​
1102/** Palette limits shared by web and mobile. */
1103export const PALETTE_THREAD_LIMIT = 20;
1104export const PALETTE_MESSAGE_LIMIT = 10;
1105/** Next to matching threads, other groups show only their best few rows. */
1106export const PALETTE_SECONDARY_LIMIT = 3;
1107​
1108// The whole name typed (1.5 and up), every token at a word start of a main
1109// field (0.7 and up), a typo in a main field (0.4 and up), or weaker. Whole
1110// word against prefix is too fine a line for group order: "compact" must not
1111// lift a setting named "Compact…" over the thread "Compaction…". But the
1112// project named "lakebed" leads for "lakebed", and "keybindngs" is the setting
1113// of that name, not a command that lists it as a keyword.
1114function matchClass(quality: number): number {
1115 return quality >= WHOLE_NAME ? 3 : quality >= 0.7 ? 2 : quality >= 0.4 ? 1 : 0;
1117​
1118export interface RankedSearchItem<T, M> {
1119 readonly item: T;
1120 readonly match: M;
1122​
1123/**
1124 * Ranks grouped items: within a group, word matches before weaker ones,
1125 * results picked for exactly the query first among them (the latest pick
1126 * first), then by match class, then results picked for a query that starts
1127 * with this one, then best score. Groups with no match are dropped. The rest order by the class of
1128 * their best match (the whole name, word starts in a name, typos in a name or
1129 * keyword matches, or weaker), and ties keep the given order. Classes
1130 * rather than scores keep the group order steady while a word is typed, and
1131 * keep use, which only counts for threads, from outweighing a command that
1132 * matches as well.
1134 * Typos are only tried when no result matches every token at a word start:
1135 * next to a real match, typo matches are noise ("enter" finding "external"),
1136 * but they should beat a mid-word accident ("ilde" in "Builder" for "idle").
1137 * Skipping them also keeps a keystroke cheap.
1138 */
1139export function rankSearchGroups<
1140 G,
1141 T,
1142 M extends {
1143 readonly score: number;
1144 readonly quality: number;
1145 readonly strong: boolean;
1146 readonly pickedAt?: number;
1147 readonly pickedExactly?: boolean;
1148 readonly groupQuality?: number;
1149 },
1151 groups: ReadonlyArray<{ readonly group: G; readonly items: ReadonlyArray<T> }>,
1152 score: (item: T, options: { readonly typos: boolean }, group: G) => M | null,
1153): Array<{ readonly group: G; readonly ranked: ReadonlyArray<RankedSearchItem<T, M>> }> {
1154 const rank = (typos: boolean) =>
1155 groups.map(({ group, items }) => ({
1156 group,
1157 ranked: items.flatMap((item) => {
1158 const match = score(item, { typos }, group);
1159 return match === null ? [] : [{ item, match }];
1160 }),
1161 }));
1162 let ranked = rank(false);
1163 if (!ranked.some((entry) => entry.ranked.some(({ match }) => match.strong))) {
1164 ranked = rank(true);
1166 return ranked
1167 .flatMap(({ group, ranked: items }, order) => {
1168 if (items.length === 0) return [];
1169 // Use decides within a match class, never across one: a busy thread
1170 // matched through its project does not pass a title that holds the words.
1171 // Picks reorder word matches but never lift a match inside a word or a
1172 // typo above one, and a pick for a longer query ("lakebed perf") does not
1173 // pass the result whose whole name is the query ("Lakebed").
1174 const wordMatch = (match: M) => Math.min(matchClass(match.quality), 2);
1175 const exactPickAt = (match: M) => (match.pickedExactly ? (match.pickedAt ?? 0) : 0);
1176 const sorted = [...items].sort(
1177 (left, right) =>
1178 wordMatch(right.match) - wordMatch(left.match) ||
1179 exactPickAt(right.match) - exactPickAt(left.match) ||
1180 matchClass(right.match.quality) - matchClass(left.match.quality) ||
1181 (right.match.pickedAt ?? 0) - (left.match.pickedAt ?? 0) ||
1182 right.match.score - left.match.score,
1183 );
1184 const best = Math.max(
1185 ...items.map(({ match }) => matchClass(match.groupQuality ?? match.quality)),
1186 );
1187 return [{ group, ranked: sorted, best, order }];
1188 })
1189 .sort((left, right) => right.best - left.best || left.order - right.order)
1190 .map(({ group, ranked: items }) => ({ group, ranked: items }));
1192​
1193/** `rankSearchGroups` for a single list. */
1194export function rankSearchItems<
1195 T,
1196 M extends { readonly score: number; readonly quality: number; readonly strong: boolean },
1198 items: ReadonlyArray<T>,
1199 score: (item: T, options: { readonly typos: boolean }) => M | null,
1200): ReadonlyArray<RankedSearchItem<T, M>> {
1201 return rankSearchGroups([{ group: null, items }], score)[0]?.ranked ?? [];
1203​
1204export interface SearchTermsMatch {
1205 readonly score: number;
1206 readonly quality: number;
1207 /** The quality its group ranks by, when lower; see `scoreSearchTerms`. */
1208 readonly groupQuality?: number;
1209 readonly strong: boolean;
1210 readonly ranges: ReadonlyArray<SearchRange>;
1212​
1213const KEYWORD_QUALITY = 0.65;
1214// Below this, keyword prefixes match too much: "co" or "pro" would list most
1215// settings. A short query still matches a keyword it equals ("pr").
1216const KEYWORD_QUERY_MIN_LENGTH = 4;
1217​
1218/**
1219 * Scores a non-thread result such as a command or project. The first term
1220 * names it; the others are keywords that help it match but count less, so a
1221 * keyword match ranks a group below a name match ("mcp" finds the thread
1222 * named for it before a command with that keyword). Keywords match only at
1223 * word starts, and for queries under four characters only as whole words.
1224 */
1225export function scoreSearchTerms(
1226 normalizedQuery: string,
1227 terms: ReadonlyArray<string>,
1228 options?: { readonly typos?: boolean },
1229): SearchTermsMatch | null {
1230 // Filler words ("the ci") do not make a short query long.
1231 const meaningful = normalizedQuery
1232 .split(" ")
1233 .filter((token) => !FILLER_WORDS.has(token))
1234 .join(" ");
1235 const short = (meaningful || normalizedQuery).length < KEYWORD_QUERY_MIN_LENGTH;
1236 const match = matchSearchFields(
1237 normalizedQuery,
1238 terms.map((value, index) =>
1239 index === 0
1240 ? { value, weight: 1 }
1241 : // An alias typed in full ("pr") is deliberate, above a mere name prefix.
1242 { value, weight: short ? 0.8 : 0.6, wholeWords: short, keyword: true },
1243 ),
1244 options,
1245 );
1246 return (
1247 match && {
1248 score: match.quality,
1249 quality: match.quality,
1250 // Below the word-start class: a match only in hidden keywords must not put
1251 // its group above a result whose name matches. Inside the group an exact
1252 // alias still beats a name prefix ("pr" lists "Open pull requests" first).
1253 ...(match.primaryRanges.length > 0
1254 ? {}
1255 : { groupQuality: Math.min(match.quality, KEYWORD_QUALITY) }),
1256 strong: match.strong,
1257 ranges: match.primaryRanges,
1259 );