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