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