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