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

CommandPalette.logic.ts

753 lines24.0 KB

1import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
2import type { CommandPaletteLinkedThreads } from "../commandPaletteBus";
3import {
4 addProjectRemoteSourceLabel,
5 addProjectRemoteSourcePathHint,
6 buildAddProjectRemoteSourceReadiness,
7 type AddProjectRemoteSource,
8 type AddProjectRemoteSourceReadiness,
9} from "@t3tools/client-runtime/operations/projects";
10import {
11 type EnvironmentId,
12 type EnvironmentMachineKind,
13 type FilesystemBrowseEntry,
14 type KeybindingCommand,
15 type SourceControlDiscoveryResult,
16 type SourceControlRepositoryInfo,
17 THREAD_JUMP_KEYBINDING_COMMANDS,
18} from "@t3tools/contracts";
19import { filterFilesystemBrowseEntries } from "@t3tools/client-runtime/state/filesystem";
20import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
21import * as Arr from "effect/Array";
22import * as Result from "effect/Result";
23import { type ReactNode } from "react";
24import { getThreadSortTimestamp, sortThreads } from "../lib/threadSort";
25import { normalizeSearchText } from "../lib/utils";
26import { formatRelativeTimeLabel } from "../timestampFormat";
27import { type Project, type SidebarThreadSummary, type Thread } from "../types";
28​
29export const RECENT_THREAD_LIMIT = 12;
30export const ITEM_ICON_CLASS = "size-4 text-icon-muted";
31export const ADDON_ICON_CLASS = "size-4";
32​
33export function buildLinkedThreadActionItems(
34 input: CommandPaletteLinkedThreads & {
35 query: string;
36 icon: ReactNode;
37 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
38 },
39): CommandPaletteActionItem[] {
40 return input.threads.map((thread) => ({
41 kind: "action",
42 value: `thread:${input.environmentId}:${thread.id}`,
43 title: thread.title || "Untitled thread",
44 description: thread.archivedAt === null ? "Linked thread" : "Archived thread",
45 searchTerms: [input.query, thread.title],
46 icon: input.icon,
47 run: () => input.runThread({ environmentId: input.environmentId, id: thread.id }),
48 }));
50​
51export function browseInputEndPaddingClass(input: {
52 readonly willCreateProjectPath: boolean;
53 readonly hasHighlightedBrowseItem: boolean;
54}): string {
55 if (input.willCreateProjectPath) {
56 return "*:data-[slot=autocomplete-input]:pe-38!";
57 }
58 if (input.hasHighlightedBrowseItem) {
59 return "*:data-[slot=autocomplete-input]:pe-30!";
60 }
61 return "*:data-[slot=autocomplete-input]:pe-24!";
63​
64export type SearchOverlayMode = "command" | "files" | "content";
65​
66export type CommandPaletteOpenIntent =
67 | { readonly kind: "add-project" | "new-thread-in" | "change-theme" }
68 | {
69 readonly kind: "search";
70 readonly query: string;
71 readonly linkedThreads?: CommandPaletteLinkedThreads;
72 };
73​
74export interface CommandPaletteUiState {
75 readonly open: boolean;
76 readonly mode: SearchOverlayMode;
77 readonly openIntent: CommandPaletteOpenIntent | null;
78 readonly parentSearch?: CommandPaletteReturnContext;
79 readonly restoredSearch?: CommandPaletteReturnContext;
81​
82export type CommandPaletteUiAction =
83 | { readonly _tag: "SetOpen"; readonly open: boolean }
84 | { readonly _tag: "ToggleMode"; readonly mode: SearchOverlayMode }
85 | {
86 readonly _tag: "OpenSearch";
87 readonly query: string;
88 readonly linkedThreads?: CommandPaletteLinkedThreads;
89 }
90 | { readonly _tag: "OpenAddProject" }
91 | { readonly _tag: "OpenNewThreadIn" }
92 | { readonly _tag: "OpenChangeTheme" }
93 | { readonly _tag: "ClearOpenIntent" }
94 | {
95 readonly _tag: "OpenChildSearch";
96 readonly mode: "files" | "content";
97 readonly context: CommandPaletteReturnContext;
98 }
99 | { readonly _tag: "BackToCommand" };
100​
101export function reduceCommandPaletteUiState(
102 state: CommandPaletteUiState,
103 action: CommandPaletteUiAction,
104): CommandPaletteUiState {
105 switch (action._tag) {
106 case "SetOpen":
107 return action.open
108 ? { open: true, mode: "command", openIntent: state.openIntent }
109 : { open: false, mode: state.mode, openIntent: null };
110 case "ToggleMode":
111 return state.open && state.mode === action.mode
112 ? { open: false, mode: state.mode, openIntent: null }
113 : { open: true, mode: action.mode, openIntent: null };
114 case "OpenChildSearch":
115 return { open: true, mode: action.mode, openIntent: null, parentSearch: action.context };
116 case "BackToCommand":
117 return state.open && state.mode !== "command"
118 ? {
119 open: true,
120 mode: "command",
121 openIntent: null,
122 ...(state.parentSearch ? { restoredSearch: state.parentSearch } : {}),
123 }
124 : state;
125 case "OpenSearch":
126 return {
127 open: true,
128 mode: "command",
129 openIntent: {
130 kind: "search",
131 query: action.query,
132 ...(action.linkedThreads ? { linkedThreads: action.linkedThreads } : {}),
133 },
134 };
135 case "OpenAddProject":
136 return { open: true, mode: "command", openIntent: { kind: "add-project" } };
137 case "OpenNewThreadIn":
138 return { open: true, mode: "command", openIntent: { kind: "new-thread-in" } };
139 case "OpenChangeTheme":
140 return { open: true, mode: "command", openIntent: { kind: "change-theme" } };
141 case "ClearOpenIntent":
142 return state.openIntent ? { ...state, openIntent: null } : state;
143 }
145​
146export interface CommandPaletteThreadContentMatch {
147 readonly source: "user" | "assistant";
148 readonly snippet: string;
149 readonly query: string;
151​
152export interface CommandPaletteItem {
153 readonly kind: "action" | "submenu";
154 readonly value: string;
155 readonly searchTerms: ReadonlyArray<string>;
156 readonly title: ReactNode;
157 readonly description?: ReactNode;
158 readonly threadContentMatch?: CommandPaletteThreadContentMatch;
159 readonly timestamp?: string;
160 readonly searchRecency?: number;
161 readonly icon: ReactNode;
162 readonly disabled?: boolean;
163 readonly titleLeadingContent?: ReactNode;
164 readonly titleTrailingContent?: ReactNode;
165 readonly shortcutCommand?: KeybindingCommand;
166 readonly secondary?: boolean;
168​
169export interface CommandPaletteActionItem extends CommandPaletteItem {
170 readonly kind: "action";
171 readonly keepOpen?: boolean;
172 readonly run: () => Promise<void>;
174​
175export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
176 readonly kind: "submenu";
177 readonly addonIcon: ReactNode;
178 readonly groups: ReadonlyArray<CommandPaletteGroup>;
179 readonly initialQuery?: string;
181​
182export interface CommandPaletteGroup {
183 readonly value: string;
184 readonly label: string;
185 readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
187​
188export interface CommandPaletteView {
189 readonly addonIcon: ReactNode;
190 readonly groups: ReadonlyArray<CommandPaletteGroup>;
191 readonly initialQuery?: string;
193​
194// Child search unmounts the palette; retain search data without its view closures.
195export interface CommandPaletteReturnContext {
196 readonly query: string;
197 readonly linkedThreadSearch: Extract<CommandPaletteOpenIntent, { kind: "search" }> | null;
199​
200export interface CommandPaletteSearchState {
201 readonly query: string;
202 readonly views: ReadonlyArray<{
203 readonly view: CommandPaletteView;
204 readonly parentQuery: string;
205 }>;
207​
208export function createCommandPaletteSearchState(query = ""): CommandPaletteSearchState {
209 return { query, views: [] };
211​
212export function reduceCommandPaletteSearchState(
213 state: CommandPaletteSearchState,
214 action:
215 | { readonly type: "query"; readonly query: string }
216 | { readonly type: "push"; readonly view: CommandPaletteView }
217 | { readonly type: "back" }
218 | { readonly type: "reset"; readonly query?: string },
219): CommandPaletteSearchState {
220 switch (action.type) {
221 case "query":
222 return { ...state, query: action.query };
223 case "push":
224 return {
225 query: action.view.initialQuery ?? "",
226 views: [...state.views, { view: action.view, parentQuery: state.query }],
227 };
228 case "back": {
229 const parent = state.views.at(-1);
230 return parent ? { query: parent.parentQuery, views: state.views.slice(0, -1) } : state;
231 }
232 case "reset":
233 return createCommandPaletteSearchState(action.query);
234 }
236​
237export type CommandPaletteRow =
238 | {
239 readonly kind: "label";
240 readonly key: string;
241 readonly label: string;
242 readonly first: boolean;
243 }
244 | {
245 readonly kind: "item";
246 readonly key: string;
247 readonly item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
248 readonly itemIndex: number | null;
249 };
250​
251export function buildCommandPaletteRows(groups: ReadonlyArray<CommandPaletteGroup>) {
252 const rows: CommandPaletteRow[] = [];
253 const itemValues: string[] = [];
254 const rowIndexByItemIndex: number[] = [];
255 for (const group of groups) {
256 if (group.label) {
257 rows.push({
258 kind: "label",
259 key: `group:${group.value}`,
260 label: group.label,
261 first: rows.length === 0,
262 });
263 }
264 for (const item of group.items) {
265 const itemIndex = item.disabled ? null : itemValues.length;
266 if (itemIndex !== null) {
267 itemValues.push(item.value);
268 rowIndexByItemIndex.push(rows.length);
269 }
270 rows.push({ kind: "item", key: `${group.value}:${item.value}`, item, itemIndex });
271 }
272 }
273 return { rows, itemValues, rowIndexByItemIndex };
275​
276export function findHighlightedCommandPaletteItem(
277 groups: ReadonlyArray<CommandPaletteGroup>,
278 highlightedItemValue: string | null,
279): CommandPaletteActionItem | CommandPaletteSubmenuItem | null {
280 if (highlightedItemValue === null) return null;
281 for (const group of groups) {
282 for (const item of group.items) {
283 if (item.value === highlightedItemValue && !item.disabled) return item;
284 }
285 }
286 return null;
288​
289export function enumerateCommandPaletteItems(
290 items: ReadonlyArray<CommandPaletteActionItem>,
291): CommandPaletteActionItem[] {
292 return items.map((item, index) => {
293 const shortcutCommand = THREAD_JUMP_KEYBINDING_COMMANDS[index];
294 if (shortcutCommand) return { ...item, shortcutCommand };
295​
296 const { shortcutCommand: _shortcutCommand, ...itemWithoutShortcut } = item;
297 return itemWithoutShortcut;
298 });
300​
301export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
302​
303export type CommandPaletteProject = Project & { readonly displayName: string };
304​
305export function buildCommandPaletteProjectMetadata(input: {
306 readonly projects: ReadonlyArray<Pick<Project, "environmentId" | "title" | "workspaceRoot">>;
307 readonly locationByEnvironmentId: ReadonlyMap<EnvironmentId, { readonly label: string }>;
308}) {
309 const searchTerms: string[] = [];
310 const environmentLabels = new Set<string>();
311​
312 for (const project of input.projects) {
313 const label = input.locationByEnvironmentId.get(project.environmentId)?.label ?? "Remote";
314 searchTerms.push(project.title, project.workspaceRoot, label);
315 environmentLabels.add(label);
316 }
317​
318 return { searchTerms, environmentLabels: [...environmentLabels] };
320​
321export function buildProjectActionItems(input: {
322 projects: ReadonlyArray<CommandPaletteProject>;
323 valuePrefix: string;
324 icon: (project: CommandPaletteProject) => ReactNode;
325 runProject: (project: CommandPaletteProject) => Promise<void>;
326 searchTerms?: (project: CommandPaletteProject) => ReadonlyArray<string>;
327 renderDescription?: (project: CommandPaletteProject) => ReactNode;
328 shortcutCommand?: KeybindingCommand;
329}): CommandPaletteActionItem[] {
330 return input.projects.map((project) => ({
331 kind: "action",
332 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
333 searchTerms: [
334 project.displayName,
335 project.title,
336 project.workspaceRoot,
337 ...(input.searchTerms?.(project) ?? []),
338 ],
339 title: project.displayName,
340 description: input.renderDescription?.(project) ?? project.workspaceRoot,
341 icon: input.icon(project),
342 ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
343 run: async () => {
344 await input.runProject(project);
345 },
346 }));
348​
349export type BuildThreadActionItemsThread = Pick<
350 SidebarThreadSummary,
351 | "archivedAt"
352 | "branch"
353 | "createdAt"
354 | "environmentId"
355 | "id"
356 | "modelSelection"
357 | "projectId"
358 | "runtime"
359 | "title"
360 | "worktreePath"
361> & {
362 pullRequests?: SidebarThreadSummary["pullRequests"];
363 updatedAt: string;
364 latestUserMessageAt?: string | null;
365};
366​
367export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: {
368 threads: ReadonlyArray<TThread>;
369 activeThreadId?: Thread["id"];
370 projectTitleById: ReadonlyMap<Project["id"], string>;
371 sortOrder: SidebarThreadSortOrder;
372 icon: ReactNode;
373 renderLeadingContent?: (thread: TThread) => ReactNode;
374 renderTrailingContent?: (thread: TThread) => ReactNode;
375 renderDescription?: (thread: TThread, meta: { projectTitle: string | undefined }) => ReactNode;
376 getContentMatch?: (thread: TThread) => CommandPaletteThreadContentMatch | undefined;
377 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
378 limit?: number;
379}): CommandPaletteActionItem[] {
380 const sortedThreads = sortThreads(
381 input.threads.filter((thread) => thread.archivedAt === null),
382 input.sortOrder,
383 );
384 const visibleThreads =
385 input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
386​
387 return visibleThreads.map((thread) => {
388 const projectTitle = input.projectTitleById.get(thread.projectId);
389 const descriptionParts: string[] = [];
390​
391 if (projectTitle) {
392 descriptionParts.push(projectTitle);
393 }
394 if (thread.branch) {
395 descriptionParts.push(`#${thread.branch}`);
396 }
397 if (thread.id === input.activeThreadId) {
398 descriptionParts.push("Current thread");
399 }
400​
401 const leadingContent = input.renderLeadingContent?.(thread);
402 const trailingContent = input.renderTrailingContent?.(thread);
403 const contentMatch = input.getContentMatch?.(thread);
404 const description = input.renderDescription
405 ? input.renderDescription(thread, { projectTitle })
406 : descriptionParts.join(` · `);
407​
408 return Object.assign(
409 {
410 kind: "action" as const,
411 value: `thread:${thread.id}`,
412 searchTerms: [
413 thread.title,
414 ...threadPullRequestSearchTerms(thread),
415 projectTitle ?? ``,
416 thread.branch ?? ``,
417 contentMatch?.snippet ?? ``,
418 thread.id,
419 ],
420 title: thread.title,
421 description,
422 timestamp: formatRelativeTimeLabel(
423 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
424 ),
425 searchRecency: getThreadSortTimestamp(thread, "updated_at"),
426 icon: input.icon,
427 },
428 leadingContent ? { titleLeadingContent: leadingContent } : {},
429 trailingContent ? { titleTrailingContent: trailingContent } : {},
430 contentMatch ? { threadContentMatch: contentMatch } : {},
431 {
432 run: async () => {
433 await input.runThread(thread);
434 },
435 },
436 );
437 });
439​
440function rankSearchFieldMatch(
441 field: string,
442 normalizedQuery: string,
443 queryTokens: ReadonlyArray<string>,
444): number {
445 const normalizedField = normalizeSearchText(field);
446 if (
447 normalizedField.length === 0 ||
448 !queryTokens.every((token) => normalizedField.includes(token))
449 ) {
450 return Number.NEGATIVE_INFINITY;
451 }
452 if (normalizedField === normalizedQuery) {
453 return 3;
454 }
455 if (normalizedField.startsWith(normalizedQuery)) {
456 return 2;
457 }
458 if (normalizedField.includes(normalizedQuery)) {
459 return 1;
460 }
461 return 0;
463​
464function rankCommandPaletteItemMatch(
465 item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
466 normalizedQuery: string,
467 queryTokens: ReadonlyArray<string>,
468): number {
469 const terms = item.searchTerms.filter((term) => term.length > 0);
470 if (terms.length === 0) {
471 return 0;
472 }
473​
474 for (const [index, field] of terms.entries()) {
475 const fieldRank = rankSearchFieldMatch(field, normalizedQuery, queryTokens);
476 if (fieldRank !== Number.NEGATIVE_INFINITY) {
477 if (index === 0 && item.searchRecency !== undefined) {
478 return 1_000 + Number(fieldRank === 3);
479 }
480 return 1_000 - index * 100 + fieldRank;
481 }
482 }
483​
484 return 0;
486​
487export function filterCommandPaletteGroups(input: {
488 activeGroups: ReadonlyArray<CommandPaletteGroup>;
489 query: string;
490 isInSubmenu: boolean;
491 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
492 settingsSearchItems?: ReadonlyArray<CommandPaletteActionItem>;
493 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
494}): CommandPaletteGroup[] {
495 const isActionsFilter = input.query.startsWith(">");
496 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
497 const normalizedQuery = normalizeSearchText(searchQuery);
498​
499 if (normalizedQuery.length === 0) {
500 if (isActionsFilter) {
501 return input.activeGroups.filter((group) => group.value === "actions");
502 }
503 return [...input.activeGroups];
504 }
505 const queryTokens = normalizedQuery.split(" ");
506​
507 let baseGroups = [...input.activeGroups];
508 if (isActionsFilter) {
509 baseGroups = baseGroups.filter((group) => group.value === "actions");
510 } else if (!input.isInSubmenu) {
511 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
512 }
513​
514 const searchableGroups = [...baseGroups];
515 if (!input.isInSubmenu && !isActionsFilter) {
516 if (input.projectSearchItems.length > 0) {
517 searchableGroups.push({
518 value: "projects-search",
519 label: "Projects",
520 items: input.projectSearchItems,
521 });
522 }
523 if (input.settingsSearchItems && input.settingsSearchItems.length > 0) {
524 searchableGroups.push({
525 value: "settings-search",
526 label: "Settings",
527 items: input.settingsSearchItems,
528 });
529 }
530 if (input.threadSearchItems.length > 0) {
531 searchableGroups.push({
532 value: "threads-search",
533 label: "Threads",
534 items: input.threadSearchItems,
535 });
536 }
537 }
538​
539 return searchableGroups.flatMap((group) => {
540 const items = Arr.filterMap(group.items, (item, index) => {
541 const haystack = normalizeSearchText(item.searchTerms.join(" "));
542 if (!queryTokens.every((token) => haystack.includes(token))) {
543 return Result.failVoid;
544 }
545​
546 return Result.succeed({
547 item,
548 index,
549 rank: rankCommandPaletteItemMatch(item, normalizedQuery, queryTokens),
550 });
551 })
552 .toSorted(
553 (left, right) =>
554 Number(left.item.secondary ?? false) - Number(right.item.secondary ?? false) ||
555 right.rank - left.rank ||
556 (right.item.searchRecency ?? 0) - (left.item.searchRecency ?? 0) ||
557 left.index - right.index,
558 )
559 .map((entry) => entry.item);
560​
561 if (items.length === 0) {
562 return [];
563 }
564​
565 return [{ value: group.value, label: group.label, items }];
566 });
568​
569export function buildBrowseGroups(input: {
570 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
571 browseQuery: string;
572 canBrowseUp: boolean;
573 upIcon: ReactNode;
574 directoryIcon: ReactNode;
575 browseUp: () => void | Promise<void>;
576 browseTo: (name: string) => void | Promise<void>;
577}): CommandPaletteGroup[] {
578 const items: CommandPaletteActionItem[] = [];
579​
580 if (input.canBrowseUp) {
581 items.push({
582 kind: "action",
583 value: "browse:up",
584 searchTerms: [input.browseQuery, ".."],
585 title: "..",
586 icon: input.upIcon,
587 keepOpen: true,
588 run: async () => {
589 await input.browseUp();
590 },
591 });
592 }
593​
594 for (const entry of input.browseEntries) {
595 items.push({
596 kind: "action",
597 value: `browse:${entry.fullPath}`,
598 searchTerms: [input.browseQuery, entry.fullPath, entry.name],
599 title: entry.name,
600 icon: input.directoryIcon,
601 keepOpen: true,
602 run: async () => {
603 await input.browseTo(entry.name);
604 },
605 });
606 }
607​
608 return [{ value: "directories", label: "Directories", items }];
610​
611export function filterPinnedBrowseEntries(input: {
612 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
613 filterQuery: string;
614 pinnedDirectoryName: string;
615 caseSensitive: boolean;
616}): ReturnType<typeof filterFilesystemBrowseEntries> {
617 const namesMatch = (left: string, right: string) =>
618 input.caseSensitive ? left === right : left.toLowerCase() === right.toLowerCase();
619 const visibleFilterQuery = namesMatch(input.filterQuery, input.pinnedDirectoryName)
620 ? ""
621 : input.filterQuery;
622 const { visibleEntries } = filterFilesystemBrowseEntries(input.browseEntries, visibleFilterQuery);
623 const exactEntry =
624 input.filterQuery.length > 0
625 ? (input.browseEntries.find((entry) => namesMatch(entry.name, input.filterQuery)) ?? null)
626 : null;
627 return { visibleEntries, exactEntry };
629​
630export function getCommandPaletteMode(input: {
631 currentView: CommandPaletteView | null;
632 isBrowsing: boolean;
633}): CommandPaletteMode {
634 if (input.currentView) {
635 return input.isBrowsing ? "submenu-browse" : "submenu";
636 }
637 return input.isBrowsing ? "root-browse" : "root";
639​
640export function buildRootGroups(input: {
641 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
642 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
643}): CommandPaletteGroup[] {
644 const groups: CommandPaletteGroup[] = [];
645 if (input.actionItems.length > 0) {
646 groups.push({ value: "actions", label: "Actions", items: input.actionItems });
647 }
648 if (input.recentThreadItems.length > 0) {
649 groups.push({
650 value: "recent-threads",
651 label: "Recent Threads",
652 items: input.recentThreadItems,
653 });
654 }
655 return groups;
657​
658export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
659 switch (mode) {
660 case "root":
661 return "Search commands, projects, and threads...";
662 case "root-browse":
663 return "Enter project path (e.g. ~/projects/my-app)";
664 case "submenu":
665 return "Search...";
666 case "submenu-browse":
667 return "Enter path (e.g. ~/projects/my-app)";
668 }
670​
671export function getEnvironmentBrowsePlatform(os: string | null | undefined): string {
672 if (os === "windows") {
673 return "Win32";
674 }
675 if (os === "darwin") {
676 return "MacIntel";
677 }
678 if (os === "linux") {
679 return "Linux";
680 }
681 return typeof navigator === "undefined" ? "" : navigator.platform;
683​
684export interface AddProjectEnvironmentOption {
685 readonly environmentId: EnvironmentId;
686 readonly label: string;
687 readonly machine: EnvironmentMachineKind;
688 readonly isPrimary: boolean;
689 readonly isConnected: boolean;
690 readonly status: string;
692​
693export type AddProjectCloneFlow =
694 | {
695 readonly step: "repository";
696 readonly environmentId: EnvironmentId;
697 readonly source: AddProjectRemoteSource;
698 }
699 | {
700 readonly step: "confirm";
701 readonly environmentId: EnvironmentId;
702 readonly source: AddProjectRemoteSource;
703 readonly repositoryInput: string;
704 readonly repository: SourceControlRepositoryInfo | null;
705 readonly remoteUrl: string;
706 };
707​
708export function remoteProjectInputPlaceholder(flow: AddProjectCloneFlow | null): string | null {
709 if (!flow) return null;
710 if (flow.step === "confirm") return null;
711 if (flow.source === "url") {
712 return "Enter Git clone URL";
713 }
714 return `Enter ${addProjectRemoteSourceLabel(flow.source)} repository (${addProjectRemoteSourcePathHint(flow.source)})`;
716​
717export function buildPaletteRemoteSourceReadiness(
718 discovery: SourceControlDiscoveryResult | null,
719): AddProjectRemoteSourceReadiness {
720 const readiness = buildAddProjectRemoteSourceReadiness(discovery);
721 return (source) => {
722 const entry = readiness(source);
723 return entry.hint === null
724 ? entry
725 : {
726 ...entry,
727 hint: entry.hint.replace(
728 "Open Source Control settings",
729 "Open Settings -> Source Control",
730 ),
731 };
732 };
734​
735export function errorMessage(error: unknown): string {
736 if (error instanceof Error && error.message.trim().length > 0) {
737 return error.message;
738 }
739 return "An error occurred.";
741​
742const OVERLAY_MODE_BY_COMMAND = {
743 "commandPalette.toggle": "command",
744 "filePicker.toggle": "files",
745 "projectSearch.toggle": "content",
746} as const satisfies Partial<Record<string, SearchOverlayMode>>;
747​
748export function overlayModeForCommand(command: string | null): SearchOverlayMode | null {
749 if (command === null) return null;
750 return command in OVERLAY_MODE_BY_COMMAND
751 ? OVERLAY_MODE_BY_COMMAND[command as keyof typeof OVERLAY_MODE_BY_COMMAND]
752 : null;