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

paletteSearch.test.ts

769 lines33.6 KB

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