The best way to control Claude Code, Codex and more from any computer or phone

main
ts 817 lines 35.6 KB
Raw
1 import { describe, expect, it } from "vite-plus/test";
2
3 import {
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
19 const NOW = Date.UTC(2026, 9, 23);
20 const scoreMessageMatch = (text: string, query: string) => messageMatcher(query)(text);
21 const DAY = 24 * 60 * 60 * 1000;
22
23 function thread(title: string, overrides: Partial<ThreadSearchSubject> = {}): ThreadSearchSubject {
24 return { title, activityAt: NOW - 30 * DAY, ...overrides };
25 }
26
27 function 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
34 describe("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
285 describe("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
296 describe("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("stores picked queries without splitting an emoji", () => {
394 expect(pickedQuery(`${"a".repeat(31)}🚀`)).toBe("a".repeat(31));
395 expect(pickedQuery(" Upl ")).toBe("upl");
396 // Folded before it is cut, as stored and as compared.
397 const spaced = "investigate workspace thread reset bug";
398 expect(pickedQuery(spaced)).toBe(pickedQuery(foldSearchQuery(spaced)));
399 });
400
401 it("matches emoji in titles", () => {
402 expect(rankTitles("🚀", [thread("🚀 Launch checklist"), thread("Launch notes")])).toEqual([
403 "🚀 Launch checklist",
404 ]);
405 });
406
407 it("treats each Chinese or Japanese character as a word start", () => {
408 expect(scoreThreadSearch("搜索", thread("实现全文搜索"), NOW)).not.toBeNull();
409 expect(scoreThreadSearch("検索", thread("新しい検索機能"), NOW)).not.toBeNull();
410 });
411 });
412
413 describe("scoreThreadSearch with heavy use and loose input", () => {
414 it("keeps a whole word on a quiet thread above a mid-word hit on a thread opened daily", () => {
415 let opens = recordThreadOpen(null, NOW - 60 * DAY, undefined);
416 for (let day = 59; day >= 1; day--) opens = recordThreadOpen(opens, NOW - day * DAY, undefined);
417 expect(
418 rankTitles("auth", [
419 thread("Fix oauth redirect", { activityAt: NOW, opens }),
420 thread("Share auth across worktrees", { activityAt: NOW - 90 * DAY }),
421 ]),
422 ).toEqual(["Share auth across worktrees", "Fix oauth redirect"]);
423 });
424
425 it("reads a word and the start of the next typed together, highlighting each part", () => {
426 const threads = [thread("Fix sidebar lag"), thread("Unrelated work")];
427 expect(rankTitles("fixsid", threads)).toEqual(["Fix sidebar lag"]);
428 // A later "F" can start the run.
429 expect(rankTitles("fixsid", [thread("Feature: Fix sidebar lag")])).toEqual([
430 "Feature: Fix sidebar lag",
431 ]);
432 expect(scoreThreadSearch("fixsid", threads[0]!, NOW)?.ranges).toEqual([
433 { start: 0, end: 3 },
434 { start: 4, end: 7 },
435 ]);
436 // Initials are not words typed together.
437 expect(rankTitles("fsl", threads)).toEqual([]);
438 });
439
440 it("finds nothing rather than an unrelated thread when no word matches", () => {
441 const threads = [
442 thread("Projectless threads without Git"),
443 thread("Concern about connection setup"),
444 thread("Simplify worktree thread creation"),
445 thread("Start a new conversation"),
446 thread("Setting up the sentinel"),
447 thread("I plan to open source all of lakebed in the next few weeks"),
448 thread("Design notes"),
449 thread("Link pull request to thread"),
450 ];
451 for (const query of ["posthog", "cron", "stripe", "gpu", "fxsb", "lint", "deno"]) {
452 expect(rankTitles(query, threads), query).toEqual([]);
453 }
454 });
455
456 it("matches pieces of references that hold a number, and environment names", () => {
457 const subject = thread("Trim model lists", {
458 id: "thread-5fe6f59c-4976",
459 environmentLabel: "BeeBox",
460 pullRequests: [
461 {
462 number: 22889,
463 references: ["pingdotgg/t3code#22889", "https://github.com/pingdotgg/t3code/pull/22889"],
464 },
465 ],
466 });
467 for (const query of [
468 "t3code#22889",
469 "github.com/pingdotgg/t3code/pull/22889",
470 "https://github.com/pingdotgg/t3code/pull/22889/files",
471 "5fe6f59c",
472 "beebox",
473 ]) {
474 expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW), query).not.toBeNull();
475 }
476 expect(scoreThreadSearch("github.com", subject, NOW)).toBeNull();
477 // A number is never cut short.
478 for (const query of ["github.com/pingdotgg/t3code/pull/2288", "t3code#2288"]) {
479 expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW), query).toBeNull();
480 }
481 });
482 });
483
484 describe("rankMessageMatches", () => {
485 it("merges environments by word match, then picks, then quality and use", () => {
486 const subjects = new Map([
487 ["a-word", thread("A word")],
488 ["a-word-2", thread("A word too")],
489 ["b-prefix", thread("B prefix")],
490 ["b-recent", thread("B recent", { activityAt: NOW })],
491 [
492 "b-picked",
493 thread("B picked", {
494 opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "needle", at: NOW - DAY }] },
495 }),
496 ],
497 ]);
498 // Environment A sent two whole words, environment B a prefix and two more.
499 const matches = [
500 { key: "a-word", quality: 1 },
501 { key: "a-word-2", quality: 1 },
502 { key: "b-prefix", quality: 0.8 },
503 { key: "b-recent", quality: 1 },
504 { key: "b-picked", quality: 0.8 },
505 ];
506 expect(
507 rankMessageMatches(matches, (match) => subjects.get(match.key), "needle", NOW).map(
508 (match) => match.key,
509 ),
510 ).toEqual(["b-picked", "b-recent", "a-word", "a-word-2", "b-prefix"]);
511 // A palette lists title matches above, so they use up no message rows.
512 const titled = new Map([...subjects, ["c-titled", thread("Needle cleanup")]]);
513 expect(
514 rankMessageMatches(
515 [{ key: "c-titled", quality: 1 }, ...matches],
516 (match) => titled.get(match.key),
517 "needle",
518 NOW,
519 { withoutTitleMatches: true },
520 ).map((match) => match.key),
521 ).not.toContain("c-titled");
522 });
523
524 it("ranks a thread that keeps using the word above a passing mention of equal quality", () => {
525 // The real case: 21 hits seven weeks back against one this week, opened today.
526 const subjects = new Map([
527 [
528 "mention",
529 thread("Mention", {
530 activityAt: NOW - 3 * DAY,
531 opens: { openedAt: NOW, score: 1, picks: [] },
532 }),
533 ],
534 ["about", thread("About it", { activityAt: NOW - 48 * DAY })],
535 ]);
536 const matches = [
537 { key: "mention", quality: 1, hits: 1 },
538 { key: "about", quality: 1, hits: 21 },
539 ];
540 expect(
541 rankMessageMatches(matches, (match) => subjects.get(match.key), "tailscale", NOW).map(
542 (match) => match.key,
543 ),
544 ).toEqual(["about", "mention"]);
545 });
546
547 it("keeps matches inside words below word matches, however used", () => {
548 const busy = thread("Busy", {
549 activityAt: NOW,
550 opens: { openedAt: NOW, score: 20, picks: [] },
551 });
552 const matches = [
553 { key: "busy", quality: 0.3 },
554 { key: "quiet", quality: 1 },
555 ];
556 const subjects = new Map([
557 ["busy", busy],
558 ["quiet", thread("Quiet")],
559 ]);
560 expect(
561 rankMessageMatches(matches, (match) => subjects.get(match.key), "rust", NOW).map(
562 (match) => match.key,
563 ),
564 ).toEqual(["quiet", "busy"]);
565 });
566 });
567
568 describe("rankSearchGroups", () => {
569 it("orders groups by their best match and keeps the given order on ties", () => {
570 const groups = rankSearchGroups(
571 [
572 { group: "actions", items: ["Open settings", "New thread"] },
573 { group: "threads", items: ["Settings sync rewrite", "Thread settings"] },
574 { group: "projects", items: ["Settings app"] },
575 ],
576 (item, options) => scoreSearchTerms("settings", [item], options),
577 );
578 expect(groups.map(({ group, ranked }) => [group, ranked.map(({ item }) => item)])).toEqual([
579 ["actions", ["Open settings"]],
580 ["threads", ["Settings sync rewrite", "Thread settings"]],
581 ["projects", ["Settings app"]],
582 ]);
583 });
584 });
585
586 describe("rankSearchGroups with keywords and picks", () => {
587 it("matches inside a word only in thread titles", () => {
588 expect(scoreSearchTerms("arch", ["Search project contents"])).toBeNull();
589 expect(
590 scoreThreadSearch("arch", thread("Notes", { branch: "research-extension-system" }), NOW),
591 ).toBeNull();
592 expect(scoreThreadSearch("arch", thread("Research notes"), NOW)?.quality).toBe(0.3);
593 });
594
595 it("forgives typos in names but not in hidden keywords", () => {
596 const groups = rankSearchGroups(
597 [
598 { group: "actions", items: [["Open settings", "preferences", "keybindings"]] },
599 { group: "settings", items: [["Keybindings", "General"]] },
600 ],
601 (terms, options) => scoreSearchTerms("keybindngs", terms, options),
602 );
603 expect(groups.map(({ group }) => group)).toEqual(["settings"]);
604 expect(scoreSearchTerms("duckdb", ["Search engine", "duckduckgo"], { typos: true })).toBeNull();
605 expect(scoreSearchTerms("rust", ["GitHub sharing", "trusted"])).toBeNull();
606 // Filler words do not make a short query long enough for keyword prefixes.
607 expect(scoreSearchTerms("the ci", ["Context window indicator", "circle"])).toBeNull();
608 });
609
610 it("lists a thread named for the query above a command with it as a keyword", () => {
611 const rank = (command: string[], subject: ThreadSearchSubject) =>
612 rankSearchGroups<string, string[] | ThreadSearchSubject, SearchTermsMatch>(
613 [
614 { group: "actions", items: [command] },
615 { group: "threads", items: [subject] },
616 ],
617 (item, options) => {
618 if (Array.isArray(item)) return scoreSearchTerms("mcp", item, options);
619 return scoreThreadSearch("mcp", item, NOW, options);
620 },
621 ).map(({ group }) => group);
622 const named = thread("Trim MCP model lists");
623 const picked = thread("Trim MCP model lists", {
624 opens: { openedAt: NOW, score: 1, picks: [{ query: "mcp", at: NOW }] },
625 });
626 expect(rank(["Restart agent session", "reload", "mcp"], named)).toEqual(["threads", "actions"]);
627 // A command named for the query stays first; a pick reorders threads but
628 // never moves their group, so one pick for "mcp" does not pass the command.
629 expect(rank(["Reload MCP servers"], named)).toEqual(["actions", "threads"]);
630 expect(rank(["Reload MCP servers"], picked)).toEqual(["actions", "threads"]);
631 });
632 });
633
634 describe("recordThreadOpen", () => {
635 it("decays the open count, merges quick reopens, and keeps the latest picked queries", () => {
636 const first = recordThreadOpen(null, NOW, " Upl ");
637 expect(first).toEqual({ openedAt: NOW, score: 1, picks: [{ query: "upl", at: NOW }] });
638 const reopened = recordThreadOpen(first, NOW + 60_000, "uploadthing");
639 expect(reopened).toEqual({
640 openedAt: NOW,
641 score: 1,
642 picks: [
643 { query: "uploadthing", at: NOW + 60_000 },
644 { query: "upl", at: NOW },
645 ],
646 });
647 const later = recordThreadOpen(reopened, NOW + SEARCH_RECENCY_HALF_LIFE_MS, "x".repeat(50));
648 expect(later.score).toBe(1.5);
649 expect(later.picks.map((pick) => pick.query)).toEqual(["x".repeat(32), "uploadthing", "upl"]);
650 const repicked = recordThreadOpen(later, later.openedAt + DAY, "upl");
651 expect(repicked.picks).toEqual([
652 { query: "upl", at: later.openedAt + DAY },
653 { query: "x".repeat(32), at: later.openedAt },
654 { query: "uploadthing", at: NOW + 60_000 },
655 ]);
656 });
657
658 it("drops picks that no longer count when the thread is opened again", () => {
659 const opens = {
660 openedAt: NOW - 30 * DAY,
661 score: 1,
662 picks: [{ query: "old", at: NOW - 30 * DAY }],
663 };
664 expect(recordThreadOpen(opens, NOW, "new").picks).toEqual([{ query: "new", at: NOW }]);
665 });
666
667 it("does not renew a query's pick when the thread is picked for another one", () => {
668 const deploy = [
669 thread("Deploy notes", {
670 opens: {
671 openedAt: NOW,
672 score: 2,
673 picks: [
674 { query: "scripts", at: NOW },
675 { query: "deploy", at: NOW - 60 * DAY },
676 ],
677 },
678 }),
679 thread("Deploy timeout", {
680 opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "deploy", at: NOW - DAY }] },
681 }),
682 ];
683 expect(rankTitles("deploy", deploy)).toEqual(["Deploy timeout", "Deploy notes"]);
684 });
685 });
686
687 describe("findSearchTokenRanges", () => {
688 it("maps folded matches back to the source text and skips short tokens", () => {
689 const text = "Le Café résumé ci";
690 expect(findSearchTokenRanges(text, "CAFE resume ci")).toEqual([
691 { start: 3, end: 7 },
692 { start: 8, end: 14 },
693 ]);
694 });
695
696 it("highlights a three-letter token only where it starts a word", () => {
697 expect(findSearchTokenRanges("drafts, enableFTS", "fts")).toEqual([{ start: 14, end: 17 }]);
698 expect(findSearchTokenRanges("Open handlers.ts", ".ts")).toEqual([{ start: 13, end: 16 }]);
699 });
700 });
701
702 describe("scoreMessageMatch", () => {
703 it("needs short words at a word start and ranks other words found inside words lower", () => {
704 const text = `Saved the drafts. ${"More notes. ".repeat(40)}Then enableFTS and Enable FTS.`;
705 const fts = scoreMessageMatch(text, "fts");
706 expect(fts?.quality).toBe(1);
707 expect(text.slice(fts?.offset)).toMatch(/^FTS and/);
708 expect(scoreMessageMatch("saved two drafts", "fts")).toBeNull();
709 expect(scoreMessageMatch("We trust the build", "rust")).toEqual({ quality: 0.3, offset: 4 });
710 expect(scoreMessageMatch("Rust and trust", "rust")).toEqual({ quality: 1, offset: 0 });
711 expect(scoreMessageMatch("Use the sidebar", '"sidebar"')).toEqual({ quality: 1, offset: 8 });
712 for (const [text, query, expected] of [
713 ["model mode mode", "mode", { quality: 1, offset: 6 }],
714 ["xmode model models", "mode", { quality: 0.8, offset: 6 }],
715 ["model models", "mode", { quality: 0.8, offset: 0 }],
716 ["xmode ymode", "mode", { quality: 0.3, offset: 1 }],
717 ["mode mode", "mode", { quality: 1, offset: 0 }],
718 ["fts fts", "fts", { quality: 1, offset: 0 }],
719 ["the theme", "he", null],
720 ["he theme", "he", { quality: 1, offset: 0 }],
721 ["notes", "", { quality: 1, offset: 0 }],
722 ["", "notes", null],
723 ["same same same", "same same", { quality: 1.25, offset: 0 }],
724 ["7cafe52bb8 cafe cafe", "cafe", { quality: 1, offset: 11 }],
725 ["7cafe52bb8 7cafe52bb8", "7cafe52", { quality: 1, offset: 0 }],
726 ["明天部署部署到生产环境", "部署", { quality: 1, offset: 2 }],
727 ["gannet’s gannet's", "gannet's", { quality: 1, offset: 9 }],
728 ["gannet's gannet’s", "gannet’s", { quality: 1, offset: 0 }],
729 ] as const) {
730 expect(scoreMessageMatch(text, query), `${query} in ${text}`).toEqual(expected);
731 }
732 // Words written together as typed rank above the same words apart, and
733 // the snippet starts where they are together.
734 const together = "Run the tests, then vp run dev to check";
735 expect(scoreMessageMatch(together, "vp run dev")).toEqual({
736 quality: 1.25,
737 offset: together.indexOf("vp run dev"),
738 });
739 // Near each other ranks above far apart.
740 expect(scoreMessageMatch("dev notes: vp is slow, run it", "vp run dev")?.quality).toBe(1.1);
741 const far = `run the tests. ${"More notes. ".repeat(10)}Then dev mode, then vp`;
742 expect(scoreMessageMatch(far, "vp run dev")?.quality).toBe(1);
743 expect(scoreMessageMatch("I don\u2019t know why", "don't know")?.quality).toBe(1.25);
744 expect(scoreMessageMatch("Le Café open late", "cafe open")?.quality).toBe(1.25);
745 expect(scoreMessageMatch("The cafe open late", "café open")?.quality).toBe(1.25);
746 // The snippet starts where the words meet, not at an early one.
747 const phrase = `The plan. ${"More notes. ".repeat(10)}Since the last fix, the sidebar works`;
748 expect(scoreMessageMatch(phrase, "fix the sidebar")?.offset).toBe(phrase.indexOf("fix,"));
749 const apart = `The lakebed app. ${"Notes. ".repeat(30)}Lakebed page perf is slow`;
750 expect(apart.slice(scoreMessageMatch(apart, "lakebed perf")?.offset)).toMatch(/^Lakebed page/);
751 // Only where a word counts: not "fix" in "prefix".
752 const prefix = `fix ${"unrelated words ".repeat(40)}prefix has CI`;
753 expect(scoreMessageMatch(prefix, "fix ci")?.offset).toBe(0);
754 // A commit SHA is one word: "cafe" inside one does not match, its start does.
755 expect(scoreMessageMatch("see commit 7cafe52bb8", "cafe")).toBeNull();
756 expect(scoreMessageMatch("see commit 7cafe52bb8", "7cafe52")).toEqual({
757 quality: 1,
758 offset: 11,
759 });
760 expect(scoreMessageMatch("7cafe52bb8, then the cafe", "cafe")?.quality).toBe(1);
761 // A whole word beats a word prefix: "mode" prefers "mode" over "model".
762 expect(scoreMessageMatch("model settings", "mode")?.quality).toBe(0.8);
763 expect(scoreMessageMatch("The model and the mode switch", "mode")).toEqual({
764 quality: 1,
765 offset: 18,
766 });
767 expect(scoreMessageMatch("v12rc build", "rc")?.quality).toBe(1);
768 expect(scoreMessageMatch("Fix the CLIAdapter state", "ada")?.quality).toBe(0.8);
769 // Words too short for the index must start a word too.
770 expect(scoreMessageMatch("Switch off the connection", "switch on")).toBeNull();
771 expect(scoreMessageMatch("Upgrade pnpm 512 today", "pnpm 12")).toBeNull();
772 expect(scoreMessageMatch("Upgrade to pnpm12 today", "pnpm 12")?.quality).toBe(1);
773 // A word too short to search only narrows, so typing the next word
774 // ("nvme s") does not reorder results; written together still counts.
775 expect(scoreMessageMatch("Fix circle rendering", "fix ci")?.quality).toBe(1);
776 expect(scoreMessageMatch("Fix CI failures", "fix ci")?.quality).toBe(1.25);
777 expect(scoreMessageMatch("Upgrade pnpm 123 today", "pnpm 12")?.quality).toBe(1);
778 expect(scoreMessageMatch("Rename the file to index.ts", ".ts")?.quality).toBe(1);
779 });
780
781 it("finds words through case and accents, also after the same letters inside a word", () => {
782 expect(scoreMessageMatch("This addresses Résumé indexing", "res")).toMatchObject({
783 offset: 15,
784 });
785 expect(scoreMessageMatch("Le CAFÉ ouvert", "cafe")).toMatchObject({ quality: 1, offset: 3 });
786 // An accented whole word beats a plain prefix earlier on.
787 expect(scoreMessageMatch("The cafeteria, then the Café", "cafe")).toMatchObject({
788 quality: 1,
789 offset: 24,
790 });
791 expect(scoreMessageMatch("I presume this. Résumé indexing", "resume")).toMatchObject({
792 quality: 1,
793 offset: 16,
794 });
795 expect(scoreMessageMatch("明天部署到生产环境", "部署")).toMatchObject({ offset: 2 });
796 // Vietnamese and combining accents fold too.
797 expect(scoreMessageMatch("Properties: tiếng Việt support", "tie")).toMatchObject({
798 offset: 12,
799 });
800 expect(scoreMessageMatch("Properties: tie\u0301ng support", "tie")).toMatchObject({
801 offset: 12,
802 });
803 // A letter that grows when lowercased does not shift later offsets.
804 expect(scoreMessageMatch("İ Enable fts and model", "fts")).toMatchObject({ offset: 9 });
805 expect(scoreMessageMatch("İ Enable fts and model", "model")?.quality).toBe(1);
806 expect(scoreMessageMatch("Trip to İstanbul", "İstanbul")).toEqual({ quality: 1, offset: 8 });
807 for (const [text, query, expected] of [
808 ["İ cafeteria Café CAFÉ", "cafe", { quality: 1, offset: 12 }],
809 ["Café cafe", "cafe", { quality: 1, offset: 5 }],
810 ["İ Café Café", "café", { quality: 1, offset: 2 }],
811 ["İ Résumé Résumé", "resume", { quality: 1, offset: 2 }],
812 ["İ résuméprefix résumé", "resume", { quality: 1, offset: 15 }],
813 ] as const) {
814 expect(scoreMessageMatch(text, query), `${query} in ${text}`).toEqual(expected);
815 }
816 });
817 });