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

CommandPalette.logic.test.ts

1,025 lines32.5 KB

1import { describe, expect, it, vi } from "vite-plus/test";
2import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
3import type { Project, Thread } from "../types";
4import { makeThreadFixture } from "../test-fixtures";
5import {
6 buildBrowseGroups,
7 buildCommandPaletteProjectMetadata,
8 buildCommandPaletteRows,
9 buildProjectActionItems,
10 buildThreadActionItems,
11 buildLinkedThreadActionItems,
12 enumerateCommandPaletteItems,
13 filterPinnedBrowseEntries,
14 filterCommandPaletteGroups,
15 findHighlightedCommandPaletteItem,
16 reduceCommandPaletteUiState,
17 createCommandPaletteSearchState,
18 reduceCommandPaletteSearchState,
19 type CommandPaletteActionItem,
20 type CommandPaletteGroup,
21 type CommandPaletteUiState,
22} from "./CommandPalette.logic";
23​
24describe("linked pull request thread navigation", () => {
25 it("keeps archived relations searchable and routes them through the PR environment", async () => {
26 const environmentId = EnvironmentId.make("remote");
27 const id = ThreadId.make("archived-thread");
28 const runThread = vi.fn(async () => {});
29 const query = "https://github.com/acme/web/pull/42";
30 const linkedThreads = {
31 environmentId,
32 threads: [
33 {
34 id,
35 projectId: ProjectId.make("project"),
36 title: "Completed work",
37 archivedAt: "2026-09-01T00:00:00.000Z",
38 },
39 ],
40 };
41 const state = reduceCommandPaletteUiState(
42 { open: false, mode: "command", openIntent: null },
43 {
44 _tag: "OpenSearch",
45 query,
46 linkedThreads,
47 },
48 );
49 expect(state.openIntent).toEqual({ kind: "search", query, linkedThreads });
50 const items = buildLinkedThreadActionItems({ ...linkedThreads, query, icon: null, runThread });
51 const groups = filterCommandPaletteGroups({
52 activeGroups: [],
53 query,
54 isInSubmenu: false,
55 projectSearchItems: [],
56 settingsSearchItems: [],
57 threadSearchItems: items,
58 });
59 expect(groups.flatMap((group) => group.items)).toEqual(items);
60 expect(items[0]?.description).toBe("Archived thread");
61 await items[0]?.run();
62 expect(runThread).toHaveBeenCalledWith({ environmentId, id });
63 });
64});
65​
66describe("buildCommandPaletteProjectMetadata", () => {
67 const localEnvironmentId = EnvironmentId.make("environment-local");
68 const remoteEnvironmentId = EnvironmentId.make("environment-build-box");
69 const locations = new Map([
70 [localEnvironmentId, { kind: "local" as const, label: "Local", machine: "laptop" as const }],
71 [
72 remoteEnvironmentId,
73 { kind: "remote" as const, label: "Build box", machine: "server" as const },
74 ],
75 ]);
76​
77 it("makes every member environment and path searchable", () => {
78 const metadata = buildCommandPaletteProjectMetadata({
79 projects: [
80 {
81 environmentId: localEnvironmentId,
82 title: "T3 Code",
83 workspaceRoot: "/Users/theo/Projects/t3code",
84 },
85 {
86 environmentId: remoteEnvironmentId,
87 title: "t3code",
88 workspaceRoot: "/srv/t3code",
89 },
90 ],
91 locationByEnvironmentId: locations,
92 });
93​
94 expect(metadata.searchTerms).toEqual([
95 "T3 Code",
96 "/Users/theo/Projects/t3code",
97 "Local",
98 "t3code",
99 "/srv/t3code",
100 "Build box",
101 ]);
102 expect(metadata.environmentLabels).toEqual(["Local", "Build box"]);
103​
104 const [filteredGroup] = filterCommandPaletteGroups({
105 activeGroups: [],
106 query: "build box",
107 isInSubmenu: false,
108 projectSearchItems: [
109 {
110 kind: "action",
111 value: "project:t3code",
112 title: "T3 Code",
113 searchTerms: metadata.searchTerms,
114 icon: null,
115 run: async () => undefined,
116 },
117 ],
118 threadSearchItems: [],
119 });
120 expect(filteredGroup?.items).toHaveLength(1);
121 });
122​
123 it("deduplicates grouped checkouts by environment", () => {
124 const metadata = buildCommandPaletteProjectMetadata({
125 projects: [
126 {
127 environmentId: remoteEnvironmentId,
128 title: "T3 Code",
129 workspaceRoot: "/srv/t3code",
130 },
131 {
132 environmentId: remoteEnvironmentId,
133 title: "T3 Code worktree",
134 workspaceRoot: "/srv/t3code-feature",
135 },
136 ],
137 locationByEnvironmentId: locations,
138 });
139​
140 expect(metadata.environmentLabels).toEqual(["Build box"]);
141 });
142​
143 it("deduplicates distinct environments with the same label", () => {
144 const secondRemoteEnvironmentId = EnvironmentId.make("environment-build-box-2");
145 const metadata = buildCommandPaletteProjectMetadata({
146 projects: [
147 {
148 environmentId: remoteEnvironmentId,
149 title: "T3 Code",
150 workspaceRoot: "/srv/t3code",
151 },
152 {
153 environmentId: secondRemoteEnvironmentId,
154 title: "T3 Code mirror",
155 workspaceRoot: "/srv/mirror/t3code",
156 },
157 ],
158 locationByEnvironmentId: new Map([
159 [remoteEnvironmentId, { label: "Build box" }],
160 [secondRemoteEnvironmentId, { label: "Build box" }],
161 ]),
162 });
163​
164 expect(metadata.environmentLabels).toEqual(["Build box"]);
165 });
166​
167 it("uses a human-readable fallback when presentation data is unavailable", () => {
168 const metadata = buildCommandPaletteProjectMetadata({
169 projects: [
170 {
171 environmentId: remoteEnvironmentId,
172 title: "T3 Code",
173 workspaceRoot: "/srv/t3code",
174 },
175 ],
176 locationByEnvironmentId: new Map(),
177 });
178​
179 expect(metadata.searchTerms).toContain("Remote");
180 expect(metadata.environmentLabels).toEqual(["Remote"]);
181 });
182});
183​
184describe("reduceCommandPaletteUiState", () => {
185 const closedState = { open: false, mode: "command", openIntent: null } as const;
186​
187 it("toggles each overlay mode open and closed", () => {
188 const filesOpen = reduceCommandPaletteUiState(closedState, {
189 _tag: "ToggleMode",
190 mode: "files",
191 });
192 expect(filesOpen).toEqual({ open: true, mode: "files", openIntent: null });
193​
194 const contentOpen = reduceCommandPaletteUiState(filesOpen, {
195 _tag: "ToggleMode",
196 mode: "content",
197 });
198 expect(contentOpen).toEqual({ open: true, mode: "content", openIntent: null });
199​
200 expect(
201 reduceCommandPaletteUiState(contentOpen, { _tag: "ToggleMode", mode: "content" }),
202 ).toEqual({ open: false, mode: "content", openIntent: null });
203 });
204​
205 it("switches between open modes without closing", () => {
206 const filesOpen = reduceCommandPaletteUiState(closedState, {
207 _tag: "ToggleMode",
208 mode: "files",
209 });
210 expect(reduceCommandPaletteUiState(filesOpen, { _tag: "ToggleMode", mode: "command" })).toEqual(
211 {
212 open: true,
213 mode: "command",
214 openIntent: null,
215 },
216 );
217 });
218​
219 it("opens PR search from another overlay and replaces an earlier search", () => {
220 const first = reduceCommandPaletteUiState(
221 { open: true, mode: "files", openIntent: null },
222 {
223 _tag: "OpenSearch",
224 query: "https://github.com/acme/web/pull/7",
225 },
226 );
227 expect(first).toEqual({
228 open: true,
229 mode: "command",
230 openIntent: { kind: "search", query: "https://github.com/acme/web/pull/7" },
231 });
232 const second = reduceCommandPaletteUiState(first, {
233 _tag: "OpenSearch",
234 query: "https://github.com/acme/web/pull/8",
235 });
236 expect(second.openIntent).toEqual({
237 kind: "search",
238 query: "https://github.com/acme/web/pull/8",
239 });
240 expect(
241 reduceCommandPaletteUiState(second, { _tag: "SetOpen", open: false }).openIntent,
242 ).toBeNull();
243 });
244​
245 it("routes open intents to command mode", () => {
246 const filesOpen = reduceCommandPaletteUiState(closedState, {
247 _tag: "ToggleMode",
248 mode: "files",
249 });
250 expect(reduceCommandPaletteUiState(filesOpen, { _tag: "OpenAddProject" })).toEqual({
251 open: true,
252 mode: "command",
253 openIntent: { kind: "add-project" },
254 });
255 expect(reduceCommandPaletteUiState(filesOpen, { _tag: "OpenNewThreadIn" })).toEqual({
256 open: true,
257 mode: "command",
258 openIntent: { kind: "new-thread-in" },
259 });
260 });
261​
262 it("preserves the mode on close and resets it on open", () => {
263 const filesOpen = reduceCommandPaletteUiState(closedState, {
264 _tag: "ToggleMode",
265 mode: "files",
266 });
267​
268 expect(reduceCommandPaletteUiState(filesOpen, { _tag: "SetOpen", open: false })).toEqual({
269 open: false,
270 mode: "files",
271 openIntent: null,
272 });
273 expect(reduceCommandPaletteUiState(filesOpen, { _tag: "SetOpen", open: true })).toEqual({
274 open: true,
275 mode: "command",
276 openIntent: null,
277 });
278 });
279});
280​
281describe("enumerateCommandPaletteItems", () => {
282 it("assigns positional jump shortcuts to the first nine displayed items", () => {
283 const items = Array.from({ length: 10 }, (_, index) => ({
284 kind: "action" as const,
285 value: `project-${index + 1}`,
286 searchTerms: [],
287 title: `Project ${index + 1}`,
288 icon: null,
289 shortcutCommand: "chat.new" as const,
290 run: async () => undefined,
291 }));
292​
293 expect(enumerateCommandPaletteItems(items).map((item) => item.shortcutCommand)).toEqual([
294 "thread.jump.1",
295 "thread.jump.2",
296 "thread.jump.3",
297 "thread.jump.4",
298 "thread.jump.5",
299 "thread.jump.6",
300 "thread.jump.7",
301 "thread.jump.8",
302 "thread.jump.9",
303 undefined,
304 ]);
305 });
306});
307​
308const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
309const PROJECT_ID = ProjectId.make("project-1");
310​
311function makeProject(overrides: Partial<Project> = {}): Project {
312 return {
313 id: PROJECT_ID,
314 environmentId: LOCAL_ENVIRONMENT_ID,
315 title: "Project",
316 workspaceRoot: "/workspace/project",
317 defaultModelSelection: null,
318 scripts: [],
319 createdAt: "2026-03-01T00:00:00.000Z",
320 updatedAt: "2026-03-01T00:00:00.000Z",
321 ...overrides,
322 };
324​
325function makeThread(overrides: Partial<Thread> = {}): Thread {
326 return makeThreadFixture({
327 id: ThreadId.make("thread-1"),
328 environmentId: LOCAL_ENVIRONMENT_ID,
329 projectId: PROJECT_ID,
330 title: "Thread",
331 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
332 runtimeMode: "full-access",
333 interactionMode: "default",
334 runtime: null,
335 messages: [],
336 proposedPlans: [],
337 createdAt: "2026-03-01T00:00:00.000Z",
338 archivedAt: null,
339 settledOverride: null,
340 settledAt: null,
341 deletedAt: null,
342 updatedAt: "2026-03-01T00:00:00.000Z",
343 latestRun: null,
344 branch: null,
345 worktreePath: null,
346 ...overrides,
347 });
349​
350describe("buildProjectActionItems", () => {
351 it("shows offline checkout rows but excludes them from keyboard selection", () => {
352 const local = makeProject();
353 const remote = makeProject({
354 id: local.id,
355 environmentId: EnvironmentId.make("offline"),
356 });
357 const items = buildProjectActionItems({
358 projects: [remote, local].map((project) => ({ ...project, displayName: "shared-repo" })),
359 valuePrefix: "new-thread-in",
360 icon: () => null,
361 runProject: async () => undefined,
362 disabled: (project) => project.environmentId === remote.environmentId,
363 });
364 const groups = [{ value: "projects", label: "Projects", items }];
365 const { rows, itemValues } = buildCommandPaletteRows(groups);
366​
367 expect(rows.filter((row) => row.kind === "item").map((row) => row.item.value)).toEqual([
368 `new-thread-in:${remote.environmentId}:${remote.id}`,
369 `new-thread-in:${local.environmentId}:${local.id}`,
370 ]);
371 expect(itemValues).toEqual([`new-thread-in:${local.environmentId}:${local.id}`]);
372 expect(findHighlightedCommandPaletteItem(groups, items[0]!.value)).toBeNull();
373 expect(findHighlightedCommandPaletteItem(groups, items[1]!.value)).toBe(items[1]);
374 });
375​
376 it("shows the grouped display name but keeps the real title for icons", () => {
377 const project = makeProject({ title: "fleet", workspaceRoot: "/Users/theo/Code/p/fleet" });
378 const iconTitles: string[] = [];
379 const [item] = buildProjectActionItems({
380 projects: [{ ...project, displayName: "t3dotgg/fleet" }],
381 valuePrefix: "project",
382 icon: (candidate) => {
383 iconTitles.push(candidate.title);
384 return null;
385 },
386 runProject: async () => undefined,
387 });
388​
389 expect(item?.title).toBe("t3dotgg/fleet");
390 expect(item?.searchTerms).toEqual(
391 expect.arrayContaining(["t3dotgg/fleet", "fleet", "/Users/theo/Code/p/fleet"]),
392 );
393 expect(iconTitles).toEqual(["fleet"]);
394 });
395});
396​
397describe("buildThreadActionItems", () => {
398 it("orders threads by most recent activity and formats timestamps from updatedAt", () => {
399 vi.useFakeTimers();
400 vi.setSystemTime(new Date("2026-03-25T12:00:00.000Z"));
401​
402 try {
403 const items = buildThreadActionItems({
404 threads: [
405 makeThread({
406 id: ThreadId.make("thread-older"),
407 title: "Older thread",
408 updatedAt: "2026-03-24T12:00:00.000Z",
409 }),
410 makeThread({
411 id: ThreadId.make("thread-newer"),
412 title: "Newer thread",
413 createdAt: "2026-03-20T00:00:00.000Z",
414 updatedAt: "2026-03-20T00:00:00.000Z",
415 }),
416 ],
417 projectTitleById: new Map([[PROJECT_ID, "Project"]]),
418 sortOrder: "updated_at",
419 icon: null,
420 runThread: async (_thread) => undefined,
421 });
422​
423 expect(items.map((item) => item.value)).toEqual([
424 "thread:thread-older",
425 "thread:thread-newer",
426 ]);
427 expect(items[0]?.timestamp).toBe("1d ago");
428 expect(items[1]?.timestamp).toBe("5d ago");
429 } finally {
430 vi.useRealTimers();
431 }
432 });
433​
434 it("ranks thread title matches ahead of contextual project-name matches", () => {
435 const threadItems = buildThreadActionItems({
436 threads: [
437 makeThread({
438 id: ThreadId.make("thread-context-match"),
439 title: "Fix navbar spacing",
440 updatedAt: "2026-03-20T00:00:00.000Z",
441 }),
442 makeThread({
443 id: ThreadId.make("thread-title-match"),
444 title: "Project kickoff notes",
445 createdAt: "2026-03-02T00:00:00.000Z",
446 updatedAt: "2026-03-19T00:00:00.000Z",
447 }),
448 ],
449 projectTitleById: new Map([[PROJECT_ID, "Project"]]),
450 sortOrder: "updated_at",
451 icon: null,
452 runThread: async (_thread) => undefined,
453 });
454​
455 const groups = filterCommandPaletteGroups({
456 activeGroups: [],
457 query: "project",
458 isInSubmenu: false,
459 projectSearchItems: [],
460 threadSearchItems: threadItems,
461 });
462​
463 expect(groups).toHaveLength(1);
464 expect(groups[0]?.value).toBe("threads-search");
465 expect(groups[0]?.items.map((item) => item.value)).toEqual([
466 "thread:thread-title-match",
467 "thread:thread-context-match",
468 ]);
469 });
470​
471 it("orders title matches by recent activity before older prefix matches", () => {
472 const threads = [
473 makeThread({
474 id: ThreadId.make("old-prefix"),
475 title: "Convex InvalidCursor in Convex threads query",
476 createdAt: "2026-01-01T00:00:00.000Z",
477 updatedAt: "2026-01-02T00:00:00.000Z",
478 }),
479 makeThread({
480 id: ThreadId.make("recent-title"),
481 title: "Disable Convex schema validation",
482 createdAt: "2025-12-01T00:00:00.000Z",
483 updatedAt: "2026-03-24T00:00:00.000Z",
484 }),
485 makeThread({
486 id: ThreadId.make("recent-content"),
487 title: "Fix schema validation",
488 createdAt: "2026-03-25T00:00:00.000Z",
489 updatedAt: "2026-03-25T00:00:00.000Z",
490 }),
491 ];
492 const items = buildThreadActionItems({
493 threads,
494 projectTitleById: new Map([[PROJECT_ID, "T3 Code"]]),
495 sortOrder: "created_at",
496 icon: null,
497 getContentMatch: (thread) =>
498 thread.id === ThreadId.make("recent-content")
499 ? { source: "user", snippet: "Please check Convex", query: "convex" }
500 : undefined,
501 runThread: async () => undefined,
502 });
503​
504 const groups = filterCommandPaletteGroups({
505 activeGroups: [],
506 query: "convex",
507 isInSubmenu: false,
508 projectSearchItems: [],
509 threadSearchItems: items,
510 });
511​
512 expect(groups[0]?.items.map((item) => item.value)).toEqual([
513 "thread:recent-title",
514 "thread:old-prefix",
515 "thread:recent-content",
516 ]);
517 });
518​
519 it("preserves thread project-name matches when there is no stronger title match", () => {
520 const group: CommandPaletteGroup = {
521 value: "threads-search",
522 label: "Threads",
523 items: [
524 {
525 kind: "action",
526 value: "thread:project-context-only",
527 searchTerms: ["Fix navbar spacing", "Project"],
528 title: "Fix navbar spacing",
529 description: "Project",
530 icon: null,
531 run: async () => undefined,
532 },
533 ],
534 };
535​
536 const groups = filterCommandPaletteGroups({
537 activeGroups: [group],
538 query: "project",
539 isInSubmenu: false,
540 projectSearchItems: [],
541 threadSearchItems: [],
542 });
543​
544 expect(groups).toHaveLength(1);
545 expect(groups[0]?.items.map((item) => item.value)).toEqual(["thread:project-context-only"]);
546 });
547​
548 it("ranks an order-independent setting title match above a split context match", () => {
549 const settingsSearchItems = [
550 {
551 kind: "action" as const,
552 value: "setting:context-match",
553 searchTerms: ["Pairing settings", "remote backend"],
554 title: "Context match",
555 icon: null,
556 run: async () => undefined,
557 },
558 {
559 kind: "action" as const,
560 value: "setting:remote-pairing",
561 searchTerms: ["Remote pairing", "connections"],
562 title: "Remote pairing",
563 icon: null,
564 run: async () => undefined,
565 },
566 ];
567​
568 const groups = filterCommandPaletteGroups({
569 activeGroups: [],
570 query: "pairing remote",
571 isInSubmenu: false,
572 projectSearchItems: [],
573 settingsSearchItems,
574 threadSearchItems: [],
575 });
576​
577 expect(groups).toHaveLength(1);
578 expect(groups[0]?.value).toBe("settings-search");
579 expect(groups[0]?.items.map((item) => item.value)).toEqual([
580 "setting:remote-pairing",
581 "setting:context-match",
582 ]);
583 });
584​
585 it("keeps accent-insensitive setting results", () => {
586 const groups = filterCommandPaletteGroups({
587 activeGroups: [],
588 query: "thè\u{1ab0}mes",
589 isInSubmenu: false,
590 projectSearchItems: [],
591 settingsSearchItems: [
592 {
593 kind: "action",
594 value: "setting:theme",
595 searchTerms: ["Themes", "Appearance"],
596 title: "Themes",
597 icon: null,
598 run: async () => undefined,
599 },
600 ],
601 threadSearchItems: [],
602 });
603​
604 expect(groups[0]?.items.map((item) => item.value)).toEqual(["setting:theme"]);
605 });
606​
607 it("normalizes case independently of the host locale", () => {
608 const toLocaleLowerCase = String.prototype.toLocaleLowerCase;
609 const localeLowerCase = vi
610 .spyOn(String.prototype, "toLocaleLowerCase")
611 .mockImplementation(function (this: string) {
612 return toLocaleLowerCase.call(this, "tr");
613 });
614 try {
615 const groups = filterCommandPaletteGroups({
616 activeGroups: [],
617 query: "GIT",
618 isInSubmenu: false,
619 projectSearchItems: [],
620 threadSearchItems: [],
621 settingsSearchItems: [
622 {
623 kind: "action",
624 value: "setting:version-control",
625 title: "Version control",
626 searchTerms: ["git"],
627 icon: null,
628 run: async () => undefined,
629 },
630 ],
631 });
632 expect(groups.flatMap((group) => group.items.map((item) => item.value))).toEqual([
633 "setting:version-control",
634 ]);
635 } finally {
636 localeLowerCase.mockRestore();
637 }
638 });
639​
640 it("keeps message excerpts searchable without replacing thread metadata", () => {
641 const [item] = buildThreadActionItems({
642 threads: [makeThread({ branch: "feat/search" })],
643 projectTitleById: new Map([[PROJECT_ID, "T3 Code"]]),
644 sortOrder: "updated_at",
645 icon: null,
646 getContentMatch: () => ({
647 source: "assistant",
648 snippet: "The relay reconnect is now bounded.",
649 query: "reconnect",
650 }),
651 runThread: async (_thread) => undefined,
652 });
653​
654 expect(item?.searchTerms).toContain("The relay reconnect is now bounded.");
655 expect(item?.threadContentMatch).toEqual({
656 source: "assistant",
657 snippet: "The relay reconnect is now bounded.",
658 query: "reconnect",
659 });
660 expect(item?.description).toBe("T3 Code · #feat/search");
661 });
662​
663 it("surfaces threads when the query is their ID, without outranking title matches", () => {
664 const idThread = makeThread({
665 id: ThreadId.make("thread-alpha-1234"),
666 title: "Unrelated work",
667 updatedAt: "2026-03-05T00:00:00.000Z",
668 });
669 const titleThread = makeThread({
670 id: ThreadId.make("thread-other-9999"),
671 title: "Fix thread-alpha-1234 flakes",
672 updatedAt: "2026-03-04T00:00:00.000Z",
673 });
674 const items = buildThreadActionItems({
675 threads: [idThread, titleThread],
676 projectTitleById: new Map([[PROJECT_ID, "T3 Code"]]),
677 sortOrder: "updated_at",
678 icon: null,
679 runThread: async (_thread) => undefined,
680 });
681​
682 const groups = filterCommandPaletteGroups({
683 activeGroups: [],
684 query: " THREAD-ALPHA-1234 ",
685 isInSubmenu: false,
686 projectSearchItems: [],
687 settingsSearchItems: [],
688 threadSearchItems: items,
689 });
690​
691 expect(groups.flatMap((group) => group.items)).toEqual([
692 expect.objectContaining({ value: `thread:${titleThread.id}` }),
693 expect.objectContaining({ value: `thread:${idThread.id}` }),
694 ]);
695 });
696​
697 it("prefers renderDescription when provided", () => {
698 const [item] = buildThreadActionItems({
699 threads: [makeThread({ branch: "feat/search", worktreePath: "/tmp/wt" })],
700 projectTitleById: new Map([[PROJECT_ID, "T3 Code"]]),
701 sortOrder: "updated_at",
702 icon: null,
703 renderDescription: (thread, { projectTitle }) =>
704 `${projectTitle}:${thread.branch}:${thread.worktreePath ? "wt" : "local"}`,
705 runThread: async (_thread) => undefined,
706 });
707​
708 expect(item?.description).toBe("T3 Code:feat/search:wt");
709 });
710​
711 it("filters archived threads out of thread search items", () => {
712 const items = buildThreadActionItems({
713 threads: [
714 makeThread({
715 id: ThreadId.make("thread-active"),
716 title: "Active thread",
717 createdAt: "2026-03-02T00:00:00.000Z",
718 updatedAt: "2026-03-19T00:00:00.000Z",
719 }),
720 makeThread({
721 id: ThreadId.make("thread-archived"),
722 title: "Archived thread",
723 archivedAt: "2026-03-20T00:00:00.000Z",
724 updatedAt: "2026-03-20T00:00:00.000Z",
725 }),
726 ],
727 projectTitleById: new Map([[PROJECT_ID, "Project"]]),
728 sortOrder: "updated_at",
729 icon: null,
730 runThread: async (_thread) => undefined,
731 });
732​
733 expect(items.map((item) => item.value)).toEqual(["thread:thread-active"]);
734 });
735});
736​
737describe("buildBrowseGroups", () => {
738 it("waits for asynchronous browse navigation actions", async () => {
739 let finishNavigation: (() => void) | undefined;
740 const browseTo = vi.fn(
741 () =>
742 new Promise<void>((resolve) => {
743 finishNavigation = resolve;
744 }),
745 );
746 const groups = buildBrowseGroups({
747 browseEntries: [{ name: "Downloads", fullPath: "/Users/test/Downloads" }],
748 browseQuery: "~/",
749 canBrowseUp: false,
750 upIcon: null,
751 directoryIcon: null,
752 browseUp: vi.fn(),
753 browseTo,
754 });
755 const item = groups[0]?.items[0];
756 if (!item || item.kind !== "action") {
757 throw new Error("Expected a browse action");
758 }
759​
760 let actionSettled = false;
761 const action = item.run().then(() => {
762 actionSettled = true;
763 });
764 await Promise.resolve();
765​
766 expect(browseTo).toHaveBeenCalledWith("Downloads");
767 expect(actionSettled).toBe(false);
768​
769 finishNavigation?.();
770 await action;
771 expect(actionSettled).toBe(true);
772 });
773});
774​
775describe("filterPinnedBrowseEntries", () => {
776 const entries = [
777 { name: "repo", fullPath: "/projects/repo" },
778 { name: "work", fullPath: "/projects/work" },
779 ];
780​
781 it("shows sibling folders without losing an existing pinned destination", () => {
782 expect(
783 filterPinnedBrowseEntries({
784 browseEntries: entries,
785 filterQuery: "repo",
786 pinnedDirectoryName: "repo",
787 caseSensitive: true,
788 }),
789 ).toEqual({ visibleEntries: entries, exactEntry: entries[0] });
790 });
791​
792 it("matches an existing pinned destination without Windows casing", () => {
793 const windowsEntries = [
794 { name: "Repo", fullPath: "C:\\projects\\Repo" },
795 { name: "work", fullPath: "C:\\projects\\work" },
796 ];
797 expect(
798 filterPinnedBrowseEntries({
799 browseEntries: windowsEntries,
800 filterQuery: "repo",
801 pinnedDirectoryName: "repo",
802 caseSensitive: false,
803 }),
804 ).toEqual({
805 visibleEntries: windowsEntries,
806 exactEntry: windowsEntries[0],
807 });
808 });
809});
810​
811it.each([
812 "#10839",
813 "10839",
814 "pingdotgg/t3code#10839",
815 "https://github.com/pingdotgg/t3code/pull/10839",
816])("finds linked threads from PR query %s", (query) => {
817 const items = buildThreadActionItems({
818 threads: [
819 makeThread({
820 title: "Implementation",
821 pullRequests: [
822 {
823 host: "github.com",
824 repository: "pingdotgg/t3code",
825 number: 10839,
826 url: "https://github.com/pingdotgg/t3code/pull/10839",
827 source: "manual",
828 linkedAt: "2026-09-08T00:00:00Z",
829 snapshot: null,
830 stack: null,
831 },
832 ],
833 }),
834 makeThread({ id: ThreadId.make("unrelated"), title: "Other work" }),
835 ],
836 projectTitleById: new Map(),
837 sortOrder: "updated_at",
838 icon: null,
839 runThread: async () => undefined,
840 });
841 const groups = filterCommandPaletteGroups({
842 activeGroups: [],
843 query,
844 isInSubmenu: false,
845 projectSearchItems: [],
846 threadSearchItems: items,
847 });
848 expect(groups.flatMap((group) => group.items.map((item) => item.title))).toEqual([
849 "Implementation",
850 ]);
851});
852​
853describe("filterCommandPaletteGroups", () => {
854 it("sorts secondary settings results after other matches", () => {
855 const item = (value: string, title: string, secondary?: boolean) =>
856 ({
857 kind: "action",
858 value,
859 title,
860 searchTerms: [title, "General"],
861 icon: null,
862 run: async () => undefined,
863 ...(secondary ? { secondary } : {}),
864 }) satisfies CommandPaletteActionItem;
865 const [group] = filterCommandPaletteGroups({
866 activeGroups: [],
867 query: "model",
868 isInSubmenu: false,
869 projectSearchItems: [],
870 settingsSearchItems: [
871 item("setting:keybinding-modelPicker.toggle", "Model Picker: Toggle", true),
872 item("setting:default-model", "Default model"),
873 ],
874 threadSearchItems: [],
875 });
876 expect(group?.items.map((entry) => entry.value)).toEqual([
877 "setting:default-model",
878 "setting:keybinding-modelPicker.toggle",
879 ]);
880 });
881});
882​
883describe("virtualized command palette rows", () => {
884 const action = (value: string, disabled = false): CommandPaletteActionItem => ({
885 kind: "action",
886 value,
887 searchTerms: [],
888 title: value,
889 icon: null,
890 ...(disabled ? { disabled } : {}),
891 run: async () => {},
892 });
893 const groups: CommandPaletteGroup[] = [
894 { value: "actions", label: "Actions", items: [action("new-thread"), action("offline", true)] },
895 { value: "threads", label: "Threads", items: [action("thread-a"), action("thread-b")] },
896 ];
897​
898 it("keeps group order and headings while indexing only enabled items", () => {
899 const { rows, itemValues, rowIndexByItemIndex } = buildCommandPaletteRows(groups);
900​
901 expect(rows.map((row) => (row.kind === "label" ? `# ${row.label}` : row.key))).toEqual([
902 "# Actions",
903 "actions:new-thread",
904 "actions:offline",
905 "# Threads",
906 "threads:thread-a",
907 "threads:thread-b",
908 ]);
909 expect(itemValues).toEqual(["new-thread", "thread-a", "thread-b"]);
910 expect(rowIndexByItemIndex).toEqual([1, 4, 5]);
911 expect(rows.flatMap((row) => (row.kind === "item" ? [row.itemIndex] : []))).toEqual([
912 0,
913 null,
914 1,
915 2,
916 ]);
917 });
918​
919 it("resolves Enter to the highlighted item without needing its row mounted", () => {
920 expect(findHighlightedCommandPaletteItem(groups, "thread-b")?.value).toBe("thread-b");
921 expect(findHighlightedCommandPaletteItem(groups, "offline")).toBeNull();
922 expect(findHighlightedCommandPaletteItem(groups, null)).toBeNull();
923 });
924});
925​
926describe("command palette search return", () => {
927 const picker = { addonIcon: null, groups: [] };
928​
929 it("restores each parent query when backing out of nested pickers", () => {
930 let state = createCommandPaletteSearchState(">new thread");
931 state = reduceCommandPaletteSearchState(state, { type: "push", view: picker });
932 expect(state.query).toBe("");
933 state = reduceCommandPaletteSearchState(state, { type: "query", query: "remote project" });
934 state = reduceCommandPaletteSearchState(state, {
935 type: "push",
936 view: { ...picker, initialQuery: "~/" },
937 });
938 expect(state.query).toBe("~/");
939​
940 state = reduceCommandPaletteSearchState(state, { type: "query", query: "" });
941 state = reduceCommandPaletteSearchState(state, { type: "back" });
942 expect(state.query).toBe("remote project");
943 expect(state.views).toHaveLength(1);
944 state = reduceCommandPaletteSearchState(state, { type: "back" });
945 expect(state.query).toBe(">new thread");
946 expect(state.views).toHaveLength(0);
947 });
948​
949 it("cannot return to an old picker after a new search replaces it", () => {
950 let state = reduceCommandPaletteSearchState(createCommandPaletteSearchState("old"), {
951 type: "push",
952 view: picker,
953 });
954 state = reduceCommandPaletteSearchState(state, { type: "reset", query: "fresh" });
955 state = reduceCommandPaletteSearchState(state, { type: "back" });
956 expect(state.query).toBe("fresh");
957 expect(state.views).toHaveLength(0);
958 });
959});
960​
961describe("returning from file and content search", () => {
962 const root: CommandPaletteUiState = { open: true, mode: "command", openIntent: null };
963 const query = "https://github.com/acme/web/pull/7";
964 const context = {
965 query,
966 linkedThreadSearch: {
967 kind: "search" as const,
968 query,
969 linkedThreads: {
970 environmentId: EnvironmentId.make("remote"),
971 threads: [
972 {
973 id: ThreadId.make("linked-thread"),
974 projectId: ProjectId.make("project"),
975 title: "Completed work",
976 archivedAt: "2026-09-01T00:00:00.000Z",
977 },
978 ],
979 },
980 },
981 };
982​
983 it.each(["files", "content"] as const)(
984 "Escape from %s restores the query and linked-thread results",
985 (mode) => {
986 const child = reduceCommandPaletteUiState(root, { _tag: "OpenChildSearch", mode, context });
987 expect(child.mode).toBe(mode);
988 const returned = reduceCommandPaletteUiState(child, { _tag: "BackToCommand" });
989 expect(returned).toEqual({ ...root, restoredSearch: context });
990 expect(reduceCommandPaletteUiState(returned, { _tag: "BackToCommand" })).toEqual(returned);
991 },
992 );
993​
994 it("closing a child search discards its return context before reopening", () => {
995 const child: CommandPaletteUiState = { ...root, mode: "files", parentSearch: context };
996 const closed = reduceCommandPaletteUiState(child, { _tag: "SetOpen", open: false });
997 expect(closed).toEqual({ open: false, mode: "files", openIntent: null });
998 expect(reduceCommandPaletteUiState(closed, { _tag: "BackToCommand" })).toEqual(closed);
999 expect(reduceCommandPaletteUiState(closed, { _tag: "SetOpen", open: true })).toEqual(root);
1000 });
1001​
1002 it("a fresh overlay shortcut has no parent search to return to", () => {
1003 const child = reduceCommandPaletteUiState(root, {
1004 _tag: "OpenChildSearch",
1005 mode: "files",
1006 context,
1007 });
1008 const fresh = reduceCommandPaletteUiState(child, { _tag: "ToggleMode", mode: "content" });
1009 expect(fresh).toEqual({ open: true, mode: "content", openIntent: null });
1010 expect(reduceCommandPaletteUiState(fresh, { _tag: "BackToCommand" })).toEqual(root);
1011 });
1012​
1013 it("a direct search intent replaces restored query and linked-thread context", () => {
1014 const child = reduceCommandPaletteUiState(root, {
1015 _tag: "OpenChildSearch",
1016 mode: "content",
1017 context,
1018 });
1019 const returned = reduceCommandPaletteUiState(child, { _tag: "BackToCommand" });
1020 expect(reduceCommandPaletteUiState(returned, { _tag: "OpenSearch", query: "fresh" })).toEqual({
1021 ...root,
1022 openIntent: { kind: "search", query: "fresh" },
1023 });
1024 });
1025});