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