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 { 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 icon: ReactNode;
139 readonly disabled?: boolean;
140 /** Optional content rendered inline before the title text. */
141 readonly titleLeadingContent?: ReactNode;
142 /** Optional content rendered inline after the title text (before the timestamp). */
143 readonly titleTrailingContent?: ReactNode;
144 readonly shortcutCommand?: KeybindingCommand;
145 /** Sorts after every other match in its group; see `SettingsSearchItem.secondary`. */
146 readonly secondary?: boolean;
147}
148
149export interface CommandPaletteActionItem extends CommandPaletteItem {
150 readonly kind: "action";
151 readonly keepOpen?: boolean;
152 readonly run: () => Promise<void>;
153}
154
155export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
156 readonly kind: "submenu";
157 readonly addonIcon: ReactNode;
158 readonly groups: ReadonlyArray<CommandPaletteGroup>;
159 readonly initialQuery?: string;
160}
161
162export interface CommandPaletteGroup {
163 readonly value: string;
164 readonly label: string;
165 readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
166}
167
168export interface CommandPaletteView {
169 readonly addonIcon: ReactNode;
170 readonly groups: ReadonlyArray<CommandPaletteGroup>;
171 readonly initialQuery?: string;
172}
173
174export function enumerateCommandPaletteItems(
175 items: ReadonlyArray<CommandPaletteActionItem>,
176): CommandPaletteActionItem[] {
177 return items.map((item, index) => {
178 const shortcutCommand = THREAD_JUMP_KEYBINDING_COMMANDS[index];
179 if (shortcutCommand) return { ...item, shortcutCommand };
180
181 const { shortcutCommand: _shortcutCommand, ...itemWithoutShortcut } = item;
182 return itemWithoutShortcut;
183 });
184}
185
186export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
187
188// A project as the palette shows it. `displayName` is the grouped label (for
189// example "owner/repo" when projects are merged across machines). Keep `title`
190// as the real project title: the automatic project icon is derived from it, and
191// every other surface uses the real title, so overriding it desyncs the icon.
192export type CommandPaletteProject = Project & { readonly displayName: string };
193
194export function buildCommandPaletteProjectMetadata(input: {
195 readonly projects: ReadonlyArray<Pick<Project, "environmentId" | "title" | "workspaceRoot">>;
196 readonly locationByEnvironmentId: ReadonlyMap<EnvironmentId, { readonly label: string }>;
197}) {
198 const searchTerms: string[] = [];
199 const environmentLabels = new Set<string>();
200
201 for (const project of input.projects) {
202 const label = input.locationByEnvironmentId.get(project.environmentId)?.label ?? "Remote";
203 searchTerms.push(project.title, project.workspaceRoot, label);
204 environmentLabels.add(label);
205 }
206
207 return { searchTerms, environmentLabels: [...environmentLabels] };
208}
209
210export function buildProjectActionItems(input: {
211 projects: ReadonlyArray<CommandPaletteProject>;
212 valuePrefix: string;
213 icon: (project: CommandPaletteProject) => ReactNode;
214 runProject: (project: CommandPaletteProject) => Promise<void>;
215 searchTerms?: (project: CommandPaletteProject) => ReadonlyArray<string>;
216 renderDescription?: (project: CommandPaletteProject) => ReactNode;
217 shortcutCommand?: KeybindingCommand;
218}): CommandPaletteActionItem[] {
219 return input.projects.map((project) => ({
220 kind: "action",
221 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
222 searchTerms: [
223 project.displayName,
224 project.title,
225 project.workspaceRoot,
226 ...(input.searchTerms?.(project) ?? []),
227 ],
228 title: project.displayName,
229 description: input.renderDescription?.(project) ?? project.workspaceRoot,
230 icon: input.icon(project),
231 ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
232 run: async () => {
233 await input.runProject(project);
234 },
235 }));
236}
237
238export type BuildThreadActionItemsThread = Pick<
239 SidebarThreadSummary,
240 | "archivedAt"
241 | "branch"
242 | "createdAt"
243 | "environmentId"
244 | "id"
245 | "modelSelection"
246 | "projectId"
247 | "session"
248 | "title"
249 | "worktreePath"
250> & {
251 pullRequests?: SidebarThreadSummary["pullRequests"];
252 updatedAt: string;
253 latestUserMessageAt?: string | null;
254};
255
256export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: {
257 threads: ReadonlyArray<TThread>;
258 activeThreadId?: Thread["id"];
259 projectTitleById: ReadonlyMap<Project["id"], string>;
260 sortOrder: SidebarThreadSortOrder;
261 icon: ReactNode;
262 /** Optional content rendered inline before the title text per-thread. */
263 renderLeadingContent?: (thread: TThread) => ReactNode;
264 /** Optional content rendered inline after the title text per-thread. */
265 renderTrailingContent?: (thread: TThread) => ReactNode;
266 /** Optional rich description (e.g. favicon + workspace icons). Falls back to text. */
267 renderDescription?: (thread: TThread, meta: { projectTitle: string | undefined }) => ReactNode;
268 getContentMatch?: (thread: TThread) => CommandPaletteThreadContentMatch | undefined;
269 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
270 limit?: number;
271}): CommandPaletteActionItem[] {
272 const sortedThreads = sortThreads(
273 input.threads.filter((thread) => thread.archivedAt === null),
274 input.sortOrder,
275 );
276 const visibleThreads =
277 input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
278
279 return visibleThreads.map((thread) => {
280 const projectTitle = input.projectTitleById.get(thread.projectId);
281 const descriptionParts: string[] = [];
282
283 if (projectTitle) {
284 descriptionParts.push(projectTitle);
285 }
286 if (thread.branch) {
287 descriptionParts.push(`#${thread.branch}`);
288 }
289 if (thread.id === input.activeThreadId) {
290 descriptionParts.push("Current thread");
291 }
292
293 const leadingContent = input.renderLeadingContent?.(thread);
294 const trailingContent = input.renderTrailingContent?.(thread);
295 const contentMatch = input.getContentMatch?.(thread);
296 const description = input.renderDescription
297 ? input.renderDescription(thread, { projectTitle })
298 : descriptionParts.join(` · `);
299
300 return Object.assign(
301 {
302 kind: "action" as const,
303 value: `thread:${thread.id}`,
304 searchTerms: [
305 thread.title,
306 ...threadPullRequestSearchTerms(thread),
307 projectTitle ?? ``,
308 thread.branch ?? ``,
309 contentMatch?.snippet ?? ``,
310 ],
311 title: thread.title,
312 description,
313 timestamp: formatRelativeTimeLabel(
314 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
315 ),
316 icon: input.icon,
317 },
318 leadingContent ? { titleLeadingContent: leadingContent } : {},
319 trailingContent ? { titleTrailingContent: trailingContent } : {},
320 contentMatch ? { threadContentMatch: contentMatch } : {},
321 {
322 run: async () => {
323 await input.runThread(thread);
324 },
325 },
326 );
327 });
328}
329
330function rankSearchFieldMatch(
331 field: string,
332 normalizedQuery: string,
333 queryTokens: ReadonlyArray<string>,
334): number {
335 const normalizedField = normalizeSearchText(field);
336 if (
337 normalizedField.length === 0 ||
338 !queryTokens.every((token) => normalizedField.includes(token))
339 ) {
340 return Number.NEGATIVE_INFINITY;
341 }
342 if (normalizedField === normalizedQuery) {
343 return 3;
344 }
345 if (normalizedField.startsWith(normalizedQuery)) {
346 return 2;
347 }
348 if (normalizedField.includes(normalizedQuery)) {
349 return 1;
350 }
351 return 0;
352}
353
354function rankCommandPaletteItemMatch(
355 item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
356 normalizedQuery: string,
357 queryTokens: ReadonlyArray<string>,
358): number {
359 const terms = item.searchTerms.filter((term) => term.length > 0);
360 if (terms.length === 0) {
361 return 0;
362 }
363
364 for (const [index, field] of terms.entries()) {
365 const fieldRank = rankSearchFieldMatch(field, normalizedQuery, queryTokens);
366 if (fieldRank !== Number.NEGATIVE_INFINITY) {
367 return 1_000 - index * 100 + fieldRank;
368 }
369 }
370
371 return 0;
372}
373
374export function filterCommandPaletteGroups(input: {
375 activeGroups: ReadonlyArray<CommandPaletteGroup>;
376 query: string;
377 isInSubmenu: boolean;
378 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
379 settingsSearchItems?: ReadonlyArray<CommandPaletteActionItem>;
380 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
381}): CommandPaletteGroup[] {
382 const isActionsFilter = input.query.startsWith(">");
383 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
384 const normalizedQuery = normalizeSearchText(searchQuery);
385
386 if (normalizedQuery.length === 0) {
387 if (isActionsFilter) {
388 return input.activeGroups.filter((group) => group.value === "actions");
389 }
390 return [...input.activeGroups];
391 }
392 const queryTokens = normalizedQuery.split(" ");
393
394 let baseGroups = [...input.activeGroups];
395 if (isActionsFilter) {
396 baseGroups = baseGroups.filter((group) => group.value === "actions");
397 } else if (!input.isInSubmenu) {
398 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
399 }
400
401 const searchableGroups = [...baseGroups];
402 if (!input.isInSubmenu && !isActionsFilter) {
403 if (input.projectSearchItems.length > 0) {
404 searchableGroups.push({
405 value: "projects-search",
406 label: "Projects",
407 items: input.projectSearchItems,
408 });
409 }
410 if (input.settingsSearchItems && input.settingsSearchItems.length > 0) {
411 searchableGroups.push({
412 value: "settings-search",
413 label: "Settings",
414 items: input.settingsSearchItems,
415 });
416 }
417 if (input.threadSearchItems.length > 0) {
418 searchableGroups.push({
419 value: "threads-search",
420 label: "Threads",
421 items: input.threadSearchItems,
422 });
423 }
424 }
425
426 return searchableGroups.flatMap((group) => {
427 const items = Arr.filterMap(group.items, (item, index) => {
428 const haystack = normalizeSearchText(item.searchTerms.join(" "));
429 if (!queryTokens.every((token) => haystack.includes(token))) {
430 return Result.failVoid;
431 }
432
433 return Result.succeed({
434 item,
435 index,
436 rank: rankCommandPaletteItemMatch(item, normalizedQuery, queryTokens),
437 });
438 })
439 .toSorted(
440 (left, right) =>
441 Number(left.item.secondary ?? false) - Number(right.item.secondary ?? false) ||
442 right.rank - left.rank ||
443 left.index - right.index,
444 )
445 .map((entry) => entry.item);
446
447 if (items.length === 0) {
448 return [];
449 }
450
451 return [{ value: group.value, label: group.label, items }];
452 });
453}
454
455export function buildBrowseGroups(input: {
456 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
457 browseQuery: string;
458 canBrowseUp: boolean;
459 upIcon: ReactNode;
460 directoryIcon: ReactNode;
461 browseUp: () => void | Promise<void>;
462 browseTo: (name: string) => void | Promise<void>;
463}): CommandPaletteGroup[] {
464 const items: CommandPaletteActionItem[] = [];
465
466 if (input.canBrowseUp) {
467 items.push({
468 kind: "action",
469 value: "browse:up",
470 searchTerms: [input.browseQuery, ".."],
471 title: "..",
472 icon: input.upIcon,
473 keepOpen: true,
474 run: async () => {
475 await input.browseUp();
476 },
477 });
478 }
479
480 for (const entry of input.browseEntries) {
481 items.push({
482 kind: "action",
483 value: `browse:${entry.fullPath}`,
484 searchTerms: [input.browseQuery, entry.fullPath, entry.name],
485 title: entry.name,
486 icon: input.directoryIcon,
487 keepOpen: true,
488 run: async () => {
489 await input.browseTo(entry.name);
490 },
491 });
492 }
493
494 return [{ value: "directories", label: "Directories", items }];
495}
496
497export function filterPinnedBrowseEntries(input: {
498 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
499 filterQuery: string;
500 pinnedDirectoryName: string;
501 caseSensitive: boolean;
502}): ReturnType<typeof filterFilesystemBrowseEntries> {
503 const namesMatch = (left: string, right: string) =>
504 input.caseSensitive ? left === right : left.toLowerCase() === right.toLowerCase();
505 const visibleFilterQuery = namesMatch(input.filterQuery, input.pinnedDirectoryName)
506 ? ""
507 : input.filterQuery;
508 const { visibleEntries } = filterFilesystemBrowseEntries(input.browseEntries, visibleFilterQuery);
509 const exactEntry =
510 input.filterQuery.length > 0
511 ? (input.browseEntries.find((entry) => namesMatch(entry.name, input.filterQuery)) ?? null)
512 : null;
513 return { visibleEntries, exactEntry };
514}
515
516export function getCommandPaletteMode(input: {
517 currentView: CommandPaletteView | null;
518 isBrowsing: boolean;
519}): CommandPaletteMode {
520 if (input.currentView) {
521 return input.isBrowsing ? "submenu-browse" : "submenu";
522 }
523 return input.isBrowsing ? "root-browse" : "root";
524}
525
526export function buildRootGroups(input: {
527 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
528 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
529}): CommandPaletteGroup[] {
530 const groups: CommandPaletteGroup[] = [];
531 if (input.actionItems.length > 0) {
532 groups.push({ value: "actions", label: "Actions", items: input.actionItems });
533 }
534 if (input.recentThreadItems.length > 0) {
535 groups.push({
536 value: "recent-threads",
537 label: "Recent Threads",
538 items: input.recentThreadItems,
539 });
540 }
541 return groups;
542}
543
544export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
545 switch (mode) {
546 case "root":
547 return "Search commands, projects, and threads...";
548 case "root-browse":
549 return "Enter project path (e.g. ~/projects/my-app)";
550 case "submenu":
551 return "Search...";
552 case "submenu-browse":
553 return "Enter path (e.g. ~/projects/my-app)";
554 }
555}