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