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