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