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

CommandPalette.logic.test.ts

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