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

paletteSearch.ts

1,461 lines55.9 KB

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