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