Open History to see the last commit
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 { 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";
120}
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;
133}
134
135interface AddProjectEnvironmentOption {
136 readonly environmentId: EnvironmentId;
137 readonly label: string;
138 readonly isPrimary: boolean;
139}
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 );
186}
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 />;
203}
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 type: "error",
610 title: "Unable to browse projects",
611 description: "No environment is available.",
612 });
613 return;
614 }
615
616 startAddProjectBrowse(environmentId);
617 }, [
618 addProjectEnvironmentGroups,
619 addProjectEnvironmentOptions.length,
620 defaultAddProjectEnvironmentId,
621 startAddProjectBrowse,
622 ]);
623
624 useEffect(() => {
625 if (openIntent?.kind !== "add-project") {
626 return;
627 }
628 clearOpenIntent();
629 openAddProjectFlow();
630 }, [clearOpenIntent, openAddProjectFlow, openIntent]);
631
632 const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
633
634 if (projects.length > 0) {
635 const activeProjectTitle = currentProjectId
636 ? (projectTitleById.get(currentProjectId) ?? null)
637 : null;
638
639 if (activeProjectTitle) {
640 actionItems.push({
641 kind: "action",
642 value: "action:new-thread",
643 searchTerms: ["new thread", "chat", "create", "draft"],
644 title: (
645 <>
646 New thread in <span className="font-semibold">{activeProjectTitle}</span>
647 </>
648 ),
649 icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
650 shortcutCommand: "chat.new",
651 run: async () => {
652 await startNewThreadFromContext({
653 activeDraftThread,
654 activeThread,
655 defaultProjectRef,
656 defaultThreadEnvMode: settings.defaultThreadEnvMode,
657 handleNewThread,
658 });
659 },
660 });
661 }
662
663 actionItems.push({
664 kind: "submenu",
665 value: "action:new-thread-in",
666 searchTerms: ["new thread", "project", "pick", "choose", "select"],
667 title: "New thread in...",
668 icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
669 addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
670 groups: [{ value: "projects", label: "Projects", items: projectThreadItems }],
671 });
672 }
673
674 if (addProjectEnvironmentOptions.length > 1) {
675 actionItems.push({
676 kind: "submenu",
677 value: "action:add-project",
678 searchTerms: ["add project", "folder", "directory", "browse", "environment"],
679 title: "Add project",
680 icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
681 addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
682 groups: addProjectEnvironmentGroups,
683 });
684 } else {
685 actionItems.push({
686 kind: "action",
687 value: "action:add-project",
688 searchTerms: ["add project", "folder", "directory", "browse"],
689 title: "Add project",
690 icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
691 keepOpen: true,
692 run: async () => {
693 openAddProjectFlow();
694 },
695 });
696 }
697
698 actionItems.push({
699 kind: "action",
700 value: "action:settings",
701 searchTerms: ["settings", "preferences", "configuration", "keybindings"],
702 title: "Open settings",
703 icon: <SettingsIcon className={ITEM_ICON_CLASS} />,
704 run: async () => {
705 await navigate({ to: "/settings" });
706 },
707 });
708
709 const rootGroups = buildRootGroups({ actionItems, recentThreadItems });
710 const activeGroups = currentView ? currentView.groups : rootGroups;
711
712 const filteredGroups = filterCommandPaletteGroups({
713 activeGroups,
714 query: deferredQuery,
715 isInSubmenu: currentView !== null,
716 projectSearchItems: projectSearchItems,
717 threadSearchItems: allThreadItems,
718 });
719
720 const handleAddProject = useCallback(
721 async (rawCwd: string) => {
722 if (!browseEnvironmentId) return;
723 const api = readEnvironmentApi(browseEnvironmentId);
724 if (!api) return;
725
726 if (isUnsupportedWindowsProjectPath(rawCwd.trim(), browseEnvironmentPlatform)) {
727 toastManager.add({
728 type: "error",
729 title: "Failed to add project",
730 description: "Windows-style paths are only supported on Windows.",
731 });
732 return;
733 }
734
735 if (isExplicitRelativeProjectPath(rawCwd.trim()) && !currentProjectCwdForBrowse) {
736 toastManager.add({
737 type: "error",
738 title: "Failed to add project",
739 description: "Relative paths require an active project.",
740 });
741 return;
742 }
743
744 const cwd = resolveProjectPathForDispatch(rawCwd, currentProjectCwdForBrowse);
745 if (cwd.length === 0) return;
746
747 const existing = findProjectByPath(
748 projects.filter((project) => project.environmentId === browseEnvironmentId),
749 cwd,
750 );
751 if (existing) {
752 const latestThread = getLatestThreadForProject(
753 threads.filter((thread) => thread.environmentId === existing.environmentId),
754 existing.id,
755 settings.sidebarThreadSortOrder,
756 );
757 if (latestThread) {
758 await navigate({
759 to: "/$environmentId/$threadId",
760 params: buildThreadRouteParams(
761 scopeThreadRef(latestThread.environmentId, latestThread.id),
762 ),
763 });
764 } else {
765 await handleNewThread(scopeProjectRef(existing.environmentId, existing.id), {
766 envMode: settings.defaultThreadEnvMode,
767 }).catch(() => undefined);
768 }
769 setOpen(false);
770 return;
771 }
772
773 try {
774 const projectId = newProjectId();
775 await api.orchestration.dispatchCommand({
776 type: "project.create",
777 commandId: newCommandId(),
778 projectId,
779 title: inferProjectTitleFromPath(cwd),
780 workspaceRoot: cwd,
781 createWorkspaceRootIfMissing: true,
782 defaultModelSelection: {
783 provider: "codex",
784 model: DEFAULT_MODEL_BY_PROVIDER.codex,
785 },
786 createdAt: new Date().toISOString(),
787 });
788 await handleNewThread(scopeProjectRef(browseEnvironmentId, projectId), {
789 envMode: settings.defaultThreadEnvMode,
790 }).catch(() => undefined);
791 setOpen(false);
792 } catch (error) {
793 toastManager.add({
794 type: "error",
795 title: "Failed to add project",
796 description: error instanceof Error ? error.message : "An error occurred.",
797 });
798 }
799 },
800 [
801 browseEnvironmentId,
802 browseEnvironmentPlatform,
803 currentProjectCwdForBrowse,
804 handleNewThread,
805 navigate,
806 projects,
807 setOpen,
808 settings.defaultThreadEnvMode,
809 settings.sidebarThreadSortOrder,
810 threads,
811 ],
812 );
813
814 function browseTo(name: string): void {
815 const nextQuery = appendBrowsePathSegment(query, name);
816 setHighlightedItemValue(null);
817 setQuery(nextQuery);
818 setBrowseGeneration((generation) => generation + 1);
819 }
820
821 function browseUp(): void {
822 const parentPath = getBrowseParentPath(query);
823 if (parentPath === null) {
824 return;
825 }
826
827 setHighlightedItemValue(null);
828 setQuery(parentPath);
829 setBrowseGeneration((generation) => generation + 1);
830 }
831
832 // Resolve the add-project path from browse data when available. When the
833 // query has a trailing separator (e.g. "~/projects/foo/"), parentPath is the
834 // directory itself. Otherwise the user typed a partial leaf name, so we need
835 // the exact browse entry's fullPath or fall back to the raw query.
836 const resolvedAddProjectPath = hasTrailingPathSeparator(query)
837 ? (browseResult?.parentPath ?? query.trim())
838 : (exactBrowseEntry?.fullPath ?? query.trim());
839
840 const canBrowseUp =
841 isBrowsing && !relativePathNeedsActiveProject && canNavigateUp(browseDirectoryPath);
842
843 const browseGroups = buildBrowseGroups({
844 browseEntries: filteredBrowseEntries,
845 browseQuery: query,
846 canBrowseUp,
847 upIcon: <CornerLeftUpIcon className={ITEM_ICON_CLASS} />,
848 directoryIcon: <FolderIcon className={ITEM_ICON_CLASS} />,
849 browseUp,
850 browseTo,
851 });
852
853 let displayedGroups = filteredGroups;
854 if (isBrowsing) {
855 displayedGroups = relativePathNeedsActiveProject ? [] : browseGroups;
856 }
857
858 const inputPlaceholder = getCommandPaletteInputPlaceholder(paletteMode);
859 const isSubmenu = paletteMode === "submenu" || paletteMode === "submenu-browse";
860 const hasHighlightedBrowseItem = highlightedItemValue?.startsWith("browse:") ?? false;
861 const canSubmitBrowsePath = isBrowsing && !relativePathNeedsActiveProject;
862 const willCreateProjectPath =
863 canSubmitBrowsePath &&
864 !isBrowsePending &&
865 query.trim().length > 0 &&
866 !hasHighlightedBrowseItem &&
867 (hasTrailingPathSeparator(query) ? !browseResult : exactBrowseEntry === null);
868 const useMetaForMod = isMacPlatform(navigator.platform);
869 const submitModifierLabel = useMetaForMod ? "\u2318" : "Ctrl";
870 const submitActionLabel = willCreateProjectPath ? "Create & Add" : "Add";
871 const addShortcutLabel = hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter";
872 const fileManagerName = getLocalFileManagerName(navigator.platform);
873 const canOpenProjectFromFileManager =
874 isBrowsing &&
875 browseEnvironmentId !== null &&
876 primaryEnvironmentId !== null &&
877 browseEnvironmentId === primaryEnvironmentId &&
878 typeof window !== "undefined" &&
879 window.desktopBridge !== undefined;
880 const fileManagerInitialPath = useMemo(() => {
881 if (!canOpenProjectFromFileManager) {
882 return undefined;
883 }
884
885 const trimmedQuery = query.trim();
886 if (trimmedQuery.length === 0) {
887 return undefined;
888 }
889
890 const initialPath = hasTrailingPathSeparator(query)
891 ? (browseResult?.parentPath ?? trimmedQuery)
892 : browseDirectoryPath || trimmedQuery;
893
894 const resolvedPath = resolveProjectPathForDispatch(initialPath, currentProjectCwdForBrowse);
895 return resolvedPath.length > 0 ? resolvedPath : undefined;
896 }, [
897 browseDirectoryPath,
898 browseResult?.parentPath,
899 canOpenProjectFromFileManager,
900 currentProjectCwdForBrowse,
901 query,
902 ]);
903
904 function isPrimaryModifierPressed(event: KeyboardEvent<HTMLInputElement>): boolean {
905 return useMetaForMod ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
906 }
907
908 function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
909 const shouldSubmitBrowsePath =
910 canSubmitBrowsePath &&
911 event.key === "Enter" &&
912 (!hasHighlightedBrowseItem || isPrimaryModifierPressed(event));
913
914 if (shouldSubmitBrowsePath) {
915 event.preventDefault();
916 void handleAddProject(resolvedAddProjectPath);
917 return;
918 }
919
920 if (event.key === "Backspace" && query === "" && isSubmenu) {
921 event.preventDefault();
922 popView();
923 }
924 }
925
926 function executeItem(item: CommandPaletteActionItem | CommandPaletteSubmenuItem): void {
927 if (item.kind === "submenu") {
928 pushView(item);
929 return;
930 }
931
932 if (!item.keepOpen) {
933 setOpen(false);
934 }
935
936 void item.run().catch((error: unknown) => {
937 toastManager.add({
938 type: "error",
939 title: "Unable to run command",
940 description: error instanceof Error ? error.message : "An unexpected error occurred.",
941 });
942 });
943 }
944
945 const handleOpenProjectFromFileManager = useCallback(async () => {
946 if (!canOpenProjectFromFileManager || isPickingProjectFolder) {
947 return;
948 }
949 const api = readLocalApi();
950 if (!api) {
951 return;
952 }
953
954 setIsPickingProjectFolder(true);
955 let pickedPath: string | null = null;
956 try {
957 pickedPath = await api.dialogs.pickFolder(
958 fileManagerInitialPath ? { initialPath: fileManagerInitialPath } : undefined,
959 );
960 } catch {
961 // Ignore picker failures and leave the palette open.
962 setIsPickingProjectFolder(false);
963 return;
964 }
965 setIsPickingProjectFolder(false);
966 if (!pickedPath) {
967 return;
968 }
969 await handleAddProject(pickedPath);
970 }, [
971 canOpenProjectFromFileManager,
972 fileManagerInitialPath,
973 handleAddProject,
974 isPickingProjectFolder,
975 ]);
976
977 return (
978 <CommandDialogPopup
979 aria-label="Command palette"
980 className="overflow-hidden p-0"
981 data-testid="command-palette"
982 finalFocus={() => {
983 composerHandleRef?.current?.focusAtEnd();
984 return false;
985 }}
986 >
987 <Command
988 key={`${viewStack.length}-${browseGeneration}-${isBrowsing}`}
989 aria-label="Command palette"
990 autoHighlight={isBrowsing ? false : "always"}
991 mode="none"
992 onItemHighlighted={(value) => {
993 setHighlightedItemValue(typeof value === "string" ? value : null);
994 }}
995 onValueChange={handleQueryChange}
996 value={query}
997 >
998 <div className="relative">
999 <CommandInput
1000 className={isBrowsing ? (willCreateProjectPath ? "pe-36" : "pe-16") : undefined}
1001 placeholder={inputPlaceholder}
1002 wrapperClassName={
1003 isSubmenu ? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto" : undefined
1004 }
1005 {...(isSubmenu
1006 ? {
1007 startAddon: (
1008 <button
1009 type="button"
1010 className="flex cursor-pointer items-center"
1011 aria-label="Back"
1012 onClick={popView}
1013 >
1014 <ArrowLeftIcon />
1015 </button>
1016 ),
1017 }
1018 : isBrowsing && !isSubmenu
1019 ? {
1020 startAddon: <FolderPlusIcon />,
1021 }
1022 : {})}
1023 onKeyDown={handleKeyDown}
1024 />
1025 {isBrowsing ? (
1026 <Button
1027 variant="outline"
1028 size="xs"
1029 tabIndex={-1}
1030 className={cn(
1031 "absolute end-2.5 top-1/2 pe-1 ps-2 -translate-y-1/2",
1032 hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
1033 )}
1034 aria-label={`${submitActionLabel} (${addShortcutLabel})`}
1035 disabled={relativePathNeedsActiveProject}
1036 onMouseDown={(event) => {
1037 event.preventDefault();
1038 }}
1039 onClick={() => {
1040 if (relativePathNeedsActiveProject) {
1041 return;
1042 }
1043 void handleAddProject(resolvedAddProjectPath);
1044 }}
1045 title={`${submitActionLabel} (${addShortcutLabel})`}
1046 >
1047 <span>{submitActionLabel}</span>
1048 <KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
1049 <Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
1050 </KbdGroup>
1051 </Button>
1052 ) : null}
1053 </div>
1054 <CommandPanel className="max-h-[min(28rem,70vh)]">
1055 <CommandPaletteResults
1056 groups={displayedGroups}
1057 highlightedItemValue={highlightedItemValue}
1058 isActionsOnly={isActionsOnly}
1059 keybindings={keybindings}
1060 onExecuteItem={executeItem}
1061 {...(relativePathNeedsActiveProject
1062 ? { emptyStateMessage: "Relative paths require an active project." }
1063 : willCreateProjectPath
1064 ? {
1065 emptyStateMessage: "Press Enter to create this folder and add it as a project.",
1066 }
1067 : {})}
1068 />
1069 </CommandPanel>
1070 <CommandFooter className="gap-3 max-sm:flex-col max-sm:items-start">
1071 <div className="flex items-center gap-3">
1072 <KbdGroup className="items-center gap-1.5">
1073 <Kbd>
1074 <ArrowUpIcon />
1075 </Kbd>
1076 <Kbd>
1077 <ArrowDownIcon />
1078 </Kbd>
1079 <span className={cn("text-muted-foreground/80")}>Navigate</span>
1080 </KbdGroup>
1081 {!canSubmitBrowsePath || hasHighlightedBrowseItem ? (
1082 <KbdGroup className="items-center gap-1.5">
1083 <Kbd>Enter</Kbd>
1084 <span className={cn("text-muted-foreground/80")}>Select</span>
1085 </KbdGroup>
1086 ) : null}
1087 {isSubmenu ? (
1088 <KbdGroup className="items-center gap-1.5">
1089 <Kbd>Backspace</Kbd>
1090 <span className={cn("text-muted-foreground/80")}>Back</span>
1091 </KbdGroup>
1092 ) : null}
1093 <KbdGroup className="items-center gap-1.5">
1094 <Kbd>Esc</Kbd>
1095 <span className={cn("text-muted-foreground/80")}>Close</span>
1096 </KbdGroup>
1097 </div>
1098 {canOpenProjectFromFileManager ? (
1099 <Button
1100 variant="ghost"
1101 size="xs"
1102 className="h-auto px-2 text-xs text-muted-foreground/80 hover:bg-transparent hover:text-foreground"
1103 disabled={isPickingProjectFolder}
1104 onClick={() => {
1105 void handleOpenProjectFromFileManager();
1106 }}
1107 >
1108 {`Open in ${fileManagerName}`}
1109 </Button>
1110 ) : null}
1111 </CommandFooter>
1112 </Command>
1113 </CommandDialogPopup>
1114 );
1115}