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

CommandPalette.logic.test.ts

740 lines22.0 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 {
5 buildBrowseGroups,
6 buildCommandPaletteProjectMetadata,
7 buildProjectActionItems,
8 buildThreadActionItems,
9 buildLinkedThreadActionItems,
10 enumerateCommandPaletteItems,
11 filterPinnedBrowseEntries,
12 filterCommandPaletteGroups,
13 reduceCommandPaletteUiState,
14 type CommandPaletteGroup,
15} from "./CommandPalette.logic";
16​
17describe("linked pull request thread navigation", () => {
18 it("keeps archived relations searchable and routes them through the PR environment", async () => {
19 const environmentId = EnvironmentId.make("remote");
20 const id = ThreadId.make("archived-thread");
21 const runThread = vi.fn(async () => {});
22 const query = "https://github.com/acme/web/pull/42";
23 const linkedThreads = {
24 environmentId,
25 threads: [
26 {
27 id,
28 projectId: ProjectId.make("project"),
29 title: "Completed work",
30 archivedAt: "2026-09-01T00:00:00.000Z",
31 },
32 ],
33 };
34 const state = reduceCommandPaletteUiState(
35 { open: false, mode: "command", openIntent: null },
36 {
37 _tag: "OpenSearch",
38 query,
39 linkedThreads,
40 },
41 );
42 expect(state.openIntent).toEqual({ kind: "search", query, linkedThreads });
43 const items = buildLinkedThreadActionItems({ ...linkedThreads, query, icon: null, runThread });
44 const groups = filterCommandPaletteGroups({
45 activeGroups: [],
46 query,
47 isInSubmenu: false,
48 projectSearchItems: [],
49 settingsSearchItems: [],
50 threadSearchItems: items,
51 });
52 expect(groups.flatMap((group) => group.items)).toEqual(items);
53 expect(items[0]?.description).toBe("Archived thread");
54 await items[0]?.run();
55 expect(runThread).toHaveBeenCalledWith({ environmentId, id });
56 });
57});
58​
59describe("buildCommandPaletteProjectMetadata", () => {
60 const localEnvironmentId = EnvironmentId.make("environment-local");
61 const remoteEnvironmentId = EnvironmentId.make("environment-build-box");
62 const locations = new Map([
63 [localEnvironmentId, { kind: "local" as const, label: "Local", machine: "laptop" as const }],
64 [
65 remoteEnvironmentId,
66 { kind: "remote" as const, label: "Build box", machine: "server" as const },
67 ],
68 ]);
69​
70 it("makes every member environment and path searchable", () => {
71 const metadata = buildCommandPaletteProjectMetadata({
72 projects: [
73 {
74 environmentId: localEnvironmentId,
75 title: "T3 Code",
76 workspaceRoot: "/Users/theo/Projects/t3code",
77 },
78 {
79 environmentId: remoteEnvironmentId,
80 title: "t3code",
81 workspaceRoot: "/srv/t3code",
82 },
83 ],
84 locationByEnvironmentId: locations,
85 });
86​
87 expect(metadata.searchTerms).toEqual([
88 "T3 Code",
89 "/Users/theo/Projects/t3code",
90 "Local",
91 "t3code",
92 "/srv/t3code",
93 "Build box",
94 ]);
95 expect(metadata.environmentLabels).toEqual(["Local", "Build box"]);
96​
97 const [filteredGroup] = filterCommandPaletteGroups({
98 activeGroups: [],
99 query: "build box",
100 isInSubmenu: false,
101 projectSearchItems: [
102 {
103 kind: "action",
104 value: "project:t3code",
105 title: "T3 Code",
106 searchTerms: metadata.searchTerms,
107 icon: null,
108 run: async () => undefined,
109 },
110 ],
111 threadSearchItems: [],
112 });
113 expect(filteredGroup?.items).toHaveLength(1);
114 });
115​
116 it("deduplicates grouped checkouts by environment", () => {
117 const metadata = buildCommandPaletteProjectMetadata({
118 projects: [
119 {
120 environmentId: remoteEnvironmentId,
121 title: "T3 Code",
122 workspaceRoot: "/srv/t3code",
123 },
124 {
125 environmentId: remoteEnvironmentId,
126 title: "T3 Code worktree",
127 workspaceRoot: "/srv/t3code-feature",
128 },
129 ],
130 locationByEnvironmentId: locations,
131 });
132​
133 expect(metadata.environmentLabels).toEqual(["Build box"]);
134 });
135​
136 it("deduplicates distinct environments with the same label", () => {
137 const secondRemoteEnvironmentId = EnvironmentId.make("environment-build-box-2");
138 const metadata = buildCommandPaletteProjectMetadata({
139 projects: [
140 {
141 environmentId: remoteEnvironmentId,
142 title: "T3 Code",
143 workspaceRoot: "/srv/t3code",
144 },
145 {
146 environmentId: secondRemoteEnvironmentId,
147 title: "T3 Code mirror",
148 workspaceRoot: "/srv/mirror/t3code",
149 },
150 ],
151 locationByEnvironmentId: new Map([
152 [remoteEnvironmentId, { label: "Build box" }],
153 [secondRemoteEnvironmentId, { label: "Build box" }],
154 ]),
155 });
156​
157 expect(metadata.environmentLabels).toEqual(["Build box"]);
158 });
159​
160 it("uses a human-readable fallback when presentation data is unavailable", () => {
161 const metadata = buildCommandPaletteProjectMetadata({
162 projects: [
163 {
164 environmentId: remoteEnvironmentId,
165 title: "T3 Code",
166 workspaceRoot: "/srv/t3code",
167 },
168 ],
169 locationByEnvironmentId: new Map(),
170 });
171​
172 expect(metadata.searchTerms).toContain("Remote");
173 expect(metadata.environmentLabels).toEqual(["Remote"]);
174 });
175});
176​
177describe("reduceCommandPaletteUiState", () => {
178 const closedState = { open: false, mode: "command", openIntent: null } as const;
179​
180 it("toggles each overlay mode open and closed", () => {
181 const filesOpen = reduceCommandPaletteUiState(closedState, {
182 _tag: "ToggleMode",
183 mode: "files",
184 });
185 expect(filesOpen).toEqual({ open: true, mode: "files", openIntent: null });
186​
187 const contentOpen = reduceCommandPaletteUiState(filesOpen, {
188 _tag: "ToggleMode",
189 mode: "content",
190 });
191 expect(contentOpen).toEqual({ open: true, mode: "content", openIntent: null });
192​
193 expect(
194 reduceCommandPaletteUiState(contentOpen, { _tag: "ToggleMode", mode: "content" }),
195 ).toEqual({ open: false, mode: "content", openIntent: null });
196 });
197​
198 it("switches between open modes without closing", () => {
199 const filesOpen = reduceCommandPaletteUiState(closedState, {
200 _tag: "ToggleMode",
201 mode: "files",
202 });
203 expect(reduceCommandPaletteUiState(filesOpen, { _tag: "ToggleMode", mode: "command" })).toEqual(
204 {
205 open: true,
206 mode: "command",
207 openIntent: null,
208 },
209 );
210 });
211​
212 it("opens PR search from another overlay and replaces an earlier search", () => {
213 const first = reduceCommandPaletteUiState(
214 { open: true, mode: "files", openIntent: null },
215 {
216 _tag: "OpenSearch",
217 query: "https://github.com/acme/web/pull/7",
218 },
219 );
220 expect(first).toEqual({
221 open: true,
222 mode: "command",
223 openIntent: { kind: "search", query: "https://github.com/acme/web/pull/7" },
224 });
225 const second = reduceCommandPaletteUiState(first, {
226 _tag: "OpenSearch",
227 query: "https://github.com/acme/web/pull/8",
228 });
229 expect(second.openIntent).toEqual({
230 kind: "search",
231 query: "https://github.com/acme/web/pull/8",
232 });
233 expect(
234 reduceCommandPaletteUiState(second, { _tag: "SetOpen", open: false }).openIntent,
235 ).toBeNull();
236 });
237​
238 it("routes open intents to command mode", () => {
239 const filesOpen = reduceCommandPaletteUiState(closedState, {
240 _tag: "ToggleMode",
241 mode: "files",
242 });
243 expect(reduceCommandPaletteUiState(filesOpen, { _tag: "OpenAddProject" })).toEqual({
244 open: true,
245 mode: "command",
246 openIntent: { kind: "add-project" },
247 });
248 expect(reduceCommandPaletteUiState(filesOpen, { _tag: "OpenNewThreadIn" })).toEqual({
249 open: true,
250 mode: "command",
251 openIntent: { kind: "new-thread-in" },
252 });
253 });
254​
255 it("preserves the mode on close and resets it on open", () => {
256 const filesOpen = reduceCommandPaletteUiState(closedState, {
257 _tag: "ToggleMode",
258 mode: "files",
259 });
260​
261 expect(reduceCommandPaletteUiState(filesOpen, { _tag: "SetOpen", open: false })).toEqual({
262 open: false,
263 mode: "files",
264 openIntent: null,
265 });
266 expect(reduceCommandPaletteUiState(filesOpen, { _tag: "SetOpen", open: true })).toEqual({
267 open: true,
268 mode: "command",
269 openIntent: null,
270 });
271 });
272});
273​
274describe("enumerateCommandPaletteItems", () => {
275 it("assigns positional jump shortcuts to the first nine displayed items", () => {
276 const items = Array.from({ length: 10 }, (_, index) => ({
277 kind: "action" as const,
278 value: `project-${index + 1}`,
279 searchTerms: [],
280 title: `Project ${index + 1}`,
281 icon: null,
282 shortcutCommand: "chat.new" as const,
283 run: async () => undefined,
284 }));
285​
286 expect(enumerateCommandPaletteItems(items).map((item) => item.shortcutCommand)).toEqual([
287 "thread.jump.1",
288 "thread.jump.2",
289 "thread.jump.3",
290 "thread.jump.4",
291 "thread.jump.5",
292 "thread.jump.6",
293 "thread.jump.7",
294 "thread.jump.8",
295 "thread.jump.9",
296 undefined,
297 ]);
298 });
299});
300​
301const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
302const PROJECT_ID = ProjectId.make("project-1");
303​
304function makeProject(overrides: Partial<Project> = {}): Project {
305 return {
306 id: PROJECT_ID,
307 environmentId: LOCAL_ENVIRONMENT_ID,
308 title: "Project",
309 workspaceRoot: "/workspace/project",
310 defaultModelSelection: null,
311 scripts: [],
312 createdAt: "2026-03-01T00:00:00.000Z",
313 updatedAt: "2026-03-01T00:00:00.000Z",
314 ...overrides,
315 };
317​
318function makeThread(overrides: Partial<Thread> = {}): Thread {
319 return {
320 id: ThreadId.make("thread-1"),
321 environmentId: LOCAL_ENVIRONMENT_ID,
322 projectId: PROJECT_ID,
323 title: "Thread",
324 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
325 runtimeMode: "full-access",
326 interactionMode: "default",
327 session: null,
328 messages: [],
329 proposedPlans: [],
330 createdAt: "2026-03-01T00:00:00.000Z",
331 archivedAt: null,
332 settledOverride: null,
333 settledAt: null,
334 deletedAt: null,
335 updatedAt: "2026-03-01T00:00:00.000Z",
336 latestTurn: null,
337 branch: null,
338 worktreePath: null,
339 checkpoints: [],
340 pullRequests: [],
341 activities: [],
342 ...overrides,
343 };
345​
346describe("buildProjectActionItems", () => {
347 it("shows the grouped display name but keeps the real title for icons", () => {
348 const project = makeProject({ title: "fleet", workspaceRoot: "/Users/theo/Code/p/fleet" });
349 const iconTitles: string[] = [];
350 const [item] = buildProjectActionItems({
351 projects: [{ ...project, displayName: "t3dotgg/fleet" }],
352 valuePrefix: "project",
353 icon: (candidate) => {
354 iconTitles.push(candidate.title);
355 return null;
356 },
357 runProject: async () => undefined,
358 });
359​
360 expect(item?.title).toBe("t3dotgg/fleet");
361 expect(item?.searchTerms).toEqual(
362 expect.arrayContaining(["t3dotgg/fleet", "fleet", "/Users/theo/Code/p/fleet"]),
363 );
364 expect(iconTitles).toEqual(["fleet"]);
365 });
366});
367​
368describe("buildThreadActionItems", () => {
369 it("orders threads by most recent activity and formats timestamps from updatedAt", () => {
370 vi.useFakeTimers();
371 vi.setSystemTime(new Date("2026-03-25T12:00:00.000Z"));
372​
373 try {
374 const items = buildThreadActionItems({
375 threads: [
376 makeThread({
377 id: ThreadId.make("thread-older"),
378 title: "Older thread",
379 updatedAt: "2026-03-24T12:00:00.000Z",
380 }),
381 makeThread({
382 id: ThreadId.make("thread-newer"),
383 title: "Newer thread",
384 createdAt: "2026-03-20T00:00:00.000Z",
385 updatedAt: "2026-03-20T00:00:00.000Z",
386 }),
387 ],
388 projectTitleById: new Map([[PROJECT_ID, "Project"]]),
389 sortOrder: "updated_at",
390 icon: null,
391 runThread: async (_thread) => undefined,
392 });
393​
394 expect(items.map((item) => item.value)).toEqual([
395 "thread:thread-older",
396 "thread:thread-newer",
397 ]);
398 expect(items[0]?.timestamp).toBe("1d ago");
399 expect(items[1]?.timestamp).toBe("5d ago");
400 } finally {
401 vi.useRealTimers();
402 }
403 });
404​
405 it("ranks thread title matches ahead of contextual project-name matches", () => {
406 const threadItems = buildThreadActionItems({
407 threads: [
408 makeThread({
409 id: ThreadId.make("thread-context-match"),
410 title: "Fix navbar spacing",
411 updatedAt: "2026-03-20T00:00:00.000Z",
412 }),
413 makeThread({
414 id: ThreadId.make("thread-title-match"),
415 title: "Project kickoff notes",
416 createdAt: "2026-03-02T00:00:00.000Z",
417 updatedAt: "2026-03-19T00:00:00.000Z",
418 }),
419 ],
420 projectTitleById: new Map([[PROJECT_ID, "Project"]]),
421 sortOrder: "updated_at",
422 icon: null,
423 runThread: async (_thread) => undefined,
424 });
425​
426 const groups = filterCommandPaletteGroups({
427 activeGroups: [],
428 query: "project",
429 isInSubmenu: false,
430 projectSearchItems: [],
431 threadSearchItems: threadItems,
432 });
433​
434 expect(groups).toHaveLength(1);
435 expect(groups[0]?.value).toBe("threads-search");
436 expect(groups[0]?.items.map((item) => item.value)).toEqual([
437 "thread:thread-title-match",
438 "thread:thread-context-match",
439 ]);
440 });
441​
442 it("preserves thread project-name matches when there is no stronger title match", () => {
443 const group: CommandPaletteGroup = {
444 value: "threads-search",
445 label: "Threads",
446 items: [
447 {
448 kind: "action",
449 value: "thread:project-context-only",
450 searchTerms: ["Fix navbar spacing", "Project"],
451 title: "Fix navbar spacing",
452 description: "Project",
453 icon: null,
454 run: async () => undefined,
455 },
456 ],
457 };
458​
459 const groups = filterCommandPaletteGroups({
460 activeGroups: [group],
461 query: "project",
462 isInSubmenu: false,
463 projectSearchItems: [],
464 threadSearchItems: [],
465 });
466​
467 expect(groups).toHaveLength(1);
468 expect(groups[0]?.items.map((item) => item.value)).toEqual(["thread:project-context-only"]);
469 });
470​
471 it("ranks an order-independent setting title match above a split context match", () => {
472 const settingsSearchItems = [
473 {
474 kind: "action" as const,
475 value: "setting:context-match",
476 searchTerms: ["Pairing settings", "remote backend"],
477 title: "Context match",
478 icon: null,
479 run: async () => undefined,
480 },
481 {
482 kind: "action" as const,
483 value: "setting:remote-pairing",
484 searchTerms: ["Remote pairing", "connections"],
485 title: "Remote pairing",
486 icon: null,
487 run: async () => undefined,
488 },
489 ];
490​
491 const groups = filterCommandPaletteGroups({
492 activeGroups: [],
493 query: "pairing remote",
494 isInSubmenu: false,
495 projectSearchItems: [],
496 settingsSearchItems,
497 threadSearchItems: [],
498 });
499​
500 expect(groups).toHaveLength(1);
501 expect(groups[0]?.value).toBe("settings-search");
502 expect(groups[0]?.items.map((item) => item.value)).toEqual([
503 "setting:remote-pairing",
504 "setting:context-match",
505 ]);
506 });
507​
508 it("keeps accent-insensitive setting results", () => {
509 const groups = filterCommandPaletteGroups({
510 activeGroups: [],
511 query: "thè\u{1ab0}mes",
512 isInSubmenu: false,
513 projectSearchItems: [],
514 settingsSearchItems: [
515 {
516 kind: "action",
517 value: "setting:theme",
518 searchTerms: ["Themes", "Appearance"],
519 title: "Themes",
520 icon: null,
521 run: async () => undefined,
522 },
523 ],
524 threadSearchItems: [],
525 });
526​
527 expect(groups[0]?.items.map((item) => item.value)).toEqual(["setting:theme"]);
528 });
529​
530 it("normalizes case independently of the host locale", () => {
531 const toLocaleLowerCase = String.prototype.toLocaleLowerCase;
532 const localeLowerCase = vi
533 .spyOn(String.prototype, "toLocaleLowerCase")
534 .mockImplementation(function (this: string) {
535 return toLocaleLowerCase.call(this, "tr");
536 });
537 try {
538 const groups = filterCommandPaletteGroups({
539 activeGroups: [],
540 query: "GIT",
541 isInSubmenu: false,
542 projectSearchItems: [],
543 threadSearchItems: [],
544 settingsSearchItems: [
545 {
546 kind: "action",
547 value: "setting:version-control",
548 title: "Version control",
549 searchTerms: ["git"],
550 icon: null,
551 run: async () => undefined,
552 },
553 ],
554 });
555 expect(groups.flatMap((group) => group.items.map((item) => item.value))).toEqual([
556 "setting:version-control",
557 ]);
558 } finally {
559 localeLowerCase.mockRestore();
560 }
561 });
562​
563 it("keeps message excerpts searchable without replacing thread metadata", () => {
564 const [item] = buildThreadActionItems({
565 threads: [makeThread({ branch: "feat/search" })],
566 projectTitleById: new Map([[PROJECT_ID, "T3 Code"]]),
567 sortOrder: "updated_at",
568 icon: null,
569 getContentMatch: () => ({
570 source: "assistant",
571 snippet: "The relay reconnect is now bounded.",
572 query: "reconnect",
573 }),
574 runThread: async (_thread) => undefined,
575 });
576​
577 expect(item?.searchTerms).toContain("The relay reconnect is now bounded.");
578 expect(item?.threadContentMatch).toEqual({
579 source: "assistant",
580 snippet: "The relay reconnect is now bounded.",
581 query: "reconnect",
582 });
583 expect(item?.description).toBe("T3 Code · #feat/search");
584 });
585​
586 it("prefers renderDescription when provided", () => {
587 const [item] = buildThreadActionItems({
588 threads: [makeThread({ branch: "feat/search", worktreePath: "/tmp/wt" })],
589 projectTitleById: new Map([[PROJECT_ID, "T3 Code"]]),
590 sortOrder: "updated_at",
591 icon: null,
592 renderDescription: (thread, { projectTitle }) =>
593 `${projectTitle}:${thread.branch}:${thread.worktreePath ? "wt" : "local"}`,
594 runThread: async (_thread) => undefined,
595 });
596​
597 expect(item?.description).toBe("T3 Code:feat/search:wt");
598 });
599​
600 it("filters archived threads out of thread search items", () => {
601 const items = buildThreadActionItems({
602 threads: [
603 makeThread({
604 id: ThreadId.make("thread-active"),
605 title: "Active thread",
606 createdAt: "2026-03-02T00:00:00.000Z",
607 updatedAt: "2026-03-19T00:00:00.000Z",
608 }),
609 makeThread({
610 id: ThreadId.make("thread-archived"),
611 title: "Archived thread",
612 archivedAt: "2026-03-20T00:00:00.000Z",
613 updatedAt: "2026-03-20T00:00:00.000Z",
614 }),
615 ],
616 projectTitleById: new Map([[PROJECT_ID, "Project"]]),
617 sortOrder: "updated_at",
618 icon: null,
619 runThread: async (_thread) => undefined,
620 });
621​
622 expect(items.map((item) => item.value)).toEqual(["thread:thread-active"]);
623 });
624});
625​
626describe("buildBrowseGroups", () => {
627 it("waits for asynchronous browse navigation actions", async () => {
628 let finishNavigation: (() => void) | undefined;
629 const browseTo = vi.fn(
630 () =>
631 new Promise<void>((resolve) => {
632 finishNavigation = resolve;
633 }),
634 );
635 const groups = buildBrowseGroups({
636 browseEntries: [{ name: "Downloads", fullPath: "/Users/test/Downloads" }],
637 browseQuery: "~/",
638 canBrowseUp: false,
639 upIcon: null,
640 directoryIcon: null,
641 browseUp: vi.fn(),
642 browseTo,
643 });
644 const item = groups[0]?.items[0];
645 if (!item || item.kind !== "action") {
646 throw new Error("Expected a browse action");
647 }
648​
649 let actionSettled = false;
650 const action = item.run().then(() => {
651 actionSettled = true;
652 });
653 await Promise.resolve();
654​
655 expect(browseTo).toHaveBeenCalledWith("Downloads");
656 expect(actionSettled).toBe(false);
657​
658 finishNavigation?.();
659 await action;
660 expect(actionSettled).toBe(true);
661 });
662});
663​
664describe("filterPinnedBrowseEntries", () => {
665 const entries = [
666 { name: "repo", fullPath: "/projects/repo" },
667 { name: "work", fullPath: "/projects/work" },
668 ];
669​
670 it("shows sibling folders without losing an existing pinned destination", () => {
671 expect(
672 filterPinnedBrowseEntries({
673 browseEntries: entries,
674 filterQuery: "repo",
675 pinnedDirectoryName: "repo",
676 caseSensitive: true,
677 }),
678 ).toEqual({ visibleEntries: entries, exactEntry: entries[0] });
679 });
680​
681 it("matches an existing pinned destination without Windows casing", () => {
682 const windowsEntries = [
683 { name: "Repo", fullPath: "C:\\projects\\Repo" },
684 { name: "work", fullPath: "C:\\projects\\work" },
685 ];
686 expect(
687 filterPinnedBrowseEntries({
688 browseEntries: windowsEntries,
689 filterQuery: "repo",
690 pinnedDirectoryName: "repo",
691 caseSensitive: false,
692 }),
693 ).toEqual({
694 visibleEntries: windowsEntries,
695 exactEntry: windowsEntries[0],
696 });
697 });
698});
699​
700it.each([
701 "#10839",
702 "10839",
703 "pingdotgg/t3code#10839",
704 "https://github.com/pingdotgg/t3code/pull/10839",
705])("finds linked threads from PR query %s", (query) => {
706 const items = buildThreadActionItems({
707 threads: [
708 makeThread({
709 title: "Implementation",
710 pullRequests: [
711 {
712 host: "github.com",
713 repository: "pingdotgg/t3code",
714 number: 10839,
715 url: "https://github.com/pingdotgg/t3code/pull/10839",
716 source: "manual",
717 linkedAt: "2026-09-08T00:00:00Z",
718 snapshot: null,
719 stack: null,
720 },
721 ],
722 }),
723 makeThread({ id: ThreadId.make("unrelated"), title: "Other work" }),
724 ],
725 projectTitleById: new Map(),
726 sortOrder: "updated_at",
727 icon: null,
728 runThread: async () => undefined,
729 });
730 const groups = filterCommandPaletteGroups({
731 activeGroups: [],
732 query,
733 isInSubmenu: false,
734 projectSearchItems: [],
735 threadSearchItems: items,
736 });
737 expect(groups.flatMap((group) => group.items.map((item) => item.title))).toEqual([
738 "Implementation",
739 ]);
740});