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

CommandPalette.logic.ts

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