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

CommandPalette.tsx

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