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

CommandPalette.logic.test.ts

472 lines14.0 KB

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