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