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

CommandPalette.logic.ts

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