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

CommandPalette.logic.test.ts

479 lines14.2 KB

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