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