Open History to see the last commit
1import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2import {
3 foldSearchQuery,
4 PALETTE_SECONDARY_LIMIT,
5 PALETTE_THREAD_LIMIT,
6 rankSearchGroups,
7 scoreSearchTerms,
8 scoreThreadSearch,
9 type SearchMatchHint,
10 type SearchRange,
11 type ThreadSearchSubject,
12} from "@t3tools/shared/paletteSearch";
13import { threadSearchSubject } from "@t3tools/client-runtime/state/thread-search";
14import type { CommandPaletteLinkedThreads } from "../commandPaletteBus";
15import type { DraftId } from "../composerDraftStore";
16import {
17 addProjectRemoteSourceLabel,
18 addProjectRemoteSourcePathHint,
19 buildAddProjectRemoteSourceReadiness,
20 type AddProjectRemoteSource,
21 type AddProjectRemoteSourceReadiness,
22} from "@t3tools/client-runtime/operations/projects";
23import {
24 type ScopedThreadRef,
25 type EnvironmentId,
26 type ProjectId,
27 type EnvironmentMachineKind,
28 type FilesystemBrowseEntry,
29 type KeybindingCommand,
30 type SourceControlDiscoveryResult,
31 type SourceControlRepositoryInfo,
32 THREAD_JUMP_KEYBINDING_COMMANDS,
33} from "@t3tools/contracts";
34import { filterFilesystemBrowseEntries } from "@t3tools/client-runtime/state/filesystem";
35import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
36import { type ReactNode } from "react";
37import { msg } from "gt-react";
38import { m, type MessageResolver } from "../i18n/messages";
39import { formatRelativeTimeLabel } from "../timestampFormat";
40import { type Project, type SidebarThreadSummary, type Thread } from "../types";
41
42export const RECENT_THREAD_LIMIT = 12;
43const NO_THREAD_KEYS: ReadonlySet<string> = new Set();
44export const ITEM_ICON_CLASS = "size-4 text-icon-muted";
45export const ADDON_ICON_CLASS = "size-4";
46
47export function buildLinkedThreadActionItems(
48 input: CommandPaletteLinkedThreads & {
49 query: string;
50 icon: ReactNode;
51 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
52 },
53 resolve: MessageResolver = m,
54): CommandPaletteActionItem[] {
55 return input.threads.map((thread) => ({
56 kind: "action",
57 value: `thread:${input.environmentId}:${thread.id}`,
58 threadRef: { environmentId: input.environmentId, threadId: thread.id },
59 title: thread.title || resolve(msg("Untitled thread")),
60 description:
61 thread.archivedAt === null ? resolve(msg("Linked thread")) : resolve(msg("Archived thread")),
62 searchTerms: [input.query, thread.title],
63 icon: input.icon,
64 run: () => input.runThread({ environmentId: input.environmentId, id: thread.id }),
65 }));
66}
67
68export function browseInputEndPaddingClass(input: {
69 readonly willCreateProjectPath: boolean;
70 readonly hasHighlightedBrowseItem: boolean;
71}): string {
72 if (input.willCreateProjectPath) {
73 return "*:data-[slot=autocomplete-input]:pe-38!";
74 }
75 if (input.hasHighlightedBrowseItem) {
76 return "*:data-[slot=autocomplete-input]:pe-30!";
77 }
78 return "*:data-[slot=autocomplete-input]:pe-24!";
79}
80
81export type SearchOverlayMode = "command" | "files" | "content";
82
83export interface WorkspaceFolderPickerTarget {
84 readonly thread: ScopedThreadRef;
85 readonly mode: "directory" | "project-directory";
86}
87
88export type CommandPaletteOpenIntent =
89 | { readonly kind: "new-thread-in" | "change-theme" }
90 | { readonly kind: "change-workspace-folder"; readonly target: WorkspaceFolderPickerTarget }
91 | {
92 readonly kind: "add-project";
93 /** The draft a project is being picked for; one with user content moves to it. */
94 readonly draftId?: DraftId;
95 }
96 | {
97 readonly kind: "search";
98 readonly query: string;
99 readonly linkedThreads?: CommandPaletteLinkedThreads;
100 };
101
102export interface CommandPaletteUiState {
103 readonly open: boolean;
104 readonly mode: SearchOverlayMode;
105 /** What the current palette session opened to; read once when the palette view mounts. */
106 readonly openIntent: CommandPaletteOpenIntent | null;
107 /** Advances when the palette opens or a new intent replaces the current session. */
108 readonly session: number;
109 readonly parentSearch?: CommandPaletteReturnContext;
110 readonly restoredSearch?: CommandPaletteReturnContext;
111}
112
113export type CommandPaletteUiAction =
114 | { readonly _tag: "SetOpen"; readonly open: boolean }
115 | { readonly _tag: "ToggleMode"; readonly mode: SearchOverlayMode }
116 | {
117 readonly _tag: "OpenSearch";
118 readonly query: string;
119 readonly linkedThreads?: CommandPaletteLinkedThreads;
120 }
121 | { readonly _tag: "OpenAddProject"; readonly draftId?: DraftId }
122 | { readonly _tag: "OpenNewThreadIn" }
123 | { readonly _tag: "OpenWorkspaceFolder"; readonly target: WorkspaceFolderPickerTarget }
124 | { readonly _tag: "OpenChangeTheme" }
125 | {
126 readonly _tag: "OpenChildSearch";
127 readonly mode: "files" | "content";
128 readonly context: CommandPaletteReturnContext;
129 }
130 | { readonly _tag: "BackToCommand" };
131
132export function reduceCommandPaletteUiState(
133 state: CommandPaletteUiState,
134 action: CommandPaletteUiAction,
135): CommandPaletteUiState {
136 const { session } = state;
137 const openWithIntent = (openIntent: CommandPaletteOpenIntent): CommandPaletteUiState => ({
138 open: true,
139 mode: "command",
140 openIntent,
141 session: session + 1,
142 });
143 switch (action._tag) {
144 case "SetOpen":
145 return action.open
146 ? {
147 open: true,
148 mode: "command",
149 openIntent: state.openIntent,
150 session: state.open && state.mode === "command" ? session : session + 1,
151 }
152 : { open: false, mode: state.mode, openIntent: null, session };
153 case "ToggleMode":
154 return state.open && state.mode === action.mode
155 ? { open: false, mode: state.mode, openIntent: null, session }
156 : { open: true, mode: action.mode, openIntent: null, session: session + 1 };
157 case "OpenChildSearch":
158 return {
159 open: true,
160 mode: action.mode,
161 openIntent: null,
162 session: state.open ? session : session + 1,
163 parentSearch: action.context,
164 };
165 case "BackToCommand":
166 return state.open && state.mode !== "command"
167 ? {
168 open: true,
169 mode: "command",
170 openIntent: null,
171 session,
172 ...(state.parentSearch ? { restoredSearch: state.parentSearch } : {}),
173 }
174 : state;
175 case "OpenSearch":
176 return openWithIntent({
177 kind: "search",
178 query: action.query,
179 ...(action.linkedThreads ? { linkedThreads: action.linkedThreads } : {}),
180 });
181 case "OpenAddProject":
182 return openWithIntent({
183 kind: "add-project",
184 ...(action.draftId ? { draftId: action.draftId } : {}),
185 });
186 case "OpenWorkspaceFolder":
187 return openWithIntent({ kind: "change-workspace-folder", target: action.target });
188 case "OpenNewThreadIn":
189 return openWithIntent({ kind: "new-thread-in" });
190 case "OpenChangeTheme":
191 return openWithIntent({ kind: "change-theme" });
192 }
193}
194
195/** Where "Add project" starts, given the environments that can take a new project. */
196export type AddProjectEntry =
197 | { readonly kind: "connect-environment" }
198 | { readonly kind: "choose-environment" }
199 | { readonly kind: "choose-source"; readonly environmentId: EnvironmentId };
200
201export function resolveAddProjectEntry(
202 options: ReadonlyArray<Pick<AddProjectEnvironmentOption, "environmentId">>,
203 defaultEnvironmentId: EnvironmentId | null,
204): AddProjectEntry {
205 if (options.length === 0) return { kind: "connect-environment" };
206 if (options.length > 1 || defaultEnvironmentId === null) return { kind: "choose-environment" };
207 return { kind: "choose-source", environmentId: defaultEnvironmentId };
208}
209
210export interface CommandPaletteThreadContentMatch {
211 readonly source: "user" | "assistant";
212 readonly snippet: string;
213 readonly query: string;
214}
215
216export interface CommandPaletteItem {
217 readonly kind: "action" | "submenu";
218 readonly value: string;
219 readonly searchTerms: ReadonlyArray<string>;
220 readonly title: ReactNode;
221 /** The title as plain text, for searching, when `title` is styled. */
222 readonly searchTitle?: string;
223 readonly description?: ReactNode;
224 readonly threadContentMatch?: CommandPaletteThreadContentMatch;
225 readonly timestamp?: string;
226 /** Thread rows rank by this, with use history, instead of by `searchTerms`. */
227 readonly threadSearch?: ThreadSearchSubject;
228 readonly threadRef?: ScopedThreadRef;
229 /** Shown in place of the description when the match is not in the title. */
230 readonly matchHint?: SearchMatchHint;
231 readonly icon: ReactNode;
232 readonly disabled?: boolean;
233 readonly titleLeadingContent?: ReactNode;
234 readonly titleTrailingContent?: ReactNode;
235 readonly shortcutCommand?: KeybindingCommand;
236 readonly secondary?: boolean;
237}
238
239export interface CommandPaletteActionItem extends CommandPaletteItem {
240 readonly kind: "action";
241 readonly keepOpen?: boolean;
242 readonly run: () => Promise<void>;
243 /** A pin toggle on the row, also reached with the pin shortcut while the row is highlighted. */
244 readonly pin?: CommandPaletteItemPin;
245 /** Set on toggle rows; exposed to assistive technology as `aria-checked`. */
246 readonly checked?: boolean;
247}
248
249export interface CommandPaletteItemPin {
250 readonly name: string;
251 readonly pinned: boolean;
252 readonly toggle: () => void;
253}
254
255export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
256 readonly kind: "submenu";
257 readonly addonIcon: ReactNode;
258 readonly groups: ReadonlyArray<CommandPaletteGroup>;
259 readonly initialQuery?: string;
260}
261
262export interface CommandPaletteGroup {
263 readonly value: string;
264 readonly label: string;
265 readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
266}
267
268export interface CommandPaletteView {
269 readonly addonIcon: ReactNode;
270 readonly groups: ReadonlyArray<CommandPaletteGroup>;
271 readonly initialQuery?: string;
272}
273
274// Child search unmounts the palette; retain search data without its view closures.
275export interface CommandPaletteReturnContext {
276 readonly query: string;
277 readonly linkedThreadSearch: Extract<CommandPaletteOpenIntent, { kind: "search" }> | null;
278}
279
280export interface CommandPaletteSearchState {
281 readonly query: string;
282 readonly views: ReadonlyArray<{
283 readonly view: CommandPaletteView;
284 readonly parentQuery: string;
285 }>;
286}
287
288export function createCommandPaletteSearchState(query = ""): CommandPaletteSearchState {
289 return { query, views: [] };
290}
291
292export function reduceCommandPaletteSearchState(
293 state: CommandPaletteSearchState,
294 action:
295 | { readonly type: "query"; readonly query: string }
296 | { readonly type: "push"; readonly view: CommandPaletteView }
297 | { readonly type: "back" }
298 | { readonly type: "reset"; readonly query?: string },
299): CommandPaletteSearchState {
300 switch (action.type) {
301 case "query":
302 return { ...state, query: action.query };
303 case "push":
304 return {
305 query: action.view.initialQuery ?? "",
306 views: [...state.views, { view: action.view, parentQuery: state.query }],
307 };
308 case "back": {
309 const parent = state.views.at(-1);
310 return parent ? { query: parent.parentQuery, views: state.views.slice(0, -1) } : state;
311 }
312 case "reset":
313 return createCommandPaletteSearchState(action.query);
314 }
315}
316
317export type CommandPaletteRow =
318 | {
319 readonly kind: "label";
320 readonly key: string;
321 readonly label: string;
322 readonly first: boolean;
323 }
324 | {
325 readonly kind: "item";
326 readonly key: string;
327 readonly item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
328 readonly itemIndex: number | null;
329 };
330
331export function buildCommandPaletteRows(groups: ReadonlyArray<CommandPaletteGroup>) {
332 const rows: CommandPaletteRow[] = [];
333 const itemValues: string[] = [];
334 const rowIndexByItemIndex: number[] = [];
335 for (const group of groups) {
336 if (group.label) {
337 rows.push({
338 kind: "label",
339 key: `group:${group.value}`,
340 label: group.label,
341 first: rows.length === 0,
342 });
343 }
344 for (const item of group.items) {
345 const itemIndex = item.disabled ? null : itemValues.length;
346 if (itemIndex !== null) {
347 itemValues.push(item.value);
348 rowIndexByItemIndex.push(rows.length);
349 }
350 rows.push({ kind: "item", key: `${group.value}:${item.value}`, item, itemIndex });
351 }
352 }
353 return { rows, itemValues, rowIndexByItemIndex };
354}
355
356export function findHighlightedCommandPaletteItem(
357 groups: ReadonlyArray<CommandPaletteGroup>,
358 highlightedItemValue: string | null,
359): CommandPaletteActionItem | CommandPaletteSubmenuItem | null {
360 if (highlightedItemValue === null) return null;
361 for (const group of groups) {
362 for (const item of group.items) {
363 if (item.value === highlightedItemValue && !item.disabled) return item;
364 }
365 }
366 return null;
367}
368
369export function enumerateCommandPaletteItems(
370 items: ReadonlyArray<CommandPaletteActionItem>,
371): CommandPaletteActionItem[] {
372 return items.map((item, index) => {
373 const shortcutCommand = THREAD_JUMP_KEYBINDING_COMMANDS[index];
374 if (shortcutCommand) return { ...item, shortcutCommand };
375
376 const { shortcutCommand: _shortcutCommand, ...itemWithoutShortcut } = item;
377 return itemWithoutShortcut;
378 });
379}
380
381export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
382
383export type CommandPaletteProject = Project & { readonly displayName: string };
384
385export function buildCommandPaletteProjectMetadata(
386 input: {
387 readonly projects: ReadonlyArray<Pick<Project, "environmentId" | "title" | "workspaceRoot">>;
388 readonly locationByEnvironmentId: ReadonlyMap<EnvironmentId, { readonly label: string }>;
389 },
390 resolve: MessageResolver = m,
391) {
392 const searchTerms: string[] = [];
393 const environmentLabels = new Set<string>();
394
395 for (const project of input.projects) {
396 const label =
397 input.locationByEnvironmentId.get(project.environmentId)?.label ??
398 resolve(msg({ context: "machine location" })`Remote`);
399 searchTerms.push(project.title, project.workspaceRoot, label);
400 environmentLabels.add(label);
401 }
402
403 return { searchTerms, environmentLabels: [...environmentLabels] };
404}
405
406export function buildProjectActionItems(input: {
407 projects: ReadonlyArray<CommandPaletteProject>;
408 valuePrefix: string;
409 icon: (project: CommandPaletteProject) => ReactNode;
410 runProject: (project: CommandPaletteProject) => Promise<void>;
411 searchTerms?: (project: CommandPaletteProject) => ReadonlyArray<string>;
412 renderDescription?: (project: CommandPaletteProject) => ReactNode;
413 shortcutCommand?: KeybindingCommand;
414 pin?: (project: CommandPaletteProject) => CommandPaletteItemPin | null;
415}): CommandPaletteActionItem[] {
416 return input.projects.map((project) => {
417 const pin = input.pin?.(project) ?? null;
418 return {
419 kind: "action",
420 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
421 searchTerms: [
422 project.displayName,
423 project.title,
424 project.workspaceRoot,
425 ...(input.searchTerms?.(project) ?? []),
426 ],
427 title: project.displayName,
428 description: input.renderDescription?.(project) ?? project.workspaceRoot,
429 icon: input.icon(project),
430 ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
431 ...(pin ? { pin } : {}),
432 run: async () => {
433 await input.runProject(project);
434 },
435 };
436 });
437}
438
439export type BuildThreadActionItemsThread = Pick<
440 SidebarThreadSummary,
441 | "archivedAt"
442 | "branch"
443 | "createdAt"
444 | "environmentId"
445 | "id"
446 | "lineage"
447 | "modelSelection"
448 | "projectId"
449 | "runtime"
450 | "title"
451 | "worktreePath"
452> &
453 Partial<
454 Pick<
455 SidebarThreadSummary,
456 "pullRequests" | "linkedPullRequest" | "branchPullRequest" | "opens" | "latestUserMessageAt"
457 >
458 > & {
459 updatedAt: string;
460 };
461
462export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(
463 input: {
464 threads: ReadonlyArray<TThread>;
465 activeThread?: Pick<Thread, "environmentId" | "id">;
466 projectByKey: ReadonlyMap<string, Pick<Project, "title">>;
467 icon: ReactNode;
468 renderLeadingContent?: (thread: TThread) => ReactNode;
469 renderTrailingContent?: (thread: TThread) => ReactNode;
470 renderDescription?: (thread: TThread, meta: { projectTitle: string | undefined }) => ReactNode;
471 runThread: (thread: TThread) => Promise<void>;
472 /** Makes the environment searchable; pass it only with two or more environments. */
473 environmentLabelOf?: (thread: TThread) => string | null;
474 /** Tasks linked environments run for a listed thread; they open from under that thread. */
475 delegatedUnderParent?: ReadonlySet<string>;
476 },
477 resolve: MessageResolver = m,
478): CommandPaletteActionItem[] {
479 const delegatedUnderParent = input.delegatedUnderParent ?? NO_THREAD_KEYS;
480 // Callers order these: recents by last use, search results by rank.
481 const visibleThreads = input.threads.filter(
482 (thread) =>
483 thread.archivedAt === null &&
484 !isShownUnderParent(
485 { environmentId: thread.environmentId, threadId: thread.id },
486 thread.lineage,
487 delegatedUnderParent,
488 ),
489 );
490
491 return visibleThreads.map((thread) => {
492 const projectTitle = input.projectByKey.get(
493 `${thread.environmentId}:${thread.projectId}`,
494 )?.title;
495 const descriptionParts: string[] = [];
496
497 if (projectTitle) {
498 descriptionParts.push(projectTitle);
499 }
500 if (thread.branch) {
501 descriptionParts.push(`#${thread.branch}`);
502 }
503 const isCurrent =
504 thread.id === input.activeThread?.id &&
505 thread.environmentId === input.activeThread.environmentId;
506 if (isCurrent) {
507 descriptionParts.push(resolve(msg("Current thread")));
508 }
509
510 const leadingContent = input.renderLeadingContent?.(thread);
511 const trailingContent = input.renderTrailingContent?.(thread);
512 const description = input.renderDescription
513 ? input.renderDescription(thread, { projectTitle })
514 : descriptionParts.join(` · `);
515
516 return Object.assign(
517 {
518 kind: "action" as const,
519 value: `thread:${thread.environmentId}:${thread.id}`,
520 threadRef: { environmentId: thread.environmentId, threadId: thread.id },
521 searchTerms: [thread.title],
522 threadSearch: threadSearchSubject(
523 {
524 ...thread,
525 latestUserMessageAt: thread.latestUserMessageAt ?? null,
526 opens: thread.opens ?? null,
527 },
528 projectTitle,
529 input.environmentLabelOf?.(thread),
530 ),
531 title: thread.title,
532 description,
533 timestamp: formatRelativeTimeLabel(
534 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
535 undefined,
536 resolve,
537 ),
538 icon: input.icon,
539 },
540 leadingContent ? { titleLeadingContent: leadingContent } : {},
541 trailingContent ? { titleTrailingContent: trailingContent } : {},
542 // Last in its group: picking the thread already open does nothing.
543 isCurrent ? { secondary: true } : {},
544 {
545 run: async () => {
546 await input.runThread(thread);
547 },
548 },
549 );
550 });
551}
552
553type PaletteItem = CommandPaletteActionItem | CommandPaletteSubmenuItem;
554
555function rankPaletteItem(
556 item: PaletteItem,
557 normalizedQuery: string,
558 now: number,
559 options: { readonly typos: boolean },
560): {
561 readonly score: number;
562 readonly quality: number;
563 readonly groupQuality?: number;
564 readonly strong: boolean;
565 readonly ranges: ReadonlyArray<SearchRange>;
566 readonly explain?: () => SearchMatchHint | undefined;
567 readonly pickedAt?: number;
568 readonly pickedExactly?: boolean;
569} | null {
570 const match = scorePaletteItem(item, normalizedQuery, now, options);
571 // A row listed last in its group (a keybinding setting, the open thread)
572 // does not decide where the group sits.
573 return match && item.secondary ? { ...match, groupQuality: 0 } : match;
574}
575
576function scorePaletteItem(
577 item: PaletteItem,
578 normalizedQuery: string,
579 now: number,
580 options: { readonly typos: boolean },
581) {
582 if (item.threadSearch) return scoreThreadSearch(normalizedQuery, item.threadSearch, now, options);
583 // The title names the item; search terms are keywords. Ranges index the
584 // first term, so they only highlight a title that is that term.
585 const name = typeof item.title === "string" ? item.title : item.searchTitle;
586 const terms =
587 name !== undefined && name !== item.searchTerms[0]
588 ? [name, ...item.searchTerms]
589 : item.searchTerms;
590 const match = scoreSearchTerms(normalizedQuery, terms, options);
591 return match && (item.title === terms[0] ? match : { ...match, ranges: [] });
592}
593
594/**
595 * Equal match classes put commands before threads, so "new" runs "New thread".
596 * Server message matches stay in a final group so late results cannot move earlier rows.
597 */
598export function filterCommandPaletteGroups(
599 input: {
600 activeGroups: ReadonlyArray<CommandPaletteGroup>;
601 query: string;
602 isInSubmenu: boolean;
603 /** Submenu options join the root search, and a submenu with no match falls back to it. */
604 allOptions?: {
605 readonly rootGroups: ReadonlyArray<CommandPaletteGroup>;
606 readonly nestedItems: ReadonlyArray<CommandPaletteActionItem>;
607 };
608 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
609 settingsSearchItems?: ReadonlyArray<CommandPaletteActionItem>;
610 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
611 /** Threads whose messages match, best first; threads already listed are skipped. */
612 threadMessageItems?: ReadonlyArray<CommandPaletteActionItem>;
613 now?: number;
614 },
615 resolve: MessageResolver = m,
616): CommandPaletteGroup[] {
617 if (input.allOptions && input.isInSubmenu) {
618 const { allOptions, ...submenuInput } = input;
619 const scoped = filterCommandPaletteGroups(submenuInput, resolve);
620 if (scoped.length > 0 || input.query.trim().length === 0) return scoped;
621 return filterCommandPaletteGroups(
622 {
623 ...input,
624 activeGroups: allOptions.rootGroups,
625 isInSubmenu: false,
626 },
627 resolve,
628 );
629 }
630
631 const isActionsFilter = input.query.startsWith(">");
632 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
633 const normalizedQuery = foldSearchQuery(searchQuery);
634
635 if (normalizedQuery.length === 0) {
636 if (isActionsFilter) {
637 return input.activeGroups.filter((group) => group.value === "actions");
638 }
639 return [...input.activeGroups];
640 }
641
642 let baseGroups = [...input.activeGroups];
643 if (isActionsFilter) {
644 baseGroups = baseGroups.filter((group) => group.value === "actions");
645 } else if (!input.isInSubmenu) {
646 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
647 }
648
649 const searchableGroups = [...baseGroups];
650 const searchesEverything = !input.isInSubmenu && !isActionsFilter;
651 // On equal match classes, groups keep this order: threads, what people search
652 // for most, right after commands.
653 if (searchesEverything) {
654 if (input.allOptions && input.allOptions.nestedItems.length > 0) {
655 searchableGroups.push({
656 value: "nested-search",
657 label: resolve(msg("Suggestions")),
658 items: input.allOptions.nestedItems,
659 });
660 }
661 if (input.threadSearchItems.length > 0) {
662 searchableGroups.push({
663 value: "threads-search",
664 label: resolve(msg("Threads")),
665 items: input.threadSearchItems,
666 });
667 }
668 if (input.projectSearchItems.length > 0) {
669 searchableGroups.push({
670 value: "projects-search",
671 label: resolve(msg("Projects")),
672 items: input.projectSearchItems,
673 });
674 }
675 if (input.settingsSearchItems && input.settingsSearchItems.length > 0) {
676 searchableGroups.push({
677 value: "settings-search",
678 label: resolve(msg("Settings")),
679 items: input.settingsSearchItems,
680 });
681 }
682 }
683
684 const now = input.now ?? Date.now();
685 const ranked = rankSearchGroups(
686 searchableGroups.map((group) => ({ group, items: group.items })),
687 (item, options) => rankPaletteItem(item, normalizedQuery, now, options),
688 );
689 const threadsMatch = ranked.some(({ group }) => group.value === "threads-search");
690 const groups = ranked.map(({ group, ranked }): CommandPaletteGroup => {
691 // Secondary items stay below the rest; the sort is stable, so score order holds.
692 const limit =
693 group.value === "threads-search"
694 ? PALETTE_THREAD_LIMIT
695 : group.value === "nested-search" || (searchesEverything && threadsMatch)
696 ? PALETTE_SECONDARY_LIMIT
697 : ranked.length;
698 // Hints are built only for the rows shown.
699 const items = ranked
700 .toSorted(
701 (left, right) =>
702 Number(left.item.secondary ?? false) - Number(right.item.secondary ?? false),
703 )
704 .slice(0, limit)
705 .map(({ item, match }) => {
706 if (match.ranges.length > 0) return item;
707 // Built only for the rows shown.
708 const matchHint = match.explain?.();
709 return matchHint ? { ...item, matchHint } : item;
710 });
711 return { value: group.value, label: group.label, items };
712 });
713
714 if (!searchesEverything) return groups;
715 const listed = new Set(groups.flatMap((group) => group.items.map((item) => item.value)));
716 // The items arrive cut to what the palette shows; see `nextShownOrder`.
717 const messageItems = (input.threadMessageItems ?? []).filter((item) => !listed.has(item.value));
718 return messageItems.length === 0
719 ? groups
720 : [
721 ...groups,
722 { value: "threads-messages", label: resolve(msg("In messages")), items: messageItems },
723 ];
724}
725
726/** Every option inside a submenu as one row, e.g. "New thread in t3code" or "Change theme: Dracula". */
727export function buildNestedSearchItems(
728 items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>,
729 query: string,
730): CommandPaletteActionItem[] {
731 const nameOf = (item: CommandPaletteItem) =>
732 typeof item.title === "string" ? item.title : item.searchTitle;
733 const topLevelNames = new Set(items.map(nameOf));
734 const foldedQuery = foldSearchQuery(query);
735 return items.flatMap((parent) => {
736 if (parent.kind !== "submenu" || typeof parent.title !== "string") return [];
737 const stem = parent.title.replace(/(\.\.\.|…)$/u, "");
738 // A query that only names the submenu ("new thread in") wants the submenu row itself.
739 if (foldSearchQuery(stem).startsWith(foldedQuery)) return [];
740 const prefix = stem === parent.title ? `${stem}: ` : `${stem.trimEnd()} `;
741 return parent.groups.flatMap((group) =>
742 group.items.flatMap((child) => {
743 const name = nameOf(child);
744 if (child.kind !== "action" || name === undefined) return [];
745 const title = `${prefix}${name}`;
746 if (topLevelNames.has(title)) return [];
747 const { searchTitle: _searchTitle, ...rest } = child;
748 // Only the combined title: child keywords like "theme" would list every theme.
749 return [{ ...rest, title, searchTerms: [title] }];
750 }),
751 );
752 });
753}
754
755export function buildBrowseGroups(
756 input: {
757 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
758 browseQuery: string;
759 canBrowseUp: boolean;
760 upIcon: ReactNode;
761 directoryIcon: ReactNode;
762 browseUp: () => void | Promise<void>;
763 browseTo: (name: string) => void | Promise<void>;
764 },
765 resolve: MessageResolver = m,
766): CommandPaletteGroup[] {
767 const items: CommandPaletteActionItem[] = [];
768
769 if (input.canBrowseUp) {
770 items.push({
771 kind: "action",
772 value: "browse:up",
773 searchTerms: [input.browseQuery, ".."],
774 title: "..",
775 icon: input.upIcon,
776 keepOpen: true,
777 run: async () => {
778 await input.browseUp();
779 },
780 });
781 }
782
783 for (const entry of input.browseEntries) {
784 items.push({
785 kind: "action",
786 value: `browse:${entry.fullPath}`,
787 searchTerms: [input.browseQuery, entry.fullPath, entry.name],
788 title: entry.name,
789 icon: input.directoryIcon,
790 keepOpen: true,
791 run: async () => {
792 await input.browseTo(entry.name);
793 },
794 });
795 }
796
797 return [{ value: "directories", label: resolve(msg("Directories")), items }];
798}
799
800export function filterPinnedBrowseEntries(input: {
801 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
802 filterQuery: string;
803 pinnedDirectoryName: string;
804 caseSensitive: boolean;
805}): ReturnType<typeof filterFilesystemBrowseEntries> {
806 const namesMatch = (left: string, right: string) =>
807 input.caseSensitive ? left === right : left.toLowerCase() === right.toLowerCase();
808 const visibleFilterQuery = namesMatch(input.filterQuery, input.pinnedDirectoryName)
809 ? ""
810 : input.filterQuery;
811 const { visibleEntries } = filterFilesystemBrowseEntries(input.browseEntries, visibleFilterQuery);
812 const normalizedFilterQuery = input.filterQuery.normalize("NFC");
813 const normalizedMatches = input.browseEntries.filter((entry) =>
814 namesMatch(entry.name.normalize("NFC"), normalizedFilterQuery),
815 );
816 const exactEntry =
817 input.filterQuery.length > 0
818 ? (input.browseEntries.find((entry) => namesMatch(entry.name, input.filterQuery)) ??
819 (normalizedMatches.length === 1 ? normalizedMatches[0] : null))
820 : null;
821 return { visibleEntries, exactEntry };
822}
823
824export function getCommandPaletteMode(input: {
825 currentView: CommandPaletteView | null;
826 isBrowsing: boolean;
827}): CommandPaletteMode {
828 if (input.currentView) {
829 return input.isBrowsing ? "submenu-browse" : "submenu";
830 }
831 return input.isBrowsing ? "root-browse" : "root";
832}
833
834export function buildRootGroups(
835 input: {
836 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
837 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
838 },
839 resolve: MessageResolver = m,
840): CommandPaletteGroup[] {
841 const groups: CommandPaletteGroup[] = [];
842 if (input.actionItems.length > 0) {
843 groups.push({ value: "actions", label: resolve(msg("Actions")), items: input.actionItems });
844 }
845 if (input.recentThreadItems.length > 0) {
846 groups.push({
847 value: "recent-threads",
848 label: resolve(msg("Recent Threads")),
849 items: input.recentThreadItems,
850 });
851 }
852 return groups;
853}
854
855export function getCommandPaletteInputPlaceholder(
856 mode: CommandPaletteMode,
857 resolve: MessageResolver = m,
858): string {
859 switch (mode) {
860 case "root":
861 return resolve(msg("Search commands, projects, and threads..."));
862 case "root-browse":
863 return resolve(msg("Enter project path (e.g. ~/projects/my-app)"));
864 case "submenu":
865 return resolve(msg("Search..."));
866 case "submenu-browse":
867 return resolve(msg("Enter path (e.g. ~/projects/my-app)"));
868 }
869}
870
871export function getEnvironmentBrowsePlatform(os: string | null | undefined): string {
872 if (os === "windows") {
873 return "Win32";
874 }
875 if (os === "darwin") {
876 return "MacIntel";
877 }
878 if (os === "linux") {
879 return "Linux";
880 }
881 return typeof navigator === "undefined" ? "" : navigator.platform;
882}
883
884export interface AddProjectEnvironmentOption {
885 readonly environmentId: EnvironmentId;
886 readonly label: string;
887 readonly machine: EnvironmentMachineKind;
888 readonly isPrimary: boolean;
889 readonly isConnected: boolean;
890 readonly status: string;
891}
892
893export type AddProjectCloneFlow =
894 | {
895 readonly step: "repository";
896 readonly environmentId: EnvironmentId;
897 readonly source: AddProjectRemoteSource;
898 }
899 | {
900 readonly step: "confirm";
901 readonly environmentId: EnvironmentId;
902 readonly source: AddProjectRemoteSource;
903 readonly repositoryInput: string;
904 readonly repository: SourceControlRepositoryInfo | null;
905 readonly remoteUrl: string;
906 };
907
908export function remoteProjectInputPlaceholder(
909 flow: AddProjectCloneFlow | null,
910 resolve: MessageResolver = m,
911): string | null {
912 if (!flow) return null;
913 if (flow.step === "confirm") return null;
914 if (flow.source === "url") {
915 return resolve(msg("Enter Git clone URL"));
916 }
917 return resolve(
918 msg`Enter ${{ source: addProjectRemoteSourceLabel(flow.source, resolve) }} repository (${{ hint: addProjectRemoteSourcePathHint(flow.source, resolve) }})`,
919 );
920}
921
922export function buildPaletteRemoteSourceReadiness(
923 discovery: SourceControlDiscoveryResult | null,
924 resolve: MessageResolver = m,
925): AddProjectRemoteSourceReadiness {
926 return buildAddProjectRemoteSourceReadiness(discovery, resolve);
927}
928
929export function errorMessage(error: unknown, resolve: MessageResolver = m): string {
930 return (
931 (error instanceof Error ? errorDisplayMessage(error, resolve) : null) ??
932 resolve(msg("An error occurred."))
933 );
934}
935
936const OVERLAY_MODE_BY_COMMAND = {
937 "commandPalette.toggle": "command",
938 "filePicker.toggle": "files",
939 "projectSearch.toggle": "content",
940} as const satisfies Partial<Record<string, SearchOverlayMode>>;
941
942export function overlayModeForCommand(command: string | null): SearchOverlayMode | null {
943 if (command === null) return null;
944 return command in OVERLAY_MODE_BY_COMMAND
945 ? OVERLAY_MODE_BY_COMMAND[command as keyof typeof OVERLAY_MODE_BY_COMMAND]
946 : null;
947}
948
949export function resolveCommandPaletteProject<TProject>(
950 projects: ReadonlyMap<string, TProject>,
951 environmentId: EnvironmentId | null,
952 projectId: ProjectId | null,
953) {
954 return environmentId && projectId ? projects.get(`${environmentId}:${projectId}`) : undefined;
955}
956
957/**
958 * Where "No project" goes among the new-thread picker's real projects: at the
959 * scratch project's own place when it is pinned or current, else after the
960 * pinned projects and the first unpinned one.
961 */
962export function newThreadNoProjectIndex(
963 entries: ReadonlyArray<{
964 readonly isScratch: boolean;
965 readonly pinned: boolean;
966 readonly isPreferred: boolean;
967 }>,
968): number {
969 const projects = entries.filter((entry) => !entry.isScratch);
970 const scratchAt = entries.findIndex((entry) => entry.isScratch);
971 const scratch = entries[scratchAt];
972 if (scratch && (scratch.pinned || scratch.isPreferred)) {
973 return entries.slice(0, scratchAt).filter((entry) => !entry.isScratch).length;
974 }
975 const pinnedCount = projects.filter((entry) => entry.pinned).length;
976 return Math.min(pinnedCount + 1, projects.length);
977}