Open History to see the last commit
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 }));
56}
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!";
69}
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;
87}
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 }
151}
152
153export interface CommandPaletteThreadContentMatch {
154 readonly source: "user" | "assistant";
155 readonly snippet: string;
156 readonly query: string;
157}
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 /** Title ranges the current query matched, for highlighting. */
172 readonly titleRanges?: ReadonlyArray<SearchRange>;
173 /** Shown in place of the description when the match is not in the title. */
174 readonly matchHint?: SearchMatchHint;
175 readonly icon: ReactNode;
176 readonly disabled?: boolean;
177 readonly titleLeadingContent?: ReactNode;
178 readonly titleTrailingContent?: ReactNode;
179 readonly shortcutCommand?: KeybindingCommand;
180 readonly secondary?: boolean;
181}
182
183export interface CommandPaletteActionItem extends CommandPaletteItem {
184 readonly kind: "action";
185 readonly keepOpen?: boolean;
186 readonly run: () => Promise<void>;
187}
188
189export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
190 readonly kind: "submenu";
191 readonly addonIcon: ReactNode;
192 readonly groups: ReadonlyArray<CommandPaletteGroup>;
193 readonly initialQuery?: string;
194}
195
196export interface CommandPaletteGroup {
197 readonly value: string;
198 readonly label: string;
199 readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
200}
201
202export interface CommandPaletteView {
203 readonly addonIcon: ReactNode;
204 readonly groups: ReadonlyArray<CommandPaletteGroup>;
205 readonly initialQuery?: string;
206}
207
208// Child search unmounts the palette; retain search data without its view closures.
209export interface CommandPaletteReturnContext {
210 readonly query: string;
211 readonly linkedThreadSearch: Extract<CommandPaletteOpenIntent, { kind: "search" }> | null;
212}
213
214export interface CommandPaletteSearchState {
215 readonly query: string;
216 readonly views: ReadonlyArray<{
217 readonly view: CommandPaletteView;
218 readonly parentQuery: string;
219 }>;
220}
221
222export function createCommandPaletteSearchState(query = ""): CommandPaletteSearchState {
223 return { query, views: [] };
224}
225
226export function reduceCommandPaletteSearchState(
227 state: CommandPaletteSearchState,
228 action:
229 | { readonly type: "query"; readonly query: string }
230 | { readonly type: "push"; readonly view: CommandPaletteView }
231 | { readonly type: "back" }
232 | { readonly type: "reset"; readonly query?: string },
233): CommandPaletteSearchState {
234 switch (action.type) {
235 case "query":
236 return { ...state, query: action.query };
237 case "push":
238 return {
239 query: action.view.initialQuery ?? "",
240 views: [...state.views, { view: action.view, parentQuery: state.query }],
241 };
242 case "back": {
243 const parent = state.views.at(-1);
244 return parent ? { query: parent.parentQuery, views: state.views.slice(0, -1) } : state;
245 }
246 case "reset":
247 return createCommandPaletteSearchState(action.query);
248 }
249}
250
251export type CommandPaletteRow =
252 | {
253 readonly kind: "label";
254 readonly key: string;
255 readonly label: string;
256 readonly first: boolean;
257 }
258 | {
259 readonly kind: "item";
260 readonly key: string;
261 readonly item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
262 readonly itemIndex: number | null;
263 };
264
265export function buildCommandPaletteRows(groups: ReadonlyArray<CommandPaletteGroup>) {
266 const rows: CommandPaletteRow[] = [];
267 const itemValues: string[] = [];
268 const rowIndexByItemIndex: number[] = [];
269 for (const group of groups) {
270 if (group.label) {
271 rows.push({
272 kind: "label",
273 key: `group:${group.value}`,
274 label: group.label,
275 first: rows.length === 0,
276 });
277 }
278 for (const item of group.items) {
279 const itemIndex = item.disabled ? null : itemValues.length;
280 if (itemIndex !== null) {
281 itemValues.push(item.value);
282 rowIndexByItemIndex.push(rows.length);
283 }
284 rows.push({ kind: "item", key: `${group.value}:${item.value}`, item, itemIndex });
285 }
286 }
287 return { rows, itemValues, rowIndexByItemIndex };
288}
289
290export function findHighlightedCommandPaletteItem(
291 groups: ReadonlyArray<CommandPaletteGroup>,
292 highlightedItemValue: string | null,
293): CommandPaletteActionItem | CommandPaletteSubmenuItem | null {
294 if (highlightedItemValue === null) return null;
295 for (const group of groups) {
296 for (const item of group.items) {
297 if (item.value === highlightedItemValue && !item.disabled) return item;
298 }
299 }
300 return null;
301}
302
303export function enumerateCommandPaletteItems(
304 items: ReadonlyArray<CommandPaletteActionItem>,
305): CommandPaletteActionItem[] {
306 return items.map((item, index) => {
307 const shortcutCommand = THREAD_JUMP_KEYBINDING_COMMANDS[index];
308 if (shortcutCommand) return { ...item, shortcutCommand };
309
310 const { shortcutCommand: _shortcutCommand, ...itemWithoutShortcut } = item;
311 return itemWithoutShortcut;
312 });
313}
314
315export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
316
317export type CommandPaletteProject = Project & { readonly displayName: string };
318
319export function buildCommandPaletteProjectMetadata(input: {
320 readonly projects: ReadonlyArray<Pick<Project, "environmentId" | "title" | "workspaceRoot">>;
321 readonly locationByEnvironmentId: ReadonlyMap<EnvironmentId, { readonly label: string }>;
322}) {
323 const searchTerms: string[] = [];
324 const environmentLabels = new Set<string>();
325
326 for (const project of input.projects) {
327 const label = input.locationByEnvironmentId.get(project.environmentId)?.label ?? "Remote";
328 searchTerms.push(project.title, project.workspaceRoot, label);
329 environmentLabels.add(label);
330 }
331
332 return { searchTerms, environmentLabels: [...environmentLabels] };
333}
334
335export function buildProjectActionItems(input: {
336 projects: ReadonlyArray<CommandPaletteProject>;
337 valuePrefix: string;
338 icon: (project: CommandPaletteProject) => ReactNode;
339 runProject: (project: CommandPaletteProject) => Promise<void>;
340 searchTerms?: (project: CommandPaletteProject) => ReadonlyArray<string>;
341 renderDescription?: (project: CommandPaletteProject) => ReactNode;
342 shortcutCommand?: KeybindingCommand;
343}): CommandPaletteActionItem[] {
344 return input.projects.map((project) => ({
345 kind: "action",
346 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
347 searchTerms: [
348 project.displayName,
349 project.title,
350 project.workspaceRoot,
351 ...(input.searchTerms?.(project) ?? []),
352 ],
353 title: project.displayName,
354 description: input.renderDescription?.(project) ?? project.workspaceRoot,
355 icon: input.icon(project),
356 ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
357 run: async () => {
358 await input.runProject(project);
359 },
360 }));
361}
362
363export type BuildThreadActionItemsThread = Pick<
364 SidebarThreadSummary,
365 | "archivedAt"
366 | "branch"
367 | "createdAt"
368 | "environmentId"
369 | "id"
370 | "lineage"
371 | "modelSelection"
372 | "projectId"
373 | "runtime"
374 | "title"
375 | "worktreePath"
376> &
377 Partial<
378 Pick<
379 SidebarThreadSummary,
380 "pullRequests" | "linkedPullRequest" | "branchPullRequest" | "opens" | "latestUserMessageAt"
381 >
382 > & {
383 updatedAt: string;
384 };
385
386export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: {
387 threads: ReadonlyArray<TThread>;
388 activeThread?: Pick<Thread, "environmentId" | "id">;
389 projectByKey: ReadonlyMap<string, Pick<Project, "title">>;
390 icon: ReactNode;
391 renderLeadingContent?: (thread: TThread) => ReactNode;
392 renderTrailingContent?: (thread: TThread) => ReactNode;
393 renderDescription?: (thread: TThread, meta: { projectTitle: string | undefined }) => ReactNode;
394 runThread: (thread: TThread) => Promise<void>;
395 /** Makes the environment searchable; pass it only with two or more environments. */
396 environmentLabelOf?: (thread: TThread) => string | null;
397}): CommandPaletteActionItem[] {
398 // Callers order these: recents by last use, search results by rank.
399 const visibleThreads = input.threads.filter(
400 (thread) => thread.archivedAt === null && !isSidebarSubagentThread(thread),
401 );
402
403 return visibleThreads.map((thread) => {
404 const projectTitle = input.projectByKey.get(
405 `${thread.environmentId}:${thread.projectId}`,
406 )?.title;
407 const descriptionParts: string[] = [];
408
409 if (projectTitle) {
410 descriptionParts.push(projectTitle);
411 }
412 if (thread.branch) {
413 descriptionParts.push(`#${thread.branch}`);
414 }
415 const isCurrent =
416 thread.id === input.activeThread?.id &&
417 thread.environmentId === input.activeThread.environmentId;
418 if (isCurrent) {
419 descriptionParts.push("Current thread");
420 }
421
422 const leadingContent = input.renderLeadingContent?.(thread);
423 const trailingContent = input.renderTrailingContent?.(thread);
424 const description = input.renderDescription
425 ? input.renderDescription(thread, { projectTitle })
426 : descriptionParts.join(` · `);
427
428 return Object.assign(
429 {
430 kind: "action" as const,
431 value: `thread:${thread.environmentId}:${thread.id}`,
432 searchTerms: [thread.title],
433 threadSearch: threadSearchSubject(
434 {
435 ...thread,
436 latestUserMessageAt: thread.latestUserMessageAt ?? null,
437 opens: thread.opens ?? null,
438 },
439 projectTitle,
440 input.environmentLabelOf?.(thread),
441 ),
442 title: thread.title,
443 description,
444 timestamp: formatRelativeTimeLabel(
445 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
446 ),
447 icon: input.icon,
448 },
449 leadingContent ? { titleLeadingContent: leadingContent } : {},
450 trailingContent ? { titleTrailingContent: trailingContent } : {},
451 // Last in its group: picking the thread already open does nothing.
452 isCurrent ? { secondary: true } : {},
453 {
454 run: async () => {
455 await input.runThread(thread);
456 },
457 },
458 );
459 });
460}
461
462type PaletteItem = CommandPaletteActionItem | CommandPaletteSubmenuItem;
463
464function rankPaletteItem(
465 item: PaletteItem,
466 normalizedQuery: string,
467 now: number,
468 options: { readonly typos: boolean },
469): {
470 readonly score: number;
471 readonly quality: number;
472 readonly groupQuality?: number;
473 readonly strong: boolean;
474 readonly ranges: ReadonlyArray<SearchRange>;
475 readonly explain?: () => SearchMatchHint | undefined;
476 readonly pickedAt?: number;
477 readonly pickedExactly?: boolean;
478} | null {
479 const match = scorePaletteItem(item, normalizedQuery, now, options);
480 // A row listed last in its group (a keybinding setting, the open thread)
481 // does not decide where the group sits.
482 return match && item.secondary ? { ...match, groupQuality: 0 } : match;
483}
484
485function scorePaletteItem(
486 item: PaletteItem,
487 normalizedQuery: string,
488 now: number,
489 options: { readonly typos: boolean },
490) {
491 if (item.threadSearch) return scoreThreadSearch(normalizedQuery, item.threadSearch, now, options);
492 // The title names the item; search terms are keywords. Ranges index the
493 // first term, so they only highlight a title that is that term.
494 const name = typeof item.title === "string" ? item.title : item.searchTitle;
495 const terms =
496 name !== undefined && name !== item.searchTerms[0]
497 ? [name, ...item.searchTerms]
498 : item.searchTerms;
499 const match = scoreSearchTerms(normalizedQuery, terms, options);
500 return match && (item.title === terms[0] ? match : { ...match, ranges: [] });
501}
502
503/**
504 * Equal match classes put commands before threads, so "new" runs "New thread".
505 * Server message matches stay in a final group so late results cannot move earlier rows.
506 */
507export function filterCommandPaletteGroups(input: {
508 activeGroups: ReadonlyArray<CommandPaletteGroup>;
509 query: string;
510 isInSubmenu: boolean;
511 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
512 settingsSearchItems?: ReadonlyArray<CommandPaletteActionItem>;
513 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
514 /** Threads whose messages match, best first; threads already listed are skipped. */
515 threadMessageItems?: ReadonlyArray<CommandPaletteActionItem>;
516 now?: number;
517}): CommandPaletteGroup[] {
518 const isActionsFilter = input.query.startsWith(">");
519 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
520 const normalizedQuery = foldSearchQuery(searchQuery);
521
522 if (normalizedQuery.length === 0) {
523 if (isActionsFilter) {
524 return input.activeGroups.filter((group) => group.value === "actions");
525 }
526 return [...input.activeGroups];
527 }
528
529 let baseGroups = [...input.activeGroups];
530 if (isActionsFilter) {
531 baseGroups = baseGroups.filter((group) => group.value === "actions");
532 } else if (!input.isInSubmenu) {
533 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
534 }
535
536 const searchableGroups = [...baseGroups];
537 const searchesEverything = !input.isInSubmenu && !isActionsFilter;
538 // On equal match classes, groups keep this order: threads, what people search
539 // for most, right after commands.
540 if (searchesEverything) {
541 if (input.threadSearchItems.length > 0) {
542 searchableGroups.push({
543 value: "threads-search",
544 label: "Threads",
545 items: input.threadSearchItems,
546 });
547 }
548 if (input.projectSearchItems.length > 0) {
549 searchableGroups.push({
550 value: "projects-search",
551 label: "Projects",
552 items: input.projectSearchItems,
553 });
554 }
555 if (input.settingsSearchItems && input.settingsSearchItems.length > 0) {
556 searchableGroups.push({
557 value: "settings-search",
558 label: "Settings",
559 items: input.settingsSearchItems,
560 });
561 }
562 }
563
564 const now = input.now ?? Date.now();
565 const ranked = rankSearchGroups(
566 searchableGroups.map((group) => ({ group, items: group.items })),
567 (item, options) => rankPaletteItem(item, normalizedQuery, now, options),
568 );
569 const threadsMatch = ranked.some(({ group }) => group.value === "threads-search");
570 const groups = ranked.map(({ group, ranked }): CommandPaletteGroup => {
571 // Secondary items stay below the rest; the sort is stable, so score order holds.
572 const limit =
573 group.value === "threads-search"
574 ? PALETTE_THREAD_LIMIT
575 : searchesEverything && threadsMatch
576 ? PALETTE_SECONDARY_LIMIT
577 : ranked.length;
578 // Hints are built only for the rows shown.
579 const items = ranked
580 .toSorted(
581 (left, right) =>
582 Number(left.item.secondary ?? false) - Number(right.item.secondary ?? false),
583 )
584 .slice(0, limit)
585 .map(({ item, match }) => {
586 if (match.ranges.length > 0) return { ...item, titleRanges: match.ranges };
587 // Built only for the rows shown.
588 const matchHint = match.explain?.();
589 return matchHint ? { ...item, matchHint } : item;
590 });
591 return { value: group.value, label: group.label, items };
592 });
593
594 if (!searchesEverything) return groups;
595 const listed = new Set(groups.flatMap((group) => group.items.map((item) => item.value)));
596 // The items arrive cut to what the palette shows; see `nextShownOrder`.
597 const messageItems = (input.threadMessageItems ?? []).filter((item) => !listed.has(item.value));
598 return messageItems.length === 0
599 ? groups
600 : [...groups, { value: "threads-messages", label: "In messages", items: messageItems }];
601}
602
603export function buildBrowseGroups(input: {
604 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
605 browseQuery: string;
606 canBrowseUp: boolean;
607 upIcon: ReactNode;
608 directoryIcon: ReactNode;
609 browseUp: () => void | Promise<void>;
610 browseTo: (name: string) => void | Promise<void>;
611}): CommandPaletteGroup[] {
612 const items: CommandPaletteActionItem[] = [];
613
614 if (input.canBrowseUp) {
615 items.push({
616 kind: "action",
617 value: "browse:up",
618 searchTerms: [input.browseQuery, ".."],
619 title: "..",
620 icon: input.upIcon,
621 keepOpen: true,
622 run: async () => {
623 await input.browseUp();
624 },
625 });
626 }
627
628 for (const entry of input.browseEntries) {
629 items.push({
630 kind: "action",
631 value: `browse:${entry.fullPath}`,
632 searchTerms: [input.browseQuery, entry.fullPath, entry.name],
633 title: entry.name,
634 icon: input.directoryIcon,
635 keepOpen: true,
636 run: async () => {
637 await input.browseTo(entry.name);
638 },
639 });
640 }
641
642 return [{ value: "directories", label: "Directories", items }];
643}
644
645export function filterPinnedBrowseEntries(input: {
646 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
647 filterQuery: string;
648 pinnedDirectoryName: string;
649 caseSensitive: boolean;
650}): ReturnType<typeof filterFilesystemBrowseEntries> {
651 const namesMatch = (left: string, right: string) =>
652 input.caseSensitive ? left === right : left.toLowerCase() === right.toLowerCase();
653 const visibleFilterQuery = namesMatch(input.filterQuery, input.pinnedDirectoryName)
654 ? ""
655 : input.filterQuery;
656 const { visibleEntries } = filterFilesystemBrowseEntries(input.browseEntries, visibleFilterQuery);
657 const exactEntry =
658 input.filterQuery.length > 0
659 ? (input.browseEntries.find((entry) => namesMatch(entry.name, input.filterQuery)) ?? null)
660 : null;
661 return { visibleEntries, exactEntry };
662}
663
664export function getCommandPaletteMode(input: {
665 currentView: CommandPaletteView | null;
666 isBrowsing: boolean;
667}): CommandPaletteMode {
668 if (input.currentView) {
669 return input.isBrowsing ? "submenu-browse" : "submenu";
670 }
671 return input.isBrowsing ? "root-browse" : "root";
672}
673
674export function buildRootGroups(input: {
675 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
676 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
677}): CommandPaletteGroup[] {
678 const groups: CommandPaletteGroup[] = [];
679 if (input.actionItems.length > 0) {
680 groups.push({ value: "actions", label: "Actions", items: input.actionItems });
681 }
682 if (input.recentThreadItems.length > 0) {
683 groups.push({
684 value: "recent-threads",
685 label: "Recent Threads",
686 items: input.recentThreadItems,
687 });
688 }
689 return groups;
690}
691
692export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
693 switch (mode) {
694 case "root":
695 return "Search commands, projects, and threads...";
696 case "root-browse":
697 return "Enter project path (e.g. ~/projects/my-app)";
698 case "submenu":
699 return "Search...";
700 case "submenu-browse":
701 return "Enter path (e.g. ~/projects/my-app)";
702 }
703}
704
705export function getEnvironmentBrowsePlatform(os: string | null | undefined): string {
706 if (os === "windows") {
707 return "Win32";
708 }
709 if (os === "darwin") {
710 return "MacIntel";
711 }
712 if (os === "linux") {
713 return "Linux";
714 }
715 return typeof navigator === "undefined" ? "" : navigator.platform;
716}
717
718export interface AddProjectEnvironmentOption {
719 readonly environmentId: EnvironmentId;
720 readonly label: string;
721 readonly machine: EnvironmentMachineKind;
722 readonly isPrimary: boolean;
723 readonly isConnected: boolean;
724 readonly status: string;
725}
726
727export type AddProjectCloneFlow =
728 | {
729 readonly step: "repository";
730 readonly environmentId: EnvironmentId;
731 readonly source: AddProjectRemoteSource;
732 }
733 | {
734 readonly step: "confirm";
735 readonly environmentId: EnvironmentId;
736 readonly source: AddProjectRemoteSource;
737 readonly repositoryInput: string;
738 readonly repository: SourceControlRepositoryInfo | null;
739 readonly remoteUrl: string;
740 };
741
742export function remoteProjectInputPlaceholder(flow: AddProjectCloneFlow | null): string | null {
743 if (!flow) return null;
744 if (flow.step === "confirm") return null;
745 if (flow.source === "url") {
746 return "Enter Git clone URL";
747 }
748 return `Enter ${addProjectRemoteSourceLabel(flow.source)} repository (${addProjectRemoteSourcePathHint(flow.source)})`;
749}
750
751export function buildPaletteRemoteSourceReadiness(
752 discovery: SourceControlDiscoveryResult | null,
753): AddProjectRemoteSourceReadiness {
754 const readiness = buildAddProjectRemoteSourceReadiness(discovery);
755 return (source) => {
756 const entry = readiness(source);
757 return entry.hint === null
758 ? entry
759 : {
760 ...entry,
761 hint: entry.hint.replace(
762 "Open Source Control settings",
763 "Open Settings -> Source Control",
764 ),
765 };
766 };
767}
768
769export function errorMessage(error: unknown): string {
770 if (error instanceof Error && error.message.trim().length > 0) {
771 return error.message;
772 }
773 return "An error occurred.";
774}
775
776const OVERLAY_MODE_BY_COMMAND = {
777 "commandPalette.toggle": "command",
778 "filePicker.toggle": "files",
779 "projectSearch.toggle": "content",
780} as const satisfies Partial<Record<string, SearchOverlayMode>>;
781
782export function overlayModeForCommand(command: string | null): SearchOverlayMode | null {
783 if (command === null) return null;
784 return command in OVERLAY_MODE_BY_COMMAND
785 ? OVERLAY_MODE_BY_COMMAND[command as keyof typeof OVERLAY_MODE_BY_COMMAND]
786 : null;
787}