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 });
102
103 it("lets recent activity and frequent opens decide between equal matches", () => {
104 expect(
105 rankTitles("goldbug", [
106 thread("Goldbug epilogue", { activityAt: NOW - 20 * DAY }),
107 thread("Goldbug processes", { activityAt: NOW - DAY }),
108 ]),
109 ).toEqual(["Goldbug processes", "Goldbug epilogue"]);
110 expect(
111 rankTitles("goldbug", [
112 thread("Goldbug processes", { activityAt: NOW - DAY }),
113 thread("Goldbug notes", {
114 activityAt: NOW - 40 * DAY,
115 opens: { openedAt: NOW - DAY, score: 12, picks: [] },
116 }),
117 ]),
118 ).toEqual(["Goldbug notes", "Goldbug processes"]);
119 });
120
121 it("puts the thread picked for a query first when that query is typed again", () => {
122 const threads = [
123 thread("Release checklist", {
124 opens: { openedAt: NOW - 5 * DAY, score: 1, picks: [{ query: "rel", at: NOW - 5 * DAY }] },
125 }),
126 thread("Relay pairing", { activityAt: NOW }),
127 ];
128 expect(rankTitles("rel", threads)).toEqual(["Release checklist", "Relay pairing"]);
129 // A pick never lifts a match inside a word above a word match.
130 expect(
131 rankTitles("auth", [
132 thread("Fix oauth redirect", {
133 opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "auth", at: NOW - DAY }] },
134 }),
135 thread("Share auth across worktrees"),
136 ]),
137 ).toEqual(["Share auth across worktrees", "Fix oauth redirect"]);
138 // Two letters are too little to go on.
139 expect(rankTitles("re", threads)).toEqual(["Relay pairing", "Release checklist"]);
140 // Once the query leaves the pick behind, the better match wins again.
141 expect(rankTitles("rela", threads)).toEqual(["Relay pairing"]);
142 // An old pick fades with the thread's last open.
143 const stale = [
144 thread("Release checklist", {
145 opens: {
146 openedAt: NOW - 90 * DAY,
147 score: 1,
148 picks: [{ query: "rel", at: NOW - 90 * DAY }],
149 },
150 }),
151 thread("Relay pairing", { activityAt: NOW }),
152 ];
153 expect(rankTitles("rel", stale)).toEqual(["Relay pairing", "Release checklist"]);
154 // Opening an old pick some other way does not revive it over a newer pick.
155 const reopened = [
156 thread("Release checklist", {
157 opens: { openedAt: NOW - DAY, score: 2, picks: [{ query: "rel", at: NOW - 30 * DAY }] },
158 }),
159 thread("Relay pairing", {
160 opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "rel", at: NOW - DAY }] },
161 }),
162 ];
163 expect(rankTitles("rel", reopened)).toEqual(["Relay pairing", "Release checklist"]);
164 // The latest pick for a query wins over an earlier one with a better title match.
165 const repicked = [
166 thread("Deploy", {
167 opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "deploy", at: NOW - DAY }] },
168 }),
169 thread("Deploy timeout on Railway", {
170 opens: { openedAt: NOW, score: 1, picks: [{ query: "deploy", at: NOW }] },
171 }),
172 ];
173 expect(rankTitles("deploy", repicked)).toEqual(["Deploy timeout on Railway", "Deploy"]);
174 // A thread's exact pick counts even after a newer pick for a longer query.
175 const exact = [
176 thread("Fix browser", {
177 opens: {
178 openedAt: NOW,
179 score: 2,
180 picks: [
181 { query: "fix browser", at: NOW },
182 { query: "fix", at: NOW - 2 * DAY },
183 ],
184 },
185 }),
186 thread("Fix sidebar", {
187 opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "fix", at: NOW - DAY }] },
188 }),
189 ];
190 expect(rankTitles("fix", exact)).toEqual(["Fix sidebar", "Fix browser"]);
191 // A pick for a longer query does not pass the thread named by the query.
192 const named = [
193 thread("Lakebed perf audit", {
194 opens: { openedAt: NOW, score: 1, picks: [{ query: "lakebed perf", at: NOW }] },
195 }),
196 thread("Lakebed"),
197 ];
198 expect(rankTitles("lakebed", named)).toEqual(["Lakebed", "Lakebed perf audit"]);
199 });
200
201 it("finds a branch pasted with the app's worktree prefix", () => {
202 const subject = thread("Cmd+K search", { branch: "t3/cmdk-search-v2" });
203 expect(scoreThreadSearch(foldSearchQuery("t3/cmdk-search-v2"), subject, NOW)).not.toBeNull();
204 expect(scoreThreadSearch(foldSearchQuery("t3/cmdk"), subject, NOW)).not.toBeNull();
205 });
206
207 it("ranks a title holding the words above the app's own branch prefix and project name", () => {
208 const busy = { activityAt: NOW, opens: { openedAt: NOW, score: 6, picks: [] } };
209 expect(
210 rankTitles("t3 connect", [
211 thread("Diagnose Connect provisioning failures", {
212 ...busy,
213 branch: "t3/diagnose-connect",
214 projectTitle: "t3code",
215 }),
216 thread("T3 Connect Tunnel Lifecycle Review", { projectTitle: "t3code" }),
217 ])[0],
218 ).toBe("T3 Connect Tunnel Lifecycle Review");
219 expect(
220 rankTitles("t3code", [
221 thread("Fix sidebar lag", { ...busy, projectTitle: "t3code", branch: "t3code/sidebar" }),
222 thread("T3 Code vs Gemini Token Volume", { projectTitle: "slophouse" }),
223 ])[0],
224 ).toBe("T3 Code vs Gemini Token Volume");
225 });
226
227 it("matches pull request numbers, branches, and projects with every token somewhere", () => {
228 const subject = thread("Trim model lists", {
229 branch: "t3/trim-mcp-models",
230 projectTitle: "t3code",
231 pullRequests: [{ number: 22889, title: "Smaller MCP payloads" }],
232 });
233 for (const query of ["#22889", "22889", "trim mcp", "payloads t3code", "models trim"]) {
234 expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW), query).not.toBeNull();
235 }
236 expect(scoreThreadSearch("trim lakebed", subject, NOW)).toBeNull();
237 });
238
239 it("forgives one typo only when nothing matches exactly", () => {
240 const threads = [thread("Hosting alternatives to Railway"), thread("Trim MCP model lists")];
241 expect(rankTitles("railwya", threads)).toEqual(["Hosting alternatives to Railway"]);
242 expect(rankTitles("trim mpc", threads)).toEqual(["Trim MCP model lists"]);
243 expect(
244 rankTitles("drga", [thread("Restore drag handles"), thread("Organize indicators")]),
245 ).toEqual(["Restore drag handles"]);
246 expect(rankTitles("22889", [thread("Stats", { pullRequests: [{ number: 22189 }] })])).toEqual(
247 [],
248 );
249 // Words with digits still forgive one.
250 expect(rankTitles("t3coed", [thread("t3code perf audit"), thread("Other")])).toEqual([
251 "t3code perf audit",
252 ]);
253 expect(rankTitles("oath2", [thread("Fix oauth2 redirect")])).toEqual(["Fix oauth2 redirect"]);
254 // A typo beats a mid-word accident: "ilde" is "idle", not the middle of "Builder".
255 expect(
256 rankTitles("ilde", [thread("Typesafe App Builder"), thread("De-risk idle tunnel cleanup")]),
257 ).toEqual(["De-risk idle tunnel cleanup", "Typesafe App Builder"]);
258 // "ing" is not "Nightly": a three-letter typo keeps the first letter.
259 expect(rankTitles("ing", [thread("Nightly build fix")])).toEqual([]);
260 // A short word may miss one letter while it is typed, but not change one.
261 expect(rankTitles("srv", [thread("Server restart"), thread("Other")])).toEqual([
262 "Server restart",
263 ]);
264 expect(rankTitles("sidb", [thread("Fix sidebar lag")])).toEqual(["Fix sidebar lag"]);
265 expect(rankTitles("cron", [thread("Config cleanup")])).toEqual([]);
266 // Filler words in a phrase-style query are not required, but alone they are.
267 expect(rankTitles("fix the sidebar", [thread("Fix Sidebar Lag")])).toEqual(["Fix Sidebar Lag"]);
268 expect(rankTitles("the", [thread("Fix sidebar lag")])).toEqual([]);
269 // A typed straight apostrophe finds a curly one.
270 expect(rankTitles("don't", [thread("Don’t merge yet")])).toEqual(["Don’t merge yet"]);
271 // Typos count across camelCase joins.
272 expect(rankTitles("githbu", [thread("GitHub API usage"), thread("Other")])).toEqual([
273 "GitHub API usage",
274 ]);
275 expect(rankTitles("macso", [thread("Fix macOS window"), thread("Other")])).toEqual([
276 "Fix macOS window",
277 ]);
278 // "enter" is not "external" when the right thread is already there.
279 expect(
280 rankTitles("cmd enter", [thread("Fix Cmd+Enter"), thread("Open links external")]),
281 ).toEqual(["Fix Cmd+Enter"]);
282 });
283});
284
285describe("queries that fold to empty words", () => {
286 it("returns for a hash and a space, or marks that fold to nothing", () => {
287 expect(rankTitles("# fix", [thread("Fix sidebar lag")])).toEqual(["Fix sidebar lag"]);
288 expect(rankTitles("#", [thread("Fix sidebar lag")])).toEqual([]);
289 expect(rankTitles("´´´", [thread("Fix sidebar lag")])).toEqual([]);
290 expect(scoreSearchTerms("# fix", ["Fix sidebar"])).toBeNull();
291 expect(findSearchTokenRanges("Fix sidebar", "´´´")).toEqual([]);
292 expect(scoreMessageMatch("Fix sidebar", "´´´")).toBeNull();
293 });
294});
295
296describe("scoreThreadSearch beyond Latin text and titles", () => {
297 it("leaves out a row whose words only meet across unrelated fields", () => {
298 const scattered = thread("eMudhra certificate update request", {
299 pullRequests: [
300 { number: 22645, title: "fix model picker" },
301 { number: 22649, title: "CI speedups" },
302 ],
303 });
304 expect(scoreThreadSearch("fix ci", scattered, NOW)).toBeNull();
305 // The project explains its own words; one field explains the rest.
306 const lakebed = thread("Weekly notes", {
307 projectTitle: "lakebed",
308 pullRequests: [{ number: 243, title: "perf: faster cold starts" }],
309 });
310 expect(scoreThreadSearch("lakebed perf", lakebed, NOW)?.explain?.()).toEqual({
311 field: "pull-request",
312 label: "PR",
313 text: "#243 perf: faster cold starts",
314 ranges: [{ start: 5, end: 9 }],
315 });
316 });
317
318 it("says which field matched when the title does not", () => {
319 const subject = thread("Trim model lists", {
320 branch: "t3/cleanup-payloads",
321 pullRequests: [{ number: 22889, title: "Smaller MCP payloads" }],
322 });
323 for (const query of ["#22889", "pr 22889", "pr22889", "pull request #22889"]) {
324 expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW)?.explain?.(), query).toEqual({
325 field: "pull-request",
326 label: "PR",
327 text: "#22889 Smaller MCP payloads",
328 ranges: [{ start: 1, end: 6 }],
329 });
330 }
331 // The app's own worktree prefix is not part of what the branch says.
332 expect(scoreThreadSearch("cleanup", subject, NOW)?.explain?.()).toEqual({
333 field: "branch",
334 label: "Branch",
335 text: "cleanup-payloads",
336 ranges: [{ start: 0, end: 7 }],
337 });
338 expect(scoreThreadSearch("trim", subject, NOW)?.explain?.()).toBeUndefined();
339 // Nor is it in the flat t3-<hex> form used when a `t3` branch blocks nested refs.
340 const flat = thread("Add search", { branch: "t3-abcd1234" });
341 expect(scoreThreadSearch("t3", flat, NOW)).toBeNull();
342 expect(scoreThreadSearch("t3 connect", flat, NOW)).toBeNull();
343 expect(scoreThreadSearch("abcd1234", flat, NOW)).not.toBeNull();
344 for (const query of ["t3-abcd", "t3-abcd1234 connect", "connect t3-abcd1234"]) {
345 expect(scoreThreadSearch(query, { ...flat, projectTitle: "connect" }, NOW)).not.toBeNull();
346 }
347 });
348
349 it("reads letters and numbers typed together, without forgiving typos in numbers", () => {
350 const threads = [
351 thread("Upgrade to pnpm 12"),
352 thread("GPT-5 eval"),
353 thread("iOS 26 support"),
354 thread("Other"),
355 ];
356 expect(rankTitles("pnpm12", threads)).toEqual(["Upgrade to pnpm 12"]);
357 expect(rankTitles("gpt5", threads)).toEqual(["GPT-5 eval"]);
358 expect(rankTitles("ios26", threads)).toEqual(["iOS 26 support"]);
359 expect(rankTitles("pnpm13", threads)).toEqual([]);
360 });
361
362 it("reads whole words typed together, but not scattered letters", () => {
363 const threads = [
364 thread("VS Code extension settings"),
365 thread("Fix UI bug in sidebar"),
366 thread("I plan to open source all of lakebed in the next few weeks"),
367 ];
368 expect(rankTitles("vscode", threads)).toEqual(["VS Code extension settings"]);
369 expect(rankTitles("fixuibug", threads)).toEqual(["Fix UI bug in sidebar"]);
370 expect(rankTitles("lint", threads)).toEqual([]);
371 // Short words before a mere prefix are a coincidence.
372 expect(rankTitles("inth", [thread("Show skill names in thread overview")])).toEqual([]);
373 expect(rankTitles("tos", [thread("Move Client State to Server")])).toEqual([]);
374 expect(rankTitles("t3co", [thread("T3 Code vs Gemini")])).toEqual(["T3 Code vs Gemini"]);
375 expect(rankTitles('"sidebar lag"', [thread("Fix sidebar lag")])).toEqual(["Fix sidebar lag"]);
376 // A pasted query with a separate accent mark matches the composed title.
377 expect(rankTitles("cafe\u0301", [thread("Café menu")])).toEqual(["Café menu"]);
378 // Three letters of the last word are enough, as it is typed.
379 expect(rankTitles("gomod", [thread("Migrate to Go modules")])).toEqual([
380 "Migrate to Go modules",
381 ]);
382 // Joined words beat an earlier match inside a word.
383 expect(scoreThreadSearch("vscode", thread("Fixvscode and VS Code"), NOW)?.quality).toBe(0.6);
384 // A strong match elsewhere does not hide joined words.
385 expect(
386 rankTitles("vscode", [
387 thread("VS Code remote support"),
388 thread("Old work", { branch: "vscode", activityAt: NOW - 400 * DAY }),
389 ]),
390 ).toContain("VS Code remote support");
391 });
392
393 it("matches a query in double quotes only as whole words together, as typed", () => {
394 const threads = [
395 thread("Fix sidebar lag"),
396 thread("Sidebar scroll lag"),
397 thread("Fix sidebar lagging"),
398 thread("Lag in the sidebar"),
399 ];
400 expect(rankTitles("sidebar lag", threads)).toHaveLength(4);
401 expect(rankTitles('"sidebar lag"', threads)).toEqual(["Fix sidebar lag"]);
402 expect(rankTitles("“Sidebar Lag”", threads)).toEqual(["Fix sidebar lag"]);
403 // No typos and no optional filler.
404 expect(rankTitles('"sidebra lag"', threads)).toEqual([]);
405 expect(rankTitles('"fix the sidebar"', threads)).toEqual([]);
406 // Without its closing quote the query is still being typed.
407 expect(rankTitles('"sidebar lag', threads)).toHaveLength(4);
408 // Whitespace runs in a title do not hide the phrase.
409 expect(rankTitles('"sidebar lag"', [thread("Fix sidebar lag")])).toEqual(["Fix sidebar lag"]);
410 // A long run of quotes inside a query folds at once, and quotes around nothing match nothing.
411 const quotes = '"'.repeat(34);
412 expect(foldSearchQuery(`a${quotes}x`)).toBe(`a${quotes}x`);
413 expect(scoreThreadSearch(foldSearchQuery('"#"'), thread('Fix "" handling'), NOW)).toBeNull();
414 // A query folded elsewhere may hold stray spaces.
415 expect(scoreThreadSearch('" lag"', thread("Fix sidebar lag"), NOW)).not.toBeNull();
416 const subject = thread("Trim model lists", {
417 branch: "t3/cleanup-payloads",
418 pullRequests: [{ number: 22889, title: "Smaller MCP payloads" }],
419 });
420 expect(
421 scoreThreadSearch(foldSearchQuery('"mcp payloads"'), subject, NOW)?.explain?.(),
422 ).toMatchObject({
423 label: "PR",
424 text: "#22889 Smaller MCP payloads",
425 ranges: [{ start: 15, end: 27 }],
426 });
427 expect(scoreThreadSearch(foldSearchQuery('"payloads mcp"'), subject, NOW)).toBeNull();
428 // A branch or pull request pasted in quotes still finds its thread.
429 for (const query of ['"t3/cleanup-payloads"', '"#22889"', '"pr 22889"']) {
430 expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW), query).not.toBeNull();
431 }
432 expect(scoreSearchTerms(foldSearchQuery('"pull requests"'), ["Open pull requests"])).not.toBe(
433 null,
434 );
435 expect(scoreSearchTerms(foldSearchQuery('"pull request"'), ["Open pull requests"])).toBeNull();
436 });
437
438 it("stores picked queries without splitting an emoji", () => {
439 expect(pickedQuery(`${"a".repeat(31)}🚀`)).toBe("a".repeat(31));
440 expect(pickedQuery(" Upl ")).toBe("upl");
441 // A pick counts for its words, in quotes or not.
442 expect(pickedQuery('"Fix Sidebar"')).toBe("fix sidebar");
443 // Folded before it is cut, as stored and as compared.
444 const spaced = "investigate workspace thread reset bug";
445 expect(pickedQuery(spaced)).toBe(pickedQuery(foldSearchQuery(spaced)));
446 });
447
448 it("matches emoji in titles", () => {
449 expect(rankTitles("🚀", [thread("🚀 Launch checklist"), thread("Launch notes")])).toEqual([
450 "🚀 Launch checklist",
451 ]);
452 });
453
454 it("treats each Chinese or Japanese character as a word start", () => {
455 expect(scoreThreadSearch("搜索", thread("实现全文搜索"), NOW)).not.toBeNull();
456 expect(scoreThreadSearch("検索", thread("新しい検索機能"), NOW)).not.toBeNull();
457 });
458});
459
460describe("scoreThreadSearch with heavy use and loose input", () => {
461 it("keeps a whole word on a quiet thread above a mid-word hit on a thread opened daily", () => {
462 let opens = recordThreadOpen(null, NOW - 60 * DAY, undefined);
463 for (let day = 59; day >= 1; day--) opens = recordThreadOpen(opens, NOW - day * DAY, undefined);
464 expect(
465 rankTitles("auth", [
466 thread("Fix oauth redirect", { activityAt: NOW, opens }),
467 thread("Share auth across worktrees", { activityAt: NOW - 90 * DAY }),
468 ]),
469 ).toEqual(["Share auth across worktrees", "Fix oauth redirect"]);
470 });
471
472 it("reads a word and the start of the next typed together, highlighting each part", () => {
473 const threads = [thread("Fix sidebar lag"), thread("Unrelated work")];
474 expect(rankTitles("fixsid", threads)).toEqual(["Fix sidebar lag"]);
475 // A later "F" can start the run.
476 expect(rankTitles("fixsid", [thread("Feature: Fix sidebar lag")])).toEqual([
477 "Feature: Fix sidebar lag",
478 ]);
479 expect(scoreThreadSearch("fixsid", threads[0]!, NOW)?.ranges).toEqual([
480 { start: 0, end: 3 },
481 { start: 4, end: 7 },
482 ]);
483 // Initials are not words typed together.
484 expect(rankTitles("fsl", threads)).toEqual([]);
485 });
486
487 it("finds nothing rather than an unrelated thread when no word matches", () => {
488 const threads = [
489 thread("Projectless threads without Git"),
490 thread("Concern about connection setup"),
491 thread("Simplify worktree thread creation"),
492 thread("Start a new conversation"),
493 thread("Setting up the sentinel"),
494 thread("I plan to open source all of lakebed in the next few weeks"),
495 thread("Design notes"),
496 thread("Link pull request to thread"),
497 ];
498 for (const query of ["posthog", "cron", "stripe", "gpu", "fxsb", "lint", "deno"]) {
499 expect(rankTitles(query, threads), query).toEqual([]);
500 }
501 });
502
503 it("matches pieces of references that hold a number, and environment names", () => {
504 const subject = thread("Trim model lists", {
505 id: "thread-5fe6f59c-4976",
506 environmentLabel: "BeeBox",
507 pullRequests: [
508 {
509 number: 22889,
510 references: ["pingdotgg/t3code#22889", "https://github.com/pingdotgg/t3code/pull/22889"],
511 },
512 ],
513 });
514 for (const query of [
515 "t3code#22889",
516 "github.com/pingdotgg/t3code/pull/22889",
517 "https://github.com/pingdotgg/t3code/pull/22889/files",
518 "5fe6f59c",
519 "beebox",
520 ]) {
521 expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW), query).not.toBeNull();
522 }
523 expect(scoreThreadSearch("github.com", subject, NOW)).toBeNull();
524 // A number is never cut short.
525 for (const query of ["github.com/pingdotgg/t3code/pull/2288", "t3code#2288"]) {
526 expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW), query).toBeNull();
527 }
528 });
529});
530
531describe("rankMessageMatches", () => {
532 it("merges environments by word match, then picks, then quality and use", () => {
533 const subjects = new Map([
534 ["a-word", thread("A word")],
535 ["a-word-2", thread("A word too")],
536 ["b-prefix", thread("B prefix")],
537 ["b-recent", thread("B recent", { activityAt: NOW })],
538 [
539 "b-picked",
540 thread("B picked", {
541 opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "needle", at: NOW - DAY }] },
542 }),
543 ],
544 ]);
545 // Environment A sent two whole words, environment B a prefix and two more.
546 const matches = [
547 { key: "a-word", quality: 1 },
548 { key: "a-word-2", quality: 1 },
549 { key: "b-prefix", quality: 0.8 },
550 { key: "b-recent", quality: 1 },
551 { key: "b-picked", quality: 0.8 },
552 ];
553 expect(
554 rankMessageMatches(matches, (match) => subjects.get(match.key), "needle", NOW).map(
555 (match) => match.key,
556 ),
557 ).toEqual(["b-picked", "b-recent", "a-word", "a-word-2", "b-prefix"]);
558 // A palette lists title matches above, so they use up no message rows.
559 const titled = new Map([...subjects, ["c-titled", thread("Needle cleanup")]]);
560 expect(
561 rankMessageMatches(
562 [{ key: "c-titled", quality: 1 }, ...matches],
563 (match) => titled.get(match.key),
564 "needle",
565 NOW,
566 { withoutTitleMatches: true },
567 ).map((match) => match.key),
568 ).not.toContain("c-titled");
569 });
570
571 it("ranks a thread that keeps using the word above a passing mention of equal quality", () => {
572 // The real case: 21 hits seven weeks back against one this week, opened today.
573 const subjects = new Map([
574 [
575 "mention",
576 thread("Mention", {
577 activityAt: NOW - 3 * DAY,
578 opens: { openedAt: NOW, score: 1, picks: [] },
579 }),
580 ],
581 ["about", thread("About it", { activityAt: NOW - 48 * DAY })],
582 ]);
583 const matches = [
584 { key: "mention", quality: 1, hits: 1 },
585 { key: "about", quality: 1, hits: 21 },
586 ];
587 expect(
588 rankMessageMatches(matches, (match) => subjects.get(match.key), "tailscale", NOW).map(
589 (match) => match.key,
590 ),
591 ).toEqual(["about", "mention"]);
592 });
593
594 it("keeps matches inside words below word matches, however used", () => {
595 const busy = thread("Busy", {
596 activityAt: NOW,
597 opens: { openedAt: NOW, score: 20, picks: [] },
598 });
599 const matches = [
600 { key: "busy", quality: 0.3 },
601 { key: "quiet", quality: 1 },
602 ];
603 const subjects = new Map([
604 ["busy", busy],
605 ["quiet", thread("Quiet")],
606 ]);
607 expect(
608 rankMessageMatches(matches, (match) => subjects.get(match.key), "rust", NOW).map(
609 (match) => match.key,
610 ),
611 ).toEqual(["quiet", "busy"]);
612 });
613});
614
615describe("rankSearchGroups", () => {
616 it("orders groups by their best match and keeps the given order on ties", () => {
617 const groups = rankSearchGroups(
618 [
619 { group: "actions", items: ["Open settings", "New thread"] },
620 { group: "threads", items: ["Settings sync rewrite", "Thread settings"] },
621 { group: "projects", items: ["Settings app"] },
622 ],
623 (item, options) => scoreSearchTerms("settings", [item], options),
624 );
625 expect(groups.map(({ group, ranked }) => [group, ranked.map(({ item }) => item)])).toEqual([
626 ["actions", ["Open settings"]],
627 ["threads", ["Settings sync rewrite", "Thread settings"]],
628 ["projects", ["Settings app"]],
629 ]);
630 });
631});
632
633describe("rankSearchGroups with keywords and picks", () => {
634 it("matches inside a word only in thread titles", () => {
635 expect(scoreSearchTerms("arch", ["Search project contents"])).toBeNull();
636 expect(
637 scoreThreadSearch("arch", thread("Notes", { branch: "research-extension-system" }), NOW),
638 ).toBeNull();
639 expect(scoreThreadSearch("arch", thread("Research notes"), NOW)?.quality).toBe(0.3);
640 });
641
642 it("forgives typos in names but not in hidden keywords", () => {
643 const groups = rankSearchGroups(
644 [
645 { group: "actions", items: [["Open settings", "preferences", "keybindings"]] },
646 { group: "settings", items: [["Keybindings", "General"]] },
647 ],
648 (terms, options) => scoreSearchTerms("keybindngs", terms, options),
649 );
650 expect(groups.map(({ group }) => group)).toEqual(["settings"]);
651 expect(scoreSearchTerms("duckdb", ["Search engine", "duckduckgo"], { typos: true })).toBeNull();
652 expect(scoreSearchTerms("rust", ["GitHub sharing", "trusted"])).toBeNull();
653 // Filler words do not make a short query long enough for keyword prefixes.
654 expect(scoreSearchTerms("the ci", ["Context window indicator", "circle"])).toBeNull();
655 });
656
657 it("lists a thread named for the query above a command with it as a keyword", () => {
658 const rank = (command: string[], subject: ThreadSearchSubject) =>
659 rankSearchGroups<string, string[] | ThreadSearchSubject, SearchTermsMatch>(
660 [
661 { group: "actions", items: [command] },
662 { group: "threads", items: [subject] },
663 ],
664 (item, options) => {
665 if (Array.isArray(item)) return scoreSearchTerms("mcp", item, options);
666 return scoreThreadSearch("mcp", item, NOW, options);
667 },
668 ).map(({ group }) => group);
669 const named = thread("Trim MCP model lists");
670 const picked = thread("Trim MCP model lists", {
671 opens: { openedAt: NOW, score: 1, picks: [{ query: "mcp", at: NOW }] },
672 });
673 expect(rank(["Restart agent session", "reload", "mcp"], named)).toEqual(["threads", "actions"]);
674 // A command named for the query stays first; a pick reorders threads but
675 // never moves their group, so one pick for "mcp" does not pass the command.
676 expect(rank(["Reload MCP servers"], named)).toEqual(["actions", "threads"]);
677 expect(rank(["Reload MCP servers"], picked)).toEqual(["actions", "threads"]);
678 });
679});
680
681describe("recordThreadOpen", () => {
682 it("decays the open count, merges quick reopens, and keeps the latest picked queries", () => {
683 const first = recordThreadOpen(null, NOW, " Upl ");
684 expect(first).toEqual({ openedAt: NOW, score: 1, picks: [{ query: "upl", at: NOW }] });
685 const reopened = recordThreadOpen(first, NOW + 60_000, "uploadthing");
686 expect(reopened).toEqual({
687 openedAt: NOW,
688 score: 1,
689 picks: [
690 { query: "uploadthing", at: NOW + 60_000 },
691 { query: "upl", at: NOW },
692 ],
693 });
694 const later = recordThreadOpen(reopened, NOW + SEARCH_RECENCY_HALF_LIFE_MS, "x".repeat(50));
695 expect(later.score).toBe(1.5);
696 expect(later.picks.map((pick) => pick.query)).toEqual(["x".repeat(32), "uploadthing", "upl"]);
697 const repicked = recordThreadOpen(later, later.openedAt + DAY, "upl");
698 expect(repicked.picks).toEqual([
699 { query: "upl", at: later.openedAt + DAY },
700 { query: "x".repeat(32), at: later.openedAt },
701 { query: "uploadthing", at: NOW + 60_000 },
702 ]);
703 });
704
705 it("drops picks that no longer count when the thread is opened again", () => {
706 const opens = {
707 openedAt: NOW - 30 * DAY,
708 score: 1,
709 picks: [{ query: "old", at: NOW - 30 * DAY }],
710 };
711 expect(recordThreadOpen(opens, NOW, "new").picks).toEqual([{ query: "new", at: NOW }]);
712 });
713
714 it("does not renew a query's pick when the thread is picked for another one", () => {
715 const deploy = [
716 thread("Deploy notes", {
717 opens: {
718 openedAt: NOW,
719 score: 2,
720 picks: [
721 { query: "scripts", at: NOW },
722 { query: "deploy", at: NOW - 60 * DAY },
723 ],
724 },
725 }),
726 thread("Deploy timeout", {
727 opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "deploy", at: NOW - DAY }] },
728 }),
729 ];
730 expect(rankTitles("deploy", deploy)).toEqual(["Deploy timeout", "Deploy notes"]);
731 });
732});
733
734describe("findSearchTokenRanges", () => {
735 it("maps folded matches back to the source text and skips short tokens", () => {
736 const text = "Le Café résumé ci";
737 expect(findSearchTokenRanges(text, "CAFE resume ci")).toEqual([
738 { start: 3, end: 7 },
739 { start: 8, end: 14 },
740 ]);
741 });
742
743 it("highlights a three-letter token only where it starts a word", () => {
744 expect(findSearchTokenRanges("drafts, enableFTS", "fts")).toEqual([{ start: 14, end: 17 }]);
745 expect(findSearchTokenRanges("Open handlers.ts", ".ts")).toEqual([{ start: 13, end: 16 }]);
746 });
747
748 it("highlights a query in double quotes only where its words are together", () => {
749 expect(
750 findSearchTokenRanges("files, then the Missing osprey files", '"missing osprey files"'),
751 ).toEqual([{ start: 16, end: 37 }]);
752 expect(findSearchTokenRanges("models and the model", '"model"')).toEqual([
753 { start: 15, end: 20 },
754 ]);
755 });
756});
757
758describe("scoreMessageMatch", () => {
759 it("needs short words at a word start and ranks other words found inside words lower", () => {
760 const text = `Saved the drafts. ${"More notes. ".repeat(40)}Then enableFTS and Enable FTS.`;
761 const fts = scoreMessageMatch(text, "fts");
762 expect(fts?.quality).toBe(1);
763 expect(text.slice(fts?.offset)).toMatch(/^FTS and/);
764 expect(scoreMessageMatch("saved two drafts", "fts")).toBeNull();
765 expect(scoreMessageMatch("We trust the build", "rust")).toEqual({ quality: 0.3, offset: 4 });
766 expect(scoreMessageMatch("Rust and trust", "rust")).toEqual({ quality: 1, offset: 0 });
767 expect(scoreMessageMatch("Use the sidebar", '"sidebar"')).toEqual({ quality: 1, offset: 8 });
768 for (const [text, query, expected] of [
769 ["model mode mode", "mode", { quality: 1, offset: 6 }],
770 ["xmode model models", "mode", { quality: 0.8, offset: 6 }],
771 ["model models", "mode", { quality: 0.8, offset: 0 }],
772 ["xmode ymode", "mode", { quality: 0.3, offset: 1 }],
773 ["mode mode", "mode", { quality: 1, offset: 0 }],
774 ["fts fts", "fts", { quality: 1, offset: 0 }],
775 ["the theme", "he", null],
776 ["he theme", "he", { quality: 1, offset: 0 }],
777 ["notes", "", { quality: 1, offset: 0 }],
778 ["", "notes", null],
779 ["same same same", "same same", { quality: 1.25, offset: 0 }],
780 ["7cafe52bb8 cafe cafe", "cafe", { quality: 1, offset: 11 }],
781 ["7cafe52bb8 7cafe52bb8", "7cafe52", { quality: 1, offset: 0 }],
782 ["明天部署部署到生产环境", "部署", { quality: 1, offset: 2 }],
783 ["gannet’s gannet's", "gannet's", { quality: 1, offset: 9 }],
784 ["gannet's gannet’s", "gannet’s", { quality: 1, offset: 0 }],
785 // In double quotes, only the words together as typed, as whole words.
786 ["the missing osprey files", '"missing osprey files"', { quality: 1.25, offset: 4 }],
787 ["Missing osprey\n files", "“missing osprey files”", { quality: 1.25, offset: 0 }],
788 ["missing the osprey files", '"missing osprey files"', null],
789 ["osprey files missing", '"missing osprey files"', null],
790 // No further apart than the server's index reads.
791 [`missing${" ".repeat(17)}osprey files`, '"missing osprey files"', null],
792 // Whole words by the rule single words follow.
793 ["quickFix JSONSchema", '"fix JSON"', { quality: 1.25, offset: 5 }],
794 // Past a place where the phrase only starts a longer word, emoji first or not.
795 ["🚀 launching, then 🚀 launch", '"🚀 launch"', { quality: 1.25, offset: 19 }],
796 ["changed file", '"file"', { quality: 1, offset: 8 }],
797 ["changed files", '"file"', null],
798 ] as const) {
799 expect(scoreMessageMatch(text, query), `${query} in ${text}`).toEqual(expected);
800 }
801 // Words written together as typed rank above the same words apart, and
802 // the snippet starts where they are together.
803 const together = "Run the tests, then vp run dev to check";
804 expect(scoreMessageMatch(together, "vp run dev")).toEqual({
805 quality: 1.25,
806 offset: together.indexOf("vp run dev"),
807 });
808 // Near each other ranks above far apart.
809 expect(scoreMessageMatch("dev notes: vp is slow, run it", "vp run dev")?.quality).toBe(1.1);
810 const far = `run the tests. ${"More notes. ".repeat(10)}Then dev mode, then vp`;
811 expect(scoreMessageMatch(far, "vp run dev")?.quality).toBe(1);
812 expect(scoreMessageMatch("I don\u2019t know why", "don't know")?.quality).toBe(1.25);
813 expect(scoreMessageMatch("Le Café open late", "cafe open")?.quality).toBe(1.25);
814 expect(scoreMessageMatch("The cafe open late", "café open")?.quality).toBe(1.25);
815 // The snippet starts where the words meet, not at an early one.
816 const phrase = `The plan. ${"More notes. ".repeat(10)}Since the last fix, the sidebar works`;
817 expect(scoreMessageMatch(phrase, "fix the sidebar")?.offset).toBe(phrase.indexOf("fix,"));
818 const apart = `The lakebed app. ${"Notes. ".repeat(30)}Lakebed page perf is slow`;
819 expect(apart.slice(scoreMessageMatch(apart, "lakebed perf")?.offset)).toMatch(/^Lakebed page/);
820 // Only where a word counts: not "fix" in "prefix".
821 const prefix = `fix ${"unrelated words ".repeat(40)}prefix has CI`;
822 expect(scoreMessageMatch(prefix, "fix ci")?.offset).toBe(0);
823 // A commit SHA is one word: "cafe" inside one does not match, its start does.
824 expect(scoreMessageMatch("see commit 7cafe52bb8", "cafe")).toBeNull();
825 expect(scoreMessageMatch("see commit 7cafe52bb8", "7cafe52")).toEqual({
826 quality: 1,
827 offset: 11,
828 });
829 expect(scoreMessageMatch("7cafe52bb8, then the cafe", "cafe")?.quality).toBe(1);
830 // A whole word beats a word prefix: "mode" prefers "mode" over "model".
831 expect(scoreMessageMatch("model settings", "mode")?.quality).toBe(0.8);
832 expect(scoreMessageMatch("The model and the mode switch", "mode")).toEqual({
833 quality: 1,
834 offset: 18,
835 });
836 expect(scoreMessageMatch("v12rc build", "rc")?.quality).toBe(1);
837 expect(scoreMessageMatch("Fix the CLIAdapter state", "ada")?.quality).toBe(0.8);
838 // Words too short for the index must start a word too.
839 expect(scoreMessageMatch("Switch off the connection", "switch on")).toBeNull();
840 expect(scoreMessageMatch("Upgrade pnpm 512 today", "pnpm 12")).toBeNull();
841 expect(scoreMessageMatch("Upgrade to pnpm12 today", "pnpm 12")?.quality).toBe(1);
842 // A word too short to search only narrows, so typing the next word
843 // ("nvme s") does not reorder results; written together still counts.
844 expect(scoreMessageMatch("Fix circle rendering", "fix ci")?.quality).toBe(1);
845 expect(scoreMessageMatch("Fix CI failures", "fix ci")?.quality).toBe(1.25);
846 expect(scoreMessageMatch("Upgrade pnpm 123 today", "pnpm 12")?.quality).toBe(1);
847 expect(scoreMessageMatch("Rename the file to index.ts", ".ts")?.quality).toBe(1);
848 });
849
850 it("finds words through case and accents, also after the same letters inside a word", () => {
851 expect(scoreMessageMatch("This addresses Résumé indexing", "res")).toMatchObject({
852 offset: 15,
853 });
854 expect(scoreMessageMatch("Le CAFÉ ouvert", "cafe")).toMatchObject({ quality: 1, offset: 3 });
855 // An accented whole word beats a plain prefix earlier on.
856 expect(scoreMessageMatch("The cafeteria, then the Café", "cafe")).toMatchObject({
857 quality: 1,
858 offset: 24,
859 });
860 expect(scoreMessageMatch("I presume this. Résumé indexing", "resume")).toMatchObject({
861 quality: 1,
862 offset: 16,
863 });
864 expect(scoreMessageMatch("明天部署到生产环境", "部署")).toMatchObject({ offset: 2 });
865 // Vietnamese and combining accents fold too.
866 expect(scoreMessageMatch("Properties: tiếng Việt support", "tie")).toMatchObject({
867 offset: 12,
868 });
869 expect(scoreMessageMatch("Properties: tie\u0301ng support", "tie")).toMatchObject({
870 offset: 12,
871 });
872 // A letter that grows when lowercased does not shift later offsets.
873 expect(scoreMessageMatch("İ Enable fts and model", "fts")).toMatchObject({ offset: 9 });
874 expect(scoreMessageMatch("İ Enable fts and model", "model")?.quality).toBe(1);
875 expect(scoreMessageMatch("Trip to İstanbul", "İstanbul")).toEqual({ quality: 1, offset: 8 });
876 for (const [text, query, expected] of [
877 ["İ cafeteria Café CAFÉ", "cafe", { quality: 1, offset: 12 }],
878 ["Café cafe", "cafe", { quality: 1, offset: 5 }],
879 ["İ Café Café", "café", { quality: 1, offset: 2 }],
880 ["İ Résumé Résumé", "resume", { quality: 1, offset: 2 }],
881 ["İ résuméprefix résumé", "resume", { quality: 1, offset: 15 }],
882 ] as const) {
883 expect(scoreMessageMatch(text, query), `${query} in ${text}`).toEqual(expected);
884 }
885 });
886});