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

CommandPalette.logic.ts

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