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