The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { decodeMsg, msg, T, useGT, useMessages, Var } from "gt-react"; |
| 3 | import { m, type MessageResolver } from "../i18n/messages"; |
| 4 | import { ThreadContextDragGhost } from "./chat/ThreadContextDragGhost"; |
| 5 | import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility"; |
| 6 | import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; |
| 7 | |
| 8 | import { |
| 9 | scopedThreadKey, |
| 10 | scopeProjectRef, |
| 11 | scopeThreadRef, |
| 12 | } from "@t3tools/client-runtime/environment"; |
| 13 | import { |
| 14 | canCreateProjectInEnvironment, |
| 15 | getCloneDestinationBrowsePath, |
| 16 | getCloneDestinationForPickedFolder, |
| 17 | getCloneDestinationPath, |
| 18 | getCloneDirectoryLeafName, |
| 19 | getCloneDirectoryPath, |
| 20 | getDefaultCloneUrl, |
| 21 | getNewProjectPathPreview, |
| 22 | getNewProjectPublishTarget, |
| 23 | getNewProjectPublishTargets, |
| 24 | getNewProjectRepository, |
| 25 | getAddProjectInitialQuery, |
| 26 | githubIncompleteOwnerRepositoryMessage, |
| 27 | normalizePastedCloneUrl, |
| 28 | addProjectRemoteSourceLabel, |
| 29 | addProjectRemoteSourcePathHint, |
| 30 | addProjectRemoteSourceProvider, |
| 31 | sortAddProjectProviderSources, |
| 32 | type AddProjectRemoteSource, |
| 33 | type AddProjectRemoteSourceReadiness, |
| 34 | } from "@t3tools/client-runtime/operations/projects"; |
| 35 | import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; |
| 36 | import { connectionStatusText } from "@t3tools/client-runtime/connection"; |
| 37 | import { resolveThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread-reference"; |
| 38 | import { |
| 39 | canPreloadBrowsePath, |
| 40 | createBrowseNavigationCoordinator, |
| 41 | filterFilesystemBrowseEntries, |
| 42 | getFilesystemBrowsePath, |
| 43 | getFilesystemBrowseTabCompletion, |
| 44 | } from "@t3tools/client-runtime/state/filesystem"; |
| 45 | import { |
| 46 | isAtomCommandInterrupted, |
| 47 | settlePromise, |
| 48 | squashAtomCommandFailure, |
| 49 | } from "@t3tools/client-runtime/state/runtime"; |
| 50 | import { |
| 51 | AuthOrchestrationOperateScope, |
| 52 | AuthSourceControlWriteScope, |
| 53 | AuthFilesystemReadScope, |
| 54 | type DesktopWslState, |
| 55 | type EnvironmentId, |
| 56 | type FilesystemBrowseResult, |
| 57 | SourceControlProviderKind, |
| 58 | PRIMARY_LOCAL_ENVIRONMENT_ID, |
| 59 | resolveEnvironmentMachineKind, |
| 60 | } from "@t3tools/contracts"; |
| 61 | import { useLocation, useNavigate } from "@tanstack/react-router"; |
| 62 | import { |
| 63 | ArrowLeftIcon, |
| 64 | BugIcon, |
| 65 | ChartNoAxesColumnIcon, |
| 66 | CheckIcon, |
| 67 | ChevronRightIcon, |
| 68 | CornerLeftUpIcon, |
| 69 | FileSearchIcon, |
| 70 | FolderGit2Icon, |
| 71 | FolderIcon, |
| 72 | FolderPlusIcon, |
| 73 | MessageSquareDashedIcon, |
| 74 | LinkIcon, |
| 75 | MessageSquareIcon, |
| 76 | PaletteIcon, |
| 77 | RotateCcwIcon, |
| 78 | SettingsIcon, |
| 79 | MonitorIcon, |
| 80 | PinIcon, |
| 81 | PinOffIcon, |
| 82 | PlugIcon, |
| 83 | SquarePenIcon, |
| 84 | TextSearchIcon, |
| 85 | UserPlusIcon, |
| 86 | } from "lucide-react"; |
| 87 | import { openThreadFind } from "./chat/threadFindStore"; |
| 88 | import { dispatchPreviewAction } from "./preview/previewActionBus"; |
| 89 | import { previewBridge } from "./preview/previewBridge"; |
| 90 | import { |
| 91 | useDeferredValue, |
| 92 | useEffect, |
| 93 | useId, |
| 94 | useReducer, |
| 95 | useRef, |
| 96 | useState, |
| 97 | type KeyboardEvent, |
| 98 | type ReactNode, |
| 99 | } from "react"; |
| 100 | import type { LegendListRef } from "@legendapp/list/react"; |
| 101 | import { useAtomValue } from "@effect/atom-react"; |
| 102 | |
| 103 | import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal"; |
| 104 | import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps"; |
| 105 | import { useHandleNewThread } from "../hooks/useHandleNewThread"; |
| 106 | import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl"; |
| 107 | import { copyThreadReference } from "../lib/copyThreadReference"; |
| 108 | import { |
| 109 | queueWorkspaceFocusFromPalette, |
| 110 | restoreWorkspaceFocusFromPalette, |
| 111 | } from "../lib/workspaceFocus"; |
| 112 | import { |
| 113 | composerPromptLink, |
| 114 | copyPromptLink, |
| 115 | promptLinkRepositoryOf, |
| 116 | } from "./promptLinks/copyPromptLink"; |
| 117 | import { useClientSettings } from "../hooks/useSettings"; |
| 118 | import { useStableCallback } from "../hooks/useStableCallback"; |
| 119 | import { readLocalApi } from "../localApi"; |
| 120 | import { configuredHostedAppUrl } from "../hostedPairing"; |
| 121 | import { desktopLocalBackendId } from "../connection/desktopLocal"; |
| 122 | import { filesystemEnvironment, useFilesystemReadAccess } from "../state/filesystem"; |
| 123 | import { projectEnvironment } from "../state/projects"; |
| 124 | import { useEnvironmentQuery } from "../state/query"; |
| 125 | import { serverEnvironment } from "../state/server"; |
| 126 | import { threadEnvironment } from "../state/threads"; |
| 127 | import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; |
| 128 | import { sourceControlEnvironment } from "../state/sourceControl"; |
| 129 | import { useAtomCommand } from "../state/use-atom-command"; |
| 130 | import { useOrchestrationCommand } from "../state/use-orchestration-command"; |
| 131 | import { useAtomQueryRunner } from "../state/use-atom-query-runner"; |
| 132 | import { useScratchProject } from "../hooks/useScratchProject"; |
| 133 | import { useStartTriage } from "../hooks/useStartTriage"; |
| 134 | import { pickTriageEnvironment } from "../lib/triageTarget"; |
| 135 | import { useNewProject } from "../hooks/useNewProject"; |
| 136 | import { useOrderWhileOpen } from "../hooks/useOrderWhileOpen"; |
| 137 | import { reportProjectFailure, useProjectPin } from "../hooks/useProjectGroupUpdate"; |
| 138 | import { |
| 139 | useEnvironmentProviders, |
| 140 | useEnvironments, |
| 141 | usePrimaryEnvironmentId, |
| 142 | } from "../state/environments"; |
| 143 | import { |
| 144 | useAnyEnvironmentHiding, |
| 145 | useDelegatedUnderParent, |
| 146 | useHiddenThreadKeys, |
| 147 | useEnvironmentThreadRefs, |
| 148 | useProjects, |
| 149 | useServerConfigs, |
| 150 | useVisibleThreadShells, |
| 151 | waitForProject, |
| 152 | } from "../state/entities"; |
| 153 | import { isShownUnderParent, visibleLinkedThreads } from "@t3tools/client-runtime/state/threads"; |
| 154 | import { |
| 155 | resolveThreadActionProjectRef, |
| 156 | startNewThreadFromContext, |
| 157 | threadHasStarted, |
| 158 | } from "../lib/chatThreadActions"; |
| 159 | import { |
| 160 | appendBrowsePathSegment, |
| 161 | findProjectByPath, |
| 162 | getBrowseDirectoryPath, |
| 163 | hasTrailingPathSeparator, |
| 164 | inferProjectTitleFromPath, |
| 165 | isExplicitRelativeProjectPath, |
| 166 | isFilesystemBrowseQuery, |
| 167 | isScratchProject, |
| 168 | isUnsupportedWindowsProjectPath, |
| 169 | resolveProjectPathForDispatch, |
| 170 | } from "@t3tools/client-runtime/state/projects"; |
| 171 | import { resolvePastedPath } from "@t3tools/shared/path"; |
| 172 | import { |
| 173 | dispatchCommandPalette, |
| 174 | getCommandPaletteReturnFocus, |
| 175 | useCommandPaletteMount, |
| 176 | useCommandPaletteStore, |
| 177 | } from "../commandPaletteStore"; |
| 178 | import { |
| 179 | PULL_REQUESTS_PANEL_REF, |
| 180 | selectActiveRightPanel, |
| 181 | useRightPanelStore, |
| 182 | } from "../rightPanelStore"; |
| 183 | import { getLatestThreadForProject, sortThreads } from "@t3tools/client-runtime/state/thread-sort"; |
| 184 | import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; |
| 185 | import { |
| 186 | cn, |
| 187 | getLocalFileManagerName, |
| 188 | isMacPlatform, |
| 189 | isWindowsPlatform, |
| 190 | newProjectId, |
| 191 | } from "../lib/utils"; |
| 192 | import { buildThreadRouteParams } from "../threadRoutes"; |
| 193 | import { useAvailableSettingsSearchItems } from "./settings/useAvailableSettingsSearchItems"; |
| 194 | import { |
| 195 | applyWslEnvironmentConfiguration, |
| 196 | parseWslUncPath, |
| 197 | resolveProjectPickerTarget, |
| 198 | resolveWslProjectSelection, |
| 199 | } from "../wslPaths"; |
| 200 | import { |
| 201 | resolveCommandPaletteProject, |
| 202 | ADDON_ICON_CLASS, |
| 203 | browseInputEndPaddingClass, |
| 204 | buildBrowseGroups, |
| 205 | buildRootGroups, |
| 206 | buildLinkedThreadActionItems, |
| 207 | buildCommandPaletteRows, |
| 208 | enumerateCommandPaletteItems, |
| 209 | newThreadNoProjectIndex, |
| 210 | findHighlightedCommandPaletteItem, |
| 211 | type CommandPaletteActionItem, |
| 212 | type CommandPaletteOpenIntent, |
| 213 | type CommandPaletteProject, |
| 214 | type CommandPaletteReturnContext, |
| 215 | type CommandPaletteSubmenuItem, |
| 216 | type CommandPaletteView, |
| 217 | filterCommandPaletteGroups, |
| 218 | buildNestedSearchItems, |
| 219 | filterPinnedBrowseEntries, |
| 220 | getCommandPaletteInputPlaceholder, |
| 221 | getCommandPaletteMode, |
| 222 | ITEM_ICON_CLASS, |
| 223 | RECENT_THREAD_LIMIT, |
| 224 | createCommandPaletteSearchState, |
| 225 | type CommandPaletteGroup, |
| 226 | resolveAddProjectEntry, |
| 227 | type AddProjectCloneFlow, |
| 228 | type AddProjectEnvironmentOption, |
| 229 | buildPaletteRemoteSourceReadiness, |
| 230 | errorMessage, |
| 231 | getEnvironmentBrowsePlatform, |
| 232 | remoteProjectInputPlaceholder, |
| 233 | reduceCommandPaletteSearchState, |
| 234 | type SearchOverlayMode, |
| 235 | } from "./CommandPalette.logic"; |
| 236 | import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic"; |
| 237 | import { CommandPaletteContent, type PendingInputSelection } from "./CommandPaletteContent"; |
| 238 | import { |
| 239 | selectCommandPaletteClientSettings, |
| 240 | useEnvironmentLookups, |
| 241 | useProjectLookups, |
| 242 | useSortedProjectGroups, |
| 243 | } from "./CommandPaletteLookups"; |
| 244 | import { |
| 245 | buildNewThreadInProjectItems, |
| 246 | buildProjectSearchItems, |
| 247 | } from "./CommandPaletteProjectItems"; |
| 248 | import { |
| 249 | CommandPaletteSubmitButton, |
| 250 | NewProjectPublishHostPicker, |
| 251 | NewProjectSummary, |
| 252 | RemoteRepositorySummary, |
| 253 | remoteProjectSourceIcon, |
| 254 | sourceControlHostIcon, |
| 255 | } from "./CommandPaletteAddProject"; |
| 256 | import { useCommandPaletteThreadItems } from "./CommandPaletteThreadItems"; |
| 257 | import { useCommandPaletteThemeItems } from "./CommandPaletteThemeItems"; |
| 258 | import { |
| 259 | PORT_FORWARD_GROUP_PREFIX, |
| 260 | useCommandPalettePortForwardItem, |
| 261 | } from "./CommandPalettePortForwardItems"; |
| 262 | import { |
| 263 | CommandPaletteVirtualizedResults, |
| 264 | scrollCommandPaletteRowIntoView, |
| 265 | } from "./CommandPaletteResults"; |
| 266 | import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; |
| 267 | import { Checkbox } from "./ui/checkbox"; |
| 268 | import { ProjectFilePicker } from "./files/ProjectFilePicker"; |
| 269 | import { openLinkPullRequestDialog } from "./pullRequest/LinkPullRequestDialog"; |
| 270 | import { canShareWithGuestAtom } from "./chat/guestShareAvailability"; |
| 271 | import { openGuestShareDialog } from "./chat/guestShareDialogState"; |
| 272 | import { openUseInAnotherApp } from "./mcp/UseInAnotherAppDialog"; |
| 273 | import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog"; |
| 274 | import { settingsForThisPlatform, SETTINGS_SECTION_LABELS } from "./settings/settingsSearch"; |
| 275 | import { primaryServerKeybindingsAtom } from "../state/server"; |
| 276 | import { resolveShortcutCommand, threadJumpIndexFromCommand } from "../keybindings"; |
| 277 | import { CommandDialog, CommandDialogPopup, CommandFooterAction } from "./ui/command"; |
| 278 | import { Button } from "./ui/button"; |
| 279 | import { stackedThreadToast, toastManager } from "./ui/toast"; |
| 280 | import { suggestAppAccessForRemote } from "./sourceControlAppAccessToast"; |
| 281 | import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; |
| 282 | import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext"; |
| 283 | import type { ChatComposerHandle } from "./chat/ChatComposer"; |
| 284 | import { |
| 285 | isPickableProjectMember, |
| 286 | pickableProjectGroups, |
| 287 | } from "@t3tools/client-runtime/state/project-grouping"; |
| 288 | import { buildSidebarProjectPickerEntries } from "../sidebarProjectGrouping"; |
| 289 | import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; |
| 290 | import { readPullRequestListPreferences } from "~/components/pullRequest/pullRequestListPreferences"; |
| 291 | import { readIssueListPreferences } from "~/components/issue/issueListPreferences"; |
| 292 | import { IssueGlyph } from "~/components/issue/issuePresentation"; |
| 293 | import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget"; |
| 294 | import { threadRecentUse } from "@t3tools/shared/paletteSearch"; |
| 295 | |
| 296 | const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = []; |
| 297 | const ADD_PROJECT_ENTRY_GROUP = "add-project"; |
| 298 | const NEW_THREAD_IN_GROUP = "projects"; |
| 299 | |
| 300 | /** The submenu an open intent starts in; its groups resolve while rendering. */ |
| 301 | function openIntentView( |
| 302 | intent: CommandPaletteOpenIntent | null, |
| 303 | resolve: MessageResolver, |
| 304 | ): CommandPaletteView | null { |
| 305 | switch (intent?.kind) { |
| 306 | case "add-project": |
| 307 | return { |
| 308 | addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />, |
| 309 | groups: [{ value: ADD_PROJECT_ENTRY_GROUP, label: "", items: [] }], |
| 310 | }; |
| 311 | case "new-thread-in": |
| 312 | return { |
| 313 | addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />, |
| 314 | groups: [{ value: NEW_THREAD_IN_GROUP, label: resolve(msg("Projects")), items: [] }], |
| 315 | }; |
| 316 | case "change-theme": |
| 317 | return { |
| 318 | addonIcon: <PaletteIcon className={ADDON_ICON_CLASS} />, |
| 319 | groups: [{ value: "themes", label: resolve(msg("Change theme")), items: [] }], |
| 320 | }; |
| 321 | case "search": |
| 322 | case undefined: |
| 323 | return null; |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | const NEW_THREAD_NO_PROJECT_VALUE = "new-thread-in:no-project"; |
| 328 | |
| 329 | export function CommandPalette({ children }: { children: ReactNode }) { |
| 330 | useCommandPaletteMount(); |
| 331 | const state = useCommandPaletteStore(); |
| 332 | const setOpen = (open: boolean) => dispatchCommandPalette({ _tag: "SetOpen", open }); |
| 333 | const openChildSearch = (mode: "files" | "content", context: CommandPaletteReturnContext) => |
| 334 | dispatchCommandPalette({ _tag: "OpenChildSearch", mode, context }); |
| 335 | const composerHandleRef = useRef<ChatComposerHandle | null>(null); |
| 336 | |
| 337 | return ( |
| 338 | <ComposerHandleContext value={composerHandleRef}> |
| 339 | <ThreadContextDragGhost /> |
| 340 | <CommandDialog |
| 341 | open={state.open} |
| 342 | onOpenChange={(open, eventDetails) => { |
| 343 | if (!open && eventDetails.reason === "escape-key" && state.mode !== "command") { |
| 344 | eventDetails.cancel(); |
| 345 | dispatchCommandPalette({ _tag: "BackToCommand" }); |
| 346 | return; |
| 347 | } |
| 348 | setOpen(open); |
| 349 | }} |
| 350 | > |
| 351 | <div className="contents" inert={state.open}> |
| 352 | {children} |
| 353 | </div> |
| 354 | <CommandPaletteDialog |
| 355 | mode={state.mode} |
| 356 | session={state.session} |
| 357 | openIntent={state.openIntent} |
| 358 | setOpen={setOpen} |
| 359 | openChildSearch={openChildSearch} |
| 360 | initialContext={state.restoredSearch} |
| 361 | /> |
| 362 | </CommandDialog> |
| 363 | </ComposerHandleContext> |
| 364 | ); |
| 365 | } |
| 366 | |
| 367 | function CommandPaletteDialog(props: { |
| 368 | readonly mode: SearchOverlayMode; |
| 369 | readonly session: number; |
| 370 | readonly openIntent: CommandPaletteOpenIntent | null; |
| 371 | readonly setOpen: (open: boolean) => void; |
| 372 | readonly openChildSearch: ( |
| 373 | mode: "files" | "content", |
| 374 | context: CommandPaletteReturnContext, |
| 375 | ) => void; |
| 376 | readonly initialContext: CommandPaletteReturnContext | undefined; |
| 377 | }) { |
| 378 | const gt = useGT(); |
| 379 | const composerHandleRef = useComposerHandleContext(); |
| 380 | |
| 381 | return ( |
| 382 | <CommandDialogPopup |
| 383 | aria-label={ |
| 384 | props.mode === "files" |
| 385 | ? gt("File picker") |
| 386 | : props.mode === "content" |
| 387 | ? gt("Search project contents") |
| 388 | : gt("Command palette") |
| 389 | } |
| 390 | className={cn("overflow-hidden", props.mode === "content" && "h-105")} |
| 391 | data-command-palette="true" |
| 392 | data-palette-mode={props.mode} |
| 393 | data-testid="command-palette" |
| 394 | finalFocus={() => { |
| 395 | if (restoreWorkspaceFocusFromPalette()) return false; |
| 396 | const returnFocus = getCommandPaletteReturnFocus(); |
| 397 | if (returnFocus === false) return false; |
| 398 | const composer = composerHandleRef?.current; |
| 399 | // Behind the Settings modal the composer is inert and cannot take focus. |
| 400 | if (!composer || document.querySelector("[data-app-modal]")) return returnFocus; |
| 401 | composer.focusAtEnd(); |
| 402 | return false; |
| 403 | }} |
| 404 | onBackdropPointerDown={() => { |
| 405 | props.setOpen(false); |
| 406 | }} |
| 407 | > |
| 408 | {props.mode === "files" ? ( |
| 409 | <ProjectFilePicker setOpen={props.setOpen} /> |
| 410 | ) : props.mode === "content" ? ( |
| 411 | <ProjectContentSearchDialog onOpenChange={props.setOpen} /> |
| 412 | ) : ( |
| 413 | <OpenCommandPaletteDialog |
| 414 | key={props.session} |
| 415 | openIntent={props.openIntent} |
| 416 | setOpen={props.setOpen} |
| 417 | openChildSearch={props.openChildSearch} |
| 418 | initialContext={props.initialContext} |
| 419 | /> |
| 420 | )} |
| 421 | </CommandDialogPopup> |
| 422 | ); |
| 423 | } |
| 424 | |
| 425 | function OpenCommandPaletteDialog(props: { |
| 426 | readonly openIntent: CommandPaletteOpenIntent | null; |
| 427 | readonly setOpen: (open: boolean) => void; |
| 428 | readonly openChildSearch: ( |
| 429 | mode: "files" | "content", |
| 430 | context: CommandPaletteReturnContext, |
| 431 | ) => void; |
| 432 | readonly initialContext: CommandPaletteReturnContext | undefined; |
| 433 | }) { |
| 434 | const gt = useGT(); |
| 435 | const messages = useMessages(); |
| 436 | const navigate = useNavigate(); |
| 437 | const pathname = useLocation({ select: (location) => location.pathname }); |
| 438 | const { openChildSearch, setOpen } = props; |
| 439 | // Keyed by palette session: the intent and restored search only seed this |
| 440 | // mount, and closing must not change what the closing palette shows. |
| 441 | const [initialSearch] = useState( |
| 442 | () => |
| 443 | props.initialContext ?? { |
| 444 | query: props.openIntent?.kind === "search" ? props.openIntent.query : "", |
| 445 | linkedThreadSearch: props.openIntent?.kind === "search" ? props.openIntent : null, |
| 446 | }, |
| 447 | ); |
| 448 | const linkedThreadSearch = initialSearch.linkedThreadSearch; |
| 449 | // Rows were captured when the palette opened; drop any hidden since then. |
| 450 | const hiddenKeys = useHiddenThreadKeys(); |
| 451 | const linkedEnvironmentId = linkedThreadSearch?.linkedThreads?.environmentId ?? null; |
| 452 | const hidingAnywhere = useAnyEnvironmentHiding(); |
| 453 | const linkedThreadRefs = useEnvironmentThreadRefs(linkedEnvironmentId); |
| 454 | const [searchState, dispatchSearch] = useReducer(reduceCommandPaletteSearchState, null, () => { |
| 455 | const view = props.initialContext ? null : openIntentView(props.openIntent, messages); |
| 456 | return view |
| 457 | ? { query: "", views: [{ view, parentQuery: "" }] } |
| 458 | : createCommandPaletteSearchState(initialSearch.query); |
| 459 | }); |
| 460 | const { query, views: viewStack } = searchState; |
| 461 | const setQuery = (query: string) => dispatchSearch({ type: "query", query }); |
| 462 | const deferredQuery = useDeferredValue(query); |
| 463 | const isActionsOnly = deferredQuery.startsWith(">"); |
| 464 | const [highlightedItemValue, setHighlightedItemValue] = useState<string | null>(null); |
| 465 | const resultListRef = useRef<LegendListRef | null>(null); |
| 466 | // A pushed view drops the typed highlight until the user moves it again. |
| 467 | const highlightClearedRef = useRef(viewStack.length > 0); |
| 468 | // Entering or leaving browse mode remounts the input; carry the caret across it. |
| 469 | const remountSelectionRef = useRef<PendingInputSelection | null>(null); |
| 470 | function clearTypedHighlight(): void { |
| 471 | highlightClearedRef.current = true; |
| 472 | setHighlightedItemValue(null); |
| 473 | } |
| 474 | const clientSettings = useClientSettings(selectCommandPaletteClientSettings); |
| 475 | const createProject = useAtomCommand(projectEnvironment.create, { |
| 476 | reportFailure: false, |
| 477 | }); |
| 478 | const updateProject = useOrchestrationCommand(projectEnvironment.update, { |
| 479 | label: "project unarchive", |
| 480 | }); |
| 481 | const { scratchEnvironmentId, scratchWorkspaceRootFor, startScratchThread } = useScratchProject(); |
| 482 | const startTriage = useStartTriage(); |
| 483 | const lookupRepository = useAtomQueryRunner(sourceControlEnvironment.repository, { |
| 484 | reportFailure: false, |
| 485 | }); |
| 486 | const loadBrowsePath = useAtomQueryRunner(filesystemEnvironment.browse, { |
| 487 | reportFailure: false, |
| 488 | reportDefect: false, |
| 489 | }); |
| 490 | const startProjectClone = useAtomCommand(sourceControlEnvironment.startProjectClone, { |
| 491 | reportFailure: false, |
| 492 | }); |
| 493 | const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, { |
| 494 | reportFailure: false, |
| 495 | }); |
| 496 | const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, { |
| 497 | reportFailure: false, |
| 498 | }); |
| 499 | const { environments } = useEnvironments(); |
| 500 | const desktopLocalBootstraps = useDesktopLocalBootstraps(); |
| 501 | const primaryEnvironmentId = usePrimaryEnvironmentId(); |
| 502 | const availableSettingsSearchItems = useAvailableSettingsSearchItems(); |
| 503 | const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } = |
| 504 | useHandleNewThread(); |
| 505 | const paletteRouteTarget = useThreadRouteTarget(); |
| 506 | const projects = useProjects(); |
| 507 | const referenceThreadRef = |
| 508 | pathname === "/pull-requests" |
| 509 | ? environments.some((environment) => environment.serverConfig !== null) |
| 510 | ? PULL_REQUESTS_PANEL_REF |
| 511 | : null |
| 512 | : activeThread |
| 513 | ? scopeThreadRef(activeThread.environmentId, activeThread.id) |
| 514 | : null; |
| 515 | const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(referenceThreadRef); |
| 516 | const activeThreadServerConfig = useServerConfigs().get( |
| 517 | activeThread?.environmentId ?? ("" as EnvironmentId), |
| 518 | ); |
| 519 | const canShareActiveThreadWithGuest = useAtomValue( |
| 520 | canShareWithGuestAtom(activeThread?.environmentId ?? ("" as EnvironmentId)), |
| 521 | ); |
| 522 | const activeThreadReferenceCopyTarget = |
| 523 | referenceThreadRef === null || (pathname === "/pull-requests" && !openPanelPullRequestUrl) |
| 524 | ? null |
| 525 | : resolveThreadReferenceCopyTarget( |
| 526 | { |
| 527 | threadRef: referenceThreadRef, |
| 528 | title: activeThread?.title ?? "", |
| 529 | openPanelPullRequestUrl, |
| 530 | pullRequests: activeThread?.pullRequests, |
| 531 | linkedPullRequestUrl: |
| 532 | activeThread?.linkedPullRequest?.url ?? activeThread?.branchPullRequest?.url ?? null, |
| 533 | hostedAppUrl: configuredHostedAppUrl(), |
| 534 | }, |
| 535 | messages, |
| 536 | ); |
| 537 | const copyActiveThreadReference = async () => { |
| 538 | if (activeThreadReferenceCopyTarget === null) return; |
| 539 | await copyThreadReference(activeThreadReferenceCopyTarget); |
| 540 | }; |
| 541 | // Threads the sidebar shows under their parent open there, so opening a project never lands on one. |
| 542 | const delegatedUnderParent = useDelegatedUnderParent(); |
| 543 | const threads = useVisibleThreadShells().filter( |
| 544 | (thread) => |
| 545 | !isShownUnderParent( |
| 546 | { environmentId: thread.environmentId, threadId: thread.id }, |
| 547 | thread.lineage, |
| 548 | delegatedUnderParent, |
| 549 | ), |
| 550 | ); |
| 551 | const keybindings = useAtomValue(primaryServerKeybindingsAtom); |
| 552 | const providersByEnvironment = useEnvironmentProviders(); |
| 553 | const { changeThemeItem, changeAppearanceItem, themeEditorItem } = useCommandPaletteThemeItems(); |
| 554 | const portForwardItem = useCommandPalettePortForwardItem({ |
| 555 | activeThread: activeThread ?? null, |
| 556 | query: deferredQuery, |
| 557 | }); |
| 558 | const currentView = viewStack.at(-1)?.view ?? null; |
| 559 | const threadSearchQuery = currentView === null && !isActionsOnly ? deferredQuery : ""; |
| 560 | const [browseGeneration, setBrowseGeneration] = useState(0); |
| 561 | const [browseNavigation] = useState(createBrowseNavigationCoordinator); |
| 562 | const [addProjectEnvironmentId, setAddProjectEnvironmentId] = useState<EnvironmentId | null>( |
| 563 | null, |
| 564 | ); |
| 565 | const [isPickingProjectFolder, setIsPickingProjectFolder] = useState(false); |
| 566 | const [addProjectCloneFlow, setAddProjectCloneFlow] = useState<AddProjectCloneFlow | null>(null); |
| 567 | const [newProjectFlow, setNewProjectFlow] = useState<{ |
| 568 | readonly environmentId: EnvironmentId; |
| 569 | readonly sourcesEnvironmentId: EnvironmentId | null; |
| 570 | } | null>(null); |
| 571 | const [newProjectPublishes, setNewProjectPublishes] = useState(false); |
| 572 | const [newProjectPublishKind, setNewProjectPublishKind] = |
| 573 | useState<SourceControlProviderKind | null>(null); |
| 574 | const [isCreatingNewProject, setIsCreatingNewProject] = useState(false); |
| 575 | // State lags a render behind, so a repeated Enter could start a second create. |
| 576 | const newProjectSubmittingRef = useRef(false); |
| 577 | const createNewProject = useNewProject(); |
| 578 | const cloneLookupGeneration = useRef(0); |
| 579 | const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false); |
| 580 | const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false); |
| 581 | const { environmentLabelById, projectEnvironmentLocationById } = useEnvironmentLookups(); |
| 582 | const projectGroups = useSortedProjectGroups(environmentLabelById); |
| 583 | const contextualProjectRef = resolveThreadActionProjectRef({ |
| 584 | activeDraftThread, |
| 585 | activeThread: activeThread ?? undefined, |
| 586 | defaultProjectRef, |
| 587 | handleNewThread, |
| 588 | }); |
| 589 | const projectPickerEntries = buildSidebarProjectPickerEntries({ |
| 590 | groups: pickableProjectGroups(projectGroups), |
| 591 | preferredProjectRef: contextualProjectRef, |
| 592 | }); |
| 593 | const pickerProjects = projectPickerEntries.map(({ group, targetProject }) => ({ |
| 594 | ...targetProject, |
| 595 | displayName: group.displayName, |
| 596 | })); |
| 597 | const projectGroupByTargetKey = new Map( |
| 598 | projectPickerEntries.map(({ group, targetProject }) => [ |
| 599 | `${targetProject.environmentId}:${targetProject.id}`, |
| 600 | group, |
| 601 | ]), |
| 602 | ); |
| 603 | const { canPinProjectGroup, toggleProjectGroupPin } = useProjectPin(); |
| 604 | // A row's target record can change when another machine's copy loads, so the kept |
| 605 | // order follows the project group instead. |
| 606 | const rowOrderKey = (prefix: string) => (item: CommandPaletteActionItem) => |
| 607 | projectGroupByTargetKey.get(item.value.slice(prefix.length + 1))?.projectKey ?? item.value; |
| 608 | const projectPin = (project: CommandPaletteProject) => { |
| 609 | const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`); |
| 610 | return group && canPinProjectGroup(group) |
| 611 | ? { |
| 612 | name: group.displayName, |
| 613 | pinned: group.pinned, |
| 614 | toggle: () => toggleProjectGroupPin(group), |
| 615 | } |
| 616 | : null; |
| 617 | }; |
| 618 | |
| 619 | const addProjectEnvironmentOptions = (() => { |
| 620 | const options = environments |
| 621 | .filter((environment) => canCreateProjectInEnvironment(environment.connection.phase)) |
| 622 | .map((environment): AddProjectEnvironmentOption => { |
| 623 | const isPrimary = environment.entry.target._tag === "PrimaryConnectionTarget"; |
| 624 | return { |
| 625 | environmentId: environment.environmentId, |
| 626 | label: resolveEnvironmentOptionLabel( |
| 627 | { |
| 628 | isPrimary, |
| 629 | environmentId: environment.environmentId, |
| 630 | runtimeLabel: environment.label, |
| 631 | }, |
| 632 | messages, |
| 633 | ), |
| 634 | isPrimary, |
| 635 | machine: resolveEnvironmentMachineKind(environment.serverConfig), |
| 636 | isConnected: canCreateProjectInEnvironment(environment.connection.phase), |
| 637 | status: connectionStatusText(environment.connection, messages), |
| 638 | }; |
| 639 | }); |
| 640 | |
| 641 | options.sort((left, right) => { |
| 642 | if (left.isPrimary !== right.isPrimary) { |
| 643 | return left.isPrimary ? -1 : 1; |
| 644 | } |
| 645 | return left.label.localeCompare(right.label); |
| 646 | }); |
| 647 | |
| 648 | return options; |
| 649 | })(); |
| 650 | const defaultAddProjectEnvironmentId = |
| 651 | addProjectEnvironmentOptions.find((option) => option.isConnected)?.environmentId ?? null; |
| 652 | const wslAddProjectEnvironmentOption = |
| 653 | addProjectEnvironmentOptions.find((option) => { |
| 654 | if (!option.isConnected) { |
| 655 | return false; |
| 656 | } |
| 657 | const environment = environments.find( |
| 658 | (candidate) => candidate.environmentId === option.environmentId, |
| 659 | ); |
| 660 | return environment |
| 661 | ? desktopLocalBackendId(environment.entry.target)?.startsWith("wsl:") === true |
| 662 | : false; |
| 663 | }) ?? null; |
| 664 | const browseEnvironmentId = addProjectEnvironmentId ?? defaultAddProjectEnvironmentId; |
| 665 | const canCreateProject = useEnvironmentScope(browseEnvironmentId, AuthOrchestrationOperateScope); |
| 666 | const browseEnvironment = |
| 667 | environments.find((environment) => environment.environmentId === browseEnvironmentId) ?? null; |
| 668 | const browseEnvironmentIsDesktopLocal = |
| 669 | browseEnvironment !== null && isDesktopLocalConnectionTarget(browseEnvironment.entry.target); |
| 670 | // pickFolder routes desktop-local environments by pool id, not catalog environmentId. |
| 671 | const browseDesktopInstanceId = (() => { |
| 672 | if (!browseEnvironmentIsDesktopLocal || browseEnvironment === null) { |
| 673 | return null; |
| 674 | } |
| 675 | const displayUrl = browseEnvironment.displayUrl; |
| 676 | if (displayUrl === null) { |
| 677 | return null; |
| 678 | } |
| 679 | return ( |
| 680 | desktopLocalBootstraps.find((bootstrap) => bootstrap.httpBaseUrl === displayUrl)?.id ?? null |
| 681 | ); |
| 682 | })(); |
| 683 | const sourceControlDiscovery = useEnvironmentQuery( |
| 684 | browseEnvironmentId === null |
| 685 | ? null |
| 686 | : sourceControlEnvironment.discovery({ |
| 687 | environmentId: browseEnvironmentId, |
| 688 | input: {}, |
| 689 | }), |
| 690 | ); |
| 691 | const browseEnvironmentPlatform = getEnvironmentBrowsePlatform( |
| 692 | browseEnvironment?.serverConfig?.environment.platform.os, |
| 693 | ); |
| 694 | const isRemoteProjectCloneFlow = addProjectCloneFlow !== null; |
| 695 | const isRemoteProjectRepositoryStep = addProjectCloneFlow?.step === "repository"; |
| 696 | const pinnedCloneDirectoryName = |
| 697 | addProjectCloneFlow?.step === "confirm" |
| 698 | ? getCloneDirectoryLeafName( |
| 699 | addProjectCloneFlow.remoteUrl, |
| 700 | environments.find( |
| 701 | (candidate) => candidate.environmentId === addProjectCloneFlow.environmentId, |
| 702 | )?.serverConfig?.settings.ghqCloneLayout === true, |
| 703 | addProjectCloneFlow.repository?.nameWithOwner ?? addProjectCloneFlow.remoteUrl, |
| 704 | ) |
| 705 | : ""; |
| 706 | const canBrowsePaths = |
| 707 | browseEnvironmentId !== null && !isRemoteProjectRepositoryStep && newProjectFlow === null; |
| 708 | const browsePath = getFilesystemBrowsePath(query, browseEnvironmentPlatform, canBrowsePaths); |
| 709 | const isBrowsing = browsePath.isBrowsing; |
| 710 | const browseDirectoryPath = browsePath.directoryPath; |
| 711 | const paletteMode = getCommandPaletteMode({ currentView, isBrowsing }); |
| 712 | const getAddProjectInitialQueryForEnvironment = (environmentId: EnvironmentId | null): string => { |
| 713 | const environment = environments.find((candidate) => candidate.environmentId === environmentId); |
| 714 | return getAddProjectInitialQuery(environment?.serverConfig?.settings.addProjectBaseDirectory); |
| 715 | }; |
| 716 | |
| 717 | const { projectByKey } = useProjectLookups(); |
| 718 | |
| 719 | const activeThreadKey = activeThread |
| 720 | ? scopedThreadKey(scopeThreadRef(activeThread.environmentId, activeThread.id)) |
| 721 | : null; |
| 722 | const previewPanelThreadRef = activeThread |
| 723 | ? scopeThreadRef(activeThread.environmentId, activeThread.id) |
| 724 | : activeDraftThread |
| 725 | ? scopeThreadRef(activeDraftThread.environmentId, activeDraftThread.threadId) |
| 726 | : null; |
| 727 | const activeThreadPreviewOpen = useRightPanelStore( |
| 728 | (state) => selectActiveRightPanel(state.byThreadKey, previewPanelThreadRef) === "preview", |
| 729 | ); |
| 730 | const supportsThreadFind = |
| 731 | environments.find((environment) => environment.environmentId === activeThread?.environmentId) |
| 732 | ?.serverConfig?.threadFind === true; |
| 733 | const currentProjectEnvironmentId = |
| 734 | activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null; |
| 735 | const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null; |
| 736 | const scratchTargetEnvironmentId = scratchEnvironmentId(currentProjectEnvironmentId); |
| 737 | const supportsTriage = (environmentId: EnvironmentId | null) => |
| 738 | environments.find((environment) => environment.environmentId === environmentId)?.serverConfig |
| 739 | ?.environment.capabilities.triage === true; |
| 740 | const triageEnvironmentId = pickTriageEnvironment({ |
| 741 | onScreen: currentProjectEnvironmentId, |
| 742 | primary: primaryEnvironmentId, |
| 743 | connected: environments |
| 744 | .filter((environment) => environment.connection.phase === "connected") |
| 745 | .map((environment) => environment.environmentId), |
| 746 | supportsTriage, |
| 747 | }); |
| 748 | const canTriage = |
| 749 | useAtomValue(serverEnvironment.prepareTriage.permissionAtom(triageEnvironmentId)) && |
| 750 | supportsTriage(triageEnvironmentId); |
| 751 | const currentProject = resolveCommandPaletteProject( |
| 752 | projectByKey, |
| 753 | currentProjectEnvironmentId, |
| 754 | currentProjectId, |
| 755 | ); |
| 756 | const currentProjectCwd = currentProject?.workspaceRoot ?? null; |
| 757 | const currentProjectCwdForBrowse = |
| 758 | browseEnvironmentId && currentProjectEnvironmentId === browseEnvironmentId |
| 759 | ? currentProjectCwd |
| 760 | : null; |
| 761 | const getBrowseCwdForEnvironment = (environmentId: EnvironmentId | null): string | null => |
| 762 | environmentId && currentProjectEnvironmentId === environmentId ? currentProjectCwd : null; |
| 763 | const relativePathNeedsActiveProject = |
| 764 | isExplicitRelativeProjectPath(query.trim()) && currentProjectCwdForBrowse === null; |
| 765 | const browseAccess = useFilesystemReadAccess(browseEnvironmentId, messages); |
| 766 | const hasBrowseTarget = |
| 767 | isBrowsing && |
| 768 | browsePath.directoryPath.length > 0 && |
| 769 | browseEnvironmentId !== null && |
| 770 | !relativePathNeedsActiveProject; |
| 771 | const browseQuery = useEnvironmentQuery( |
| 772 | browseAccess.canReadFiles && hasBrowseTarget |
| 773 | ? filesystemEnvironment.browse({ |
| 774 | environmentId: browseEnvironmentId, |
| 775 | input: { |
| 776 | partialPath: browsePath.directoryPath, |
| 777 | ...(currentProjectCwdForBrowse ? { cwd: currentProjectCwdForBrowse } : {}), |
| 778 | }, |
| 779 | }) |
| 780 | : null, |
| 781 | ); |
| 782 | const browseResult = browseQuery.data; |
| 783 | const isBrowsePending = hasBrowseTarget && (browseAccess.isPending || browseQuery.isPending); |
| 784 | const browseAccessError = |
| 785 | hasBrowseTarget && !browseAccess.isPending && !browseAccess.canReadFiles |
| 786 | ? (browseAccess.error ?? gt("This connection cannot browse host folders.")) |
| 787 | : null; |
| 788 | const browseEntries = browseResult?.entries ?? EMPTY_BROWSE_ENTRIES; |
| 789 | const { visibleEntries: visibleBrowseEntries, exactEntry: exactBrowseEntry } = |
| 790 | pinnedCloneDirectoryName |
| 791 | ? filterPinnedBrowseEntries({ |
| 792 | browseEntries, |
| 793 | filterQuery: browsePath.filterQuery, |
| 794 | pinnedDirectoryName: pinnedCloneDirectoryName, |
| 795 | caseSensitive: !isWindowsPlatform(browseEnvironmentPlatform), |
| 796 | }) |
| 797 | : filterFilesystemBrowseEntries(browseEntries, browsePath.filterQuery); |
| 798 | |
| 799 | const prefetchBrowsePath = async ( |
| 800 | partialPath: string, |
| 801 | environmentId: EnvironmentId | null = browseEnvironmentId, |
| 802 | cwd: string | null = currentProjectCwdForBrowse, |
| 803 | ): Promise<void> => { |
| 804 | if (!environmentId) { |
| 805 | return; |
| 806 | } |
| 807 | const environment = environments.find((candidate) => candidate.environmentId === environmentId); |
| 808 | if ( |
| 809 | !readEnvironmentScope(environmentId, AuthFilesystemReadScope) || |
| 810 | !canPreloadBrowsePath(environment?.connection.phase) |
| 811 | ) { |
| 812 | return; |
| 813 | } |
| 814 | |
| 815 | await loadBrowsePath({ |
| 816 | environmentId, |
| 817 | input: { |
| 818 | partialPath, |
| 819 | ...(cwd ? { cwd } : {}), |
| 820 | }, |
| 821 | }); |
| 822 | }; |
| 823 | |
| 824 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- invalidates the browse navigation coordinator and in-flight clone lookups when the palette session unmounts |
| 825 | useEffect( |
| 826 | () => () => { |
| 827 | browseNavigation.invalidate(); |
| 828 | // A replaced or closed session must not report its in-flight lookup. |
| 829 | cloneLookupGeneration.current += 1; |
| 830 | }, |
| 831 | [browseNavigation], |
| 832 | ); |
| 833 | |
| 834 | const openProjectFromSearch = async (project: (typeof projects)[number]) => { |
| 835 | const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`); |
| 836 | const groupedProjectKeys = group |
| 837 | ? new Set( |
| 838 | group.memberProjectRefs.map( |
| 839 | (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`, |
| 840 | ), |
| 841 | ) |
| 842 | : null; |
| 843 | // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309) |
| 844 | const now = new Date().toISOString(); |
| 845 | const openableThreads = threads.filter( |
| 846 | (thread) => thread.settledOverride !== "settled" && !effectiveSnoozed(thread, { now }), |
| 847 | ); |
| 848 | const latestThread = groupedProjectKeys |
| 849 | ? (sortThreads( |
| 850 | openableThreads.filter( |
| 851 | (thread) => |
| 852 | thread.archivedAt === null && |
| 853 | groupedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`), |
| 854 | ), |
| 855 | clientSettings.sidebarThreadSortOrder, |
| 856 | )[0] ?? null) |
| 857 | : getLatestThreadForProject( |
| 858 | openableThreads.filter((thread) => thread.environmentId === project.environmentId), |
| 859 | project.id, |
| 860 | clientSettings.sidebarThreadSortOrder, |
| 861 | ); |
| 862 | if (latestThread) { |
| 863 | await navigate({ |
| 864 | to: "/$environmentId/$threadId", |
| 865 | params: buildThreadRouteParams(scopeThreadRef(latestThread.environmentId, latestThread.id)), |
| 866 | }); |
| 867 | return; |
| 868 | } |
| 869 | |
| 870 | await handleNewThread(scopeProjectRef(project.environmentId, project.id)); |
| 871 | }; |
| 872 | |
| 873 | // Pinning from a row keeps rows in place while the palette is open. |
| 874 | const projectSearchItems = useOrderWhileOpen( |
| 875 | buildProjectSearchItems( |
| 876 | { |
| 877 | projects: pickerProjects, |
| 878 | projectGroupByTargetKey, |
| 879 | locationByEnvironmentId: projectEnvironmentLocationById, |
| 880 | runProject: openProjectFromSearch, |
| 881 | pin: projectPin, |
| 882 | }, |
| 883 | messages, |
| 884 | ), |
| 885 | rowOrderKey("project"), |
| 886 | true, |
| 887 | ); |
| 888 | |
| 889 | const openingOrderThreadItems = useOrderWhileOpen( |
| 890 | (() => { |
| 891 | const isScratch = (project: CommandPaletteProject) => |
| 892 | isScratchProject(project, scratchWorkspaceRootFor(project.environmentId)); |
| 893 | const currentEntry = |
| 894 | currentProjectId === null |
| 895 | ? undefined |
| 896 | : projectPickerEntries.find((entry) => entry.isPreferred); |
| 897 | const projectItems = buildNewThreadInProjectItems({ |
| 898 | projects: pickerProjects.filter((project) => !isScratch(project)), |
| 899 | currentProjectKey: currentEntry |
| 900 | ? `${currentEntry.targetProject.environmentId}:${currentEntry.targetProject.id}` |
| 901 | : null, |
| 902 | projectGroupByTargetKey, |
| 903 | locationByEnvironmentId: projectEnvironmentLocationById, |
| 904 | pin: projectPin, |
| 905 | runProject: async (project) => { |
| 906 | const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`); |
| 907 | const contextualProjectIsEligible = |
| 908 | contextualProjectRef !== null && |
| 909 | group?.memberProjects.some( |
| 910 | (member) => |
| 911 | member.environmentId === contextualProjectRef.environmentId && |
| 912 | member.id === contextualProjectRef.projectId && |
| 913 | isPickableProjectMember(member), |
| 914 | ); |
| 915 | await handleNewThread( |
| 916 | contextualProjectIsEligible |
| 917 | ? contextualProjectRef |
| 918 | : scopeProjectRef(project.environmentId, project.id), |
| 919 | ); |
| 920 | }, |
| 921 | }); |
| 922 | if (scratchTargetEnvironmentId === null) return projectItems; |
| 923 | |
| 924 | const noProjectIndex = newThreadNoProjectIndex( |
| 925 | projectPickerEntries.map(({ group, targetProject, isPreferred }) => ({ |
| 926 | isScratch: isScratchProject( |
| 927 | targetProject, |
| 928 | scratchWorkspaceRootFor(targetProject.environmentId), |
| 929 | ), |
| 930 | pinned: group.pinned, |
| 931 | isPreferred, |
| 932 | })), |
| 933 | ); |
| 934 | return [ |
| 935 | ...projectItems.slice(0, noProjectIndex), |
| 936 | { |
| 937 | kind: "action" as const, |
| 938 | value: NEW_THREAD_NO_PROJECT_VALUE, |
| 939 | searchTerms: ["no project", "without project", "none"], |
| 940 | title: gt("No project"), |
| 941 | icon: <MessageSquareDashedIcon className={ITEM_ICON_CLASS} />, |
| 942 | shortcutCommand: "chat.newWithoutProject" as const, |
| 943 | run: () => startScratchThread(scratchTargetEnvironmentId), |
| 944 | }, |
| 945 | ...projectItems.slice(noProjectIndex), |
| 946 | ]; |
| 947 | })(), |
| 948 | rowOrderKey("new-thread-in"), |
| 949 | true, |
| 950 | ); |
| 951 | // Root search suggestions copy these numbers; the picker renumbers its shown rows below. |
| 952 | const projectJumpItems = new Map( |
| 953 | enumerateCommandPaletteItems( |
| 954 | openingOrderThreadItems.filter((item) => item.value !== NEW_THREAD_NO_PROJECT_VALUE), |
| 955 | ).map((item) => [item.value, item] as const), |
| 956 | ); |
| 957 | const projectThreadItems = openingOrderThreadItems.map( |
| 958 | (item) => projectJumpItems.get(item.value) ?? item, |
| 959 | ); |
| 960 | |
| 961 | const { |
| 962 | threadItems: allThreadItems, |
| 963 | threadMessageItems, |
| 964 | now: searchNow, |
| 965 | isSearchPending: isThreadSearchPending, |
| 966 | isSearchFailed: isThreadSearchFailed, |
| 967 | } = useCommandPaletteThreadItems({ activeThread: activeThread ?? null, threadSearchQuery }); |
| 968 | // Recent means used recently: written in or opened, whichever is later. The |
| 969 | // open thread would always lead that list, so it is left out. |
| 970 | const activeThreadValue = activeThread |
| 971 | ? `thread:${activeThread.environmentId}:${activeThread.id}` |
| 972 | : null; |
| 973 | const recentThreadItems = allThreadItems |
| 974 | .filter((item) => item.value !== activeThreadValue) |
| 975 | .toSorted( |
| 976 | (left, right) => |
| 977 | (right.threadSearch ? threadRecentUse(right.threadSearch) : 0) - |
| 978 | (left.threadSearch ? threadRecentUse(left.threadSearch) : 0), |
| 979 | ) |
| 980 | .slice(0, RECENT_THREAD_LIMIT); |
| 981 | |
| 982 | const pushPaletteView = useStableCallback((view: CommandPaletteView): void => { |
| 983 | browseNavigation.invalidate(); |
| 984 | dispatchSearch({ type: "push", view }); |
| 985 | highlightClearedRef.current = true; |
| 986 | setHighlightedItemValue(null); |
| 987 | }); |
| 988 | |
| 989 | function popView(): void { |
| 990 | browseNavigation.invalidate(); |
| 991 | setAddProjectCloneFlow(null); |
| 992 | setNewProjectFlow(null); |
| 993 | if (viewStack.length <= 1) { |
| 994 | setAddProjectEnvironmentId(null); |
| 995 | } else if (newProjectFlow?.sourcesEnvironmentId) { |
| 996 | setAddProjectEnvironmentId(newProjectFlow.sourcesEnvironmentId); |
| 997 | } |
| 998 | dispatchSearch({ type: "back" }); |
| 999 | setHighlightedItemValue(null); |
| 1000 | } |
| 1001 | |
| 1002 | function handleQueryChange(nextQuery: string, source: EventTarget | null): void { |
| 1003 | browseNavigation.invalidate(); |
| 1004 | clearTypedHighlight(); |
| 1005 | const resolvedQuery = canBrowsePaths ? resolvePastedPath(query, nextQuery) : nextQuery; |
| 1006 | // A rewritten paste has no matching offsets, so its caret lands at the end. |
| 1007 | if ( |
| 1008 | source instanceof HTMLInputElement && |
| 1009 | resolvedQuery === nextQuery && |
| 1010 | (canBrowsePaths && isFilesystemBrowseQuery(resolvedQuery, browseEnvironmentPlatform)) !== |
| 1011 | isBrowsing |
| 1012 | ) { |
| 1013 | remountSelectionRef.current = { |
| 1014 | value: resolvedQuery, |
| 1015 | start: source.selectionStart, |
| 1016 | end: source.selectionEnd, |
| 1017 | direction: source.selectionDirection, |
| 1018 | }; |
| 1019 | } |
| 1020 | setQuery(resolvedQuery); |
| 1021 | if (nextQuery === "" && currentView?.initialQuery) { |
| 1022 | popView(); |
| 1023 | } |
| 1024 | } |
| 1025 | |
| 1026 | const startAddProjectBrowse = async (environmentId: EnvironmentId): Promise<void> => { |
| 1027 | const initialQuery = getAddProjectInitialQueryForEnvironment(environmentId); |
| 1028 | const initialBrowsePath = getBrowseDirectoryPath(initialQuery); |
| 1029 | const browseCwd = getBrowseCwdForEnvironment(environmentId); |
| 1030 | const view: CommandPaletteView = { |
| 1031 | addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />, |
| 1032 | groups: [], |
| 1033 | initialQuery, |
| 1034 | }; |
| 1035 | |
| 1036 | await browseNavigation.run( |
| 1037 | () => |
| 1038 | initialBrowsePath.length > 0 |
| 1039 | ? prefetchBrowsePath(initialBrowsePath, environmentId, browseCwd) |
| 1040 | : Promise.resolve(), |
| 1041 | () => { |
| 1042 | setAddProjectEnvironmentId(environmentId); |
| 1043 | setAddProjectCloneFlow(null); |
| 1044 | pushPaletteView(view); |
| 1045 | }, |
| 1046 | ); |
| 1047 | }; |
| 1048 | |
| 1049 | const startAddProjectClone = ( |
| 1050 | environmentId: EnvironmentId, |
| 1051 | source: AddProjectRemoteSource, |
| 1052 | ): void => { |
| 1053 | setAddProjectEnvironmentId(environmentId); |
| 1054 | setAddProjectCloneFlow({ step: "repository", environmentId, source }); |
| 1055 | pushPaletteView({ |
| 1056 | addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS), |
| 1057 | groups: [], |
| 1058 | initialQuery: "", |
| 1059 | }); |
| 1060 | }; |
| 1061 | |
| 1062 | const newProjectsRootFor = (environmentId: EnvironmentId | null): string | null => |
| 1063 | environments.find((environment) => environment.environmentId === environmentId)?.serverConfig |
| 1064 | ?.newProjectsRoot ?? null; |
| 1065 | |
| 1066 | const offeredProvidersFor = (environmentId: EnvironmentId | null) => |
| 1067 | environments.find((environment) => environment.environmentId === environmentId)?.serverConfig |
| 1068 | ?.settings.offeredSourceControlProviders; |
| 1069 | |
| 1070 | const startNewProject = ( |
| 1071 | environmentId: EnvironmentId, |
| 1072 | sourcesEnvironmentId: EnvironmentId | null, |
| 1073 | ): void => { |
| 1074 | setAddProjectEnvironmentId(environmentId); |
| 1075 | setAddProjectCloneFlow(null); |
| 1076 | setNewProjectFlow({ environmentId, sourcesEnvironmentId }); |
| 1077 | setNewProjectPublishes(false); |
| 1078 | setNewProjectPublishKind(null); |
| 1079 | pushPaletteView({ |
| 1080 | addonIcon: <FolderGit2Icon className={ADDON_ICON_CLASS} />, |
| 1081 | groups: [], |
| 1082 | }); |
| 1083 | }; |
| 1084 | |
| 1085 | const openSourceControlSettings = () => { |
| 1086 | setOpen(false); |
| 1087 | void navigate({ to: "/settings/source-control" }); |
| 1088 | }; |
| 1089 | |
| 1090 | const buildAddProjectSourceGroups = ( |
| 1091 | environmentId: EnvironmentId, |
| 1092 | readinessBySource: AddProjectRemoteSourceReadiness, |
| 1093 | ): CommandPaletteView["groups"] => { |
| 1094 | const sourceItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [ |
| 1095 | { |
| 1096 | kind: "action", |
| 1097 | value: `action:add-project:${environmentId}:local`, |
| 1098 | searchTerms: ["local", "folder", "directory", "browse"], |
| 1099 | title: gt("Local folder"), |
| 1100 | description: gt("Browse a folder on disk"), |
| 1101 | icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />, |
| 1102 | keepOpen: true, |
| 1103 | run: async () => { |
| 1104 | await startAddProjectBrowse(environmentId); |
| 1105 | }, |
| 1106 | }, |
| 1107 | ]; |
| 1108 | |
| 1109 | if (newProjectsRootFor(environmentId) !== null) { |
| 1110 | sourceItems.unshift({ |
| 1111 | kind: "action", |
| 1112 | value: `action:add-project:${environmentId}:new`, |
| 1113 | searchTerms: ["new project", "create", "empty", "repository", "git init"], |
| 1114 | title: gt("New project"), |
| 1115 | description: gt("Start a new Git repository from a name"), |
| 1116 | icon: <FolderGit2Icon className={ITEM_ICON_CLASS} />, |
| 1117 | keepOpen: true, |
| 1118 | run: async () => { |
| 1119 | startNewProject(environmentId, environmentId); |
| 1120 | }, |
| 1121 | }); |
| 1122 | } |
| 1123 | |
| 1124 | const orderedSources: ReadonlyArray<AddProjectRemoteSource> = [ |
| 1125 | "url", |
| 1126 | ...sortAddProjectProviderSources(readinessBySource, offeredProvidersFor(environmentId)), |
| 1127 | ]; |
| 1128 | |
| 1129 | for (const source of orderedSources) { |
| 1130 | const label = addProjectRemoteSourceLabel(source, messages); |
| 1131 | const title = source === "url" ? gt("Git URL") : gt("{source} repository", { source: label }); |
| 1132 | const description = |
| 1133 | source === "url" |
| 1134 | ? gt("Clone from a remote URL") |
| 1135 | : gt("Clone {source} {hint}", { |
| 1136 | source: label, |
| 1137 | hint: addProjectRemoteSourcePathHint(source, messages), |
| 1138 | }); |
| 1139 | const readiness = readinessBySource(source); |
| 1140 | const disabledHint = readiness.hint; |
| 1141 | |
| 1142 | const titleTrailingContent = readiness.ready ? undefined : ( |
| 1143 | <span className="ml-auto"> |
| 1144 | <Tooltip> |
| 1145 | <TooltipTrigger |
| 1146 | render={ |
| 1147 | <Button |
| 1148 | variant="warning-outline" |
| 1149 | size="micro" |
| 1150 | onClick={() => { |
| 1151 | openSourceControlSettings(); |
| 1152 | }} |
| 1153 | > |
| 1154 | <T>Setup Required</T> |
| 1155 | </Button> |
| 1156 | } |
| 1157 | /> |
| 1158 | <TooltipPopup align="end" side="left"> |
| 1159 | {disabledHint ?? |
| 1160 | gt("Open Settings -> Source control & issues to configure this provider.")} |
| 1161 | </TooltipPopup> |
| 1162 | </Tooltip> |
| 1163 | </span> |
| 1164 | ); |
| 1165 | |
| 1166 | if (!readiness.ready) { |
| 1167 | sourceItems.push({ |
| 1168 | kind: "action", |
| 1169 | value: `action:add-project:${environmentId}:${source}:not-ready`, |
| 1170 | searchTerms: ["clone", "remote", "repository", "repo", "git", label, "setup required"], |
| 1171 | title, |
| 1172 | description, |
| 1173 | disabled: true, |
| 1174 | icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS), |
| 1175 | ...(titleTrailingContent ? { titleTrailingContent } : {}), |
| 1176 | run: async () => {}, |
| 1177 | }); |
| 1178 | continue; |
| 1179 | } |
| 1180 | |
| 1181 | sourceItems.push({ |
| 1182 | kind: "action", |
| 1183 | value: `action:add-project:${environmentId}:${source}`, |
| 1184 | searchTerms: ["clone", "remote", "repository", "repo", "git", label], |
| 1185 | title, |
| 1186 | description, |
| 1187 | icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS), |
| 1188 | ...(titleTrailingContent ? { titleTrailingContent } : {}), |
| 1189 | keepOpen: true, |
| 1190 | run: async () => { |
| 1191 | startAddProjectClone(environmentId, source); |
| 1192 | }, |
| 1193 | }); |
| 1194 | } |
| 1195 | |
| 1196 | return [{ value: `sources:${environmentId}`, label: gt("Sources"), items: sourceItems }]; |
| 1197 | }; |
| 1198 | |
| 1199 | const startAddProjectSourceSelection = (environmentId: EnvironmentId): void => { |
| 1200 | const environment = environments.find((candidate) => candidate.environmentId === environmentId); |
| 1201 | if (!canCreateProjectInEnvironment(environment?.connection.phase)) { |
| 1202 | toastManager.add( |
| 1203 | stackedThreadToast({ |
| 1204 | type: "error", |
| 1205 | title: gt("Environment unavailable"), |
| 1206 | description: environment |
| 1207 | ? gt("{environment} is not connected.", { environment: environment.label }) |
| 1208 | : gt("The selected environment is not connected."), |
| 1209 | }), |
| 1210 | ); |
| 1211 | return; |
| 1212 | } |
| 1213 | setAddProjectEnvironmentId(environmentId); |
| 1214 | setAddProjectCloneFlow(null); |
| 1215 | pushPaletteView({ |
| 1216 | addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />, |
| 1217 | groups: buildAddProjectSourceGroups( |
| 1218 | environmentId, |
| 1219 | buildPaletteRemoteSourceReadiness( |
| 1220 | browseEnvironmentId === environmentId ? sourceControlDiscovery.data : null, |
| 1221 | messages, |
| 1222 | ), |
| 1223 | ), |
| 1224 | }); |
| 1225 | }; |
| 1226 | |
| 1227 | const buildEnvironmentItem = ( |
| 1228 | option: AddProjectEnvironmentOption, |
| 1229 | value: string, |
| 1230 | run: (environmentId: EnvironmentId) => void, |
| 1231 | ): CommandPaletteActionItem => ({ |
| 1232 | kind: "action", |
| 1233 | value, |
| 1234 | searchTerms: [option.label, option.environmentId, option.isPrimary ? "this device" : ""], |
| 1235 | title: option.label, |
| 1236 | description: option.isConnected |
| 1237 | ? option.isPrimary |
| 1238 | ? gt("This device") |
| 1239 | : option.environmentId |
| 1240 | : option.status, |
| 1241 | disabled: !option.isConnected, |
| 1242 | icon: <EnvironmentMachineIcon kind={option.machine} className={ITEM_ICON_CLASS} />, |
| 1243 | keepOpen: true, |
| 1244 | run: async () => { |
| 1245 | run(option.environmentId); |
| 1246 | }, |
| 1247 | }); |
| 1248 | const addProjectEnvironmentItems = addProjectEnvironmentOptions.map((option) => |
| 1249 | buildEnvironmentItem( |
| 1250 | option, |
| 1251 | `action:add-project:environment:${option.environmentId}`, |
| 1252 | startAddProjectSourceSelection, |
| 1253 | ), |
| 1254 | ); |
| 1255 | const newProjectEnvironmentOptions = addProjectEnvironmentOptions.filter( |
| 1256 | (option) => option.isConnected && newProjectsRootFor(option.environmentId) !== null, |
| 1257 | ); |
| 1258 | |
| 1259 | const addProjectEnvironmentGroups = [ |
| 1260 | { |
| 1261 | value: "environments", |
| 1262 | label: gt("Environments"), |
| 1263 | items: addProjectEnvironmentItems, |
| 1264 | }, |
| 1265 | ]; |
| 1266 | |
| 1267 | const openConnectionSettings = () => { |
| 1268 | setOpen(false); |
| 1269 | void navigate({ to: "/settings/connections" }); |
| 1270 | }; |
| 1271 | const addProjectEntry = resolveAddProjectEntry( |
| 1272 | addProjectEnvironmentOptions, |
| 1273 | defaultAddProjectEnvironmentId, |
| 1274 | ); |
| 1275 | |
| 1276 | const openAddProjectFlow = () => { |
| 1277 | switch (addProjectEntry.kind) { |
| 1278 | case "connect-environment": |
| 1279 | openConnectionSettings(); |
| 1280 | return; |
| 1281 | case "choose-environment": |
| 1282 | pushPaletteView({ |
| 1283 | addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />, |
| 1284 | groups: addProjectEnvironmentGroups, |
| 1285 | }); |
| 1286 | return; |
| 1287 | case "choose-source": |
| 1288 | startAddProjectSourceSelection(addProjectEntry.environmentId); |
| 1289 | return; |
| 1290 | } |
| 1291 | }; |
| 1292 | |
| 1293 | // The view an "Add project" intent opens to follows the environments as they |
| 1294 | // connect, so it resolves here instead of being fixed when the palette opened. |
| 1295 | const addProjectEntryGroups = (): ReadonlyArray<CommandPaletteGroup> => { |
| 1296 | switch (addProjectEntry.kind) { |
| 1297 | case "connect-environment": |
| 1298 | return [ |
| 1299 | { |
| 1300 | value: ADD_PROJECT_ENTRY_GROUP, |
| 1301 | label: "", |
| 1302 | items: [ |
| 1303 | { |
| 1304 | kind: "action", |
| 1305 | value: "action:add-project:connect-environment", |
| 1306 | searchTerms: ["connect", "environment", "connection", "settings"], |
| 1307 | title: gt("Connect an environment"), |
| 1308 | description: gt("No connected environment can add a project"), |
| 1309 | icon: <SettingsIcon className={ITEM_ICON_CLASS} />, |
| 1310 | keepOpen: true, |
| 1311 | run: async () => { |
| 1312 | openConnectionSettings(); |
| 1313 | }, |
| 1314 | }, |
| 1315 | ], |
| 1316 | }, |
| 1317 | ]; |
| 1318 | case "choose-environment": |
| 1319 | return addProjectEnvironmentGroups; |
| 1320 | case "choose-source": |
| 1321 | return buildAddProjectSourceGroups( |
| 1322 | addProjectEntry.environmentId, |
| 1323 | buildPaletteRemoteSourceReadiness( |
| 1324 | browseEnvironmentId === addProjectEntry.environmentId |
| 1325 | ? sourceControlDiscovery.data |
| 1326 | : null, |
| 1327 | messages, |
| 1328 | ), |
| 1329 | ); |
| 1330 | } |
| 1331 | }; |
| 1332 | |
| 1333 | const openNewProjectFlow = () => { |
| 1334 | const firstOption = newProjectEnvironmentOptions[0]; |
| 1335 | if (firstOption) startNewProject(firstOption.environmentId, null); |
| 1336 | }; |
| 1337 | |
| 1338 | const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = []; |
| 1339 | |
| 1340 | if (projects.length > 0) { |
| 1341 | const activeProjectTitle = |
| 1342 | projectPickerEntries.find((entry) => entry.isPreferred)?.group.displayName ?? |
| 1343 | currentProject?.title ?? |
| 1344 | null; |
| 1345 | |
| 1346 | if (activeProjectTitle) { |
| 1347 | actionItems.push({ |
| 1348 | kind: "action", |
| 1349 | value: "action:new-thread", |
| 1350 | searchTerms: ["new thread", "chat", "create", "draft"], |
| 1351 | title: ( |
| 1352 | <T> |
| 1353 | New thread in{" "} |
| 1354 | <span className="font-semibold"> |
| 1355 | <Var>{activeProjectTitle}</Var> |
| 1356 | </span> |
| 1357 | </T> |
| 1358 | ), |
| 1359 | searchTitle: gt("New thread in {project}", { project: activeProjectTitle }), |
| 1360 | icon: <SquarePenIcon className={ITEM_ICON_CLASS} />, |
| 1361 | shortcutCommand: "chat.newLocal", |
| 1362 | run: async () => { |
| 1363 | await startNewThreadFromContext({ |
| 1364 | activeDraftThread, |
| 1365 | activeThread: activeThread ?? undefined, |
| 1366 | defaultProjectRef, |
| 1367 | handleNewThread, |
| 1368 | }); |
| 1369 | }, |
| 1370 | }); |
| 1371 | } |
| 1372 | |
| 1373 | actionItems.push({ |
| 1374 | kind: "submenu", |
| 1375 | value: "action:new-thread-in", |
| 1376 | searchTerms: ["new thread", "project", "pick", "choose", "select"], |
| 1377 | title: gt("New thread in..."), |
| 1378 | icon: <SquarePenIcon className={ITEM_ICON_CLASS} />, |
| 1379 | addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />, |
| 1380 | groups: [{ value: NEW_THREAD_IN_GROUP, label: gt("Projects"), items: projectThreadItems }], |
| 1381 | }); |
| 1382 | } |
| 1383 | |
| 1384 | if (scratchTargetEnvironmentId !== null) { |
| 1385 | actionItems.push({ |
| 1386 | kind: "action", |
| 1387 | value: "action:new-thread-without-project", |
| 1388 | searchTerms: ["new thread", "no project", "without project", "none", "chat"], |
| 1389 | title: gt("New thread without a project"), |
| 1390 | icon: <MessageSquareDashedIcon className={ITEM_ICON_CLASS} />, |
| 1391 | shortcutCommand: "chat.newWithoutProject", |
| 1392 | run: () => startScratchThread(scratchTargetEnvironmentId), |
| 1393 | }); |
| 1394 | } |
| 1395 | |
| 1396 | if (triageEnvironmentId !== null && canTriage) { |
| 1397 | actionItems.push({ |
| 1398 | kind: "action", |
| 1399 | value: "action:triage", |
| 1400 | searchTerms: ["triage", "bug", "issue", "report", "broken", "debug", "help", "support"], |
| 1401 | title: gt("Triage an issue"), |
| 1402 | description: gt("An agent investigates a T3 Code problem and helps file an issue"), |
| 1403 | icon: <BugIcon className={ITEM_ICON_CLASS} />, |
| 1404 | run: () => startTriage(triageEnvironmentId), |
| 1405 | }); |
| 1406 | } |
| 1407 | |
| 1408 | if (activeThreadKey !== null && supportsThreadFind) { |
| 1409 | actionItems.push({ |
| 1410 | kind: "action", |
| 1411 | value: "find-current-thread", |
| 1412 | title: gt("Find in current thread"), |
| 1413 | searchTerms: ["find", "search", "messages", "plans"], |
| 1414 | icon: <TextSearchIcon className={ITEM_ICON_CLASS} />, |
| 1415 | shortcutCommand: "chat.find", |
| 1416 | run: async () => { |
| 1417 | openThreadFind(activeThreadKey); |
| 1418 | }, |
| 1419 | }); |
| 1420 | } |
| 1421 | |
| 1422 | if (activeThreadPreviewOpen && previewBridge) { |
| 1423 | actionItems.push({ |
| 1424 | kind: "action", |
| 1425 | value: "find-in-browser-page", |
| 1426 | title: gt("Find on page in browser"), |
| 1427 | searchTerms: ["find", "search", "browser", "preview", "page"], |
| 1428 | icon: <TextSearchIcon className={ITEM_ICON_CLASS} />, |
| 1429 | shortcutCommand: "preview.find", |
| 1430 | run: async () => { |
| 1431 | dispatchPreviewAction("find"); |
| 1432 | }, |
| 1433 | }); |
| 1434 | } |
| 1435 | |
| 1436 | if (portForwardItem) actionItems.push(portForwardItem); |
| 1437 | |
| 1438 | const promptLinkTarget = paletteRouteTarget |
| 1439 | ? paletteRouteTarget.kind === "server" |
| 1440 | ? paletteRouteTarget.threadRef |
| 1441 | : paletteRouteTarget.draftId |
| 1442 | : null; |
| 1443 | const promptLinkProjectRef = activeThread ?? activeDraftThread; |
| 1444 | const promptLinkInput = |
| 1445 | promptLinkTarget === null |
| 1446 | ? null |
| 1447 | : { |
| 1448 | target: promptLinkTarget, |
| 1449 | project: projects.find( |
| 1450 | (project) => |
| 1451 | project.environmentId === promptLinkProjectRef?.environmentId && |
| 1452 | project.id === promptLinkProjectRef.projectId, |
| 1453 | ), |
| 1454 | providers: |
| 1455 | (promptLinkProjectRef |
| 1456 | ? providersByEnvironment.get(promptLinkProjectRef.environmentId) |
| 1457 | : undefined) ?? [], |
| 1458 | threadModelSelection: activeThread?.modelSelection ?? null, |
| 1459 | threadStarted: threadHasStarted(activeThread), |
| 1460 | }; |
| 1461 | const plainPromptLink = promptLinkInput |
| 1462 | ? composerPromptLink({ ...promptLinkInput, withContext: false }) |
| 1463 | : null; |
| 1464 | if (promptLinkInput !== null && plainPromptLink !== null) { |
| 1465 | actionItems.push({ |
| 1466 | kind: "action", |
| 1467 | value: "action:copy-prompt-link", |
| 1468 | searchTerms: ["copy", "share", "prompt", "link"], |
| 1469 | title: gt("Copy prompt link"), |
| 1470 | icon: <LinkIcon className={ITEM_ICON_CLASS} />, |
| 1471 | run: () => copyPromptLink(plainPromptLink), |
| 1472 | }); |
| 1473 | if (promptLinkRepositoryOf(promptLinkInput.project) !== null) { |
| 1474 | const contextLink = composerPromptLink({ ...promptLinkInput, withContext: true }); |
| 1475 | if (contextLink !== null) { |
| 1476 | actionItems.push({ |
| 1477 | kind: "action", |
| 1478 | value: "action:copy-prompt-link-with-context", |
| 1479 | searchTerms: ["copy", "share", "prompt", "link", "repository", "model"], |
| 1480 | title: gt("Copy prompt link with repo and model"), |
| 1481 | icon: <LinkIcon className={ITEM_ICON_CLASS} />, |
| 1482 | run: () => copyPromptLink(contextLink), |
| 1483 | }); |
| 1484 | } |
| 1485 | } |
| 1486 | } |
| 1487 | |
| 1488 | if (activeThreadReferenceCopyTarget !== null) { |
| 1489 | actionItems.push({ |
| 1490 | kind: "action", |
| 1491 | value: "action:copy-thread-reference", |
| 1492 | searchTerms: |
| 1493 | activeThreadReferenceCopyTarget.kind === "pull-request" |
| 1494 | ? ["copy", "pull request", "link", "reference"] |
| 1495 | : ["copy", "thread", "thread id", "reference"], |
| 1496 | title: |
| 1497 | activeThreadReferenceCopyTarget.kind === "pull-request" |
| 1498 | ? gt("Copy PR link") |
| 1499 | : gt("Copy thread"), |
| 1500 | description: activeThreadReferenceCopyTarget.description, |
| 1501 | icon: <LinkIcon className={ITEM_ICON_CLASS} />, |
| 1502 | shortcutCommand: "thread.copyReference", |
| 1503 | run: copyActiveThreadReference, |
| 1504 | }); |
| 1505 | } |
| 1506 | |
| 1507 | if ( |
| 1508 | activeThread !== null && |
| 1509 | threadPullRequestLinkMode(activeThreadServerConfig?.environment.capabilities) !== "unsupported" |
| 1510 | ) { |
| 1511 | const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id); |
| 1512 | actionItems.push({ |
| 1513 | kind: "action", |
| 1514 | value: "action:link-pull-request", |
| 1515 | searchTerms: ["link", "pull request", "pr", "attach", "stack"], |
| 1516 | title: gt("Link pull request to thread"), |
| 1517 | icon: <PullRequestGlyph.link className={ITEM_ICON_CLASS} />, |
| 1518 | run: async () => { |
| 1519 | openLinkPullRequestDialog(threadRef); |
| 1520 | }, |
| 1521 | }); |
| 1522 | actionItems.push({ |
| 1523 | kind: "action", |
| 1524 | value: "action:open-thread-pull-requests", |
| 1525 | searchTerms: ["pull requests", "issues", "linked", "stack", "prs"], |
| 1526 | title: gt("Show linked items"), |
| 1527 | disabled: |
| 1528 | visibleThreadPullRequests(activeThread.pullRequests).length === 0 && |
| 1529 | !activeThread.issues?.length, |
| 1530 | icon: <PullRequestGlyph.link className={ITEM_ICON_CLASS} />, |
| 1531 | run: async () => { |
| 1532 | useRightPanelStore.getState().open(threadRef, "pull-requests"); |
| 1533 | }, |
| 1534 | }); |
| 1535 | } |
| 1536 | |
| 1537 | if (activeThread !== null && canShareActiveThreadWithGuest) { |
| 1538 | const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id); |
| 1539 | actionItems.push({ |
| 1540 | kind: "action", |
| 1541 | value: "action:share-thread-with-guest", |
| 1542 | searchTerms: ["share", "guest", "invite", "link", "teammate"], |
| 1543 | title: gt("Share with guest"), |
| 1544 | icon: <UserPlusIcon className={ITEM_ICON_CLASS} />, |
| 1545 | run: async () => { |
| 1546 | openGuestShareDialog(threadRef); |
| 1547 | }, |
| 1548 | }); |
| 1549 | } |
| 1550 | |
| 1551 | if (activeThread !== null) { |
| 1552 | const thread = activeThread; |
| 1553 | actionItems.push({ |
| 1554 | kind: "action", |
| 1555 | value: "action:restart-agent-session", |
| 1556 | searchTerms: ["restart", "reset", "reload", "agent", "session", "skills", "plugins", "mcp"], |
| 1557 | title: gt("Restart agent session"), |
| 1558 | icon: <RotateCcwIcon className={ITEM_ICON_CLASS} />, |
| 1559 | run: async () => { |
| 1560 | const { environmentId } = thread; |
| 1561 | if (thread.runtime !== null) { |
| 1562 | const stopped = await stopThreadSession({ |
| 1563 | environmentId, |
| 1564 | input: { threadId: thread.id }, |
| 1565 | }); |
| 1566 | if (stopped._tag === "Failure") throw squashAtomCommandFailure(stopped); |
| 1567 | } |
| 1568 | toastManager.add({ |
| 1569 | type: "success", |
| 1570 | title: gt("Agent session will restart"), |
| 1571 | description: gt("Your next message starts a fresh session."), |
| 1572 | }); |
| 1573 | const project = projectByKey.get(`${environmentId}:${thread.projectId}`); |
| 1574 | if (!project) return; |
| 1575 | const refreshed = await refreshProviders({ |
| 1576 | environmentId, |
| 1577 | input: { |
| 1578 | instanceId: thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId, |
| 1579 | cwd: thread.worktreePath ?? project.workspaceRoot, |
| 1580 | fresh: true, |
| 1581 | }, |
| 1582 | }); |
| 1583 | if (refreshed._tag === "Failure") throw squashAtomCommandFailure(refreshed); |
| 1584 | }, |
| 1585 | }); |
| 1586 | } |
| 1587 | |
| 1588 | actionItems.push({ |
| 1589 | kind: "action", |
| 1590 | value: "action:open-file-picker", |
| 1591 | searchTerms: ["go to file", "open file", "file picker", "find file", "quick open"], |
| 1592 | title: gt("Go to file"), |
| 1593 | icon: <FileSearchIcon className={ITEM_ICON_CLASS} />, |
| 1594 | keepOpen: true, |
| 1595 | shortcutCommand: "filePicker.toggle", |
| 1596 | run: async () => { |
| 1597 | openChildSearch("files", { query, linkedThreadSearch }); |
| 1598 | }, |
| 1599 | }); |
| 1600 | |
| 1601 | actionItems.push({ |
| 1602 | kind: "action", |
| 1603 | value: "action:search-project-contents", |
| 1604 | searchTerms: ["search project", "find in files", "grep", "content search", "text search"], |
| 1605 | title: gt("Search project contents"), |
| 1606 | icon: <TextSearchIcon className={ITEM_ICON_CLASS} />, |
| 1607 | keepOpen: true, |
| 1608 | shortcutCommand: "projectSearch.toggle", |
| 1609 | run: async () => { |
| 1610 | openChildSearch("content", { query, linkedThreadSearch }); |
| 1611 | }, |
| 1612 | }); |
| 1613 | |
| 1614 | if (newProjectEnvironmentOptions.length > 0) { |
| 1615 | actionItems.push({ |
| 1616 | kind: "action", |
| 1617 | value: "action:new-project", |
| 1618 | searchTerms: ["new project", "create project", "empty", "repository", "repo", "git init"], |
| 1619 | title: gt("New project"), |
| 1620 | icon: <FolderGit2Icon className={ITEM_ICON_CLASS} />, |
| 1621 | keepOpen: true, |
| 1622 | run: async () => { |
| 1623 | openNewProjectFlow(); |
| 1624 | }, |
| 1625 | }); |
| 1626 | } |
| 1627 | |
| 1628 | const addProjectAction: CommandPaletteActionItem = { |
| 1629 | kind: "action", |
| 1630 | value: "action:add-project", |
| 1631 | searchTerms: [ |
| 1632 | "add project", |
| 1633 | "folder", |
| 1634 | "directory", |
| 1635 | "browse", |
| 1636 | "clone", |
| 1637 | "remote", |
| 1638 | "repository", |
| 1639 | "repo", |
| 1640 | "git", |
| 1641 | ...sourceControlClients.definitions.flatMap((definition) => |
| 1642 | definition.pickerLabel |
| 1643 | .toLowerCase() |
| 1644 | .split(/[^a-z0-9]+/u) |
| 1645 | .filter(Boolean), |
| 1646 | ), |
| 1647 | "url", |
| 1648 | "environment", |
| 1649 | ], |
| 1650 | title: gt("Add project"), |
| 1651 | icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />, |
| 1652 | keepOpen: true, |
| 1653 | run: async () => { |
| 1654 | openAddProjectFlow(); |
| 1655 | }, |
| 1656 | }; |
| 1657 | actionItems.push(addProjectAction); |
| 1658 | |
| 1659 | if (wslAddProjectEnvironmentOption) { |
| 1660 | actionItems.push({ |
| 1661 | kind: "action", |
| 1662 | value: "action:add-project:wsl-folder", |
| 1663 | searchTerms: ["add project", "open", "wsl", "linux", "folder", "directory"], |
| 1664 | title: gt("Open WSL folder"), |
| 1665 | description: wslAddProjectEnvironmentOption.label, |
| 1666 | icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />, |
| 1667 | keepOpen: true, |
| 1668 | run: async () => { |
| 1669 | await startAddProjectBrowse(wslAddProjectEnvironmentOption.environmentId); |
| 1670 | }, |
| 1671 | }); |
| 1672 | } |
| 1673 | |
| 1674 | actionItems.push(changeThemeItem); |
| 1675 | actionItems.push(changeAppearanceItem); |
| 1676 | |
| 1677 | actionItems.push(themeEditorItem); |
| 1678 | |
| 1679 | if (environments.some((environment) => environment.serverConfig !== null)) { |
| 1680 | actionItems.push({ |
| 1681 | kind: "action", |
| 1682 | value: "action:pull-requests", |
| 1683 | searchTerms: [ |
| 1684 | ...new Set( |
| 1685 | sourceControlClients.definitions.flatMap((definition) => { |
| 1686 | const shortLabel = definition.changeRequest.shortLabel.toLowerCase(); |
| 1687 | return [ |
| 1688 | definition.changeRequest.plural, |
| 1689 | `${shortLabel}s`, |
| 1690 | shortLabel, |
| 1691 | ...definition.label.toLowerCase().split(/[^a-z0-9]+/u), |
| 1692 | ].filter(Boolean); |
| 1693 | }), |
| 1694 | ), |
| 1695 | "review", |
| 1696 | "merge", |
| 1697 | "branch", |
| 1698 | ], |
| 1699 | title: gt("Open pull requests"), |
| 1700 | icon: <PullRequestGlyph.pullRequest className={ITEM_ICON_CLASS} />, |
| 1701 | run: async () => { |
| 1702 | await navigate({ to: "/pull-requests", search: readPullRequestListPreferences() }); |
| 1703 | }, |
| 1704 | }); |
| 1705 | } |
| 1706 | |
| 1707 | if ( |
| 1708 | environments.some( |
| 1709 | (environment) => environment.serverConfig?.environment.capabilities.issues === true, |
| 1710 | ) |
| 1711 | ) { |
| 1712 | actionItems.push({ |
| 1713 | kind: "action", |
| 1714 | value: "action:issues", |
| 1715 | searchTerms: ["issues", "issue", "bugs", "tracker", "github", "triage"], |
| 1716 | title: gt("Open issues"), |
| 1717 | icon: <IssueGlyph.issue className={ITEM_ICON_CLASS} />, |
| 1718 | run: async () => { |
| 1719 | await navigate({ to: "/issues", search: readIssueListPreferences() }); |
| 1720 | }, |
| 1721 | }); |
| 1722 | } |
| 1723 | |
| 1724 | actionItems.push({ |
| 1725 | kind: "action", |
| 1726 | value: "action:use-in-another-app", |
| 1727 | searchTerms: [ |
| 1728 | "mcp", |
| 1729 | "connector", |
| 1730 | "another app", |
| 1731 | "poke", |
| 1732 | "claude", |
| 1733 | "chatgpt", |
| 1734 | "grok", |
| 1735 | "muse", |
| 1736 | "instinct", |
| 1737 | "openclaw", |
| 1738 | "hermes", |
| 1739 | ], |
| 1740 | title: gt("Use T3 Code in another app (MCP)"), |
| 1741 | icon: <PlugIcon className={ITEM_ICON_CLASS} />, |
| 1742 | run: async () => { |
| 1743 | openUseInAnotherApp( |
| 1744 | currentProjectEnvironmentId ?? |
| 1745 | (paletteRouteTarget?.kind === "server" |
| 1746 | ? paletteRouteTarget.threadRef.environmentId |
| 1747 | : null), |
| 1748 | ); |
| 1749 | }, |
| 1750 | }); |
| 1751 | |
| 1752 | actionItems.push({ |
| 1753 | kind: "action", |
| 1754 | value: "action:usage", |
| 1755 | searchTerms: ["usage", "use", "tokens", "cost", "spend", "limits", "stats", "analytics"], |
| 1756 | title: gt("Open usage"), |
| 1757 | icon: <ChartNoAxesColumnIcon className={ITEM_ICON_CLASS} />, |
| 1758 | shortcutCommand: "usage.open", |
| 1759 | run: async () => { |
| 1760 | await navigate({ to: "/usage" }); |
| 1761 | }, |
| 1762 | }); |
| 1763 | |
| 1764 | for (const direction of [1, -1] as const) { |
| 1765 | const title = |
| 1766 | direction === 1 ? gt("Focus Next Workspace Area") : gt("Focus Previous Workspace Area"); |
| 1767 | actionItems.push({ |
| 1768 | kind: "action", |
| 1769 | value: `action:workspace-focus:${direction}`, |
| 1770 | title, |
| 1771 | searchTerms: [title, "accessibility", "navigation", "focus", "F6"], |
| 1772 | icon: <MonitorIcon className={ITEM_ICON_CLASS} />, |
| 1773 | shortcutCommand: direction === 1 ? "workspace.focusNext" : "workspace.focusPrevious", |
| 1774 | run: async () => { |
| 1775 | queueWorkspaceFocusFromPalette(direction); |
| 1776 | }, |
| 1777 | }); |
| 1778 | } |
| 1779 | |
| 1780 | actionItems.push({ |
| 1781 | kind: "action", |
| 1782 | value: "action:settings", |
| 1783 | searchTerms: ["settings", "preferences", "configuration", "keybindings"], |
| 1784 | title: gt("Open settings"), |
| 1785 | icon: <SettingsIcon className={ITEM_ICON_CLASS} />, |
| 1786 | run: async () => { |
| 1787 | await navigate({ to: "/settings" }); |
| 1788 | }, |
| 1789 | }); |
| 1790 | |
| 1791 | // Every group, so an archived project's thread still opens its own settings. |
| 1792 | const currentProjectGroup = |
| 1793 | (contextualProjectRef |
| 1794 | ? projectGroups.find((group) => |
| 1795 | group.memberProjectRefs.some( |
| 1796 | (ref) => |
| 1797 | ref.environmentId === contextualProjectRef.environmentId && |
| 1798 | ref.projectId === contextualProjectRef.projectId, |
| 1799 | ), |
| 1800 | ) |
| 1801 | : null) ?? null; |
| 1802 | if (currentProjectGroup && canPinProjectGroup(currentProjectGroup)) { |
| 1803 | actionItems.push({ |
| 1804 | kind: "action", |
| 1805 | value: "action:project-pin", |
| 1806 | searchTerms: ["pin", "unpin", "project", "favorite"], |
| 1807 | title: currentProjectGroup.pinned ? gt("Unpin project") : gt("Pin project"), |
| 1808 | description: currentProjectGroup.displayName, |
| 1809 | icon: currentProjectGroup.pinned ? ( |
| 1810 | <PinOffIcon className={ITEM_ICON_CLASS} /> |
| 1811 | ) : ( |
| 1812 | <PinIcon className={ITEM_ICON_CLASS} /> |
| 1813 | ), |
| 1814 | run: async () => toggleProjectGroupPin(currentProjectGroup), |
| 1815 | }); |
| 1816 | } |
| 1817 | const contextualProjectGroup = currentProjectGroup ?? projectGroups[0] ?? null; |
| 1818 | if (contextualProjectGroup) { |
| 1819 | actionItems.push({ |
| 1820 | kind: "action", |
| 1821 | value: "action:project-settings", |
| 1822 | searchTerms: [ |
| 1823 | "project", |
| 1824 | "settings", |
| 1825 | "name", |
| 1826 | "icon", |
| 1827 | "scripts", |
| 1828 | "model", |
| 1829 | "workspace", |
| 1830 | "grouping", |
| 1831 | "checkout", |
| 1832 | "remove", |
| 1833 | "t3.json", |
| 1834 | ], |
| 1835 | title: gt("Project settings"), |
| 1836 | description: contextualProjectGroup.displayName, |
| 1837 | icon: <FolderIcon className={ITEM_ICON_CLASS} />, |
| 1838 | run: async () => { |
| 1839 | await navigate({ |
| 1840 | to: "/projects/$projectKey", |
| 1841 | params: { projectKey: contextualProjectGroup.projectKey }, |
| 1842 | }); |
| 1843 | }, |
| 1844 | }); |
| 1845 | } |
| 1846 | |
| 1847 | const rootGroups = buildRootGroups({ actionItems, recentThreadItems }, messages); |
| 1848 | // Every setting goes to the palette's own matcher, so settings get the same |
| 1849 | // word starts and typo tolerance as threads. |
| 1850 | const settingsSearchItems: CommandPaletteActionItem[] = settingsForThisPlatform( |
| 1851 | availableSettingsSearchItems, |
| 1852 | ).map((item) => ({ |
| 1853 | kind: "action", |
| 1854 | value: `setting:${item.id}`, |
| 1855 | // Matches the English and the displayed language, like the settings search. |
| 1856 | searchTerms: [ |
| 1857 | item.title, |
| 1858 | SETTINGS_SECTION_LABELS[item.to], |
| 1859 | ...(item.searchTerms ?? []), |
| 1860 | ].flatMap((term) => [messages(term), decodeMsg(term)]), |
| 1861 | title: messages(item.title), |
| 1862 | description: gt("Settings · {section}", { |
| 1863 | section: messages(SETTINGS_SECTION_LABELS[item.to]), |
| 1864 | }), |
| 1865 | ...(item.secondary ? { secondary: true } : {}), |
| 1866 | icon: <SettingsIcon className={ITEM_ICON_CLASS} />, |
| 1867 | run: async () => { |
| 1868 | await navigate({ |
| 1869 | to: item.to, |
| 1870 | hash: item.targetId ?? item.id, |
| 1871 | replace: pathname === item.to, |
| 1872 | hashScrollIntoView: false, |
| 1873 | }); |
| 1874 | }, |
| 1875 | })); |
| 1876 | const sourceSelectionViewValue = |
| 1877 | addProjectEnvironmentId === null ? null : `sources:${addProjectEnvironmentId}`; |
| 1878 | const activeGroups = |
| 1879 | addProjectEnvironmentId !== null && |
| 1880 | currentView !== null && |
| 1881 | currentView.groups[0]?.value === sourceSelectionViewValue |
| 1882 | ? buildAddProjectSourceGroups( |
| 1883 | addProjectEnvironmentId, |
| 1884 | buildPaletteRemoteSourceReadiness(sourceControlDiscovery.data, messages), |
| 1885 | ) |
| 1886 | : currentView?.groups[0]?.value === ADD_PROJECT_ENTRY_GROUP |
| 1887 | ? addProjectEntryGroups() |
| 1888 | : currentView?.groups[0]?.value === NEW_THREAD_IN_GROUP |
| 1889 | ? [ |
| 1890 | { |
| 1891 | value: NEW_THREAD_IN_GROUP, |
| 1892 | label: gt("Projects"), |
| 1893 | // Every project archived and no "No project" home leaves only adding one. |
| 1894 | items: projectThreadItems.length > 0 ? projectThreadItems : [addProjectAction], |
| 1895 | }, |
| 1896 | ] |
| 1897 | : currentView?.groups[0]?.value.startsWith(PORT_FORWARD_GROUP_PREFIX) && portForwardItem |
| 1898 | ? portForwardItem.groups |
| 1899 | : currentView?.groups[0]?.value === "themes" |
| 1900 | ? changeThemeItem.groups |
| 1901 | : currentView?.groups[0]?.value === "appearance" |
| 1902 | ? changeAppearanceItem.groups |
| 1903 | : (currentView?.groups ?? rootGroups); |
| 1904 | |
| 1905 | const isLinkedThreadSearch = |
| 1906 | linkedThreadSearch?.linkedThreads !== undefined && deferredQuery === linkedThreadSearch.query; |
| 1907 | const searchedGroups = filterCommandPaletteGroups( |
| 1908 | { |
| 1909 | activeGroups, |
| 1910 | query: deferredQuery, |
| 1911 | isInSubmenu: currentView !== null, |
| 1912 | ...(deferredQuery.trim().length > 0 |
| 1913 | ? { |
| 1914 | allOptions: { |
| 1915 | rootGroups, |
| 1916 | nestedItems: buildNestedSearchItems(actionItems, deferredQuery), |
| 1917 | }, |
| 1918 | } |
| 1919 | : {}), |
| 1920 | projectSearchItems: projectSearchItems, |
| 1921 | settingsSearchItems, |
| 1922 | threadSearchItems: |
| 1923 | isLinkedThreadSearch && linkedThreadSearch?.linkedThreads |
| 1924 | ? buildLinkedThreadActionItems( |
| 1925 | { |
| 1926 | ...linkedThreadSearch.linkedThreads, |
| 1927 | threads: visibleLinkedThreads( |
| 1928 | linkedThreadSearch.linkedThreads.threads, |
| 1929 | linkedThreadSearch.linkedThreads.environmentId, |
| 1930 | linkedThreadRefs, |
| 1931 | hiddenKeys, |
| 1932 | hidingAnywhere, |
| 1933 | ), |
| 1934 | query: linkedThreadSearch.query, |
| 1935 | icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />, |
| 1936 | runThread: async (thread) => { |
| 1937 | await navigate({ |
| 1938 | to: "/$environmentId/$threadId", |
| 1939 | params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)), |
| 1940 | }); |
| 1941 | }, |
| 1942 | }, |
| 1943 | messages, |
| 1944 | ) |
| 1945 | : allThreadItems, |
| 1946 | threadMessageItems: isLinkedThreadSearch ? [] : threadMessageItems, |
| 1947 | now: searchNow, |
| 1948 | }, |
| 1949 | messages, |
| 1950 | ); |
| 1951 | // Jump shortcuts number the project rows as shown, so a pin cannot move a number to another row. |
| 1952 | const filteredGroups = searchedGroups.map((group) => { |
| 1953 | if (group.value !== NEW_THREAD_IN_GROUP) return group; |
| 1954 | const jumpItems = new Map( |
| 1955 | enumerateCommandPaletteItems( |
| 1956 | group.items.filter( |
| 1957 | (item): item is CommandPaletteActionItem => |
| 1958 | item.kind === "action" && |
| 1959 | item.value !== NEW_THREAD_NO_PROJECT_VALUE && |
| 1960 | item.value !== addProjectAction.value, |
| 1961 | ), |
| 1962 | ).map((item) => [item.value, item] as const), |
| 1963 | ); |
| 1964 | return { ...group, items: group.items.map((item) => jumpItems.get(item.value) ?? item) }; |
| 1965 | }); |
| 1966 | |
| 1967 | const handleAddProjectForEnvironment = async (input: { |
| 1968 | readonly environmentId: EnvironmentId; |
| 1969 | readonly rawCwd: string; |
| 1970 | readonly platform: string; |
| 1971 | readonly currentProjectCwd: string | null; |
| 1972 | }) => { |
| 1973 | const environment = environments.find( |
| 1974 | (candidate) => candidate.environmentId === input.environmentId, |
| 1975 | ); |
| 1976 | if (!canCreateProjectInEnvironment(environment?.connection.phase)) { |
| 1977 | toastManager.add( |
| 1978 | stackedThreadToast({ |
| 1979 | type: "error", |
| 1980 | title: gt("Environment unavailable"), |
| 1981 | description: environment |
| 1982 | ? gt("{environment} is not connected.", { environment: environment.label }) |
| 1983 | : gt("The selected environment is not connected."), |
| 1984 | }), |
| 1985 | ); |
| 1986 | return; |
| 1987 | } |
| 1988 | const rawCwd = input.rawCwd; |
| 1989 | |
| 1990 | if (isUnsupportedWindowsProjectPath(rawCwd.trim(), input.platform)) { |
| 1991 | toastManager.add( |
| 1992 | stackedThreadToast({ |
| 1993 | type: "error", |
| 1994 | title: gt("Failed to add project"), |
| 1995 | description: gt("Windows-style paths are only supported on Windows."), |
| 1996 | }), |
| 1997 | ); |
| 1998 | return; |
| 1999 | } |
| 2000 | |
| 2001 | if (isExplicitRelativeProjectPath(rawCwd.trim()) && !input.currentProjectCwd) { |
| 2002 | toastManager.add( |
| 2003 | stackedThreadToast({ |
| 2004 | type: "error", |
| 2005 | title: gt("Failed to add project"), |
| 2006 | description: gt("Relative paths require an active project."), |
| 2007 | }), |
| 2008 | ); |
| 2009 | return; |
| 2010 | } |
| 2011 | |
| 2012 | const cwd = resolveProjectPathForDispatch(rawCwd, input.currentProjectCwd); |
| 2013 | if (cwd.length === 0) return; |
| 2014 | |
| 2015 | const existing = findProjectByPath( |
| 2016 | projects.filter((project) => project.environmentId === input.environmentId), |
| 2017 | cwd, |
| 2018 | ); |
| 2019 | if (existing) { |
| 2020 | // Adding an archived project's folder again brings the project back. |
| 2021 | if (existing.archivedAt != null) { |
| 2022 | void updateProject({ |
| 2023 | environmentId: existing.environmentId, |
| 2024 | input: { projectId: existing.id, archived: false }, |
| 2025 | }).then((result) => reportProjectFailure(gt("Failed to unarchive project"), result)); |
| 2026 | } |
| 2027 | const latestThread = getLatestThreadForProject( |
| 2028 | threads.filter((thread) => thread.environmentId === existing.environmentId), |
| 2029 | existing.id, |
| 2030 | clientSettings.sidebarThreadSortOrder, |
| 2031 | ); |
| 2032 | if (latestThread && latestThread.settledOverride !== "settled") { |
| 2033 | await navigate({ |
| 2034 | to: "/$environmentId/$threadId", |
| 2035 | params: buildThreadRouteParams( |
| 2036 | scopeThreadRef(latestThread.environmentId, latestThread.id), |
| 2037 | ), |
| 2038 | }); |
| 2039 | } else { |
| 2040 | const navigationResult = await settlePromise(() => |
| 2041 | handleNewThread(scopeProjectRef(existing.environmentId, existing.id)), |
| 2042 | ); |
| 2043 | if (navigationResult._tag === "Failure") { |
| 2044 | const error = squashAtomCommandFailure(navigationResult); |
| 2045 | toastManager.add( |
| 2046 | stackedThreadToast({ |
| 2047 | type: "error", |
| 2048 | title: gt("Failed to open project"), |
| 2049 | description: thrownErrorMessage(error, m) ?? gt("An error occurred."), |
| 2050 | }), |
| 2051 | ); |
| 2052 | return; |
| 2053 | } |
| 2054 | } |
| 2055 | setOpen(false); |
| 2056 | return; |
| 2057 | } |
| 2058 | |
| 2059 | if (!readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)) { |
| 2060 | toastManager.add( |
| 2061 | stackedThreadToast({ |
| 2062 | type: "error", |
| 2063 | title: gt("Cannot add project"), |
| 2064 | description: gt("This connection cannot add projects."), |
| 2065 | }), |
| 2066 | ); |
| 2067 | return; |
| 2068 | } |
| 2069 | const projectId = newProjectId(); |
| 2070 | const createResult = await createProject({ |
| 2071 | environmentId: input.environmentId, |
| 2072 | input: { |
| 2073 | projectId, |
| 2074 | title: inferProjectTitleFromPath(cwd), |
| 2075 | workspaceRoot: cwd, |
| 2076 | createWorkspaceRootIfMissing: true, |
| 2077 | defaultModelSelection: null, |
| 2078 | }, |
| 2079 | }); |
| 2080 | if (createResult._tag === "Failure") { |
| 2081 | if (!isAtomCommandInterrupted(createResult)) { |
| 2082 | const error = squashAtomCommandFailure(createResult); |
| 2083 | toastManager.add( |
| 2084 | stackedThreadToast({ |
| 2085 | type: "error", |
| 2086 | title: gt("Failed to add project"), |
| 2087 | description: thrownErrorMessage(error, m) ?? gt("An error occurred."), |
| 2088 | }), |
| 2089 | ); |
| 2090 | } |
| 2091 | return; |
| 2092 | } |
| 2093 | |
| 2094 | const navigationResult = await settlePromise(() => |
| 2095 | handleNewThread(scopeProjectRef(input.environmentId, projectId)), |
| 2096 | ); |
| 2097 | if (navigationResult._tag === "Failure") { |
| 2098 | const error = squashAtomCommandFailure(navigationResult); |
| 2099 | toastManager.add( |
| 2100 | stackedThreadToast({ |
| 2101 | type: "error", |
| 2102 | title: gt("Failed to add project"), |
| 2103 | description: thrownErrorMessage(error, m) ?? gt("An error occurred."), |
| 2104 | }), |
| 2105 | ); |
| 2106 | return; |
| 2107 | } |
| 2108 | setOpen(false); |
| 2109 | }; |
| 2110 | |
| 2111 | const handleAddProject = async (rawCwd: string) => { |
| 2112 | if (!browseEnvironmentId) return; |
| 2113 | await handleAddProjectForEnvironment({ |
| 2114 | environmentId: browseEnvironmentId, |
| 2115 | rawCwd, |
| 2116 | platform: browseEnvironmentPlatform, |
| 2117 | currentProjectCwd: currentProjectCwdForBrowse, |
| 2118 | }); |
| 2119 | }; |
| 2120 | |
| 2121 | const newProjectPublishTargets = |
| 2122 | newProjectFlow === null |
| 2123 | ? [] |
| 2124 | : getNewProjectPublishTargets( |
| 2125 | sourceControlDiscovery.data ?? null, |
| 2126 | offeredProvidersFor(newProjectFlow.environmentId), |
| 2127 | ); |
| 2128 | const newProjectPublishTarget = getNewProjectPublishTarget( |
| 2129 | newProjectPublishTargets, |
| 2130 | newProjectPublishKind, |
| 2131 | ); |
| 2132 | const newProjectName = query.trim(); |
| 2133 | const canSubmitNewProject = |
| 2134 | newProjectFlow !== null && |
| 2135 | newProjectName.length > 0 && |
| 2136 | !isCreatingNewProject && |
| 2137 | canCreateProjectInEnvironment(browseEnvironment?.connection.phase); |
| 2138 | |
| 2139 | async function submitNewProject(): Promise<void> { |
| 2140 | if (newProjectFlow === null || !canSubmitNewProject || newProjectSubmittingRef.current) { |
| 2141 | return; |
| 2142 | } |
| 2143 | newProjectSubmittingRef.current = true; |
| 2144 | setIsCreatingNewProject(true); |
| 2145 | const created = await settlePromise(() => |
| 2146 | createNewProject({ |
| 2147 | environmentId: newProjectFlow.environmentId, |
| 2148 | name: newProjectName, |
| 2149 | publishTo: newProjectPublishes ? newProjectPublishTarget : null, |
| 2150 | }), |
| 2151 | ); |
| 2152 | newProjectSubmittingRef.current = false; |
| 2153 | setIsCreatingNewProject(false); |
| 2154 | if (created._tag === "Failure") throw squashAtomCommandFailure(created); |
| 2155 | if (created.value) setOpen(false); |
| 2156 | } |
| 2157 | |
| 2158 | function getDefaultCloneDestination( |
| 2159 | environmentId: EnvironmentId, |
| 2160 | remoteUrl: string, |
| 2161 | repository?: string, |
| 2162 | ): string { |
| 2163 | const environment = environments.find((candidate) => candidate.environmentId === environmentId); |
| 2164 | return getCloneDestinationPath( |
| 2165 | getAddProjectInitialQueryForEnvironment(environmentId), |
| 2166 | getCloneDirectoryPath( |
| 2167 | remoteUrl, |
| 2168 | environment?.serverConfig?.settings.ghqCloneLayout === true, |
| 2169 | repository, |
| 2170 | ), |
| 2171 | ); |
| 2172 | } |
| 2173 | |
| 2174 | async function submitAddProjectCloneFlow(destinationPathInput?: string): Promise<void> { |
| 2175 | if (!addProjectCloneFlow) { |
| 2176 | return; |
| 2177 | } |
| 2178 | if (!canCreateProjectInEnvironment(browseEnvironment?.connection.phase)) { |
| 2179 | toastManager.add( |
| 2180 | stackedThreadToast({ |
| 2181 | type: "error", |
| 2182 | title: gt("Environment unavailable"), |
| 2183 | description: browseEnvironment |
| 2184 | ? gt("{environment} is not connected.", { environment: browseEnvironment.label }) |
| 2185 | : gt("The selected environment is not connected."), |
| 2186 | }), |
| 2187 | ); |
| 2188 | return; |
| 2189 | } |
| 2190 | |
| 2191 | if (addProjectCloneFlow.step === "repository") { |
| 2192 | const rawRepository = query.trim(); |
| 2193 | if (rawRepository.length === 0 || isRemoteProjectLookingUp) { |
| 2194 | return; |
| 2195 | } |
| 2196 | |
| 2197 | const incompleteOwnerMessage = githubIncompleteOwnerRepositoryMessage( |
| 2198 | addProjectCloneFlow.source, |
| 2199 | rawRepository, |
| 2200 | m, |
| 2201 | ); |
| 2202 | if (incompleteOwnerMessage) { |
| 2203 | toastManager.add( |
| 2204 | stackedThreadToast({ |
| 2205 | type: "error", |
| 2206 | title: gt("Repository name incomplete"), |
| 2207 | description: incompleteOwnerMessage, |
| 2208 | }), |
| 2209 | ); |
| 2210 | return; |
| 2211 | } |
| 2212 | |
| 2213 | const provider = addProjectRemoteSourceProvider(addProjectCloneFlow.source); |
| 2214 | if (!provider) { |
| 2215 | const remoteUrl = normalizePastedCloneUrl(rawRepository); |
| 2216 | const destinationPath = getDefaultCloneDestination( |
| 2217 | addProjectCloneFlow.environmentId, |
| 2218 | remoteUrl, |
| 2219 | ); |
| 2220 | setAddProjectCloneFlow({ |
| 2221 | step: "confirm", |
| 2222 | environmentId: addProjectCloneFlow.environmentId, |
| 2223 | source: addProjectCloneFlow.source, |
| 2224 | repositoryInput: rawRepository, |
| 2225 | repository: null, |
| 2226 | remoteUrl, |
| 2227 | }); |
| 2228 | setHighlightedItemValue(null); |
| 2229 | setQuery(destinationPath); |
| 2230 | setBrowseGeneration((generation) => generation + 1); |
| 2231 | return; |
| 2232 | } |
| 2233 | |
| 2234 | setIsRemoteProjectLookingUp(true); |
| 2235 | const lookupGeneration = ++cloneLookupGeneration.current; |
| 2236 | const lookupResult = await lookupRepository({ |
| 2237 | environmentId: addProjectCloneFlow.environmentId, |
| 2238 | input: { |
| 2239 | provider, |
| 2240 | repository: rawRepository, |
| 2241 | }, |
| 2242 | }); |
| 2243 | if (lookupGeneration !== cloneLookupGeneration.current) return; |
| 2244 | setIsRemoteProjectLookingUp(false); |
| 2245 | if (lookupResult._tag === "Failure") { |
| 2246 | if (!isAtomCommandInterrupted(lookupResult)) { |
| 2247 | toastManager.add( |
| 2248 | stackedThreadToast({ |
| 2249 | type: "error", |
| 2250 | title: gt("Repository lookup failed"), |
| 2251 | description: errorMessage(squashAtomCommandFailure(lookupResult), m), |
| 2252 | }), |
| 2253 | ); |
| 2254 | } |
| 2255 | return; |
| 2256 | } |
| 2257 | const repository = lookupResult.value; |
| 2258 | const remoteUrl = getDefaultCloneUrl(repository); |
| 2259 | const destinationPath = getDefaultCloneDestination( |
| 2260 | addProjectCloneFlow.environmentId, |
| 2261 | remoteUrl, |
| 2262 | repository.nameWithOwner, |
| 2263 | ); |
| 2264 | setAddProjectCloneFlow({ |
| 2265 | step: "confirm", |
| 2266 | environmentId: addProjectCloneFlow.environmentId, |
| 2267 | source: addProjectCloneFlow.source, |
| 2268 | repositoryInput: rawRepository, |
| 2269 | repository, |
| 2270 | remoteUrl, |
| 2271 | }); |
| 2272 | setHighlightedItemValue(null); |
| 2273 | setQuery(destinationPath); |
| 2274 | setBrowseGeneration((generation) => generation + 1); |
| 2275 | return; |
| 2276 | } |
| 2277 | |
| 2278 | const rawDestination = (destinationPathInput ?? query).trim(); |
| 2279 | if ( |
| 2280 | !readEnvironmentScope(addProjectCloneFlow.environmentId, AuthSourceControlWriteScope) || |
| 2281 | !readEnvironmentScope(addProjectCloneFlow.environmentId, AuthOrchestrationOperateScope) |
| 2282 | ) { |
| 2283 | toastManager.add( |
| 2284 | stackedThreadToast({ |
| 2285 | type: "error", |
| 2286 | title: gt("Clone unavailable"), |
| 2287 | description: gt( |
| 2288 | "This connection needs permission to write source control and add projects.", |
| 2289 | ), |
| 2290 | }), |
| 2291 | ); |
| 2292 | return; |
| 2293 | } |
| 2294 | if (rawDestination.length === 0 || isRemoteProjectCloning) return; |
| 2295 | |
| 2296 | if (isUnsupportedWindowsProjectPath(rawDestination, browseEnvironmentPlatform)) { |
| 2297 | toastManager.add( |
| 2298 | stackedThreadToast({ |
| 2299 | type: "error", |
| 2300 | title: gt("Clone failed"), |
| 2301 | description: gt("Windows-style paths are only supported on Windows."), |
| 2302 | }), |
| 2303 | ); |
| 2304 | return; |
| 2305 | } |
| 2306 | |
| 2307 | if (isExplicitRelativeProjectPath(rawDestination) && !currentProjectCwdForBrowse) { |
| 2308 | toastManager.add( |
| 2309 | stackedThreadToast({ |
| 2310 | type: "error", |
| 2311 | title: gt("Clone failed"), |
| 2312 | description: gt("Relative paths require an active project."), |
| 2313 | }), |
| 2314 | ); |
| 2315 | return; |
| 2316 | } |
| 2317 | |
| 2318 | const destinationPath = resolveProjectPathForDispatch( |
| 2319 | rawDestination, |
| 2320 | currentProjectCwdForBrowse, |
| 2321 | ); |
| 2322 | if (destinationPath.length === 0) { |
| 2323 | return; |
| 2324 | } |
| 2325 | |
| 2326 | setIsRemoteProjectCloning(true); |
| 2327 | const startResult = await startProjectClone({ |
| 2328 | environmentId: addProjectCloneFlow.environmentId, |
| 2329 | input: { |
| 2330 | projectId: newProjectId(), |
| 2331 | title: inferProjectTitleFromPath(destinationPath), |
| 2332 | // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309) |
| 2333 | createdAt: new Date().toISOString(), |
| 2334 | remoteUrl: addProjectCloneFlow.remoteUrl, |
| 2335 | destinationPath, |
| 2336 | }, |
| 2337 | }); |
| 2338 | setIsRemoteProjectCloning(false); |
| 2339 | if (startResult._tag === "Failure") { |
| 2340 | if (!isAtomCommandInterrupted(startResult)) { |
| 2341 | toastManager.add( |
| 2342 | stackedThreadToast({ |
| 2343 | type: "error", |
| 2344 | title: gt("Clone failed"), |
| 2345 | description: errorMessage(squashAtomCommandFailure(startResult), m), |
| 2346 | }), |
| 2347 | ); |
| 2348 | } |
| 2349 | return; |
| 2350 | } |
| 2351 | setOpen(false); |
| 2352 | void suggestAppAccessForRemote( |
| 2353 | addProjectCloneFlow.environmentId, |
| 2354 | addProjectCloneFlow.remoteUrl, |
| 2355 | ); |
| 2356 | const projectRef = scopeProjectRef( |
| 2357 | addProjectCloneFlow.environmentId, |
| 2358 | startResult.value.projectId, |
| 2359 | ); |
| 2360 | await waitForProject(projectRef, 3_000).catch(() => null); |
| 2361 | const navigationResult = await settlePromise(() => handleNewThread(projectRef)); |
| 2362 | if (navigationResult._tag === "Failure") { |
| 2363 | const error = squashAtomCommandFailure(navigationResult); |
| 2364 | toastManager.add( |
| 2365 | stackedThreadToast({ |
| 2366 | type: "error", |
| 2367 | title: gt("Failed to open project"), |
| 2368 | description: thrownErrorMessage(error, m) ?? gt("An error occurred."), |
| 2369 | }), |
| 2370 | ); |
| 2371 | } |
| 2372 | } |
| 2373 | |
| 2374 | const browseTo = async (name: string): Promise<void> => { |
| 2375 | const nextQuery = pinnedCloneDirectoryName |
| 2376 | ? getCloneDestinationBrowsePath({ |
| 2377 | browseDirectoryPath: browsePath.directoryPath, |
| 2378 | selectedDirectoryName: name, |
| 2379 | cloneDirectoryName: pinnedCloneDirectoryName, |
| 2380 | caseSensitive: !isWindowsPlatform(browseEnvironmentPlatform), |
| 2381 | }) |
| 2382 | : appendBrowsePathSegment(query, name); |
| 2383 | await browseNavigation.run( |
| 2384 | () => prefetchBrowsePath(getBrowseDirectoryPath(nextQuery)), |
| 2385 | () => { |
| 2386 | setHighlightedItemValue(null); |
| 2387 | setQuery(nextQuery); |
| 2388 | setBrowseGeneration((generation) => generation + 1); |
| 2389 | }, |
| 2390 | ); |
| 2391 | }; |
| 2392 | |
| 2393 | const browseUp = async (): Promise<void> => { |
| 2394 | const parentPath = browsePath.parentPath; |
| 2395 | if (parentPath === null) { |
| 2396 | return; |
| 2397 | } |
| 2398 | |
| 2399 | const nextQuery = getCloneDestinationPath(parentPath, pinnedCloneDirectoryName); |
| 2400 | await browseNavigation.run( |
| 2401 | () => prefetchBrowsePath(parentPath), |
| 2402 | () => { |
| 2403 | setHighlightedItemValue(null); |
| 2404 | setQuery(nextQuery); |
| 2405 | setBrowseGeneration((generation) => generation + 1); |
| 2406 | }, |
| 2407 | ); |
| 2408 | }; |
| 2409 | |
| 2410 | const resolvedAddProjectPath = hasTrailingPathSeparator(query) |
| 2411 | ? (browseResult?.parentPath ?? query.trim()) |
| 2412 | : (exactBrowseEntry?.fullPath ?? query.trim()); |
| 2413 | |
| 2414 | const canBrowseUp = !relativePathNeedsActiveProject && browsePath.canBrowseUp; |
| 2415 | |
| 2416 | const browseGroups = buildBrowseGroups( |
| 2417 | { |
| 2418 | browseEntries: visibleBrowseEntries, |
| 2419 | browseQuery: query, |
| 2420 | canBrowseUp, |
| 2421 | upIcon: <CornerLeftUpIcon className={ITEM_ICON_CLASS} />, |
| 2422 | directoryIcon: <FolderIcon className={ITEM_ICON_CLASS} />, |
| 2423 | browseUp, |
| 2424 | browseTo, |
| 2425 | }, |
| 2426 | messages, |
| 2427 | ); |
| 2428 | const cloneDestinationBrowseGroups = browseGroups.map((group) => |
| 2429 | group.value === "directories" ? { ...group, label: gt("Select where to clone") } : group, |
| 2430 | ); |
| 2431 | |
| 2432 | const newProjectsRoot = newProjectFlow ? newProjectsRootFor(newProjectFlow.environmentId) : null; |
| 2433 | const newProjectPathPreview = |
| 2434 | newProjectsRoot === null ? null : getNewProjectPathPreview(newProjectsRoot, newProjectName); |
| 2435 | const newProjectPublishToggleValue = "new-project:publish"; |
| 2436 | const showExistingProjectSources = (environmentId: EnvironmentId) => { |
| 2437 | const sourcesEnvironmentId = newProjectFlow?.sourcesEnvironmentId ?? null; |
| 2438 | if (sourcesEnvironmentId === environmentId) { |
| 2439 | popView(); |
| 2440 | return; |
| 2441 | } |
| 2442 | if (sourcesEnvironmentId !== null) { |
| 2443 | dispatchSearch({ type: "back" }); |
| 2444 | } |
| 2445 | popView(); |
| 2446 | startAddProjectSourceSelection(environmentId); |
| 2447 | }; |
| 2448 | const switchNewProjectEnvironment = (environmentId: EnvironmentId) => { |
| 2449 | setNewProjectFlow((flow) => (flow === null ? flow : { ...flow, environmentId })); |
| 2450 | setAddProjectEnvironmentId(environmentId); |
| 2451 | }; |
| 2452 | const selectedNewProjectEnvironment = |
| 2453 | newProjectFlow === null |
| 2454 | ? undefined |
| 2455 | : newProjectEnvironmentOptions.find( |
| 2456 | (option) => option.environmentId === newProjectFlow.environmentId, |
| 2457 | ); |
| 2458 | const showNewProjectMachines = |
| 2459 | newProjectFlow !== null && |
| 2460 | (newProjectEnvironmentOptions.length > 1 || |
| 2461 | (selectedNewProjectEnvironment === undefined && newProjectEnvironmentOptions.length > 0)); |
| 2462 | const newProjectEnvironmentLabel = showNewProjectMachines |
| 2463 | ? (selectedNewProjectEnvironment?.label ?? |
| 2464 | environmentLabelById.get(newProjectFlow.environmentId) ?? |
| 2465 | null) |
| 2466 | : null; |
| 2467 | const newProjectMachineGroup: CommandPaletteView["groups"][number] | null = |
| 2468 | !showNewProjectMachines || newProjectFlow === null |
| 2469 | ? null |
| 2470 | : { |
| 2471 | value: "new-project-machines", |
| 2472 | label: gt("Environments"), |
| 2473 | items: newProjectEnvironmentOptions.map((option) => ({ |
| 2474 | ...buildEnvironmentItem( |
| 2475 | option, |
| 2476 | `new-project:environment:${option.environmentId}`, |
| 2477 | switchNewProjectEnvironment, |
| 2478 | ), |
| 2479 | ...(isCreatingNewProject ? { disabled: true } : {}), |
| 2480 | ...(option.environmentId === newProjectFlow.environmentId |
| 2481 | ? { |
| 2482 | titleTrailingContent: ( |
| 2483 | <CheckIcon className="ms-auto size-4 shrink-0 text-muted-foreground/70" /> |
| 2484 | ), |
| 2485 | } |
| 2486 | : {}), |
| 2487 | })), |
| 2488 | }; |
| 2489 | const newProjectExistingGroup: CommandPaletteView["groups"][number] | null = |
| 2490 | newProjectFlow === null |
| 2491 | ? null |
| 2492 | : { |
| 2493 | value: "new-project-existing", |
| 2494 | label: "", |
| 2495 | items: [ |
| 2496 | { |
| 2497 | kind: "action", |
| 2498 | value: "new-project:existing", |
| 2499 | searchTerms: [], |
| 2500 | title: gt("Add existing project"), |
| 2501 | description: gt("Open a folder or clone a repository"), |
| 2502 | icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />, |
| 2503 | titleTrailingContent: ( |
| 2504 | <ChevronRightIcon className="-me-0.5 ms-auto size-4 shrink-0 text-muted-foreground/70" /> |
| 2505 | ), |
| 2506 | keepOpen: true, |
| 2507 | run: async () => { |
| 2508 | showExistingProjectSources(newProjectFlow.environmentId); |
| 2509 | }, |
| 2510 | }, |
| 2511 | ], |
| 2512 | }; |
| 2513 | const newProjectOptionGroups: CommandPaletteView["groups"] = |
| 2514 | newProjectPublishTarget === null || newProjectPathPreview === null |
| 2515 | ? [] |
| 2516 | : [ |
| 2517 | { |
| 2518 | value: "new-project-options", |
| 2519 | label: gt("Options"), |
| 2520 | items: [ |
| 2521 | { |
| 2522 | kind: "action", |
| 2523 | value: newProjectPublishToggleValue, |
| 2524 | searchTerms: [], |
| 2525 | title: |
| 2526 | newProjectPublishTargets.length > 1 |
| 2527 | ? gt("Create private repository") |
| 2528 | : gt("Create private repository on {host}", { |
| 2529 | host: newProjectPublishTarget.definition.label, |
| 2530 | }), |
| 2531 | description: |
| 2532 | newProjectName.length > 0 |
| 2533 | ? getNewProjectRepository(newProjectPublishTarget, newProjectPathPreview) |
| 2534 | : (newProjectPublishTarget.owner ?? |
| 2535 | gt("Your {host} account", { |
| 2536 | host: newProjectPublishTarget.definition.label, |
| 2537 | })), |
| 2538 | icon: sourceControlHostIcon(newProjectPublishTarget.definition, ITEM_ICON_CLASS), |
| 2539 | titleTrailingContent: ( |
| 2540 | <span className="ms-auto flex items-center gap-2"> |
| 2541 | {newProjectPublishTargets.length > 1 ? ( |
| 2542 | <NewProjectPublishHostPicker |
| 2543 | disabled={isCreatingNewProject} |
| 2544 | targets={newProjectPublishTargets} |
| 2545 | value={newProjectPublishTarget.definition.kind} |
| 2546 | onValueChange={setNewProjectPublishKind} |
| 2547 | /> |
| 2548 | ) : null} |
| 2549 | <span className="pointer-events-none flex"> |
| 2550 | <Checkbox checked={newProjectPublishes} tabIndex={-1} aria-hidden /> |
| 2551 | </span> |
| 2552 | </span> |
| 2553 | ), |
| 2554 | ...(isCreatingNewProject ? { disabled: true } : {}), |
| 2555 | keepOpen: true, |
| 2556 | checked: newProjectPublishes, |
| 2557 | run: async () => { |
| 2558 | setNewProjectPublishes((publishes) => !publishes); |
| 2559 | }, |
| 2560 | }, |
| 2561 | ], |
| 2562 | }, |
| 2563 | ]; |
| 2564 | |
| 2565 | let displayedGroups: CommandPaletteView["groups"] = filteredGroups; |
| 2566 | if (newProjectFlow !== null) { |
| 2567 | displayedGroups = [ |
| 2568 | ...(newProjectMachineGroup ? [newProjectMachineGroup] : []), |
| 2569 | ...newProjectOptionGroups, |
| 2570 | ...(newProjectExistingGroup ? [newProjectExistingGroup] : []), |
| 2571 | ]; |
| 2572 | } else if (addProjectCloneFlow?.step === "repository") { |
| 2573 | displayedGroups = []; |
| 2574 | } else if (addProjectCloneFlow?.step === "confirm") { |
| 2575 | displayedGroups = relativePathNeedsActiveProject ? [] : cloneDestinationBrowseGroups; |
| 2576 | } else if (isBrowsing) { |
| 2577 | displayedGroups = relativePathNeedsActiveProject ? [] : browseGroups; |
| 2578 | } |
| 2579 | const resultRows = buildCommandPaletteRows(displayedGroups); |
| 2580 | const autoHighlightsFirstRow = |
| 2581 | !isBrowsing && !isRemoteProjectCloneFlow && newProjectFlow === null; |
| 2582 | |
| 2583 | const inputPlaceholder = |
| 2584 | newProjectFlow !== null |
| 2585 | ? gt("Project name") |
| 2586 | : (remoteProjectInputPlaceholder(addProjectCloneFlow, messages) ?? |
| 2587 | getCommandPaletteInputPlaceholder(paletteMode, messages)); |
| 2588 | const isSubmenu = paletteMode === "submenu" || paletteMode === "submenu-browse"; |
| 2589 | const hasHighlightedBrowseItem = highlightedItemValue?.startsWith("browse:") ?? false; |
| 2590 | const canWriteSourceControl = useEnvironmentScope( |
| 2591 | addProjectCloneFlow?.environmentId ?? null, |
| 2592 | AuthSourceControlWriteScope, |
| 2593 | ); |
| 2594 | const canCreateClonedProject = useEnvironmentScope( |
| 2595 | addProjectCloneFlow?.environmentId ?? null, |
| 2596 | AuthOrchestrationOperateScope, |
| 2597 | ); |
| 2598 | const canCloneProject = canWriteSourceControl && canCreateClonedProject; |
| 2599 | const isCloneDestinationStep = addProjectCloneFlow?.step === "confirm"; |
| 2600 | const canSubmitBrowsePath = |
| 2601 | isBrowsing && |
| 2602 | !relativePathNeedsActiveProject && |
| 2603 | canCreateProject && |
| 2604 | (!isCloneDestinationStep || canCloneProject) && |
| 2605 | canCreateProjectInEnvironment(browseEnvironment?.connection.phase); |
| 2606 | const willCreateProjectPath = |
| 2607 | canSubmitBrowsePath && |
| 2608 | !isBrowsePending && |
| 2609 | browseAccessError === null && |
| 2610 | query.trim().length > 0 && |
| 2611 | !hasHighlightedBrowseItem && |
| 2612 | (hasTrailingPathSeparator(query) ? !browseResult : exactBrowseEntry === null); |
| 2613 | const useMetaForMod = isMacPlatform(navigator.platform); |
| 2614 | const submitModifierLabel = useMetaForMod ? "\u2318" : "Ctrl"; |
| 2615 | const submitActionLabel = isCloneDestinationStep |
| 2616 | ? willCreateProjectPath |
| 2617 | ? gt("Create & Clone") |
| 2618 | : gt("Clone") |
| 2619 | : willCreateProjectPath |
| 2620 | ? gt("Create & Add") |
| 2621 | : gt("Add"); |
| 2622 | const addShortcutLabel = hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"; |
| 2623 | const hasHighlightedNewProjectItem = newProjectFlow !== null && highlightedItemValue !== null; |
| 2624 | const createShortcutLabel = hasHighlightedNewProjectItem |
| 2625 | ? `${submitModifierLabel} Enter` |
| 2626 | : "Enter"; |
| 2627 | const remoteProjectButtonLabel = addProjectCloneFlow |
| 2628 | ? addProjectCloneFlow.source === "url" |
| 2629 | ? gt("Continue") |
| 2630 | : gt("Lookup") |
| 2631 | : null; |
| 2632 | const isRemoteProjectPending = isRemoteProjectLookingUp || isRemoteProjectCloning; |
| 2633 | const canSubmitRemoteProjectFlow = |
| 2634 | addProjectCloneFlow?.step === "repository" && |
| 2635 | query.trim().length > 0 && |
| 2636 | canCreateProjectInEnvironment(browseEnvironment?.connection.phase) && |
| 2637 | !isRemoteProjectPending; |
| 2638 | const fileManagerName = getLocalFileManagerName(navigator.platform, messages); |
| 2639 | const canOpenProjectFromFileManager = |
| 2640 | isBrowsing && |
| 2641 | browseEnvironmentId !== null && |
| 2642 | (browseEnvironmentId === primaryEnvironmentId || |
| 2643 | (browseEnvironmentIsDesktopLocal && browseDesktopInstanceId !== null)) && |
| 2644 | typeof window !== "undefined" && |
| 2645 | window.desktopBridge !== undefined; |
| 2646 | const fileManagerInitialPath = (() => { |
| 2647 | if (!canOpenProjectFromFileManager) { |
| 2648 | return undefined; |
| 2649 | } |
| 2650 | |
| 2651 | const trimmedQuery = query.trim(); |
| 2652 | if (trimmedQuery.length === 0) { |
| 2653 | return undefined; |
| 2654 | } |
| 2655 | |
| 2656 | const initialPath = hasTrailingPathSeparator(query) |
| 2657 | ? (browseResult?.parentPath ?? trimmedQuery) |
| 2658 | : browseDirectoryPath || trimmedQuery; |
| 2659 | |
| 2660 | const resolvedPath = resolveProjectPathForDispatch(initialPath, currentProjectCwdForBrowse); |
| 2661 | return resolvedPath.length > 0 ? resolvedPath : undefined; |
| 2662 | })(); |
| 2663 | |
| 2664 | function isPrimaryModifierPressed(event: KeyboardEvent<HTMLInputElement>): boolean { |
| 2665 | return useMetaForMod ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey; |
| 2666 | } |
| 2667 | |
| 2668 | function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void { |
| 2669 | if (event.key === "Enter" && (event.nativeEvent.isComposing || event.keyCode === 229)) { |
| 2670 | // Confirming an IME candidate must not submit a path or select a row. |
| 2671 | (event as typeof event & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.(); |
| 2672 | return; |
| 2673 | } |
| 2674 | |
| 2675 | const command = resolveShortcutCommand(event, keybindings, { |
| 2676 | platform: navigator.platform, |
| 2677 | context: { modelPickerOpen: false, editableFocus: true }, |
| 2678 | }); |
| 2679 | if (command === "thread.pin") { |
| 2680 | const highlightedItem = findHighlightedCommandPaletteItem( |
| 2681 | displayedGroups, |
| 2682 | highlightedItemValue ?? |
| 2683 | (autoHighlightsFirstRow ? (resultRows.itemValues[0] ?? null) : null), |
| 2684 | ); |
| 2685 | if (highlightedItem?.kind === "action" && highlightedItem.pin) { |
| 2686 | event.preventDefault(); |
| 2687 | event.stopPropagation(); |
| 2688 | highlightedItem.pin.toggle(); |
| 2689 | return; |
| 2690 | } |
| 2691 | } |
| 2692 | // Global new-thread handlers ignore shortcuts while the palette is open. |
| 2693 | const isJump = threadJumpIndexFromCommand(command ?? "") !== null; |
| 2694 | const isNewThread = |
| 2695 | !event.nativeEvent.isComposing && |
| 2696 | event.keyCode !== 229 && |
| 2697 | (command === "chat.new" || |
| 2698 | command === "chat.newLocal" || |
| 2699 | command === "chat.newWithoutProject"); |
| 2700 | const matchingItem = |
| 2701 | isJump || isNewThread |
| 2702 | ? displayedGroups |
| 2703 | .flatMap((group) => group.items) |
| 2704 | .find((item) => item.shortcutCommand === command) |
| 2705 | : undefined; |
| 2706 | if (isJump || matchingItem) { |
| 2707 | (event as typeof event & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.(); |
| 2708 | event.preventDefault(); |
| 2709 | event.stopPropagation(); |
| 2710 | if (matchingItem) { |
| 2711 | executeItem(matchingItem); |
| 2712 | } |
| 2713 | return; |
| 2714 | } |
| 2715 | if (command === "thread.copyReference") { |
| 2716 | event.preventDefault(); |
| 2717 | event.stopPropagation(); |
| 2718 | if (activeThreadReferenceCopyTarget === null) return; |
| 2719 | setOpen(false); |
| 2720 | void copyActiveThreadReference(); |
| 2721 | return; |
| 2722 | } |
| 2723 | // ChatView ignores shortcuts while the palette is open, so intercept find here. |
| 2724 | if (command === "chat.find" && activeThreadKey !== null && !event.nativeEvent.isComposing) { |
| 2725 | event.preventDefault(); |
| 2726 | event.stopPropagation(); |
| 2727 | setOpen(false); |
| 2728 | if (supportsThreadFind) openThreadFind(activeThreadKey); |
| 2729 | else |
| 2730 | toastManager.add({ |
| 2731 | id: "thread-find-unavailable", |
| 2732 | title: gt("Thread search is unavailable on this server."), |
| 2733 | description: gt("Update the server to enable it."), |
| 2734 | }); |
| 2735 | return; |
| 2736 | } |
| 2737 | |
| 2738 | if (addProjectCloneFlow?.step === "repository" && event.key === "Enter") { |
| 2739 | event.preventDefault(); |
| 2740 | void submitAddProjectCloneFlow(); |
| 2741 | return; |
| 2742 | } |
| 2743 | |
| 2744 | if ( |
| 2745 | newProjectFlow !== null && |
| 2746 | event.key === "Enter" && |
| 2747 | (!hasHighlightedNewProjectItem || isPrimaryModifierPressed(event)) && |
| 2748 | // Enter that confirms an IME composition is part of typing the name. |
| 2749 | !event.nativeEvent.isComposing && |
| 2750 | event.keyCode !== 229 |
| 2751 | ) { |
| 2752 | // Base UI would otherwise also click the highlighted row. |
| 2753 | (event as typeof event & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.(); |
| 2754 | event.preventDefault(); |
| 2755 | void submitNewProject(); |
| 2756 | return; |
| 2757 | } |
| 2758 | |
| 2759 | const shouldSubmitBrowsePath = |
| 2760 | canSubmitBrowsePath && |
| 2761 | event.key === "Enter" && |
| 2762 | (!hasHighlightedBrowseItem || isPrimaryModifierPressed(event)); |
| 2763 | |
| 2764 | if (shouldSubmitBrowsePath) { |
| 2765 | event.preventDefault(); |
| 2766 | if (isCloneDestinationStep) { |
| 2767 | void submitAddProjectCloneFlow(resolvedAddProjectPath); |
| 2768 | } else { |
| 2769 | void handleAddProject(resolvedAddProjectPath); |
| 2770 | } |
| 2771 | return; |
| 2772 | } |
| 2773 | |
| 2774 | if (event.key === "Backspace" && query === "" && isSubmenu) { |
| 2775 | event.preventDefault(); |
| 2776 | popView(); |
| 2777 | return; |
| 2778 | } |
| 2779 | |
| 2780 | if (event.ctrlKey || event.shiftKey || event.altKey || event.metaKey) return; |
| 2781 | |
| 2782 | if (event.key === "Tab" && isBrowsing && !relativePathNeedsActiveProject) { |
| 2783 | if (event.nativeEvent.isComposing || event.keyCode === 229) return; |
| 2784 | (event as typeof event & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.(); |
| 2785 | event.preventDefault(); |
| 2786 | if (highlightedItemValue === "browse:up") { |
| 2787 | void browseUp(); |
| 2788 | return; |
| 2789 | } |
| 2790 | const highlightedEntry = visibleBrowseEntries.find( |
| 2791 | (entry) => `browse:${entry.fullPath}` === highlightedItemValue, |
| 2792 | ); |
| 2793 | const completion = highlightedEntry |
| 2794 | ? { name: highlightedEntry.name, isComplete: true } |
| 2795 | : getFilesystemBrowseTabCompletion(visibleBrowseEntries, browsePath.filterQuery); |
| 2796 | if (completion?.isComplete) { |
| 2797 | void browseTo(completion.name); |
| 2798 | } else if (completion && !pinnedCloneDirectoryName) { |
| 2799 | setHighlightedItemValue(null); |
| 2800 | setQuery(`${getBrowseDirectoryPath(query)}${completion.name}`); |
| 2801 | } |
| 2802 | return; |
| 2803 | } |
| 2804 | |
| 2805 | const firstItemValue = autoHighlightsFirstRow ? resultRows.itemValues[0] : undefined; |
| 2806 | if ( |
| 2807 | event.key === "ArrowDown" && |
| 2808 | highlightClearedRef.current && |
| 2809 | firstItemValue && |
| 2810 | !event.nativeEvent.isComposing |
| 2811 | ) { |
| 2812 | (event as typeof event & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.(); |
| 2813 | event.preventDefault(); |
| 2814 | highlightClearedRef.current = false; |
| 2815 | setHighlightedItemValue(firstItemValue); |
| 2816 | scrollCommandPaletteRowIntoView( |
| 2817 | resultListRef.current, |
| 2818 | resultRows.rowIndexByItemIndex[0] ?? 0, |
| 2819 | true, |
| 2820 | ); |
| 2821 | return; |
| 2822 | } |
| 2823 | |
| 2824 | // Virtualization may unmount the highlighted row; handle Enter directly instead of Base UI's click. |
| 2825 | if (event.key === "Enter" && !event.nativeEvent.isComposing && event.keyCode !== 229) { |
| 2826 | const highlightedItem = findHighlightedCommandPaletteItem( |
| 2827 | displayedGroups, |
| 2828 | highlightedItemValue ?? firstItemValue ?? null, |
| 2829 | ); |
| 2830 | if (highlightedItem) { |
| 2831 | (event as typeof event & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.(); |
| 2832 | event.preventDefault(); |
| 2833 | event.stopPropagation(); |
| 2834 | executeItem(highlightedItem); |
| 2835 | } |
| 2836 | } |
| 2837 | } |
| 2838 | |
| 2839 | function executeItem(item: CommandPaletteActionItem | CommandPaletteSubmenuItem): void { |
| 2840 | if (item.disabled) { |
| 2841 | return; |
| 2842 | } |
| 2843 | |
| 2844 | if (item.kind === "submenu") { |
| 2845 | pushPaletteView(item); |
| 2846 | return; |
| 2847 | } |
| 2848 | |
| 2849 | if (!item.keepOpen) { |
| 2850 | setOpen(false); |
| 2851 | } |
| 2852 | |
| 2853 | void item.run().catch((error: unknown) => { |
| 2854 | toastManager.add( |
| 2855 | stackedThreadToast({ |
| 2856 | type: "error", |
| 2857 | title: gt("Unable to run command"), |
| 2858 | description: thrownErrorMessage(error, m) ?? gt("An unexpected error occurred."), |
| 2859 | }), |
| 2860 | ); |
| 2861 | }); |
| 2862 | } |
| 2863 | |
| 2864 | const handleOpenProjectFromFileManager = async () => { |
| 2865 | if (!canOpenProjectFromFileManager || isPickingProjectFolder) { |
| 2866 | return; |
| 2867 | } |
| 2868 | const api = readLocalApi(); |
| 2869 | if (!api) { |
| 2870 | return; |
| 2871 | } |
| 2872 | |
| 2873 | setIsPickingProjectFolder(true); |
| 2874 | let pickedPath: string | null = null; |
| 2875 | let desktopWslState: DesktopWslState | null = null; |
| 2876 | try { |
| 2877 | desktopWslState = |
| 2878 | browseEnvironmentId === primaryEnvironmentId && browseEnvironmentPlatform === "Linux" |
| 2879 | ? ((await window.desktopBridge?.getWslState().catch(() => null)) ?? null) |
| 2880 | : null; |
| 2881 | // WSL-only primaries need their pool id from desktop settings; the native picker converts WSL UNC |
| 2882 | // paths. |
| 2883 | const pickerTargetEnvironmentId = resolveProjectPickerTarget({ |
| 2884 | browseEnvironmentId, |
| 2885 | primaryEnvironmentId, |
| 2886 | desktopInstanceId: browseDesktopInstanceId, |
| 2887 | wslConfiguration: desktopWslState, |
| 2888 | }); |
| 2889 | const pickerOptions = { |
| 2890 | ...(fileManagerInitialPath ? { initialPath: fileManagerInitialPath } : {}), |
| 2891 | ...(pickerTargetEnvironmentId ? { targetEnvironmentId: pickerTargetEnvironmentId } : {}), |
| 2892 | }; |
| 2893 | pickedPath = await api.dialogs.pickFolder( |
| 2894 | Object.keys(pickerOptions).length > 0 ? pickerOptions : undefined, |
| 2895 | ); |
| 2896 | } catch { |
| 2897 | setIsPickingProjectFolder(false); |
| 2898 | return; |
| 2899 | } |
| 2900 | setIsPickingProjectFolder(false); |
| 2901 | if (!pickedPath) { |
| 2902 | return; |
| 2903 | } |
| 2904 | if (parseWslUncPath(pickedPath)) { |
| 2905 | if (desktopWslState === null) { |
| 2906 | desktopWslState = (await window.desktopBridge?.getWslState().catch(() => null)) ?? null; |
| 2907 | } |
| 2908 | let primaryRunningDistro: string | null = null; |
| 2909 | try { |
| 2910 | primaryRunningDistro = |
| 2911 | window.desktopBridge |
| 2912 | ?.getLocalEnvironmentBootstraps() |
| 2913 | .find((bootstrap) => bootstrap.id === PRIMARY_LOCAL_ENVIRONMENT_ID)?.runningDistro ?? |
| 2914 | null; |
| 2915 | } catch {} |
| 2916 | const selection = resolveWslProjectSelection( |
| 2917 | pickedPath, |
| 2918 | applyWslEnvironmentConfiguration( |
| 2919 | environments.flatMap((environment) => { |
| 2920 | const backendId = desktopLocalBackendId(environment.entry.target); |
| 2921 | if (!backendId) { |
| 2922 | return []; |
| 2923 | } |
| 2924 | |
| 2925 | const bootstrap = desktopLocalBootstraps.find( |
| 2926 | (candidate) => candidate.httpBaseUrl === environment.displayUrl, |
| 2927 | ); |
| 2928 | const runningDistro = bootstrap?.runningDistro ?? null; |
| 2929 | return [{ environmentId: environment.environmentId, backendId, runningDistro }]; |
| 2930 | }), |
| 2931 | primaryEnvironmentId, |
| 2932 | desktopWslState ?? null, |
| 2933 | primaryRunningDistro, |
| 2934 | ), |
| 2935 | ); |
| 2936 | if (!selection) { |
| 2937 | toastManager.add( |
| 2938 | stackedThreadToast({ |
| 2939 | type: "error", |
| 2940 | title: gt("Could not add WSL project"), |
| 2941 | description: gt("Start the matching WSL backend, then choose the folder again."), |
| 2942 | }), |
| 2943 | ); |
| 2944 | return; |
| 2945 | } |
| 2946 | if (addProjectCloneFlow?.step === "confirm") { |
| 2947 | if (selection.environmentId !== addProjectCloneFlow.environmentId) { |
| 2948 | toastManager.add( |
| 2949 | stackedThreadToast({ |
| 2950 | type: "error", |
| 2951 | title: gt("Clone failed"), |
| 2952 | description: gt("Choose a folder in the environment the repository is cloned into."), |
| 2953 | }), |
| 2954 | ); |
| 2955 | return; |
| 2956 | } |
| 2957 | await submitAddProjectCloneFlow( |
| 2958 | getCloneDestinationForPickedFolder({ |
| 2959 | pickedPath: selection.linuxPath, |
| 2960 | cloneDirectoryName: pinnedCloneDirectoryName, |
| 2961 | caseSensitive: true, |
| 2962 | }), |
| 2963 | ); |
| 2964 | return; |
| 2965 | } |
| 2966 | await handleAddProjectForEnvironment({ |
| 2967 | environmentId: selection.environmentId, |
| 2968 | rawCwd: selection.linuxPath, |
| 2969 | platform: "Linux", |
| 2970 | currentProjectCwd: null, |
| 2971 | }); |
| 2972 | return; |
| 2973 | } |
| 2974 | if (addProjectCloneFlow?.step === "confirm") { |
| 2975 | await submitAddProjectCloneFlow( |
| 2976 | getCloneDestinationForPickedFolder({ |
| 2977 | pickedPath, |
| 2978 | cloneDirectoryName: pinnedCloneDirectoryName, |
| 2979 | caseSensitive: !isWindowsPlatform(browseEnvironmentPlatform), |
| 2980 | }), |
| 2981 | ); |
| 2982 | return; |
| 2983 | } |
| 2984 | await handleAddProject(pickedPath); |
| 2985 | }; |
| 2986 | |
| 2987 | const submitButtonId = useId(); |
| 2988 | const browseSubmitLabel = |
| 2989 | isCloneDestinationStep && !canCloneProject |
| 2990 | ? gt("This connection needs permission to write source control and add projects.") |
| 2991 | : canCreateProject |
| 2992 | ? `${submitActionLabel} (${addShortcutLabel})` |
| 2993 | : gt("This connection cannot add projects."); |
| 2994 | const inputAccessory = |
| 2995 | newProjectFlow !== null ? ( |
| 2996 | <CommandPaletteSubmitButton |
| 2997 | id={submitButtonId} |
| 2998 | label={isCreatingNewProject ? gt("Creating") : gt("Create")} |
| 2999 | shortcutLabel={createShortcutLabel} |
| 3000 | ariaLabel={gt("Create ({shortcut})", { shortcut: createShortcutLabel })} |
| 3001 | tooltip={gt("Create ({shortcut})", { shortcut: createShortcutLabel })} |
| 3002 | disabled={!canSubmitNewProject} |
| 3003 | onSubmit={() => { |
| 3004 | void submitNewProject(); |
| 3005 | }} |
| 3006 | /> |
| 3007 | ) : addProjectCloneFlow?.step === "repository" ? ( |
| 3008 | <CommandPaletteSubmitButton |
| 3009 | id={submitButtonId} |
| 3010 | label={isRemoteProjectPending ? gt("Working") : remoteProjectButtonLabel} |
| 3011 | shortcutLabel="Enter" |
| 3012 | ariaLabel={gt("{action} (Enter)", { action: remoteProjectButtonLabel ?? gt("Continue") })} |
| 3013 | tooltip={gt("{action} (Enter)", { action: remoteProjectButtonLabel ?? gt("Continue") })} |
| 3014 | disabled={!canSubmitRemoteProjectFlow} |
| 3015 | onSubmit={() => { |
| 3016 | void submitAddProjectCloneFlow(); |
| 3017 | }} |
| 3018 | /> |
| 3019 | ) : isBrowsing ? ( |
| 3020 | <CommandPaletteSubmitButton |
| 3021 | id={submitButtonId} |
| 3022 | label={isCloneDestinationStep && isRemoteProjectPending ? gt("Cloning") : submitActionLabel} |
| 3023 | shortcutLabel={addShortcutLabel} |
| 3024 | ariaLabel={browseSubmitLabel} |
| 3025 | tooltip={browseSubmitLabel} |
| 3026 | disabled={ |
| 3027 | !canCreateProject || |
| 3028 | !canCreateProjectInEnvironment(browseEnvironment?.connection.phase) || |
| 3029 | relativePathNeedsActiveProject || |
| 3030 | (isCloneDestinationStep && (!canCloneProject || isRemoteProjectPending)) |
| 3031 | } |
| 3032 | onSubmit={() => { |
| 3033 | if (relativePathNeedsActiveProject) { |
| 3034 | return; |
| 3035 | } |
| 3036 | if (isCloneDestinationStep) { |
| 3037 | void submitAddProjectCloneFlow(resolvedAddProjectPath); |
| 3038 | } else { |
| 3039 | void handleAddProject(resolvedAddProjectPath); |
| 3040 | } |
| 3041 | }} |
| 3042 | /> |
| 3043 | ) : null; |
| 3044 | |
| 3045 | const footerActionLabel = |
| 3046 | newProjectFlow !== null |
| 3047 | ? highlightedItemValue === null |
| 3048 | ? gt("Create") |
| 3049 | : highlightedItemValue === newProjectPublishToggleValue |
| 3050 | ? gt("Toggle") |
| 3051 | : gt("Select") |
| 3052 | : addProjectCloneFlow?.step === "repository" |
| 3053 | ? (remoteProjectButtonLabel ?? gt("Continue")) |
| 3054 | : !canSubmitBrowsePath || hasHighlightedBrowseItem |
| 3055 | ? gt("Select") |
| 3056 | : undefined; |
| 3057 | |
| 3058 | const footerTrailing = canOpenProjectFromFileManager ? ( |
| 3059 | <CommandFooterAction |
| 3060 | disabled={isPickingProjectFolder} |
| 3061 | onClick={() => { |
| 3062 | void handleOpenProjectFromFileManager(); |
| 3063 | }} |
| 3064 | > |
| 3065 | {gt("Open in {app}", { app: fileManagerName })} |
| 3066 | </CommandFooterAction> |
| 3067 | ) : isThreadSearchPending && !isLinkedThreadSearch && !isBrowsing ? ( |
| 3068 | // In the footer, so the list keeps its height while message results may |
| 3069 | // still arrive below it. |
| 3070 | <span className="text-muted-foreground text-xs"> |
| 3071 | <T>Searching messages…</T> |
| 3072 | </span> |
| 3073 | ) : null; |
| 3074 | |
| 3075 | return ( |
| 3076 | <CommandPaletteContent |
| 3077 | key={`${viewStack.length}-${browseGeneration}-${isBrowsing}-${newProjectFlow ? "new-project" : (addProjectCloneFlow?.step ?? "none")}`} |
| 3078 | aria-label={gt("Command palette")} |
| 3079 | autoHighlight={autoHighlightsFirstRow ? "always" : false} |
| 3080 | footerActionLabel={footerActionLabel} |
| 3081 | footerTrailing={footerTrailing} |
| 3082 | inputAccessory={inputAccessory} |
| 3083 | inputProps={{ |
| 3084 | className: hasHighlightedNewProjectItem |
| 3085 | ? "*:data-[slot=autocomplete-input]:pe-38!" |
| 3086 | : addProjectCloneFlow?.step === "repository" || newProjectFlow !== null |
| 3087 | ? "*:data-[slot=autocomplete-input]:pe-32!" |
| 3088 | : isBrowsing |
| 3089 | ? browseInputEndPaddingClass({ |
| 3090 | willCreateProjectPath, |
| 3091 | hasHighlightedBrowseItem, |
| 3092 | }) |
| 3093 | : undefined, |
| 3094 | placeholder: inputPlaceholder, |
| 3095 | "aria-describedby": inputAccessory ? submitButtonId : undefined, |
| 3096 | ...(isSubmenu |
| 3097 | ? { |
| 3098 | startAddon: ( |
| 3099 | <button |
| 3100 | type="button" |
| 3101 | className="flex cursor-pointer items-center" |
| 3102 | aria-label={gt("Back")} |
| 3103 | onClick={popView} |
| 3104 | > |
| 3105 | <ArrowLeftIcon /> |
| 3106 | </button> |
| 3107 | ), |
| 3108 | } |
| 3109 | : isBrowsing |
| 3110 | ? { startAddon: <FolderPlusIcon /> } |
| 3111 | : {}), |
| 3112 | onKeyDown: handleKeyDown, |
| 3113 | }} |
| 3114 | mode="none" |
| 3115 | items={resultRows.itemValues} |
| 3116 | virtualized |
| 3117 | onItemHighlighted={(value, eventDetails) => { |
| 3118 | if (eventDetails.reason === "none" && highlightClearedRef.current) return; |
| 3119 | highlightClearedRef.current = false; |
| 3120 | setHighlightedItemValue(typeof value === "string" ? value : null); |
| 3121 | const rowIndex = resultRows.rowIndexByItemIndex[eventDetails.index]; |
| 3122 | if (eventDetails.reason === "keyboard" && rowIndex !== undefined) { |
| 3123 | scrollCommandPaletteRowIntoView( |
| 3124 | resultListRef.current, |
| 3125 | rowIndex, |
| 3126 | eventDetails.index === 0, |
| 3127 | ); |
| 3128 | } |
| 3129 | }} |
| 3130 | onValueChange={(nextQuery, { event }) => handleQueryChange(nextQuery, event.target)} |
| 3131 | pendingSelectionRef={remountSelectionRef} |
| 3132 | showBackHint={isSubmenu} |
| 3133 | value={query} |
| 3134 | > |
| 3135 | {newProjectPathPreview !== null ? ( |
| 3136 | <NewProjectSummary |
| 3137 | name={newProjectName} |
| 3138 | pathPreview={newProjectPathPreview} |
| 3139 | projectsRoot={newProjectsRoot} |
| 3140 | environmentLabel={newProjectEnvironmentLabel} |
| 3141 | /> |
| 3142 | ) : null} |
| 3143 | {addProjectCloneFlow?.step === "confirm" ? ( |
| 3144 | <RemoteRepositorySummary |
| 3145 | source={addProjectCloneFlow.source} |
| 3146 | title={ |
| 3147 | addProjectCloneFlow.repository?.nameWithOwner ?? addProjectCloneFlow.repositoryInput |
| 3148 | } |
| 3149 | description={addProjectCloneFlow.repository?.url ?? addProjectCloneFlow.remoteUrl} |
| 3150 | /> |
| 3151 | ) : null} |
| 3152 | {browseAccessError ? ( |
| 3153 | <div role="alert" className="px-4 py-3 text-sm text-muted-foreground"> |
| 3154 | {browseAccessError} |
| 3155 | </div> |
| 3156 | ) : isBrowsePending && browseResult === null ? ( |
| 3157 | <div role="status" className="px-4 py-3 text-sm text-muted-foreground"> |
| 3158 | <T>Loading folders...</T> |
| 3159 | </div> |
| 3160 | ) : null} |
| 3161 | <CommandPaletteVirtualizedResults |
| 3162 | rows={resultRows.rows} |
| 3163 | listRef={resultListRef} |
| 3164 | highlightedItemValue={highlightedItemValue} |
| 3165 | isActionsOnly={isActionsOnly} |
| 3166 | keybindings={keybindings} |
| 3167 | onExecuteItem={executeItem} |
| 3168 | {...(addProjectCloneFlow?.step === "repository" |
| 3169 | ? { |
| 3170 | emptyStateMessage: |
| 3171 | addProjectCloneFlow.source === "url" |
| 3172 | ? gt("Enter a Git clone URL and press Enter to continue.") |
| 3173 | : gt("Enter a repository path and press Enter to look it up."), |
| 3174 | } |
| 3175 | : addProjectCloneFlow?.step === "confirm" |
| 3176 | ? { emptyStateMessage: gt("Choose a destination path and press Enter to clone.") } |
| 3177 | : relativePathNeedsActiveProject |
| 3178 | ? { emptyStateMessage: gt("Relative paths require an active project.") } |
| 3179 | : willCreateProjectPath |
| 3180 | ? { |
| 3181 | emptyStateMessage: gt( |
| 3182 | "Press Enter to create this folder and add it as a project.", |
| 3183 | ), |
| 3184 | } |
| 3185 | : isThreadSearchPending |
| 3186 | ? { emptyStateMessage: gt("Searching thread messages…") } |
| 3187 | : isThreadSearchFailed |
| 3188 | ? { emptyStateMessage: gt("Couldn't search thread messages.") } |
| 3189 | : {})} |
| 3190 | /> |
| 3191 | </CommandPaletteContent> |
| 3192 | ); |
| 3193 | } |