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