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

CommandPalette.logic.ts

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