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