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

CommandPalette.tsx

1,112 lines36.1 KB

1"use client";
2​
3import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
4import {
5 DEFAULT_MODEL_BY_PROVIDER,
6 type EnvironmentId,
7 type FilesystemBrowseResult,
8 type ProjectId,
9} from "@t3tools/contracts";
10import { useQuery, useQueryClient } from "@tanstack/react-query";
11import { useNavigate, useParams } from "@tanstack/react-router";
12import {
13 ArrowDownIcon,
14 ArrowLeftIcon,
15 ArrowUpIcon,
16 CornerLeftUpIcon,
17 FolderIcon,
18 FolderPlusIcon,
19 MessageSquareIcon,
20 SettingsIcon,
21 SquarePenIcon,
22} from "lucide-react";
23import {
24 useCallback,
25 useDeferredValue,
26 useEffect,
27 useMemo,
28 useRef,
29 useState,
30 type KeyboardEvent,
31 type ReactNode,
32} from "react";
33import { useShallow } from "zustand/react/shallow";
34import { useCommandPaletteStore } from "../commandPaletteStore";
35import { readEnvironmentApi } from "../environmentApi";
36import { readPrimaryEnvironmentDescriptor, usePrimaryEnvironmentId } from "../environments/primary";
37import {
38 useSavedEnvironmentRegistryStore,
39 useSavedEnvironmentRuntimeStore,
40} from "../environments/runtime";
41import { useHandleNewThread } from "../hooks/useHandleNewThread";
42import { useSettings } from "../hooks/useSettings";
43import { readLocalApi } from "../localApi";
44import {
45 startNewThreadInProjectFromContext,
46 startNewThreadFromContext,
47} from "../lib/chatThreadActions";
48import {
49 appendBrowsePathSegment,
50 canNavigateUp,
51 ensureBrowseDirectoryPath,
52 findProjectByPath,
53 getBrowseDirectoryPath,
54 getBrowseLeafPathSegment,
55 getBrowseParentPath,
56 hasTrailingPathSeparator,
57 inferProjectTitleFromPath,
58 isExplicitRelativeProjectPath,
59 isFilesystemBrowseQuery,
60 isUnsupportedWindowsProjectPath,
61 resolveProjectPathForDispatch,
62} from "../lib/projectPaths";
63import { isTerminalFocused } from "../lib/terminalFocus";
64import { getLatestThreadForProject } from "../lib/threadSort";
65import { cn, isMacPlatform, isWindowsPlatform, newCommandId, newProjectId } from "../lib/utils";
66import {
67 selectProjectsAcrossEnvironments,
68 selectSidebarThreadsAcrossEnvironments,
69 useStore,
70} from "../store";
71import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
72import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
73import {
74 ADDON_ICON_CLASS,
75 buildBrowseGroups,
76 buildProjectActionItems,
77 buildRootGroups,
78 buildThreadActionItems,
79 type CommandPaletteActionItem,
80 type CommandPaletteSubmenuItem,
81 type CommandPaletteView,
82 filterBrowseEntries,
83 filterCommandPaletteGroups,
84 getCommandPaletteInputPlaceholder,
85 getCommandPaletteMode,
86 ITEM_ICON_CLASS,
87 RECENT_THREAD_LIMIT,
88} from "./CommandPalette.logic";
89import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
90import { CommandPaletteResults } from "./CommandPaletteResults";
91import { ProjectFavicon } from "./ProjectFavicon";
92import { useServerKeybindings } from "../rpc/serverState";
93import { resolveShortcutCommand } from "../keybindings";
94import {
95 Command,
96 CommandDialog,
97 CommandDialogPopup,
98 CommandFooter,
99 CommandInput,
100 CommandPanel,
101} from "./ui/command";
102import { Button } from "./ui/button";
103import { Kbd, KbdGroup } from "./ui/kbd";
104import { toastManager } from "./ui/toast";
105import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
106import type { ChatComposerHandle } from "./chat/ChatComposer";
107​
108const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = [];
109const BROWSE_STALE_TIME_MS = 30_000;
110​
111function getLocalFileManagerName(platform: string): string {
112 if (isMacPlatform(platform)) {
113 return "Finder";
114 }
115 if (isWindowsPlatform(platform)) {
116 return "Explorer";
117 }
118 return "Files";
120​
121function getEnvironmentBrowsePlatform(os: string | null | undefined): string {
122 if (os === "windows") {
123 return "Win32";
124 }
125 if (os === "darwin") {
126 return "MacIntel";
127 }
128 if (os === "linux") {
129 return "Linux";
130 }
131 return typeof navigator === "undefined" ? "" : navigator.platform;
133​
134interface AddProjectEnvironmentOption {
135 readonly environmentId: EnvironmentId;
136 readonly label: string;
137 readonly isPrimary: boolean;
139​
140export function CommandPalette({ children }: { children: ReactNode }) {
141 const open = useCommandPaletteStore((store) => store.open);
142 const setOpen = useCommandPaletteStore((store) => store.setOpen);
143 const toggleOpen = useCommandPaletteStore((store) => store.toggleOpen);
144 const keybindings = useServerKeybindings();
145 const composerHandleRef = useRef<ChatComposerHandle | null>(null);
146 const routeTarget = useParams({
147 strict: false,
148 select: (params) => resolveThreadRouteTarget(params),
149 });
150 const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
151 const terminalOpen = useTerminalStateStore((state) =>
152 routeThreadRef
153 ? selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef).terminalOpen
154 : false,
155 );
156​
157 useEffect(() => {
158 const onKeyDown = (event: globalThis.KeyboardEvent) => {
159 if (event.defaultPrevented) return;
160 const command = resolveShortcutCommand(event, keybindings, {
161 context: {
162 terminalFocus: isTerminalFocused(),
163 terminalOpen,
164 },
165 });
166 if (command !== "commandPalette.toggle") {
167 return;
168 }
169 event.preventDefault();
170 event.stopPropagation();
171 toggleOpen();
172 };
173 window.addEventListener("keydown", onKeyDown);
174 return () => window.removeEventListener("keydown", onKeyDown);
175 }, [keybindings, terminalOpen, toggleOpen]);
176​
177 return (
178 <ComposerHandleContext.Provider value={composerHandleRef}>
179 <CommandDialog open={open} onOpenChange={setOpen}>
180 {children}
181 <CommandPaletteDialog />
182 </CommandDialog>
183 </ComposerHandleContext.Provider>
184 );
186​
187function CommandPaletteDialog() {
188 const open = useCommandPaletteStore((store) => store.open);
189 const setOpen = useCommandPaletteStore((store) => store.setOpen);
190​
191 useEffect(() => {
192 return () => {
193 setOpen(false);
194 };
195 }, [setOpen]);
196​
197 if (!open) {
198 return null;
199 }
200​
201 return <OpenCommandPaletteDialog />;
203​
204function OpenCommandPaletteDialog() {
205 const navigate = useNavigate();
206 const setOpen = useCommandPaletteStore((store) => store.setOpen);
207 const openIntent = useCommandPaletteStore((store) => store.openIntent);
208 const clearOpenIntent = useCommandPaletteStore((store) => store.clearOpenIntent);
209 const composerHandleRef = useComposerHandleContext();
210 const [query, setQuery] = useState("");
211 const deferredQuery = useDeferredValue(query);
212 const isActionsOnly = deferredQuery.startsWith(">");
213 const queryClient = useQueryClient();
214 const [highlightedItemValue, setHighlightedItemValue] = useState<string | null>(null);
215 const settings = useSettings();
216 const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
217 useHandleNewThread();
218 const projects = useStore(useShallow(selectProjectsAcrossEnvironments));
219 const threads = useStore(useShallow(selectSidebarThreadsAcrossEnvironments));
220 const keybindings = useServerKeybindings();
221 const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
222 const currentView = viewStack.at(-1) ?? null;
223 const [browseGeneration, setBrowseGeneration] = useState(0);
224 const [addProjectEnvironmentId, setAddProjectEnvironmentId] = useState<EnvironmentId | null>(
225 null,
226 );
227 const [isPickingProjectFolder, setIsPickingProjectFolder] = useState(false);
228 const primaryEnvironmentId = usePrimaryEnvironmentId();
229 const primaryEnvironmentLabel = readPrimaryEnvironmentDescriptor()?.label ?? null;
230 const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((state) => state.byId);
231 const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((state) => state.byId);
232​
233 const addProjectEnvironmentOptions = useMemo(() => {
234 const options: AddProjectEnvironmentOption[] = [];
235 const seenEnvironmentIds = new Set<EnvironmentId>();
236​
237 if (primaryEnvironmentId) {
238 seenEnvironmentIds.add(primaryEnvironmentId);
239 options.push({
240 environmentId: primaryEnvironmentId,
241 label: resolveEnvironmentOptionLabel({
242 isPrimary: true,
243 environmentId: primaryEnvironmentId,
244 runtimeLabel: primaryEnvironmentLabel,
245 }),
246 isPrimary: true,
247 });
248 }
249​
250 for (const record of Object.values(savedEnvironmentRegistry)) {
251 if (seenEnvironmentIds.has(record.environmentId)) {
252 continue;
253 }
254​
255 const runtimeState = savedEnvironmentRuntimeById[record.environmentId];
256 options.push({
257 environmentId: record.environmentId,
258 label: resolveEnvironmentOptionLabel({
259 isPrimary: false,
260 environmentId: record.environmentId,
261 runtimeLabel: runtimeState?.descriptor?.label ?? null,
262 savedLabel: record.label,
263 }),
264 isPrimary: false,
265 });
266 }
267​
268 options.sort((left, right) => {
269 if (left.isPrimary !== right.isPrimary) {
270 return left.isPrimary ? -1 : 1;
271 }
272 return left.label.localeCompare(right.label);
273 });
274​
275 return options;
276 }, [
277 primaryEnvironmentId,
278 primaryEnvironmentLabel,
279 savedEnvironmentRegistry,
280 savedEnvironmentRuntimeById,
281 ]);
282 const defaultAddProjectEnvironmentId = addProjectEnvironmentOptions[0]?.environmentId ?? null;
283 const browseEnvironmentId = addProjectEnvironmentId ?? defaultAddProjectEnvironmentId;
284 const browseEnvironmentPlatform = useMemo(() => {
285 const os =
286 browseEnvironmentId && primaryEnvironmentId && browseEnvironmentId === primaryEnvironmentId
287 ? (readPrimaryEnvironmentDescriptor()?.platform.os ?? null)
288 : browseEnvironmentId
289 ? (savedEnvironmentRuntimeById[browseEnvironmentId]?.descriptor?.platform.os ??
290 savedEnvironmentRuntimeById[browseEnvironmentId]?.serverConfig?.environment.platform
291 .os ??
292 null)
293 : null;
294 return getEnvironmentBrowsePlatform(os);
295 }, [browseEnvironmentId, primaryEnvironmentId, savedEnvironmentRuntimeById]);
296 const isBrowsing = isFilesystemBrowseQuery(query, browseEnvironmentPlatform);
297 const paletteMode = getCommandPaletteMode({ currentView, isBrowsing });
298 const getAddProjectInitialQueryForEnvironment = useCallback(
299 (environmentId: EnvironmentId | null): string => {
300 const environmentSettings =
301 environmentId && primaryEnvironmentId && environmentId === primaryEnvironmentId
302 ? settings
303 : environmentId
304 ? savedEnvironmentRuntimeById[environmentId]?.serverConfig?.settings
305 : null;
306 const baseDirectory = environmentSettings?.addProjectBaseDirectory?.trim() ?? "";
307 if (baseDirectory.length === 0) {
308 return "~/";
309 }
310 return ensureBrowseDirectoryPath(baseDirectory);
311 },
312 [primaryEnvironmentId, savedEnvironmentRuntimeById, settings],
313 );
314​
315 const projectCwdById = useMemo(
316 () => new Map<ProjectId, string>(projects.map((project) => [project.id, project.cwd])),
317 [projects],
318 );
319 const projectTitleById = useMemo(
320 () => new Map<ProjectId, string>(projects.map((project) => [project.id, project.name])),
321 [projects],
322 );
323​
324 const activeThreadId = activeThread?.id;
325 const currentProjectEnvironmentId =
326 activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null;
327 const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null;
328 const currentProjectCwd = currentProjectId
329 ? (projectCwdById.get(currentProjectId) ?? null)
330 : null;
331 const currentProjectCwdForBrowse =
332 browseEnvironmentId && currentProjectEnvironmentId === browseEnvironmentId
333 ? currentProjectCwd
334 : null;
335 const relativePathNeedsActiveProject =
336 isExplicitRelativeProjectPath(query.trim()) && currentProjectCwdForBrowse === null;
337 const browseDirectoryPath = isBrowsing ? getBrowseDirectoryPath(query) : "";
338 const browseFilterQuery =
339 isBrowsing && !hasTrailingPathSeparator(query) ? getBrowseLeafPathSegment(query) : "";
340​
341 const fetchBrowseResult = useCallback(
342 async (partialPath: string): Promise<FilesystemBrowseResult | null> => {
343 if (!browseEnvironmentId) return null;
344 const api = readEnvironmentApi(browseEnvironmentId);
345 if (!api) return null;
346 return api.filesystem.browse({
347 partialPath,
348 ...(currentProjectCwdForBrowse ? { cwd: currentProjectCwdForBrowse } : {}),
349 });
350 },
351 [browseEnvironmentId, currentProjectCwdForBrowse],
352 );
353​
354 const { data: browseResult, isPending: isBrowsePending } = useQuery({
355 queryKey: [
356 "filesystemBrowse",
357 browseEnvironmentId,
358 browseDirectoryPath,
359 currentProjectCwdForBrowse,
360 ],
361 queryFn: () => fetchBrowseResult(browseDirectoryPath),
362 staleTime: BROWSE_STALE_TIME_MS,
363 enabled:
364 isBrowsing &&
365 browseDirectoryPath.length > 0 &&
366 browseEnvironmentId !== null &&
367 !relativePathNeedsActiveProject,
368 });
369 const browseEntries = browseResult?.entries ?? EMPTY_BROWSE_ENTRIES;
370 const {
371 filteredEntries: filteredBrowseEntries,
372 highlightedEntry: highlightedBrowseEntry,
373 exactEntry: exactBrowseEntry,
374 } = useMemo(
375 () => filterBrowseEntries({ browseEntries, browseFilterQuery, highlightedItemValue }),
376 [browseEntries, browseFilterQuery, highlightedItemValue],
377 );
378​
379 const prefetchBrowsePath = useCallback(
380 (partialPath: string) => {
381 void queryClient.prefetchQuery({
382 queryKey: [
383 "filesystemBrowse",
384 browseEnvironmentId,
385 partialPath,
386 currentProjectCwdForBrowse,
387 ],
388 queryFn: () => fetchBrowseResult(partialPath),
389 staleTime: BROWSE_STALE_TIME_MS,
390 });
391 },
392 [browseEnvironmentId, currentProjectCwdForBrowse, fetchBrowseResult, queryClient],
393 );
394​
395 // Prefetch the parent and the most likely next child so browse navigation
396 // stays warm without scanning every child directory in large trees.
397 useEffect(() => {
398 if (!isBrowsing || filteredBrowseEntries.length === 0) return;
399​
400 if (canNavigateUp(query)) {
401 prefetchBrowsePath(getBrowseParentPath(query)!);
402 }
403​
404 const nextChild = highlightedBrowseEntry ?? exactBrowseEntry;
405 if (nextChild) {
406 prefetchBrowsePath(appendBrowsePathSegment(query, nextChild.name));
407 }
408 }, [
409 exactBrowseEntry,
410 filteredBrowseEntries.length,
411 highlightedBrowseEntry,
412 isBrowsing,
413 prefetchBrowsePath,
414 query,
415 ]);
416​
417 const openProjectFromSearch = useMemo(
418 () => async (project: (typeof projects)[number]) => {
419 const latestThread = getLatestThreadForProject(
420 threads.filter((thread) => thread.environmentId === project.environmentId),
421 project.id,
422 settings.sidebarThreadSortOrder,
423 );
424 if (latestThread) {
425 await navigate({
426 to: "/$environmentId/$threadId",
427 params: buildThreadRouteParams(
428 scopeThreadRef(latestThread.environmentId, latestThread.id),
429 ),
430 });
431 return;
432 }
433​
434 await handleNewThread(scopeProjectRef(project.environmentId, project.id), {
435 envMode: settings.defaultThreadEnvMode,
436 });
437 },
438 [
439 handleNewThread,
440 navigate,
441 settings.defaultThreadEnvMode,
442 settings.sidebarThreadSortOrder,
443 threads,
444 ],
445 );
446​
447 const projectSearchItems = useMemo(
448 () =>
449 buildProjectActionItems({
450 projects,
451 valuePrefix: "project",
452 icon: (project) => (
453 <ProjectFavicon
454 environmentId={project.environmentId}
455 cwd={project.cwd}
456 className={ITEM_ICON_CLASS}
457 />
458 ),
459 runProject: openProjectFromSearch,
460 }),
461 [openProjectFromSearch, projects],
462 );
463​
464 const projectThreadItems = useMemo(
465 () =>
466 buildProjectActionItems({
467 projects,
468 valuePrefix: "new-thread-in",
469 icon: (project) => (
470 <ProjectFavicon
471 environmentId={project.environmentId}
472 cwd={project.cwd}
473 className={ITEM_ICON_CLASS}
474 />
475 ),
476 runProject: async (project) => {
477 await startNewThreadInProjectFromContext(
478 {
479 activeDraftThread,
480 activeThread,
481 defaultProjectRef,
482 defaultThreadEnvMode: settings.defaultThreadEnvMode,
483 handleNewThread,
484 },
485 scopeProjectRef(project.environmentId, project.id),
486 );
487 },
488 }),
489 [
490 activeDraftThread,
491 activeThread,
492 defaultProjectRef,
493 handleNewThread,
494 projects,
495 settings.defaultThreadEnvMode,
496 ],
497 );
498​
499 const allThreadItems = useMemo(
500 () =>
501 buildThreadActionItems({
502 threads,
503 ...(activeThreadId ? { activeThreadId } : {}),
504 projectTitleById,
505 sortOrder: settings.sidebarThreadSortOrder,
506 icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
507 runThread: async (thread) => {
508 await navigate({
509 to: "/$environmentId/$threadId",
510 params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)),
511 });
512 },
513 }),
514 [activeThreadId, navigate, projectTitleById, settings.sidebarThreadSortOrder, threads],
515 );
516 const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT);
517​
518 function pushPaletteView(view: CommandPaletteView): void {
519 setViewStack((previousViews) => [
520 ...previousViews,
521 {
522 addonIcon: view.addonIcon,
523 groups: view.groups,
524 ...(view.initialQuery ? { initialQuery: view.initialQuery } : {}),
525 },
526 ]);
527 setHighlightedItemValue(null);
528 setQuery(view.initialQuery ?? "");
529 }
530​
531 function pushView(item: CommandPaletteSubmenuItem): void {
532 pushPaletteView({
533 addonIcon: item.addonIcon,
534 groups: item.groups,
535 ...(item.initialQuery ? { initialQuery: item.initialQuery } : {}),
536 });
537 }
538​
539 function popView(): void {
540 if (viewStack.length <= 1) {
541 setAddProjectEnvironmentId(null);
542 }
543 setViewStack((previousViews) => previousViews.slice(0, -1));
544 setHighlightedItemValue(null);
545 setQuery("");
546 }
547​
548 function handleQueryChange(nextQuery: string): void {
549 setHighlightedItemValue(null);
550 setQuery(nextQuery);
551 if (nextQuery === "" && currentView?.initialQuery) {
552 popView();
553 }
554 }
555​
556 const startAddProjectBrowse = useCallback(
557 (environmentId: EnvironmentId): void => {
558 setAddProjectEnvironmentId(environmentId);
559 pushPaletteView({
560 addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
561 groups: [],
562 initialQuery: getAddProjectInitialQueryForEnvironment(environmentId),
563 });
564 },
565 [getAddProjectInitialQueryForEnvironment],
566 );
567​
568 const addProjectEnvironmentItems: CommandPaletteActionItem[] = addProjectEnvironmentOptions.map(
569 (option) => ({
570 kind: "action",
571 value: `action:add-project:environment:${option.environmentId}`,
572 searchTerms: [option.label, option.environmentId, option.isPrimary ? "this device" : ""],
573 title: option.label,
574 description: option.isPrimary ? "This device" : option.environmentId,
575 icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
576 keepOpen: true,
577 run: async () => {
578 startAddProjectBrowse(option.environmentId);
579 },
580 }),
581 );
582​
583 const addProjectEnvironmentGroups = useMemo<CommandPaletteView["groups"]>(
584 () => [
585 {
586 value: "environments",
587 label: "Environments",
588 items: addProjectEnvironmentItems,
589 },
590 ],
591 [addProjectEnvironmentItems],
592 );
593​
594 const openAddProjectFlow = useCallback(() => {
595 if (addProjectEnvironmentOptions.length > 1) {
596 pushPaletteView({
597 addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
598 groups: addProjectEnvironmentGroups,
599 });
600 return;
601 }
602​
603 const environmentId = defaultAddProjectEnvironmentId;
604 if (!environmentId) {
605 toastManager.add({
606 type: "error",
607 title: "Unable to browse projects",
608 description: "No environment is available.",
609 });
610 return;
611 }
612​
613 startAddProjectBrowse(environmentId);
614 }, [
615 addProjectEnvironmentGroups,
616 addProjectEnvironmentOptions.length,
617 defaultAddProjectEnvironmentId,
618 startAddProjectBrowse,
619 ]);
620​
621 useEffect(() => {
622 if (openIntent?.kind !== "add-project") {
623 return;
624 }
625 clearOpenIntent();
626 openAddProjectFlow();
627 }, [clearOpenIntent, openAddProjectFlow, openIntent]);
628​
629 const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
630​
631 if (projects.length > 0) {
632 const activeProjectTitle = currentProjectId
633 ? (projectTitleById.get(currentProjectId) ?? null)
634 : null;
635​
636 if (activeProjectTitle) {
637 actionItems.push({
638 kind: "action",
639 value: "action:new-thread",
640 searchTerms: ["new thread", "chat", "create", "draft"],
641 title: (
642 <>
643 New thread in <span className="font-semibold">{activeProjectTitle}</span>
644 </>
645 ),
646 icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
647 shortcutCommand: "chat.new",
648 run: async () => {
649 await startNewThreadFromContext({
650 activeDraftThread,
651 activeThread,
652 defaultProjectRef,
653 defaultThreadEnvMode: settings.defaultThreadEnvMode,
654 handleNewThread,
655 });
656 },
657 });
658 }
659​
660 actionItems.push({
661 kind: "submenu",
662 value: "action:new-thread-in",
663 searchTerms: ["new thread", "project", "pick", "choose", "select"],
664 title: "New thread in...",
665 icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
666 addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
667 groups: [{ value: "projects", label: "Projects", items: projectThreadItems }],
668 });
669 }
670​
671 if (addProjectEnvironmentOptions.length > 1) {
672 actionItems.push({
673 kind: "submenu",
674 value: "action:add-project",
675 searchTerms: ["add project", "folder", "directory", "browse", "environment"],
676 title: "Add project",
677 icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
678 addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
679 groups: addProjectEnvironmentGroups,
680 });
681 } else {
682 actionItems.push({
683 kind: "action",
684 value: "action:add-project",
685 searchTerms: ["add project", "folder", "directory", "browse"],
686 title: "Add project",
687 icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
688 keepOpen: true,
689 run: async () => {
690 openAddProjectFlow();
691 },
692 });
693 }
694​
695 actionItems.push({
696 kind: "action",
697 value: "action:settings",
698 searchTerms: ["settings", "preferences", "configuration", "keybindings"],
699 title: "Open settings",
700 icon: <SettingsIcon className={ITEM_ICON_CLASS} />,
701 run: async () => {
702 await navigate({ to: "/settings" });
703 },
704 });
705​
706 const rootGroups = buildRootGroups({ actionItems, recentThreadItems });
707 const activeGroups = currentView ? currentView.groups : rootGroups;
708​
709 const filteredGroups = filterCommandPaletteGroups({
710 activeGroups,
711 query: deferredQuery,
712 isInSubmenu: currentView !== null,
713 projectSearchItems: projectSearchItems,
714 threadSearchItems: allThreadItems,
715 });
716​
717 const handleAddProject = useCallback(
718 async (rawCwd: string) => {
719 if (!browseEnvironmentId) return;
720 const api = readEnvironmentApi(browseEnvironmentId);
721 if (!api) return;
722​
723 if (isUnsupportedWindowsProjectPath(rawCwd.trim(), browseEnvironmentPlatform)) {
724 toastManager.add({
725 type: "error",
726 title: "Failed to add project",
727 description: "Windows-style paths are only supported on Windows.",
728 });
729 return;
730 }
731​
732 if (isExplicitRelativeProjectPath(rawCwd.trim()) && !currentProjectCwdForBrowse) {
733 toastManager.add({
734 type: "error",
735 title: "Failed to add project",
736 description: "Relative paths require an active project.",
737 });
738 return;
739 }
740​
741 const cwd = resolveProjectPathForDispatch(rawCwd, currentProjectCwdForBrowse);
742 if (cwd.length === 0) return;
743​
744 const existing = findProjectByPath(
745 projects.filter((project) => project.environmentId === browseEnvironmentId),
746 cwd,
747 );
748 if (existing) {
749 const latestThread = getLatestThreadForProject(
750 threads.filter((thread) => thread.environmentId === existing.environmentId),
751 existing.id,
752 settings.sidebarThreadSortOrder,
753 );
754 if (latestThread) {
755 await navigate({
756 to: "/$environmentId/$threadId",
757 params: buildThreadRouteParams(
758 scopeThreadRef(latestThread.environmentId, latestThread.id),
759 ),
760 });
761 } else {
762 await handleNewThread(scopeProjectRef(existing.environmentId, existing.id), {
763 envMode: settings.defaultThreadEnvMode,
764 }).catch(() => undefined);
765 }
766 setOpen(false);
767 return;
768 }
769​
770 try {
771 const projectId = newProjectId();
772 await api.orchestration.dispatchCommand({
773 type: "project.create",
774 commandId: newCommandId(),
775 projectId,
776 title: inferProjectTitleFromPath(cwd),
777 workspaceRoot: cwd,
778 createWorkspaceRootIfMissing: true,
779 defaultModelSelection: {
780 provider: "codex",
781 model: DEFAULT_MODEL_BY_PROVIDER.codex,
782 },
783 createdAt: new Date().toISOString(),
784 });
785 await handleNewThread(scopeProjectRef(browseEnvironmentId, projectId), {
786 envMode: settings.defaultThreadEnvMode,
787 }).catch(() => undefined);
788 setOpen(false);
789 } catch (error) {
790 toastManager.add({
791 type: "error",
792 title: "Failed to add project",
793 description: error instanceof Error ? error.message : "An error occurred.",
794 });
795 }
796 },
797 [
798 browseEnvironmentId,
799 browseEnvironmentPlatform,
800 currentProjectCwdForBrowse,
801 handleNewThread,
802 navigate,
803 projects,
804 setOpen,
805 settings.defaultThreadEnvMode,
806 settings.sidebarThreadSortOrder,
807 threads,
808 ],
809 );
810​
811 function browseTo(name: string): void {
812 const nextQuery = appendBrowsePathSegment(query, name);
813 setHighlightedItemValue(null);
814 setQuery(nextQuery);
815 setBrowseGeneration((generation) => generation + 1);
816 }
817​
818 function browseUp(): void {
819 const parentPath = getBrowseParentPath(query);
820 if (parentPath === null) {
821 return;
822 }
823​
824 setHighlightedItemValue(null);
825 setQuery(parentPath);
826 setBrowseGeneration((generation) => generation + 1);
827 }
828​
829 // Resolve the add-project path from browse data when available. When the
830 // query has a trailing separator (e.g. "~/projects/foo/"), parentPath is the
831 // directory itself. Otherwise the user typed a partial leaf name, so we need
832 // the exact browse entry's fullPath or fall back to the raw query.
833 const resolvedAddProjectPath = hasTrailingPathSeparator(query)
834 ? (browseResult?.parentPath ?? query.trim())
835 : (exactBrowseEntry?.fullPath ?? query.trim());
836​
837 const canBrowseUp =
838 isBrowsing && !relativePathNeedsActiveProject && canNavigateUp(browseDirectoryPath);
839​
840 const browseGroups = buildBrowseGroups({
841 browseEntries: filteredBrowseEntries,
842 browseQuery: query,
843 canBrowseUp,
844 upIcon: <CornerLeftUpIcon className={ITEM_ICON_CLASS} />,
845 directoryIcon: <FolderIcon className={ITEM_ICON_CLASS} />,
846 browseUp,
847 browseTo,
848 });
849​
850 let displayedGroups = filteredGroups;
851 if (isBrowsing) {
852 displayedGroups = relativePathNeedsActiveProject ? [] : browseGroups;
853 }
854​
855 const inputPlaceholder = getCommandPaletteInputPlaceholder(paletteMode);
856 const isSubmenu = paletteMode === "submenu" || paletteMode === "submenu-browse";
857 const hasHighlightedBrowseItem = highlightedItemValue?.startsWith("browse:") ?? false;
858 const canSubmitBrowsePath = isBrowsing && !relativePathNeedsActiveProject;
859 const willCreateProjectPath =
860 canSubmitBrowsePath &&
861 !isBrowsePending &&
862 query.trim().length > 0 &&
863 !hasHighlightedBrowseItem &&
864 (hasTrailingPathSeparator(query) ? !browseResult : exactBrowseEntry === null);
865 const useMetaForMod = isMacPlatform(navigator.platform);
866 const submitModifierLabel = useMetaForMod ? "\u2318" : "Ctrl";
867 const submitActionLabel = willCreateProjectPath ? "Create & Add" : "Add";
868 const addShortcutLabel = hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter";
869 const fileManagerName = getLocalFileManagerName(navigator.platform);
870 const canOpenProjectFromFileManager =
871 isBrowsing &&
872 browseEnvironmentId !== null &&
873 primaryEnvironmentId !== null &&
874 browseEnvironmentId === primaryEnvironmentId &&
875 typeof window !== "undefined" &&
876 window.desktopBridge !== undefined;
877 const fileManagerInitialPath = useMemo(() => {
878 if (!canOpenProjectFromFileManager) {
879 return undefined;
880 }
881​
882 const trimmedQuery = query.trim();
883 if (trimmedQuery.length === 0) {
884 return undefined;
885 }
886​
887 const initialPath = hasTrailingPathSeparator(query)
888 ? (browseResult?.parentPath ?? trimmedQuery)
889 : browseDirectoryPath || trimmedQuery;
890​
891 const resolvedPath = resolveProjectPathForDispatch(initialPath, currentProjectCwdForBrowse);
892 return resolvedPath.length > 0 ? resolvedPath : undefined;
893 }, [
894 browseDirectoryPath,
895 browseResult?.parentPath,
896 canOpenProjectFromFileManager,
897 currentProjectCwdForBrowse,
898 query,
899 ]);
900​
901 function isPrimaryModifierPressed(event: KeyboardEvent<HTMLInputElement>): boolean {
902 return useMetaForMod ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
903 }
904​
905 function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
906 const shouldSubmitBrowsePath =
907 canSubmitBrowsePath &&
908 event.key === "Enter" &&
909 (!hasHighlightedBrowseItem || isPrimaryModifierPressed(event));
910​
911 if (shouldSubmitBrowsePath) {
912 event.preventDefault();
913 void handleAddProject(resolvedAddProjectPath);
914 return;
915 }
916​
917 if (event.key === "Backspace" && query === "" && isSubmenu) {
918 event.preventDefault();
919 popView();
920 }
921 }
922​
923 function executeItem(item: CommandPaletteActionItem | CommandPaletteSubmenuItem): void {
924 if (item.kind === "submenu") {
925 pushView(item);
926 return;
927 }
928​
929 if (!item.keepOpen) {
930 setOpen(false);
931 }
932​
933 void item.run().catch((error: unknown) => {
934 toastManager.add({
935 type: "error",
936 title: "Unable to run command",
937 description: error instanceof Error ? error.message : "An unexpected error occurred.",
938 });
939 });
940 }
941​
942 const handleOpenProjectFromFileManager = useCallback(async () => {
943 if (!canOpenProjectFromFileManager || isPickingProjectFolder) {
944 return;
945 }
946 const api = readLocalApi();
947 if (!api) {
948 return;
949 }
950​
951 setIsPickingProjectFolder(true);
952 let pickedPath: string | null = null;
953 try {
954 pickedPath = await api.dialogs.pickFolder(
955 fileManagerInitialPath ? { initialPath: fileManagerInitialPath } : undefined,
956 );
957 } catch {
958 // Ignore picker failures and leave the palette open.
959 setIsPickingProjectFolder(false);
960 return;
961 }
962 setIsPickingProjectFolder(false);
963 if (!pickedPath) {
964 return;
965 }
966 await handleAddProject(pickedPath);
967 }, [
968 canOpenProjectFromFileManager,
969 fileManagerInitialPath,
970 handleAddProject,
971 isPickingProjectFolder,
972 ]);
973​
974 return (
975 <CommandDialogPopup
976 aria-label="Command palette"
977 className="overflow-hidden p-0"
978 data-testid="command-palette"
979 finalFocus={() => {
980 composerHandleRef?.current?.focusAtEnd();
981 return false;
982 }}
983 >
984 <Command
985 key={`${viewStack.length}-${browseGeneration}-${isBrowsing}`}
986 aria-label="Command palette"
987 autoHighlight={isBrowsing ? false : "always"}
988 mode="none"
989 onItemHighlighted={(value) => {
990 setHighlightedItemValue(typeof value === "string" ? value : null);
991 }}
992 onValueChange={handleQueryChange}
993 value={query}
994 >
995 <div className="relative">
996 <CommandInput
997 className={isBrowsing ? (willCreateProjectPath ? "pe-36" : "pe-16") : undefined}
998 placeholder={inputPlaceholder}
999 wrapperClassName={
1000 isSubmenu ? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto" : undefined
1002 {...(isSubmenu
1003 ? {
1004 startAddon: (
1005 <button
1006 type="button"
1007 className="flex cursor-pointer items-center"
1008 aria-label="Back"
1009 onClick={popView}
1011 <ArrowLeftIcon />
1012 </button>
1013 ),
1015 : isBrowsing && !isSubmenu
1016 ? {
1017 startAddon: <FolderPlusIcon />,
1019 : {})}
1020 onKeyDown={handleKeyDown}
1021 />
1022 {isBrowsing ? (
1023 <Button
1024 variant="outline"
1025 size="xs"
1026 tabIndex={-1}
1027 className={cn(
1028 "absolute end-2.5 top-1/2 pe-1 ps-2 -translate-y-1/2",
1029 hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
1030 )}
1031 aria-label={`${submitActionLabel} (${addShortcutLabel})`}
1032 disabled={relativePathNeedsActiveProject}
1033 onMouseDown={(event) => {
1034 event.preventDefault();
1035 }}
1036 onClick={() => {
1037 if (relativePathNeedsActiveProject) {
1038 return;
1040 void handleAddProject(resolvedAddProjectPath);
1041 }}
1042 title={`${submitActionLabel} (${addShortcutLabel})`}
1044 <span>{submitActionLabel}</span>
1045 <KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
1046 <Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
1047 </KbdGroup>
1048 </Button>
1049 ) : null}
1050 </div>
1051 <CommandPanel className="max-h-[min(28rem,70vh)]">
1052 <CommandPaletteResults
1053 groups={displayedGroups}
1054 highlightedItemValue={highlightedItemValue}
1055 isActionsOnly={isActionsOnly}
1056 keybindings={keybindings}
1057 onExecuteItem={executeItem}
1058 {...(relativePathNeedsActiveProject
1059 ? { emptyStateMessage: "Relative paths require an active project." }
1060 : willCreateProjectPath
1061 ? {
1062 emptyStateMessage: "Press Enter to create this folder and add it as a project.",
1064 : {})}
1065 />
1066 </CommandPanel>
1067 <CommandFooter className="gap-3 max-sm:flex-col max-sm:items-start">
1068 <div className="flex items-center gap-3">
1069 <KbdGroup className="items-center gap-1.5">
1070 <Kbd>
1071 <ArrowUpIcon />
1072 </Kbd>
1073 <Kbd>
1074 <ArrowDownIcon />
1075 </Kbd>
1076 <span className={cn("text-muted-foreground/80")}>Navigate</span>
1077 </KbdGroup>
1078 {!canSubmitBrowsePath || hasHighlightedBrowseItem ? (
1079 <KbdGroup className="items-center gap-1.5">
1080 <Kbd>Enter</Kbd>
1081 <span className={cn("text-muted-foreground/80")}>Select</span>
1082 </KbdGroup>
1083 ) : null}
1084 {isSubmenu ? (
1085 <KbdGroup className="items-center gap-1.5">
1086 <Kbd>Backspace</Kbd>
1087 <span className={cn("text-muted-foreground/80")}>Back</span>
1088 </KbdGroup>
1089 ) : null}
1090 <KbdGroup className="items-center gap-1.5">
1091 <Kbd>Esc</Kbd>
1092 <span className={cn("text-muted-foreground/80")}>Close</span>
1093 </KbdGroup>
1094 </div>
1095 {canOpenProjectFromFileManager ? (
1096 <Button
1097 variant="ghost"
1098 size="xs"
1099 className="h-auto px-2 text-xs text-muted-foreground/80 hover:bg-transparent hover:text-foreground"
1100 disabled={isPickingProjectFolder}
1101 onClick={() => {
1102 void handleOpenProjectFromFileManager();
1103 }}
1105 {`Open in ${fileManagerName}`}
1106 </Button>
1107 ) : null}
1108 </CommandFooter>
1109 </Command>
1110 </CommandDialogPopup>
1111 );