Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2
3import {
4 findSearchTokenRanges,
5 foldSearchQuery,
6 pickedQuery,
7 rankMessageMatches,
8 rankSearchGroups,
9 rankSearchItems,
10 recordThreadOpen,
11 messageMatcher,
12 scoreSearchTerms,
13 scoreThreadSearch,
14 SEARCH_RECENCY_HALF_LIFE_MS,
15 type SearchTermsMatch,
16 type ThreadSearchSubject,
17} from "./paletteSearch.ts";
18
19const NOW = Date.UTC(2026, 9, 23);
20const scoreMessageMatch = (text: string, query: string) => messageMatcher(query)(text);
21const DAY = 24 * 60 * 60 * 1000;
22
23function thread(title: string, overrides: Partial<ThreadSearchSubject> = {}): ThreadSearchSubject {
24 return { title, activityAt: NOW - 30 * DAY, ...overrides };
25}
26
27function rankTitles(query: string, threads: ReadonlyArray<ThreadSearchSubject>): string[] {
28 const normalized = foldSearchQuery(query);
29 return rankSearchItems(threads, (subject, options) =>
30 scoreThreadSearch(normalized, subject, NOW, options),
31 ).map(({ item }) => item.title);
32}
33
34describe("scoreThreadSearch", () => {
35 it("ranks whole words over prefixes over newer mid-word matches", () => {
36 expect(
37 rankTitles("auth", [
38 thread("Fix oauth redirect", { activityAt: NOW }),
39 thread("Authentication cleanup"),
40 thread("Share auth across worktrees"),
41 ]),
42 ).toEqual(["Share auth across worktrees", "Authentication cleanup", "Fix oauth redirect"]);
43 expect(
44 rankTitles("share auth", [
45 thread("Share authentication cleanup", {
46 activityAt: NOW,
47 opens: { openedAt: NOW, score: 12, picks: [] },
48 }),
49 thread("Auth across worktrees to share", { activityAt: NOW - 90 * DAY }),
50 ]),
51 ).toEqual(["Auth across worktrees to share", "Share authentication cleanup"]);
52 expect(
53 rankTitles("ui", [
54 thread("Parse ui tokens", { activityAt: NOW - 200 * DAY }),
55 thread("Polish UIs", { activityAt: NOW, opens: { openedAt: NOW, score: 12, picks: [] } }),
56 ]),
57 ).toEqual(["Polish UIs", "Parse ui tokens"]);
58 expect(
59 rankTitles("fix in sidebar", [
60 thread("Fix sidebar", { activityAt: NOW - 200 * DAY }),
61 thread("Fix crash in sidebar", {
62 activityAt: NOW,
63 opens: { openedAt: NOW, score: 12, picks: [] },
64 }),
65 thread("Fix sidebar input focus", {
66 activityAt: NOW,
67 opens: { openedAt: NOW, score: 6, picks: [] },
68 }),
69 ]),
70 ).toEqual(["Fix crash in sidebar", "Fix sidebar input focus", "Fix sidebar"]);
71 expect(
72 rankTitles("and", [
73 thread("Fix auth and sync", { activityAt: NOW - 200 * DAY }),
74 thread("Android build", {
75 activityAt: NOW,
76 opens: { openedAt: NOW, score: 12, picks: [] },
77 }),
78 ]),
79 ).toEqual(["Android build", "Fix auth and sync"]);
80 });
81
82 it("treats camelCase, kebab, path, and digit boundaries as word starts", () => {
83 const starts = (title: string, query: string) =>
84 scoreThreadSearch(query, thread(title), NOW)?.ranges;
85 expect(starts("useThreadSearch hook", "search")).toEqual([{ start: 9, end: 15 }]);
86 expect(starts("fix/sidebar-perf", "perf")).toEqual([{ start: 12, end: 16 }]);
87 expect(starts("Upgrade to pnpm12", "12")).toEqual([{ start: 15, end: 17 }]);
88 expect(starts("Fix JSONSchema parsing", "sch")).toEqual([{ start: 8, end: 11 }]);
89 expect(starts("Fix HTTPServer crash", "ser")).toEqual([{ start: 8, end: 11 }]);
90 expect(starts("Rename index.ts", ".ts")).toEqual([{ start: 12, end: 15 }]);
91 // A match is whole only where a word ends: "githuba" does not fill "GitHubActions".
92 expect(scoreThreadSearch("githuba", thread("GitHubActions setup"), NOW)?.quality).toBeLessThan(
93 1,
94 );
95 expect(rankTitles(".ts", [thread("Fix parser.tsx"), thread("Rename index.ts")])).toEqual([
96 "Rename index.ts",
97 "Fix parser.tsx",
98 ]);
99 // Short tokens never match mid-word.
100 expect(scoreThreadSearch("ci", thread("Decision log"), NOW)).toBeNull();
101 // A vowel sign belongs to its letter, so "ताब" is inside "किताब", not a word of its own.
102 expect(scoreThreadSearch(foldSearchQuery("ताब"), thread("किताब सूची"), NOW)).toBeNull();
103 });
104
105 it("lets recent activity and frequent opens decide between equal matches", () => {
106 expect(
107 rankTitles("goldbug", [
108 thread("Goldbug epilogue", { activityAt: NOW - 20 * DAY }),
109 thread("Goldbug processes", { activityAt: NOW - DAY }),
110 ]),
111 ).toEqual(["Goldbug processes", "Goldbug epilogue"]);
112 expect(
113 rankTitles("goldbug", [
114 thread("Goldbug processes", { activityAt: NOW - DAY }),
115 thread("Goldbug notes", {
116 activityAt: NOW - 40 * DAY,
117 opens: { openedAt: NOW - DAY, score: 12, picks: [] },
118 }),
119 ]),
120 ).toEqual(["Goldbug notes", "Goldbug processes"]);
121 });
122
123 it("puts the thread picked for a query first when that query is typed again", () => {
124 const threads = [
125 thread("Release checklist", {
126 opens: { openedAt: NOW - 5 * DAY, score: 1, picks: [{ query: "rel", at: NOW - 5 * DAY }] },
127 }),
128 thread("Relay pairing", { activityAt: NOW }),
129 ];
130 expect(rankTitles("rel", threads)).toEqual(["Release checklist", "Relay pairing"]);
131 // A pick never lifts a match inside a word above a word match.
132 expect(
133 rankTitles("auth", [
134 thread("Fix oauth redirect", {
135 opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "auth", at: NOW - DAY }] },
136 }),
137 thread("Share auth across worktrees"),
138 ]),
139 ).toEqual(["Share auth across worktrees", "Fix oauth redirect"]);
140 // Two letters are too little to go on.
141 expect(rankTitles("re", threads)).toEqual(["Relay pairing", "Release checklist"]);
142 // Once the query leaves the pick behind, the better match wins again.
143 expect(rankTitles("rela", threads)).toEqual(["Relay pairing"]);
144 // An old pick fades with the thread's last open.
145 const stale = [
146 thread("Release checklist", {
147 opens: {
148 openedAt: NOW - 90 * DAY,
149 score: 1,
150 picks: [{ query: "rel", at: NOW - 90 * DAY }],
151 },
152 }),
153 thread("Relay pairing", { activityAt: NOW }),
154 ];
155 expect(rankTitles("rel", stale)).toEqual(["Relay pairing", "Release checklist"]);
156 // Opening an old pick some other way does not revive it over a newer pick.
157 const reopened = [
158 thread("Release checklist", {
159 opens: { openedAt: NOW - DAY, score: 2, picks: [{ query: "rel", at: NOW - 30 * DAY }] },
160 }),
161 thread("Relay pairing", {
162 opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "rel", at: NOW - DAY }] },
163 }),
164 ];
165 expect(rankTitles("rel", reopened)).toEqual(["Relay pairing", "Release checklist"]);
166 // The latest pick for a query wins over an earlier one with a better title match.
167 const repicked = [
168 thread("Deploy", {
169 opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "deploy", at: NOW - DAY }] },
170 }),
171 thread("Deploy timeout on Railway", {
172 opens: { openedAt: NOW, score: 1, picks: [{ query: "deploy", at: NOW }] },
173 }),
174 ];
175 expect(rankTitles("deploy", repicked)).toEqual(["Deploy timeout on Railway", "Deploy"]);
176 // A thread's exact pick counts even after a newer pick for a longer query.
177 const exact = [
178 thread("Fix browser", {
179 opens: {
180 openedAt: NOW,
181 score: 2,
182 picks: [
183 { query: "fix browser", at: NOW },
184 { query: "fix", at: NOW - 2 * DAY },
185 ],
186 },
187 }),
188 thread("Fix sidebar", {
189 opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "fix", at: NOW - DAY }] },
190 }),
191 ];
192 expect(rankTitles("fix", exact)).toEqual(["Fix sidebar", "Fix browser"]);
193 // A pick for a longer query does not pass the thread named by the query.
194 const named = [
195 thread("Lakebed perf audit", {
196 opens: { openedAt: NOW, score: 1, picks: [{ query: "lakebed perf", at: NOW }] },
197 }),
198 thread("Lakebed"),
199 ];
200 expect(rankTitles("lakebed", named)).toEqual(["Lakebed", "Lakebed perf audit"]);
201 });
202
203 it("finds a branch pasted with the app's worktree prefix", () => {
204 const subject = thread("Cmd+K search", { branch: "t3/cmdk-search-v2" });
205 expect(scoreThreadSearch(foldSearchQuery("t3/cmdk-search-v2"), subject, NOW)).not.toBeNull();
206 expect(scoreThreadSearch(foldSearchQuery("t3/cmdk"), subject, NOW)).not.toBeNull();
207 });
208
209 it("ranks a title holding the words above the app's own branch prefix and project name", () => {
210 const busy = { activityAt: NOW, opens: { openedAt: NOW, score: 6, picks: [] } };
211 expect(
212 rankTitles("t3 connect", [
213 thread("Diagnose Connect provisioning failures", {
214 ...busy,
215 branch: "t3/diagnose-connect",
216 projectTitle: "t3code",
217 }),
218 thread("T3 Connect Tunnel Lifecycle Review", { projectTitle: "t3code" }),
219 ])[0],
220 ).toBe("T3 Connect Tunnel Lifecycle Review");
221 expect(
222 rankTitles("t3code", [
223 thread("Fix sidebar lag", { ...busy, projectTitle: "t3code", branch: "t3code/sidebar" }),
224 thread("T3 Code vs Gemini Token Volume", { projectTitle: "slophouse" }),
225 ])[0],
226 ).toBe("T3 Code vs Gemini Token Volume");
227 });
228
229 it("matches pull request numbers, branches, and projects with every token somewhere", () => {
230 const subject = thread("Trim model lists", {
231 branch: "t3/trim-mcp-models",
232 projectTitle: "t3code",
233 pullRequests: [{ number: 22889, title: "Smaller MCP payloads" }],
234 });
235 for (const query of ["#22889", "22889", "trim mcp", "payloads t3code", "models trim"]) {
236 expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW), query).not.toBeNull();
237 }
238 expect(scoreThreadSearch("trim lakebed", subject, NOW)).toBeNull();
239 });
240
241 it("forgives one typo only when nothing matches exactly", () => {
242 const threads = [thread("Hosting alternatives to Railway"), thread("Trim MCP model lists")];
243 expect(rankTitles("railwya", threads)).toEqual(["Hosting alternatives to Railway"]);
244 expect(rankTitles("trim mpc", threads)).toEqual(["Trim MCP model lists"]);
245 expect(
246 rankTitles("drga", [thread("Restore drag handles"), thread("Organize indicators")]),
247 ).toEqual(["Restore drag handles"]);
248 expect(rankTitles("22889", [thread("Stats", { pullRequests: [{ number: 22189 }] })])).toEqual(
249 [],
250 );
251 // Words with digits still forgive one.
252 expect(rankTitles("t3coed", [thread("t3code perf audit"), thread("Other")])).toEqual([
253 "t3code perf audit",
254 ]);
255 expect(rankTitles("oath2", [thread("Fix oauth2 redirect")])).toEqual(["Fix oauth2 redirect"]);
256 // A typo beats a mid-word accident: "ilde" is "idle", not the middle of "Builder".
257 expect(
258 rankTitles("ilde", [thread("Typesafe App Builder"), thread("De-risk idle tunnel cleanup")]),
259 ).toEqual(["De-risk idle tunnel cleanup", "Typesafe App Builder"]);
260 // "ing" is not "Nightly": a three-letter typo keeps the first letter.
261 expect(rankTitles("ing", [thread("Nightly build fix")])).toEqual([]);
262 // A short word may miss one letter while it is typed, but not change one.
263 expect(rankTitles("srv", [thread("Server restart"), thread("Other")])).toEqual([
264 "Server restart",
265 ]);
266 expect(rankTitles("sidb", [thread("Fix sidebar lag")])).toEqual(["Fix sidebar lag"]);
267 expect(rankTitles("cron", [thread("Config cleanup")])).toEqual([]);
268 // Filler words in a phrase-style query are not required, but alone they are.
269 expect(rankTitles("fix the sidebar", [thread("Fix Sidebar Lag")])).toEqual(["Fix Sidebar Lag"]);
270 expect(rankTitles("the", [thread("Fix sidebar lag")])).toEqual([]);
271 // A typed straight apostrophe finds a curly one.
272 expect(rankTitles("don't", [thread("Don’t merge yet")])).toEqual(["Don’t merge yet"]);
273 // Typos count across camelCase joins.
274 expect(rankTitles("githbu", [thread("GitHub API usage"), thread("Other")])).toEqual([
275 "GitHub API usage",
276 ]);
277 expect(rankTitles("macso", [thread("Fix macOS window"), thread("Other")])).toEqual([
278 "Fix macOS window",
279 ]);
280 // "enter" is not "external" when the right thread is already there.
281 expect(
282 rankTitles("cmd enter", [thread("Fix Cmd+Enter"), thread("Open links external")]),
283 ).toEqual(["Fix Cmd+Enter"]);
284 });
285});
286
287describe("queries that fold to empty words", () => {
288 it("returns for a hash and a space, or marks that fold to nothing", () => {
289 expect(rankTitles("# fix", [thread("Fix sidebar lag")])).toEqual(["Fix sidebar lag"]);
290 expect(rankTitles("#", [thread("Fix sidebar lag")])).toEqual([]);
291 expect(rankTitles("´´´", [thread("Fix sidebar lag")])).toEqual([]);
292 expect(scoreSearchTerms("# fix", ["Fix sidebar"])).toBeNull();
293 expect(findSearchTokenRanges("Fix sidebar", "´´´")).toEqual([]);
294 expect(findSearchTokenRanges("run ´´´ now", "run ´´´ now")).toEqual([
295 { start: 0, end: 3 },
296 { start: 8, end: 11 },
297 ]);
298 expect(scoreMessageMatch("Fix sidebar", "´´´")).toBeNull();
299 });
300});
301
302describe("scoreThreadSearch beyond Latin text and titles", () => {
303 it("leaves out a row whose words only meet across unrelated fields", () => {
304 const scattered = thread("eMudhra certificate update request", {
305 pullRequests: [
306 { number: 22645, title: "fix model picker" },
307 { number: 22649, title: "CI speedups" },
308 ],
309 });
310 expect(scoreThreadSearch("fix ci", scattered, NOW)).toBeNull();
311 // The project explains its own words; one field explains the rest.
312 const lakebed = thread("Weekly notes", {
313 projectTitle: "lakebed",
314 environmentLabel: "BeeBox",
315 pullRequests: [{ number: 243, title: "perf: faster cold starts" }],
316 });
317 expect(scoreThreadSearch("lakebed perf", lakebed, NOW)?.explain?.()).toEqual({
318 field: "pull-request",
319 label: "PR",
320 text: "#243 perf: faster cold starts",
321 ranges: [{ start: 5, end: 9 }],
322 });
323 for (const query of ["lakebed beebox", "beebox lakebed", "lakebed on beebox"]) {
324 expect(scoreThreadSearch(query, lakebed, NOW)?.explain?.(), query).toEqual({
325 field: "project",
326 label: "Project",
327 text: "lakebed",
328 ranges: [{ start: 0, end: 7 }],
329 });
330 }
331 expect(scoreThreadSearch("lakebed beebox perf", lakebed, NOW)?.explain?.()?.field).toBe(
332 "pull-request",
333 );
334 });
335
336 it("says which field matched when the title does not", () => {
337 const subject = thread("Trim model lists", {
338 branch: "t3/cleanup-payloads",
339 pullRequests: [{ number: 22889, title: "Smaller MCP payloads" }],
340 });
341 for (const query of ["#22889", "pr 22889", "pr22889", "pull request #22889"]) {
342 expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW)?.explain?.(), query).toEqual({
343 field: "pull-request",
344 label: "PR",
345 text: "#22889 Smaller MCP payloads",
346 ranges: [{ start: 1, end: 6 }],
347 });
348 }
349 // The app's own worktree prefix is not part of what the branch says.
350 expect(scoreThreadSearch("cleanup", subject, NOW)?.explain?.()).toEqual({
351 field: "branch",
352 label: "Branch",
353 text: "cleanup-payloads",
354 ranges: [{ start: 0, end: 7 }],
355 });
356 expect(scoreThreadSearch("trim", subject, NOW)?.explain?.()).toBeUndefined();
357 // Nor is it in the flat t3-<hex> form used when a `t3` branch blocks nested refs.
358 const flat = thread("Add search", { branch: "t3-abcd1234" });
359 expect(scoreThreadSearch("t3", flat, NOW)).toBeNull();
360 expect(scoreThreadSearch("t3 connect", flat, NOW)).toBeNull();
361 expect(scoreThreadSearch("abcd1234", flat, NOW)).not.toBeNull();
362 for (const query of ["t3-abcd", "t3-abcd1234 connect", "connect t3-abcd1234"]) {
363 expect(scoreThreadSearch(query, { ...flat, projectTitle: "connect" }, NOW)).not.toBeNull();
364 }
365 });
366
367 it("reads letters and numbers typed together, without forgiving typos in numbers", () => {
368 const threads = [
369 thread("Upgrade to pnpm 12"),
370 thread("GPT-5 eval"),
371 thread("iOS 26 support"),
372 thread("Other"),
373 ];
374 expect(rankTitles("pnpm12", threads)).toEqual(["Upgrade to pnpm 12"]);
375 expect(rankTitles("gpt5", threads)).toEqual(["GPT-5 eval"]);
376 expect(rankTitles("ios26", threads)).toEqual(["iOS 26 support"]);
377 expect(rankTitles("pnpm13", threads)).toEqual([]);
378 });
379
380 it("reads whole words typed together, but not scattered letters", () => {
381 const threads = [
382 thread("VS Code extension settings"),
383 thread("Fix UI bug in sidebar"),
384 thread("I plan to open source all of lakebed in the next few weeks"),
385 ];
386 expect(rankTitles("vscode", threads)).toEqual(["VS Code extension settings"]);
387 expect(rankTitles("fixuibug", threads)).toEqual(["Fix UI bug in sidebar"]);
388 expect(rankTitles("lint", threads)).toEqual([]);
389 // Short words before a mere prefix are a coincidence.
390 expect(rankTitles("inth", [thread("Show skill names in thread overview")])).toEqual([]);
391 expect(rankTitles("tos", [thread("Move Client State to Server")])).toEqual([]);
392 expect(rankTitles("t3co", [thread("T3 Code vs Gemini")])).toEqual(["T3 Code vs Gemini"]);
393 expect(rankTitles('"sidebar lag"', [thread("Fix sidebar lag")])).toEqual(["Fix sidebar lag"]);
394 // A pasted query with a separate accent mark matches the composed title.
395 expect(rankTitles("cafe\u0301", [thread("Café menu")])).toEqual(["Café menu"]);
396 // Letters with a stroke have no accent mark to strip, but still have a plain look-alike.
397 expect(rankTitles("lodz", [thread("Łódź trip")])).toEqual(["Łódź trip"]);
398 expect(rankTitles("kobenhavn", [thread("København plan")])).toEqual(["København plan"]);
399 expect(rankTitles("da nang", [thread("Đà Nẵng notes")])).toEqual(["Đà Nẵng notes"]);
400 expect(rankTitles("agri", [thread("Ağrı map")])).toEqual(["Ağrı map"]);
401 // Three letters of the last word are enough, as it is typed.
402 expect(rankTitles("gomod", [thread("Migrate to Go modules")])).toEqual([
403 "Migrate to Go modules",
404 ]);
405 // Joined words beat an earlier match inside a word.
406 expect(scoreThreadSearch("vscode", thread("Fixvscode and VS Code"), NOW)?.quality).toBe(0.6);
407 // A strong match elsewhere does not hide joined words.
408 expect(
409 rankTitles("vscode", [
410 thread("VS Code remote support"),
411 thread("Old work", { branch: "vscode", activityAt: NOW - 400 * DAY }),
412 ]),
413 ).toContain("VS Code remote support");
414 });
415
416 it("matches quoted phrases across decomposed accents before whitespace", () => {
417 const query = foldSearchQuery('"café install"');
418 const composed = scoreThreadSearch(query, { title: "Café install", activityAt: null }, 0);
419 expect(composed).toMatchObject({ wholeWords: true, ranges: [{ start: 0, end: 12 }] });
420 expect(scoreThreadSearch(query, { title: "Cafe\u0301 install", activityAt: null }, 0)).toEqual({
421 ...composed,
422 ranges: [{ start: 0, end: 13 }],
423 });
424 expect(
425 scoreThreadSearch(query, { title: "Cafe\u0301install", activityAt: null }, 0),
426 ).toBeNull();
427 expect(
428 scoreThreadSearch(query, { title: "Cafe\u093f install", activityAt: null }, 0),
429 ).toBeNull();
430 const lastWord = foldSearchQuery('"open cafe"');
431 expect(
432 scoreThreadSearch(lastWord, { title: "Open Cafe\u0301teria", activityAt: null }, 0),
433 ).toBeNull();
434 expect(
435 scoreThreadSearch(lastWord, { title: "Open Cafe\u0301 today", activityAt: null }, 0),
436 ).toMatchObject({ ranges: [{ start: 0, end: 10 }] });
437 expect(
438 scoreThreadSearch(lastWord, { title: "Open Cafe\u1ab0teria", activityAt: null }, 0),
439 ).toBeNull();
440 expect(
441 scoreThreadSearch(lastWord, { title: "Open CaféTools", activityAt: null }, 0),
442 ).toMatchObject({ ranges: [{ start: 0, end: 9 }] });
443 expect(
444 scoreThreadSearch(lastWord, { title: "Open Cafe\u0301Tools", activityAt: null }, 0),
445 ).toMatchObject({ ranges: [{ start: 0, end: 10 }] });
446 const insideWord = foldSearchQuery('"open re\u0301sume\u0301"');
447 const composedTitle = scoreThreadSearch(
448 insideWord,
449 { title: "Open résumé", activityAt: null },
450 0,
451 );
452 expect(composedTitle).toMatchObject({ ranges: [{ start: 0, end: 11 }] });
453 expect(
454 scoreThreadSearch(insideWord, { title: "Open re\u0301sume\u0301", activityAt: null }, 0),
455 ).toEqual({ ...composedTitle, ranges: [{ start: 0, end: 13 }] });
456 expect(
457 scoreThreadSearch(
458 foldSearchQuery('"re\u0301sume\u0301 open"'),
459 { title: "Re\u0301sume\u0301 open", activityAt: null },
460 0,
461 ),
462 ).toMatchObject({ ranges: [{ start: 0, end: 13 }] });
463 expect(
464 scoreThreadSearch(insideWord, { title: "Open re\u0301sume\u0301s", activityAt: null }, 0),
465 ).toBeNull();
466 // NFC folds the dot below into the query's letter; the acute it keeps must still match.
467 expect(
468 scoreThreadSearch(
469 foldSearchQuery('"open e\u0323\u0301ko"'),
470 { title: "Open e\u0323\u0301ko", activityAt: null },
471 0,
472 ),
473 ).toMatchObject({ ranges: [{ start: 0, end: 10 }] });
474 const acronym = foldSearchQuery('"open api"');
475 expect(
476 scoreThreadSearch(acronym, { title: "Open APIE\u0301diteur", activityAt: null }, 0),
477 ).toMatchObject({ ranges: [{ start: 0, end: 8 }] });
478 expect(
479 scoreThreadSearch(acronym, { title: "Open APIE\u0301DITEUR", activityAt: null }, 0),
480 ).toBeNull();
481 expect(
482 scoreThreadSearch(
483 foldSearchQuery('"кафе install"'),
484 { title: "кафе\u0301 install", activityAt: null },
485 0,
486 ),
487 ).not.toBeNull();
488 });
489
490 it("matches a query in double quotes only as whole words together, as typed", () => {
491 const threads = [
492 thread("Fix sidebar lag"),
493 thread("Sidebar scroll lag"),
494 thread("Fix sidebar lagging"),
495 thread("Lag in the sidebar"),
496 ];
497 expect(rankTitles("sidebar lag", threads)).toHaveLength(4);
498 expect(rankTitles('"sidebar lag"', threads)).toEqual(["Fix sidebar lag"]);
499 expect(rankTitles("“Sidebar Lag”", threads)).toEqual(["Fix sidebar lag"]);
500 // No typos and no optional filler.
501 expect(rankTitles('"sidebra lag"', threads)).toEqual([]);
502 expect(rankTitles('"fix the sidebar"', threads)).toEqual([]);
503 // Without its closing quote the query is still being typed.
504 expect(rankTitles('"sidebar lag', threads)).toHaveLength(4);
505 // Whitespace runs in a title do not hide the phrase.
506 expect(rankTitles('"sidebar lag"', [thread("Fix sidebar lag")])).toEqual(["Fix sidebar lag"]);
507 // A vowel sign, or a joiner before a letter, after the last word continues it.
508 expect(rankTitles('"open शक्"', [thread("Open शक्\u200Dति"), thread("Open शक्")])).toEqual([
509 "Open शक्",
510 ]);
511 expect(rankTitles('"open किताब"', [thread("Open किताबें"), thread("Open किताब")])).toEqual([
512 "Open किताब",
513 ]);
514 // A long run of quotes inside a query folds at once, and quotes around nothing match nothing.
515 const quotes = '"'.repeat(34);
516 expect(foldSearchQuery(`a${quotes}x`)).toBe(`a${quotes}x`);
517 expect(scoreThreadSearch(foldSearchQuery('"#"'), thread('Fix "" handling'), NOW)).toBeNull();
518 // A query folded elsewhere may hold stray spaces.
519 expect(scoreThreadSearch('" lag"', thread("Fix sidebar lag"), NOW)).not.toBeNull();
520 const subject = thread("Trim model lists", {
521 branch: "t3/cleanup-payloads",
522 pullRequests: [{ number: 22889, title: "Smaller MCP payloads" }],
523 });
524 expect(
525 scoreThreadSearch(foldSearchQuery('"mcp payloads"'), subject, NOW)?.explain?.(),
526 ).toMatchObject({
527 label: "PR",
528 text: "#22889 Smaller MCP payloads",
529 ranges: [{ start: 15, end: 27 }],
530 });
531 expect(scoreThreadSearch(foldSearchQuery('"payloads mcp"'), subject, NOW)).toBeNull();
532 // A branch or pull request pasted in quotes still finds its thread.
533 for (const query of ['"t3/cleanup-payloads"', '"#22889"', '"pr 22889"']) {
534 expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW), query).not.toBeNull();
535 }
536 expect(scoreSearchTerms(foldSearchQuery('"pull requests"'), ["Open pull requests"])).not.toBe(
537 null,
538 );
539 expect(scoreSearchTerms(foldSearchQuery('"pull request"'), ["Open pull requests"])).toBeNull();
540 });
541
542 it("stores picked queries without splitting an emoji", () => {
543 expect(pickedQuery(`${"a".repeat(31)}🚀`)).toBe("a".repeat(31));
544 expect(pickedQuery(" Upl ")).toBe("upl");
545 // A pick counts for its words, in quotes or not.
546 expect(pickedQuery('"Fix Sidebar"')).toBe("fix sidebar");
547 // Folded before it is cut, as stored and as compared.
548 const spaced = "investigate workspace thread reset bug";
549 expect(pickedQuery(spaced)).toBe(pickedQuery(foldSearchQuery(spaced)));
550 });
551
552 it("matches emoji in titles", () => {
553 expect(rankTitles("🚀", [thread("🚀 Launch checklist"), thread("Launch notes")])).toEqual([
554 "🚀 Launch checklist",
555 ]);
556 });
557
558 it("treats each Chinese or Japanese character as a word start", () => {
559 expect(scoreThreadSearch("搜索", thread("实现全文搜索"), NOW)).not.toBeNull();
560 expect(scoreThreadSearch("検索", thread("新しい検索機能"), NOW)).not.toBeNull();
561 });
562});
563
564describe("scoreThreadSearch with heavy use and loose input", () => {
565 it("keeps a whole word on a quiet thread above a mid-word hit on a thread opened daily", () => {
566 let opens = recordThreadOpen(null, NOW - 60 * DAY, undefined);
567 for (let day = 59; day >= 1; day--) opens = recordThreadOpen(opens, NOW - day * DAY, undefined);
568 expect(
569 rankTitles("auth", [
570 thread("Fix oauth redirect", { activityAt: NOW, opens }),
571 thread("Share auth across worktrees", { activityAt: NOW - 90 * DAY }),
572 ]),
573 ).toEqual(["Share auth across worktrees", "Fix oauth redirect"]);
574 });
575
576 it("reads a word and the start of the next typed together, highlighting each part", () => {
577 const threads = [thread("Fix sidebar lag"), thread("Unrelated work")];
578 expect(rankTitles("fixsid", threads)).toEqual(["Fix sidebar lag"]);
579 // A later "F" can start the run.
580 expect(rankTitles("fixsid", [thread("Feature: Fix sidebar lag")])).toEqual([
581 "Feature: Fix sidebar lag",
582 ]);
583 expect(scoreThreadSearch("fixsid", threads[0]!, NOW)?.ranges).toEqual([
584 { start: 0, end: 3 },
585 { start: 4, end: 7 },
586 ]);
587 // Initials are not words typed together.
588 expect(rankTitles("fsl", threads)).toEqual([]);
589 });
590
591 it("finds nothing rather than an unrelated thread when no word matches", () => {
592 const threads = [
593 thread("Projectless threads without Git"),
594 thread("Concern about connection setup"),
595 thread("Simplify worktree thread creation"),
596 thread("Start a new conversation"),
597 thread("Setting up the sentinel"),
598 thread("I plan to open source all of lakebed in the next few weeks"),
599 thread("Design notes"),
600 thread("Link pull request to thread"),
601 ];
602 for (const query of ["posthog", "cron", "stripe", "gpu", "fxsb", "lint", "deno"]) {
603 expect(rankTitles(query, threads), query).toEqual([]);
604 }
605 });
606
607 it("matches pieces of references that hold a number, and environment names", () => {
608 const subject = thread("Trim model lists", {
609 id: "thread-5fe6f59c-4976",
610 environmentLabel: "BeeBox",
611 pullRequests: [
612 {
613 number: 22889,
614 references: ["pingdotgg/t3code#22889", "https://github.com/pingdotgg/t3code/pull/22889"],
615 },
616 ],
617 });
618 for (const query of [
619 "t3code#22889",
620 "github.com/pingdotgg/t3code/pull/22889",
621 "https://github.com/pingdotgg/t3code/pull/22889/files",
622 "5fe6f59c",
623 "beebox",
624 ]) {
625 expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW), query).not.toBeNull();
626 }
627 expect(scoreThreadSearch("github.com", subject, NOW)).toBeNull();
628 // A number is never cut short.
629 for (const query of ["github.com/pingdotgg/t3code/pull/2288", "t3code#2288"]) {
630 expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW), query).toBeNull();
631 }
632 });
633});
634
635describe("rankMessageMatches", () => {
636 it("merges environments by word match, then picks, then quality and use", () => {
637 const subjects = new Map([
638 ["a-word", thread("A word")],
639 ["a-word-2", thread("A word too")],
640 ["b-prefix", thread("B prefix")],
641 ["b-recent", thread("B recent", { activityAt: NOW })],
642 [
643 "b-picked",
644 thread("B picked", {
645 opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "needle", at: NOW - DAY }] },
646 }),
647 ],
648 ]);
649 // Environment A sent two whole words, environment B a prefix and two more.
650 const matches = [
651 { key: "a-word", quality: 1 },
652 { key: "a-word-2", quality: 1 },
653 { key: "b-prefix", quality: 0.8 },
654 { key: "b-recent", quality: 1 },
655 { key: "b-picked", quality: 0.8 },
656 ];
657 expect(
658 rankMessageMatches(matches, (match) => subjects.get(match.key), "needle", NOW).map(
659 (match) => match.key,
660 ),
661 ).toEqual(["b-picked", "b-recent", "a-word", "a-word-2", "b-prefix"]);
662 // A palette lists title matches above, so they use up no message rows.
663 const titled = new Map([...subjects, ["c-titled", thread("Needle cleanup")]]);
664 expect(
665 rankMessageMatches(
666 [{ key: "c-titled", quality: 1 }, ...matches],
667 (match) => titled.get(match.key),
668 "needle",
669 NOW,
670 { withoutTitleMatches: true },
671 ).map((match) => match.key),
672 ).not.toContain("c-titled");
673 });
674
675 it("ranks a thread that keeps using the word above a passing mention of equal quality", () => {
676 // The real case: 21 hits seven weeks back against one this week, opened today.
677 const subjects = new Map([
678 [
679 "mention",
680 thread("Mention", {
681 activityAt: NOW - 3 * DAY,
682 opens: { openedAt: NOW, score: 1, picks: [] },
683 }),
684 ],
685 ["about", thread("About it", { activityAt: NOW - 48 * DAY })],
686 ]);
687 const matches = [
688 { key: "mention", quality: 1, hits: 1 },
689 { key: "about", quality: 1, hits: 21 },
690 ];
691 expect(
692 rankMessageMatches(matches, (match) => subjects.get(match.key), "tailscale", NOW).map(
693 (match) => match.key,
694 ),
695 ).toEqual(["about", "mention"]);
696 });
697
698 it("keeps matches inside words below word matches, however used", () => {
699 const busy = thread("Busy", {
700 activityAt: NOW,
701 opens: { openedAt: NOW, score: 20, picks: [] },
702 });
703 const matches = [
704 { key: "busy", quality: 0.3 },
705 { key: "quiet", quality: 1 },
706 ];
707 const subjects = new Map([
708 ["busy", busy],
709 ["quiet", thread("Quiet")],
710 ]);
711 expect(
712 rankMessageMatches(matches, (match) => subjects.get(match.key), "rust", NOW).map(
713 (match) => match.key,
714 ),
715 ).toEqual(["quiet", "busy"]);
716 });
717});
718
719describe("rankSearchGroups", () => {
720 it("orders groups by their best match and keeps the given order on ties", () => {
721 const groups = rankSearchGroups(
722 [
723 { group: "actions", items: ["Open settings", "New thread"] },
724 { group: "threads", items: ["Settings sync rewrite", "Thread settings"] },
725 { group: "projects", items: ["Settings app"] },
726 ],
727 (item, options) => scoreSearchTerms("settings", [item], options),
728 );
729 expect(groups.map(({ group, ranked }) => [group, ranked.map(({ item }) => item)])).toEqual([
730 ["actions", ["Open settings"]],
731 ["threads", ["Settings sync rewrite", "Thread settings"]],
732 ["projects", ["Settings app"]],
733 ]);
734 });
735});
736
737describe("rankSearchGroups with keywords and picks", () => {
738 it("matches inside a word only in thread titles", () => {
739 expect(scoreSearchTerms("arch", ["Search project contents"])).toBeNull();
740 expect(
741 scoreThreadSearch("arch", thread("Notes", { branch: "research-extension-system" }), NOW),
742 ).toBeNull();
743 expect(scoreThreadSearch("arch", thread("Research notes"), NOW)?.quality).toBe(0.3);
744 });
745
746 it("forgives typos in names but not in hidden keywords", () => {
747 const groups = rankSearchGroups(
748 [
749 { group: "actions", items: [["Open settings", "preferences", "keybindings"]] },
750 { group: "settings", items: [["Keybindings", "General"]] },
751 ],
752 (terms, options) => scoreSearchTerms("keybindngs", terms, options),
753 );
754 expect(groups.map(({ group }) => group)).toEqual(["settings"]);
755 expect(scoreSearchTerms("duckdb", ["Search engine", "duckduckgo"], { typos: true })).toBeNull();
756 expect(scoreSearchTerms("rust", ["GitHub sharing", "trusted"])).toBeNull();
757 // Filler words do not make a short query long enough for keyword prefixes.
758 expect(scoreSearchTerms("the ci", ["Context window indicator", "circle"])).toBeNull();
759 });
760
761 it("lists a thread named for the query above a command with it as a keyword", () => {
762 const rank = (command: string[], subject: ThreadSearchSubject) =>
763 rankSearchGroups<string, string[] | ThreadSearchSubject, SearchTermsMatch>(
764 [
765 { group: "actions", items: [command] },
766 { group: "threads", items: [subject] },
767 ],
768 (item, options) => {
769 if (Array.isArray(item)) return scoreSearchTerms("mcp", item, options);
770 return scoreThreadSearch("mcp", item, NOW, options);
771 },
772 ).map(({ group }) => group);
773 const named = thread("Trim MCP model lists");
774 const picked = thread("Trim MCP model lists", {
775 opens: { openedAt: NOW, score: 1, picks: [{ query: "mcp", at: NOW }] },
776 });
777 expect(rank(["Restart agent session", "reload", "mcp"], named)).toEqual(["threads", "actions"]);
778 // A command named for the query stays first; a pick reorders threads but
779 // never moves their group, so one pick for "mcp" does not pass the command.
780 expect(rank(["Reload MCP servers"], named)).toEqual(["actions", "threads"]);
781 expect(rank(["Reload MCP servers"], picked)).toEqual(["actions", "threads"]);
782 });
783});
784
785describe("recordThreadOpen", () => {
786 it("advances openedAt on quick reopens while keeping the open score deduped and decayed from scoredAt", () => {
787 const first = recordThreadOpen(null, NOW, " Upl ");
788 expect(first).toEqual({ openedAt: NOW, score: 1, picks: [{ query: "upl", at: NOW }] });
789 const reopened = recordThreadOpen(first, NOW + 60_000, "uploadthing");
790 expect(reopened).toEqual({
791 openedAt: NOW + 60_000,
792 scoredAt: NOW,
793 score: 1,
794 picks: [
795 { query: "uploadthing", at: NOW + 60_000 },
796 { query: "upl", at: NOW },
797 ],
798 });
799 // Decay and frequency dedupe stay anchored to scoredAt, not the quick reopen's openedAt.
800 const uploadQuery = foldSearchQuery("upload");
801 expect(
802 scoreThreadSearch(uploadQuery, thread("Upload notes", { opens: reopened }), NOW + DAY)?.score,
803 ).toBeCloseTo(
804 scoreThreadSearch(uploadQuery, thread("Upload notes", { opens: first }), NOW + DAY)!.score,
805 9,
806 );
807 const later = recordThreadOpen(reopened, NOW + SEARCH_RECENCY_HALF_LIFE_MS, "x".repeat(50));
808 expect(later.score).toBe(1.5);
809 expect(later.scoredAt).toBeUndefined();
810 expect(later.picks.map((pick) => pick.query)).toEqual(["x".repeat(32), "uploadthing", "upl"]);
811 const repicked = recordThreadOpen(later, later.openedAt + DAY, "upl");
812 expect(repicked.picks).toEqual([
813 { query: "upl", at: later.openedAt + DAY },
814 { query: "x".repeat(32), at: later.openedAt },
815 { query: "uploadthing", at: NOW + 60_000 },
816 ]);
817 });
818
819 it("drops picks that no longer count when the thread is opened again", () => {
820 const opens = {
821 openedAt: NOW - 30 * DAY,
822 score: 1,
823 picks: [{ query: "old", at: NOW - 30 * DAY }],
824 };
825 expect(recordThreadOpen(opens, NOW, "new").picks).toEqual([{ query: "new", at: NOW }]);
826 });
827
828 it("does not renew a query's pick when the thread is picked for another one", () => {
829 const deploy = [
830 thread("Deploy notes", {
831 opens: {
832 openedAt: NOW,
833 score: 2,
834 picks: [
835 { query: "scripts", at: NOW },
836 { query: "deploy", at: NOW - 60 * DAY },
837 ],
838 },
839 }),
840 thread("Deploy timeout", {
841 opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "deploy", at: NOW - DAY }] },
842 }),
843 ];
844 expect(rankTitles("deploy", deploy)).toEqual(["Deploy timeout", "Deploy notes"]);
845 });
846});
847
848describe("findSearchTokenRanges", () => {
849 it("maps folded matches back to the source text and skips short tokens", () => {
850 const text = "Le Café résumé ci";
851 expect(findSearchTokenRanges(text, "CAFE resume ci")).toEqual([
852 { start: 3, end: 7 },
853 { start: 8, end: 14 },
854 ]);
855 });
856
857 it("highlights a three-letter token only where it starts a word", () => {
858 expect(findSearchTokenRanges("drafts, enableFTS", "fts")).toEqual([{ start: 14, end: 17 }]);
859 expect(findSearchTokenRanges("Open handlers.ts", ".ts")).toEqual([{ start: 13, end: 16 }]);
860 });
861
862 it("highlights plain text for query accents that survive NFC", () => {
863 expect(findSearchTokenRanges("try eko sale", "ẹ\u0301ko")).toEqual([{ start: 4, end: 7 }]);
864 expect(findSearchTokenRanges("скажи привет", "приве\u0301т")).toEqual([{ start: 6, end: 12 }]);
865 expect(findSearchTokenRanges("try eko sale", '"ẹ\u0301ko sale"')).toEqual([
866 { start: 4, end: 12 },
867 ]);
868 });
869
870 it("highlights SHA prefixes but not ignored SHA substrings", () => {
871 const sha = "7dead52bb8";
872 const text = `dead ${sha}`;
873 expect(messageMatcher("dead")(sha)).toBeNull();
874 expect(findSearchTokenRanges(text, "dead")).toEqual([{ start: 0, end: 4 }]);
875 expect(messageMatcher("7dead")(sha)).not.toBeNull();
876 expect(findSearchTokenRanges(text, "7dead")).toEqual([{ start: 5, end: 10 }]);
877 });
878
879 it("highlights a query in double quotes only where its words are together", () => {
880 expect(
881 findSearchTokenRanges("files, then the Missing osprey files", '"missing osprey files"'),
882 ).toEqual([{ start: 16, end: 37 }]);
883 expect(findSearchTokenRanges("Open किताबें", '"open किताब"')).toEqual([]);
884 expect(findSearchTokenRanges("models and the model", '"model"')).toEqual([
885 { start: 15, end: 20 },
886 ]);
887 expect(findSearchTokenRanges("日本日本", '"日本"')).toEqual([
888 { start: 0, end: 2 },
889 { start: 2, end: 4 },
890 ]);
891 });
892
893 it("keeps the quotes of a quoted word inside a longer query", () => {
894 expect(findSearchTokenRanges("npm is not the command: run 'npm' now", "run 'npm' now")).toEqual(
895 [
896 { start: 24, end: 27 },
897 { start: 28, end: 33 },
898 { start: 34, end: 37 },
899 ],
900 );
901 });
902
903 it("highlights a dotted capital I as the message matches it", () => {
904 const text = "İ, then İstanbul guide";
905 expect(findSearchTokenRanges(text, "İstanbul")).toEqual([{ start: 8, end: 16 }]);
906 expect(findSearchTokenRanges(text, "İSTANBUL guide")).toEqual([
907 { start: 8, end: 16 },
908 { start: 17, end: 22 },
909 ]);
910 expect(findSearchTokenRanges(text, '"İstanbul guide"')).toEqual([{ start: 8, end: 22 }]);
911 // Other marks stay: a short word keeps its vowel sign rather than lighting up a lone consonant.
912 expect(findSearchTokenRanges("दिल्ली में मौसम मेरा", "में")).toEqual([{ start: 7, end: 10 }]);
913 // Touching exact matches stay apart; an overlap does not hide the next match.
914 expect(findSearchTokenRanges("Foo BarFoo Bar", '"foo bar"')).toEqual([
915 { start: 0, end: 7 },
916 { start: 7, end: 14 },
917 ]);
918 expect(findSearchTokenRanges("i i\u0307 i i", '"İ i"')).toEqual([
919 { start: 0, end: 4 },
920 { start: 5, end: 8 },
921 ]);
922 // Token order does not matter.
923 for (const query of ["ist İst", "İst ist"]) {
924 expect(findSearchTokenRanges("list and İst", query)).toEqual([
925 { start: 1, end: 4 },
926 { start: 9, end: 12 },
927 ]);
928 }
929 });
930});
931
932describe("scoreMessageMatch", () => {
933 it("needs short words at a word start and ranks other words found inside words lower", () => {
934 const text = `Saved the drafts. ${"More notes. ".repeat(40)}Then enableFTS and Enable FTS.`;
935 const fts = scoreMessageMatch(text, "fts");
936 expect(fts?.quality).toBe(1);
937 expect(text.slice(fts?.offset)).toMatch(/^FTS and/);
938 expect(scoreMessageMatch("saved two drafts", "fts")).toBeNull();
939 expect(scoreMessageMatch("मुझे किताब चाहिए", "ताब")).toBeNull();
940 expect(scoreMessageMatch("⚠️Fix login", "fix")).toEqual({ quality: 1, offset: 2 });
941 expect(scoreMessageMatch("कि⚠️Fix", '"⚠️Fix"')).toEqual({ quality: 1, offset: 2 });
942 expect(scoreMessageMatch("ฉันมีงาน", "งาน")).toEqual({ quality: 1, offset: 5 });
943 expect(scoreMessageMatch("আমি বাংলাদেশে থাকি", "বাংলা")).toEqual({ quality: 0.8, offset: 4 });
944 expect(scoreMessageMatch("ช่วยค้นหาไฟล์นี้", "ค้นหา")?.offset).toBe(4);
945 expect(scoreMessageMatch("We trust the build", "rust")).toEqual({ quality: 0.3, offset: 4 });
946 expect(scoreMessageMatch("Rust and trust", "rust")).toEqual({ quality: 1, offset: 0 });
947 expect(scoreMessageMatch("Use the sidebar", '"sidebar"')).toEqual({ quality: 1, offset: 8 });
948 for (const [text, query, expected] of [
949 ["model mode mode", "mode", { quality: 1, offset: 6 }],
950 ["xmode model models", "mode", { quality: 0.8, offset: 6 }],
951 ["model models", "mode", { quality: 0.8, offset: 0 }],
952 ["xmode ymode", "mode", { quality: 0.3, offset: 1 }],
953 ["mode mode", "mode", { quality: 1, offset: 0 }],
954 ["fts fts", "fts", { quality: 1, offset: 0 }],
955 ["the theme", "he", null],
956 ["he theme", "he", { quality: 1, offset: 0 }],
957 ["notes", "", { quality: 1, offset: 0 }],
958 ["", "notes", null],
959 ["same same same", "same same", { quality: 1.25, offset: 0 }],
960 ["7cafe52bb8 cafe cafe", "cafe", { quality: 1, offset: 11 }],
961 ["7cafe52bb8 7cafe52bb8", "7cafe52", { quality: 1, offset: 0 }],
962 ["明天部署部署到生产环境", "部署", { quality: 1, offset: 2 }],
963 ["gannet’s gannet's", "gannet's", { quality: 1, offset: 9 }],
964 ["gannet's gannet’s", "gannet’s", { quality: 1, offset: 0 }],
965 // In double quotes, only the words together as typed, as whole words.
966 ["the missing osprey files", '"missing osprey files"', { quality: 1.25, offset: 4 }],
967 ["Missing osprey\n files", "“missing osprey files”", { quality: 1.25, offset: 0 }],
968 ["missing the osprey files", '"missing osprey files"', null],
969 ["osprey files missing", '"missing osprey files"', null],
970 // No further apart than the server's index reads.
971 [`missing${" ".repeat(17)}osprey files`, '"missing osprey files"', null],
972 // Whole words by the rule single words follow.
973 ["quickFix JSONSchema", '"fix JSON"', { quality: 1.25, offset: 5 }],
974 // Past a place where the phrase only starts a longer word, emoji first or not.
975 ["🚀 launching, then 🚀 launch", '"🚀 launch"', { quality: 1.25, offset: 19 }],
976 ["changed file", '"file"', { quality: 1, offset: 8 }],
977 ["changed files", '"file"', null],
978 ["Open किताबें", '"open किताब"', null],
979 ["Open शक्\u200Dति", '"open शक्"', null],
980 ] as const) {
981 expect(scoreMessageMatch(text, query), `${query} in ${text}`).toEqual(expected);
982 }
983 // Words written together as typed rank above the same words apart, and
984 // the snippet starts where they are together.
985 const together = "Run the tests, then vp run dev to check";
986 expect(scoreMessageMatch(together, "vp run dev")).toEqual({
987 quality: 1.25,
988 offset: together.indexOf("vp run dev"),
989 });
990 // Near each other ranks above far apart.
991 expect(scoreMessageMatch("dev notes: vp is slow, run it", "vp run dev")?.quality).toBe(1.1);
992 const far = `run the tests. ${"More notes. ".repeat(10)}Then dev mode, then vp`;
993 expect(scoreMessageMatch(far, "vp run dev")?.quality).toBe(1);
994 expect(scoreMessageMatch("I don\u2019t know why", "don't know")?.quality).toBe(1.25);
995 expect(scoreMessageMatch("Le Café open late", "cafe open")?.quality).toBe(1.25);
996 expect(scoreMessageMatch("The cafe open late", "café open")?.quality).toBe(1.25);
997 // The snippet starts where the words meet, not at an early one.
998 const phrase = `The plan. ${"More notes. ".repeat(10)}Since the last fix, the sidebar works`;
999 expect(scoreMessageMatch(phrase, "fix the sidebar")?.offset).toBe(phrase.indexOf("fix,"));
1000 const apart = `The lakebed app. ${"Notes. ".repeat(30)}Lakebed page perf is slow`;
1001 expect(apart.slice(scoreMessageMatch(apart, "lakebed perf")?.offset)).toMatch(/^Lakebed page/);
1002 // Only where a word counts: not "fix" in "prefix".
1003 const prefix = `fix ${"unrelated words ".repeat(40)}prefix has CI`;
1004 expect(scoreMessageMatch(prefix, "fix ci")?.offset).toBe(0);
1005 const padding = "padding ".repeat(40);
1006 const distantFilter = `to ${padding}deploy`;
1007 expect(scoreMessageMatch(distantFilter, "to deploy")).toEqual({
1008 quality: 1,
1009 offset: distantFilter.indexOf("deploy"),
1010 });
1011 const nearbyFilter = `deploy early. ${padding}CI pipeline deploy failed`;
1012 expect(scoreMessageMatch(nearbyFilter, "ci deploy")).toEqual({
1013 quality: 1,
1014 offset: nearbyFilter.indexOf("CI pipeline"),
1015 });
1016 // A commit SHA is one word: "cafe" inside one does not match, its start does.
1017 expect(scoreMessageMatch("see commit 7cafe52bb8", "cafe")).toBeNull();
1018 expect(scoreMessageMatch("see commit 7cafe52bb8", "7cafe52")).toEqual({
1019 quality: 1,
1020 offset: 11,
1021 });
1022 expect(scoreMessageMatch("7cafe52bb8, then the cafe", "cafe")?.quality).toBe(1);
1023 // A whole word beats a word prefix: "mode" prefers "mode" over "model".
1024 expect(scoreMessageMatch("model settings", "mode")?.quality).toBe(0.8);
1025 expect(scoreMessageMatch("The model and the mode switch", "mode")).toEqual({
1026 quality: 1,
1027 offset: 18,
1028 });
1029 expect(scoreMessageMatch("v12rc build", "rc")?.quality).toBe(1);
1030 expect(scoreMessageMatch("Fix the CLIAdapter state", "ada")?.quality).toBe(0.8);
1031 // Words too short for the index must start a word too.
1032 expect(scoreMessageMatch("Switch off the connection", "switch on")).toBeNull();
1033 expect(scoreMessageMatch("Upgrade pnpm 512 today", "pnpm 12")).toBeNull();
1034 expect(scoreMessageMatch("Upgrade to pnpm12 today", "pnpm 12")?.quality).toBe(1);
1035 // A word too short to search only narrows, so typing the next word
1036 // ("nvme s") does not reorder results; written together still counts.
1037 expect(scoreMessageMatch("Fix circle rendering", "fix ci")?.quality).toBe(1);
1038 expect(scoreMessageMatch("Fix CI failures", "fix ci")?.quality).toBe(1.25);
1039 expect(scoreMessageMatch("Upgrade pnpm 123 today", "pnpm 12")?.quality).toBe(1);
1040 expect(scoreMessageMatch("Rename the file to index.ts", ".ts")?.quality).toBe(1);
1041 });
1042
1043 it("finds words through case and accents, also after the same letters inside a word", () => {
1044 expect(scoreMessageMatch("This addresses Résumé indexing", "res")).toMatchObject({
1045 offset: 15,
1046 });
1047 expect(scoreMessageMatch("Le CAFÉ ouvert", "cafe")).toMatchObject({ quality: 1, offset: 3 });
1048 // An accented whole word beats a plain prefix earlier on.
1049 expect(scoreMessageMatch("The cafeteria, then the Café", "cafe")).toMatchObject({
1050 quality: 1,
1051 offset: 24,
1052 });
1053 expect(scoreMessageMatch("I presume this. Résumé indexing", "resume")).toMatchObject({
1054 quality: 1,
1055 offset: 16,
1056 });
1057 expect(scoreMessageMatch("明天部署到生产环境", "部署")).toMatchObject({ offset: 2 });
1058 // Vietnamese and combining accents fold too.
1059 expect(scoreMessageMatch("Properties: tiếng Việt support", "tie")).toMatchObject({
1060 offset: 12,
1061 });
1062 expect(scoreMessageMatch("Properties: tie\u0301ng support", "tie")).toMatchObject({
1063 offset: 12,
1064 });
1065 // A letter that grows when lowercased does not shift later offsets.
1066 expect(scoreMessageMatch("İ Enable fts and model", "fts")).toMatchObject({ offset: 9 });
1067 expect(scoreMessageMatch("İ Enable fts and model", "model")?.quality).toBe(1);
1068 expect(scoreMessageMatch("Trip to İstanbul", "İstanbul")).toEqual({ quality: 1, offset: 8 });
1069 for (const [text, query, expected] of [
1070 ["İ cafeteria Café CAFÉ", "cafe", { quality: 1, offset: 12 }],
1071 ["Café cafe", "cafe", { quality: 1, offset: 5 }],
1072 ["İ Café Café", "café", { quality: 1, offset: 2 }],
1073 ["İ Résumé Résumé", "resume", { quality: 1, offset: 2 }],
1074 ["İ résuméprefix résumé", "resume", { quality: 1, offset: 15 }],
1075 ] as const) {
1076 expect(scoreMessageMatch(text, query), `${query} in ${text}`).toEqual(expected);
1077 }
1078 });
1079
1080 it("reads words as together across a decomposed accent before whitespace", () => {
1081 for (const query of ['"cafe install"', '"café install"']) {
1082 expect(scoreMessageMatch("Cafe\u0301 install", query), query).toEqual({
1083 quality: 1.25,
1084 offset: 0,
1085 });
1086 expect(findSearchTokenRanges("Cafe\u0301 install", query), query).toEqual([
1087 { start: 0, end: 13 },
1088 ]);
1089 }
1090 expect(scoreMessageMatch("Cafe\u0301 install", "cafe install")).toEqual({
1091 quality: 1.25,
1092 offset: 0,
1093 });
1094 expect(scoreMessageMatch("Cafe\u0301install", '"cafe install"')).toBeNull();
1095 expect(scoreMessageMatch("Cafe\u093f install", '"cafe install"')).toBeNull();
1096 // The last word ends past its accents: "résumés" is not "résumé".
1097 expect(scoreMessageMatch("Cafe\u0301 resume\u0301s", '"cafe resume"')).toBeNull();
1098 expect(findSearchTokenRanges("Cafe\u0301 resume\u0301", '"cafe resume"')).toEqual([
1099 { start: 0, end: 13 },
1100 ]);
1101 // A single word ends past its accents too: "cafe" is whole in "Café", not "Caféteria".
1102 for (const [text, query, expected] of [
1103 ["Cafe\u0301teria", '"cafe"', null],
1104 ["Cafe\u0301teria", "cafe", { quality: 0.8, offset: 0 }],
1105 ["Cafe\u0301 today", '"cafe"', { quality: 1, offset: 0 }],
1106 ["Cafe\u0301Tools", '"cafe"', { quality: 1, offset: 0 }],
1107 ["Cafe\u1ab0\u1ab1Tools", '"cafe\u1ab0"', { quality: 1, offset: 0 }],
1108 [`${"\u1ab0".repeat(10_000)}a`, '"\u1ab0\u1ab0\u1ab0"', { quality: 1, offset: 0 }],
1109 ] as const) {
1110 expect(scoreMessageMatch(text, query), `${query} in ${text}`).toEqual(expected);
1111 }
1112 expect(findSearchTokenRanges("Cafe\u0301teria, cafe\u0301", '"cafe"')).toEqual([
1113 { start: 12, end: 16 },
1114 ]);
1115 expect(findSearchTokenRanges("Cafe\u1ab0\u1ab1Tools", '"cafe\u1ab0"')).toEqual([
1116 { start: 0, end: 5 },
1117 ]);
1118 // A word after a mark continues the word before it, so no phrase starts there.
1119 expect(scoreMessageMatch("x\u0301cafe install, then cafe is open", "cafe install")).toEqual({
1120 quality: 1.1,
1121 offset: 7,
1122 });
1123 // An acronym ends before a capital whose accent follows it.
1124 expect(scoreMessageMatch("Open APIE\u0301diteur", '"open api"')).toEqual({
1125 quality: 1.25,
1126 offset: 0,
1127 });
1128 expect(findSearchTokenRanges("Open APIE\u0301diteur", '"open api"')).toEqual([
1129 { start: 0, end: 8 },
1130 ]);
1131 expect(scoreMessageMatch("Open APIE\u0301DITEUR", '"open api"')).toBeNull();
1132 // A word of only a mark matches no phrase across a run of marks.
1133 expect(
1134 scoreMessageMatch(`${"\u0301".repeat(64)} unrelated install`, '"\u0301 install"'),
1135 ).toBeNull();
1136 });
1137
1138 it("keeps Indic and Thai vowel signs intact when grading matches", () => {
1139 expect(scoreMessageMatch("बातचीत अबत", "बात")).toEqual({ quality: 0.8, offset: 0 });
1140 expect(scoreMessageMatch("กินข้าว อกน", "กิน")).toEqual({ quality: 0.8, offset: 0 });
1141 expect(scoreMessageMatch("กน", "กิน")).toBeNull();
1142 expect(scoreMessageMatch("बत करो बातचीत", '"बात करो"')).toBeNull();
1143 expect(scoreMessageMatch("बत करो", "बात करो")).toBeNull();
1144 });
1145
1146 it("matches plain text for query accents that survive NFC", () => {
1147 expect(scoreMessageMatch("try eko sale", "ẹ\u0301ko")).toEqual({ quality: 1, offset: 4 });
1148 expect(scoreMessageMatch("скажи привет", "приве\u0301т")).toEqual({ quality: 1, offset: 6 });
1149 expect(scoreMessageMatch("try eko sale", '"ẹ\u0301ko sale"')).toEqual({
1150 quality: 1.25,
1151 offset: 4,
1152 });
1153 });
1154});