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