Open History to see the last commit
1import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
2import type { CommandPaletteLinkedThreads } from "../commandPaletteBus";
3import {
4 type EnvironmentId,
5 type FilesystemBrowseEntry,
6 type KeybindingCommand,
7 THREAD_JUMP_KEYBINDING_COMMANDS,
8} from "@t3tools/contracts";
9import { filterFilesystemBrowseEntries } from "@t3tools/client-runtime/state/filesystem";
10import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
11import * as Arr from "effect/Array";
12import * as Result from "effect/Result";
13import { type ReactNode } from "react";
14import { getThreadSortTimestamp, sortThreads } from "../lib/threadSort";
15import { normalizeSearchText } from "../lib/utils";
16import { formatRelativeTimeLabel } from "../timestampFormat";
17import { type Project, type SidebarThreadSummary, type Thread } from "../types";
18
19export const RECENT_THREAD_LIMIT = 12;
20export const ITEM_ICON_CLASS = "size-4 text-icon-muted";
21export const ADDON_ICON_CLASS = "size-4";
22
23export function buildLinkedThreadActionItems(
24 input: CommandPaletteLinkedThreads & {
25 query: string;
26 icon: ReactNode;
27 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
28 },
29): CommandPaletteActionItem[] {
30 return input.threads.map((thread) => ({
31 kind: "action",
32 value: `thread:${input.environmentId}:${thread.id}`,
33 title: thread.title || "Untitled thread",
34 description: thread.archivedAt === null ? "Linked thread" : "Archived thread",
35 searchTerms: [input.query, thread.title],
36 icon: input.icon,
37 run: () => input.runThread({ environmentId: input.environmentId, id: thread.id }),
38 }));
39}
40
41export function browseInputEndPaddingClass(input: {
42 readonly willCreateProjectPath: boolean;
43 readonly hasHighlightedBrowseItem: boolean;
44}): string {
45 if (input.willCreateProjectPath) {
46 return "*:data-[slot=autocomplete-input]:pe-38!";
47 }
48 if (input.hasHighlightedBrowseItem) {
49 return "*:data-[slot=autocomplete-input]:pe-30!";
50 }
51 return "*:data-[slot=autocomplete-input]:pe-24!";
52}
53
54export type SearchOverlayMode = "command" | "files" | "content";
55
56export type CommandPaletteOpenIntent =
57 | { readonly kind: "add-project" | "new-thread-in" | "change-theme" }
58 | {
59 readonly kind: "search";
60 readonly query: string;
61 readonly linkedThreads?: CommandPaletteLinkedThreads;
62 };
63
64export interface CommandPaletteUiState {
65 readonly open: boolean;
66 readonly mode: SearchOverlayMode;
67 readonly openIntent: CommandPaletteOpenIntent | null;
68}
69
70export type CommandPaletteUiAction =
71 | { readonly _tag: "SetOpen"; readonly open: boolean }
72 | { readonly _tag: "ToggleMode"; readonly mode: SearchOverlayMode }
73 | {
74 readonly _tag: "OpenSearch";
75 readonly query: string;
76 readonly linkedThreads?: CommandPaletteLinkedThreads;
77 }
78 | { readonly _tag: "OpenAddProject" }
79 | { readonly _tag: "OpenNewThreadIn" }
80 | { readonly _tag: "OpenChangeTheme" }
81 | { readonly _tag: "ClearOpenIntent" }
82 /** Text typed while the open view loads; it becomes that view's query. */
83 | { readonly _tag: "TypeAhead"; readonly query: string };
84
85export function reduceCommandPaletteUiState(
86 state: CommandPaletteUiState,
87 action: CommandPaletteUiAction,
88): CommandPaletteUiState {
89 switch (action._tag) {
90 case "SetOpen":
91 return action.open
92 ? { open: true, mode: "command", openIntent: state.openIntent }
93 : { ...state, open: false, openIntent: null };
94 case "ToggleMode":
95 return state.open && state.mode === action.mode
96 ? { ...state, open: false, openIntent: null }
97 : { open: true, mode: action.mode, openIntent: null };
98 case "OpenSearch":
99 return {
100 open: true,
101 mode: "command",
102 openIntent: {
103 kind: "search",
104 query: action.query,
105 ...(action.linkedThreads ? { linkedThreads: action.linkedThreads } : {}),
106 },
107 };
108 case "OpenAddProject":
109 return { open: true, mode: "command", openIntent: { kind: "add-project" } };
110 case "OpenNewThreadIn":
111 return { open: true, mode: "command", openIntent: { kind: "new-thread-in" } };
112 case "OpenChangeTheme":
113 return { open: true, mode: "command", openIntent: { kind: "change-theme" } };
114 case "ClearOpenIntent":
115 return state.openIntent ? { ...state, openIntent: null } : state;
116 case "TypeAhead": {
117 const intent = state.openIntent;
118 if (!state.open || (intent !== null && intent.kind !== "search")) return state;
119 return {
120 ...state,
121 openIntent: {
122 kind: "search",
123 query: action.query,
124 ...(intent?.linkedThreads ? { linkedThreads: intent.linkedThreads } : {}),
125 },
126 };
127 }
128 }
129}
130
131export interface CommandPaletteThreadContentMatch {
132 readonly source: "user" | "assistant";
133 readonly snippet: string;
134 readonly query: string;
135}
136
137export interface CommandPaletteItem {
138 readonly kind: "action" | "submenu";
139 readonly value: string;
140 readonly searchTerms: ReadonlyArray<string>;
141 readonly title: ReactNode;
142 readonly description?: ReactNode;
143 readonly threadContentMatch?: CommandPaletteThreadContentMatch;
144 readonly timestamp?: string;
145 readonly searchRecency?: number;
146 readonly icon: ReactNode;
147 readonly disabled?: boolean;
148 readonly titleLeadingContent?: ReactNode;
149 readonly titleTrailingContent?: ReactNode;
150 readonly shortcutCommand?: KeybindingCommand;
151 readonly secondary?: boolean;
152}
153
154export interface CommandPaletteActionItem extends CommandPaletteItem {
155 readonly kind: "action";
156 readonly keepOpen?: boolean;
157 readonly run: () => Promise<void>;
158}
159
160export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
161 readonly kind: "submenu";
162 readonly addonIcon: ReactNode;
163 readonly groups: ReadonlyArray<CommandPaletteGroup>;
164 readonly initialQuery?: string;
165}
166
167export interface CommandPaletteGroup {
168 readonly value: string;
169 readonly label: string;
170 readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
171}
172
173export interface CommandPaletteView {
174 readonly addonIcon: ReactNode;
175 readonly groups: ReadonlyArray<CommandPaletteGroup>;
176 readonly initialQuery?: string;
177}
178
179export type CommandPaletteRow =
180 | {
181 readonly kind: "label";
182 readonly key: string;
183 readonly label: string;
184 readonly first: boolean;
185 }
186 | {
187 readonly kind: "item";
188 readonly key: string;
189 readonly item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
190 readonly itemIndex: number | null;
191 };
192
193export function buildCommandPaletteRows(groups: ReadonlyArray<CommandPaletteGroup>) {
194 const rows: CommandPaletteRow[] = [];
195 const itemValues: string[] = [];
196 const rowIndexByItemIndex: number[] = [];
197 for (const group of groups) {
198 if (group.label) {
199 rows.push({
200 kind: "label",
201 key: `group:${group.value}`,
202 label: group.label,
203 first: rows.length === 0,
204 });
205 }
206 for (const item of group.items) {
207 const itemIndex = item.disabled ? null : itemValues.length;
208 if (itemIndex !== null) {
209 itemValues.push(item.value);
210 rowIndexByItemIndex.push(rows.length);
211 }
212 rows.push({ kind: "item", key: `${group.value}:${item.value}`, item, itemIndex });
213 }
214 }
215 return { rows, itemValues, rowIndexByItemIndex };
216}
217
218export function findHighlightedCommandPaletteItem(
219 groups: ReadonlyArray<CommandPaletteGroup>,
220 highlightedItemValue: string | null,
221): CommandPaletteActionItem | CommandPaletteSubmenuItem | null {
222 if (highlightedItemValue === null) return null;
223 for (const group of groups) {
224 for (const item of group.items) {
225 if (item.value === highlightedItemValue && !item.disabled) return item;
226 }
227 }
228 return null;
229}
230
231export function enumerateCommandPaletteItems(
232 items: ReadonlyArray<CommandPaletteActionItem>,
233): CommandPaletteActionItem[] {
234 return items.map((item, index) => {
235 const shortcutCommand = THREAD_JUMP_KEYBINDING_COMMANDS[index];
236 if (shortcutCommand) return { ...item, shortcutCommand };
237
238 const { shortcutCommand: _shortcutCommand, ...itemWithoutShortcut } = item;
239 return itemWithoutShortcut;
240 });
241}
242
243export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
244
245export type CommandPaletteProject = Project & { readonly displayName: string };
246
247export function buildCommandPaletteProjectMetadata(input: {
248 readonly projects: ReadonlyArray<Pick<Project, "environmentId" | "title" | "workspaceRoot">>;
249 readonly locationByEnvironmentId: ReadonlyMap<EnvironmentId, { readonly label: string }>;
250}) {
251 const searchTerms: string[] = [];
252 const environmentLabels = new Set<string>();
253
254 for (const project of input.projects) {
255 const label = input.locationByEnvironmentId.get(project.environmentId)?.label ?? "Remote";
256 searchTerms.push(project.title, project.workspaceRoot, label);
257 environmentLabels.add(label);
258 }
259
260 return { searchTerms, environmentLabels: [...environmentLabels] };
261}
262
263export function buildProjectActionItems(input: {
264 projects: ReadonlyArray<CommandPaletteProject>;
265 valuePrefix: string;
266 icon: (project: CommandPaletteProject) => ReactNode;
267 runProject: (project: CommandPaletteProject) => Promise<void>;
268 searchTerms?: (project: CommandPaletteProject) => ReadonlyArray<string>;
269 renderDescription?: (project: CommandPaletteProject) => ReactNode;
270 shortcutCommand?: KeybindingCommand;
271}): CommandPaletteActionItem[] {
272 return input.projects.map((project) => ({
273 kind: "action",
274 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
275 searchTerms: [
276 project.displayName,
277 project.title,
278 project.workspaceRoot,
279 ...(input.searchTerms?.(project) ?? []),
280 ],
281 title: project.displayName,
282 description: input.renderDescription?.(project) ?? project.workspaceRoot,
283 icon: input.icon(project),
284 ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
285 run: async () => {
286 await input.runProject(project);
287 },
288 }));
289}
290
291export type BuildThreadActionItemsThread = Pick<
292 SidebarThreadSummary,
293 | "archivedAt"
294 | "branch"
295 | "createdAt"
296 | "environmentId"
297 | "id"
298 | "modelSelection"
299 | "projectId"
300 | "runtime"
301 | "title"
302 | "worktreePath"
303> & {
304 pullRequests?: SidebarThreadSummary["pullRequests"];
305 updatedAt: string;
306 latestUserMessageAt?: string | null;
307};
308
309export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: {
310 threads: ReadonlyArray<TThread>;
311 activeThreadId?: Thread["id"];
312 projectTitleById: ReadonlyMap<Project["id"], string>;
313 sortOrder: SidebarThreadSortOrder;
314 icon: ReactNode;
315 renderLeadingContent?: (thread: TThread) => ReactNode;
316 renderTrailingContent?: (thread: TThread) => ReactNode;
317 renderDescription?: (thread: TThread, meta: { projectTitle: string | undefined }) => ReactNode;
318 getContentMatch?: (thread: TThread) => CommandPaletteThreadContentMatch | undefined;
319 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
320 limit?: number;
321}): CommandPaletteActionItem[] {
322 const sortedThreads = sortThreads(
323 input.threads.filter((thread) => thread.archivedAt === null),
324 input.sortOrder,
325 );
326 const visibleThreads =
327 input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
328
329 return visibleThreads.map((thread) => {
330 const projectTitle = input.projectTitleById.get(thread.projectId);
331 const descriptionParts: string[] = [];
332
333 if (projectTitle) {
334 descriptionParts.push(projectTitle);
335 }
336 if (thread.branch) {
337 descriptionParts.push(`#${thread.branch}`);
338 }
339 if (thread.id === input.activeThreadId) {
340 descriptionParts.push("Current thread");
341 }
342
343 const leadingContent = input.renderLeadingContent?.(thread);
344 const trailingContent = input.renderTrailingContent?.(thread);
345 const contentMatch = input.getContentMatch?.(thread);
346 const description = input.renderDescription
347 ? input.renderDescription(thread, { projectTitle })
348 : descriptionParts.join(` · `);
349
350 return Object.assign(
351 {
352 kind: "action" as const,
353 value: `thread:${thread.environmentId}:${thread.id}`,
354 searchTerms: [
355 thread.title,
356 ...threadPullRequestSearchTerms(thread),
357 projectTitle ?? ``,
358 thread.branch ?? ``,
359 contentMatch?.snippet ?? ``,
360 thread.id,
361 ],
362 title: thread.title,
363 description,
364 timestamp: formatRelativeTimeLabel(
365 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
366 ),
367 searchRecency: getThreadSortTimestamp(thread, "updated_at"),
368 icon: input.icon,
369 },
370 leadingContent ? { titleLeadingContent: leadingContent } : {},
371 trailingContent ? { titleTrailingContent: trailingContent } : {},
372 contentMatch ? { threadContentMatch: contentMatch } : {},
373 {
374 run: async () => {
375 await input.runThread(thread);
376 },
377 },
378 );
379 });
380}
381
382function rankSearchFieldMatch(
383 field: string,
384 normalizedQuery: string,
385 queryTokens: ReadonlyArray<string>,
386): number {
387 const normalizedField = normalizeSearchText(field);
388 if (
389 normalizedField.length === 0 ||
390 !queryTokens.every((token) => normalizedField.includes(token))
391 ) {
392 return Number.NEGATIVE_INFINITY;
393 }
394 if (normalizedField === normalizedQuery) {
395 return 3;
396 }
397 if (normalizedField.startsWith(normalizedQuery)) {
398 return 2;
399 }
400 if (normalizedField.includes(normalizedQuery)) {
401 return 1;
402 }
403 return 0;
404}
405
406function rankCommandPaletteItemMatch(
407 item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
408 normalizedQuery: string,
409 queryTokens: ReadonlyArray<string>,
410): number {
411 const terms = item.searchTerms.filter((term) => term.length > 0);
412 if (terms.length === 0) {
413 return 0;
414 }
415
416 for (const [index, field] of terms.entries()) {
417 const fieldRank = rankSearchFieldMatch(field, normalizedQuery, queryTokens);
418 if (fieldRank !== Number.NEGATIVE_INFINITY) {
419 if (index === 0 && item.searchRecency !== undefined) {
420 return 1_000 + Number(fieldRank === 3);
421 }
422 return 1_000 - index * 100 + fieldRank;
423 }
424 }
425
426 return 0;
427}
428
429export function filterCommandPaletteGroups(input: {
430 activeGroups: ReadonlyArray<CommandPaletteGroup>;
431 query: string;
432 isInSubmenu: boolean;
433 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
434 settingsSearchItems?: ReadonlyArray<CommandPaletteActionItem>;
435 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
436}): CommandPaletteGroup[] {
437 const isActionsFilter = input.query.startsWith(">");
438 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
439 const normalizedQuery = normalizeSearchText(searchQuery);
440
441 if (normalizedQuery.length === 0) {
442 if (isActionsFilter) {
443 return input.activeGroups.filter((group) => group.value === "actions");
444 }
445 return [...input.activeGroups];
446 }
447 const queryTokens = normalizedQuery.split(" ");
448
449 let baseGroups = [...input.activeGroups];
450 if (isActionsFilter) {
451 baseGroups = baseGroups.filter((group) => group.value === "actions");
452 } else if (!input.isInSubmenu) {
453 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
454 }
455
456 const searchableGroups = [...baseGroups];
457 if (!input.isInSubmenu && !isActionsFilter) {
458 if (input.projectSearchItems.length > 0) {
459 searchableGroups.push({
460 value: "projects-search",
461 label: "Projects",
462 items: input.projectSearchItems,
463 });
464 }
465 if (input.settingsSearchItems && input.settingsSearchItems.length > 0) {
466 searchableGroups.push({
467 value: "settings-search",
468 label: "Settings",
469 items: input.settingsSearchItems,
470 });
471 }
472 if (input.threadSearchItems.length > 0) {
473 searchableGroups.push({
474 value: "threads-search",
475 label: "Threads",
476 items: input.threadSearchItems,
477 });
478 }
479 }
480
481 return searchableGroups.flatMap((group) => {
482 const items = Arr.filterMap(group.items, (item, index) => {
483 const haystack = normalizeSearchText(item.searchTerms.join(" "));
484 if (!queryTokens.every((token) => haystack.includes(token))) {
485 return Result.failVoid;
486 }
487
488 return Result.succeed({
489 item,
490 index,
491 rank: rankCommandPaletteItemMatch(item, normalizedQuery, queryTokens),
492 });
493 })
494 .toSorted(
495 (left, right) =>
496 Number(left.item.secondary ?? false) - Number(right.item.secondary ?? false) ||
497 right.rank - left.rank ||
498 (right.item.searchRecency ?? 0) - (left.item.searchRecency ?? 0) ||
499 left.index - right.index,
500 )
501 .map((entry) => entry.item);
502
503 if (items.length === 0) {
504 return [];
505 }
506
507 return [{ value: group.value, label: group.label, items }];
508 });
509}
510
511export function buildBrowseGroups(input: {
512 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
513 browseQuery: string;
514 canBrowseUp: boolean;
515 upIcon: ReactNode;
516 directoryIcon: ReactNode;
517 browseUp: () => void | Promise<void>;
518 browseTo: (name: string) => void | Promise<void>;
519}): CommandPaletteGroup[] {
520 const items: CommandPaletteActionItem[] = [];
521
522 if (input.canBrowseUp) {
523 items.push({
524 kind: "action",
525 value: "browse:up",
526 searchTerms: [input.browseQuery, ".."],
527 title: "..",
528 icon: input.upIcon,
529 keepOpen: true,
530 run: async () => {
531 await input.browseUp();
532 },
533 });
534 }
535
536 for (const entry of input.browseEntries) {
537 items.push({
538 kind: "action",
539 value: `browse:${entry.fullPath}`,
540 searchTerms: [input.browseQuery, entry.fullPath, entry.name],
541 title: entry.name,
542 icon: input.directoryIcon,
543 keepOpen: true,
544 run: async () => {
545 await input.browseTo(entry.name);
546 },
547 });
548 }
549
550 return [{ value: "directories", label: "Directories", items }];
551}
552
553export function filterPinnedBrowseEntries(input: {
554 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
555 filterQuery: string;
556 pinnedDirectoryName: string;
557 caseSensitive: boolean;
558}): ReturnType<typeof filterFilesystemBrowseEntries> {
559 const namesMatch = (left: string, right: string) =>
560 input.caseSensitive ? left === right : left.toLowerCase() === right.toLowerCase();
561 const visibleFilterQuery = namesMatch(input.filterQuery, input.pinnedDirectoryName)
562 ? ""
563 : input.filterQuery;
564 const { visibleEntries } = filterFilesystemBrowseEntries(input.browseEntries, visibleFilterQuery);
565 const exactEntry =
566 input.filterQuery.length > 0
567 ? (input.browseEntries.find((entry) => namesMatch(entry.name, input.filterQuery)) ?? null)
568 : null;
569 return { visibleEntries, exactEntry };
570}
571
572export function getCommandPaletteMode(input: {
573 currentView: CommandPaletteView | null;
574 isBrowsing: boolean;
575}): CommandPaletteMode {
576 if (input.currentView) {
577 return input.isBrowsing ? "submenu-browse" : "submenu";
578 }
579 return input.isBrowsing ? "root-browse" : "root";
580}
581
582export function buildRootGroups(input: {
583 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
584 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
585}): CommandPaletteGroup[] {
586 const groups: CommandPaletteGroup[] = [];
587 if (input.actionItems.length > 0) {
588 groups.push({ value: "actions", label: "Actions", items: input.actionItems });
589 }
590 if (input.recentThreadItems.length > 0) {
591 groups.push({
592 value: "recent-threads",
593 label: "Recent Threads",
594 items: input.recentThreadItems,
595 });
596 }
597 return groups;
598}
599
600export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
601 switch (mode) {
602 case "root":
603 return "Search commands, projects, and threads...";
604 case "root-browse":
605 return "Enter project path (e.g. ~/projects/my-app)";
606 case "submenu":
607 return "Search...";
608 case "submenu-browse":
609 return "Enter path (e.g. ~/projects/my-app)";
610 }
611}