Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CommandPalette.logic.ts

837 lines28.3 KB

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