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

CommandPalette.logic.test.ts

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