1747 lines · 57.2 KB · TypeScript
RawDownload
"use client"; import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";import {  isAtomCommandInterrupted,  settlePromise,  squashAtomCommandFailure,} from "@t3tools/client-runtime/state/runtime";import {  DEFAULT_MODEL,  type EnvironmentId,  type FilesystemBrowseResult,  type ProjectId,  ProviderInstanceId,  type SourceControlDiscoveryResult,  type SourceControlProviderKind,  type SourceControlRepositoryInfo,} from "@t3tools/contracts";import { useNavigate, useParams } from "@tanstack/react-router";import * as Option from "effect/Option";import {  ArrowDownIcon,  ArrowLeftIcon,  ArrowUpIcon,  CornerLeftUpIcon,  FolderIcon,  FolderPlusIcon,  LinkIcon,  MessageSquareIcon,  SettingsIcon,  SquarePenIcon,} from "lucide-react";import {  useCallback,  useDeferredValue,  useEffect,  useLayoutEffect,  useMemo,  useReducer,  useRef,  useState,  type KeyboardEvent,  type ReactNode,} from "react";import { useAtomValue } from "@effect/atom-react";import { OpenAddProjectCommandPaletteProvider } from "../commandPaletteContext";import { useHandleNewThread } from "../hooks/useHandleNewThread";import { useSettings } from "../hooks/useSettings";import { readLocalApi } from "../localApi";import { filesystemEnvironment } from "../state/filesystem";import { projectEnvironment } from "../state/projects";import { useEnvironmentQuery } from "../state/query";import { sourceControlEnvironment } from "../state/sourceControl";import { useAtomCommand } from "../state/use-atom-command";import { useAtomQueryRunner } from "../state/use-atom-query-runner";import { useEnvironments, usePrimaryEnvironment } from "../state/environments";import { useProjects, useThreadShells } from "../state/entities";import {  startNewThreadInProjectFromContext,  startNewThreadFromContext,} from "../lib/chatThreadActions";import {  appendBrowsePathSegment,  canNavigateUp,  ensureBrowseDirectoryPath,  findProjectByPath,  getBrowseDirectoryPath,  getBrowseLeafPathSegment,  getBrowseParentPath,  hasTrailingPathSeparator,  inferProjectTitleFromPath,  isExplicitRelativeProjectPath,  isFilesystemBrowseQuery,  isUnsupportedWindowsProjectPath,  resolveProjectPathForDispatch,} from "../lib/projectPaths";import { isTerminalFocused } from "../lib/terminalFocus";import { getLatestThreadForProject } from "../lib/threadSort";import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";import {  ADDON_ICON_CLASS,  buildBrowseGroups,  buildProjectActionItems,  buildRootGroups,  buildThreadActionItems,  type CommandPaletteActionItem,  type CommandPaletteSubmenuItem,  type CommandPaletteView,  filterBrowseEntries,  filterCommandPaletteGroups,  getCommandPaletteInputPlaceholder,  getCommandPaletteMode,  ITEM_ICON_CLASS,  RECENT_THREAD_LIMIT,} from "./CommandPalette.logic";import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";import { CommandPaletteResults } from "./CommandPaletteResults";import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons";import { ProjectFavicon } from "./ProjectFavicon";import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators";import { primaryServerKeybindingsAtom } from "../state/server";import { resolveShortcutCommand } from "../keybindings";import {  Command,  CommandDialog,  CommandDialogPopup,  CommandFooter,  CommandInput,  CommandPanel,} from "./ui/command";import { Button } from "./ui/button";import { Kbd, KbdGroup } from "./ui/kbd";import { stackedThreadToast, toastManager } from "./ui/toast";import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";import type { ChatComposerHandle } from "./chat/ChatComposer"; const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = []; function getLocalFileManagerName(platform: string): string {  if (isMacPlatform(platform)) {    return "Finder";  }  if (isWindowsPlatform(platform)) {    return "Explorer";  }  return "Files";} function getEnvironmentBrowsePlatform(os: string | null | undefined): string {  if (os === "windows") {    return "Win32";  }  if (os === "darwin") {    return "MacIntel";  }  if (os === "linux") {    return "Linux";  }  return typeof navigator === "undefined" ? "" : navigator.platform;} interface AddProjectEnvironmentOption {  readonly environmentId: EnvironmentId;  readonly label: string;  readonly isPrimary: boolean;} type AddProjectRemoteProviderKind = Extract<  SourceControlProviderKind,  "github" | "gitlab" | "bitbucket" | "azure-devops">;type AddProjectRemoteSource = AddProjectRemoteProviderKind | "url"; type AddProjectCloneFlow =  | {      readonly step: "repository";      readonly environmentId: EnvironmentId;      readonly source: AddProjectRemoteSource;    }  | {      readonly step: "confirm";      readonly environmentId: EnvironmentId;      readonly source: AddProjectRemoteSource;      readonly repositoryInput: string;      readonly repository: SourceControlRepositoryInfo | null;      readonly remoteUrl: string;    }; const REMOTE_PROJECT_SOURCES: ReadonlyArray<AddProjectRemoteSource> = [  "url",  "github",  "gitlab",  "bitbucket",  "azure-devops",];const REMOTE_PROJECT_PROVIDER_SOURCES: ReadonlyArray<AddProjectRemoteProviderKind> = [  "github",  "gitlab",  "bitbucket",  "azure-devops",]; function remoteProjectSourceLabel(source: AddProjectRemoteSource): string {  switch (source) {    case "github":      return "GitHub";    case "gitlab":      return "GitLab";    case "bitbucket":      return "Bitbucket";    case "azure-devops":      return "Azure DevOps";    case "url":      return "Git URL";  }} function remoteProjectSourcePathHint(source: AddProjectRemoteSource): string {  switch (source) {    case "github":      return "owner/repo";    case "gitlab":      return "group/project";    case "bitbucket":      return "workspace/repository";    case "azure-devops":      return "project/repository";    case "url":      return "URL";  }} function remoteProjectSourceProvider(  source: AddProjectRemoteSource,): AddProjectRemoteProviderKind | null {  return source === "url" ? null : source;} function remoteProjectSourceIcon(source: AddProjectRemoteSource, className: string): ReactNode {  switch (source) {    case "github":      return <GitHubIcon className={className} />;    case "gitlab":      return <GitLabIcon className={className} />;    case "bitbucket":      return <BitbucketIcon className={className} />;    case "azure-devops":      return <AzureDevOpsIcon className={className} />;    case "url":      return <LinkIcon className={className} />;  }} function remoteProjectInputPlaceholder(flow: AddProjectCloneFlow | null): string | null {  if (!flow) return null;  if (flow.step === "confirm") return null;  if (flow.source === "url") {    return "Enter Git clone URL";  }  return `Enter ${remoteProjectSourceLabel(flow.source)} repository (${remoteProjectSourcePathHint(flow.source)})`;} function sourceProviderKind(source: AddProjectRemoteSource): AddProjectRemoteProviderKind | null {  return source === "url" ? null : source;} function sortAddProjectProviderSources(  readinessBySource: AddProjectRemoteSourceReadiness,): ReadonlyArray<AddProjectRemoteProviderKind> {  return REMOTE_PROJECT_PROVIDER_SOURCES.toSorted((left, right) => {    const leftReady = readinessBySource[left].ready;    const rightReady = readinessBySource[right].ready;    if (leftReady !== rightReady) {      return leftReady ? -1 : 1;    }    return remoteProjectSourceLabel(left).localeCompare(remoteProjectSourceLabel(right));  });} type AddProjectRemoteSourceReadiness = Record<  AddProjectRemoteSource,  { readonly ready: boolean; readonly hint: string | null }>; function buildAddProjectRemoteSourceReadiness(  discovery: SourceControlDiscoveryResult | null,): AddProjectRemoteSourceReadiness {  const unavailable = {    ready: false,    hint: "Provider status unavailable. Open Settings -> Source Control and rescan.",  } as const;  const defaultReadiness: AddProjectRemoteSourceReadiness = {    url: { ready: true, hint: null },    github: unavailable,    gitlab: unavailable,    bitbucket: unavailable,    "azure-devops": unavailable,  };   if (!discovery) {    return defaultReadiness;  }   const providerByKind = new Map(    discovery.sourceControlProviders.map((provider) => [provider.kind, provider]),  );  const readiness = { ...defaultReadiness };   for (const source of REMOTE_PROJECT_SOURCES) {    const kind = sourceProviderKind(source);    if (!kind) continue;    const provider = providerByKind.get(kind);    if (!provider) {      readiness[source] = unavailable;      continue;    }    if (provider.status !== "available") {      readiness[source] = { ready: false, hint: provider.installHint };      continue;    }    if (provider.auth.status === "unauthenticated") {      readiness[source] = {        ready: false,        hint:          Option.getOrNull(provider.auth.detail) ??          `${provider.label} is not authenticated. Open Settings -> Source Control for setup guidance.`,      };      continue;    }    readiness[source] = { ready: true, hint: null };  }   return readiness;} function errorMessage(error: unknown): string {  if (error instanceof Error && error.message.trim().length > 0) {    return error.message;  }  return "An error occurred.";} interface CommandPaletteOpenIntent {  readonly kind: "add-project";} interface CommandPaletteUiState {  readonly open: boolean;  readonly openIntent: CommandPaletteOpenIntent | null;} type CommandPaletteUiAction =  | { readonly _tag: "SetOpen"; readonly open: boolean }  | { readonly _tag: "Toggle" }  | { readonly _tag: "OpenAddProject" }  | { readonly _tag: "ClearOpenIntent" }; function reduceCommandPaletteUiState(  state: CommandPaletteUiState,  action: CommandPaletteUiAction,): CommandPaletteUiState {  switch (action._tag) {    case "SetOpen":      return {        open: action.open,        openIntent: action.open ? state.openIntent : null,      };    case "Toggle":      return { open: !state.open, openIntent: null };    case "OpenAddProject":      return { open: true, openIntent: { kind: "add-project" } };    case "ClearOpenIntent":      return state.openIntent ? { ...state, openIntent: null } : state;  }} export function CommandPalette({ children }: { children: ReactNode }) {  const [state, dispatch] = useReducer(reduceCommandPaletteUiState, {    open: false,    openIntent: null,  });  const setOpen = useCallback((open: boolean) => dispatch({ _tag: "SetOpen", open }), []);  const toggleOpen = useCallback(() => dispatch({ _tag: "Toggle" }), []);  const openAddProject = useCallback(() => dispatch({ _tag: "OpenAddProject" }), []);  const clearOpenIntent = useCallback(() => dispatch({ _tag: "ClearOpenIntent" }), []);  const keybindings = useAtomValue(primaryServerKeybindingsAtom);  const composerHandleRef = useRef<ChatComposerHandle | null>(null);  const routeTarget = useParams({    strict: false,    select: (params) => resolveThreadRouteTarget(params),  });  const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;  const terminalOpen = useTerminalUiStateStore((state) =>    routeThreadRef      ? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen      : false,  );   useEffect(() => {    const onKeyDown = (event: globalThis.KeyboardEvent) => {      if (event.defaultPrevented) return;      const command = resolveShortcutCommand(event, keybindings, {        context: {          terminalFocus: isTerminalFocused(),          terminalOpen,        },      });      if (command !== "commandPalette.toggle") {        return;      }      event.preventDefault();      event.stopPropagation();      toggleOpen();    };    window.addEventListener("keydown", onKeyDown);    return () => window.removeEventListener("keydown", onKeyDown);  }, [keybindings, terminalOpen, toggleOpen]);   return (    <OpenAddProjectCommandPaletteProvider openAddProject={openAddProject}>      <ComposerHandleContext value={composerHandleRef}>        <CommandDialog open={state.open} onOpenChange={setOpen}>          {children}          <CommandPaletteDialog            open={state.open}            openIntent={state.openIntent}            setOpen={setOpen}            clearOpenIntent={clearOpenIntent}          />        </CommandDialog>      </ComposerHandleContext>    </OpenAddProjectCommandPaletteProvider>  );} function CommandPaletteDialog(props: {  readonly open: boolean;  readonly openIntent: CommandPaletteOpenIntent | null;  readonly setOpen: (open: boolean) => void;  readonly clearOpenIntent: () => void;}) {  if (!props.open) {    return null;  }   return (    <OpenCommandPaletteDialog      openIntent={props.openIntent}      setOpen={props.setOpen}      clearOpenIntent={props.clearOpenIntent}    />  );} function OpenCommandPaletteDialog(props: {  readonly openIntent: CommandPaletteOpenIntent | null;  readonly setOpen: (open: boolean) => void;  readonly clearOpenIntent: () => void;}) {  const navigate = useNavigate();  const { clearOpenIntent, openIntent, setOpen } = props;  const composerHandleRef = useComposerHandleContext();  const [query, setQuery] = useState("");  const deferredQuery = useDeferredValue(query);  const isActionsOnly = deferredQuery.startsWith(">");  const [highlightedItemValue, setHighlightedItemValue] = useState<string | null>(null);  const settings = useSettings();  const createProject = useAtomCommand(projectEnvironment.create, {    reportFailure: false,  });  const lookupRepository = useAtomQueryRunner(sourceControlEnvironment.repository, {    reportFailure: false,  });  const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {    reportFailure: false,  });  const { environments } = useEnvironments();  const primaryEnvironment = usePrimaryEnvironment();  const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =    useHandleNewThread();  const projects = useProjects();  const threads = useThreadShells();  const keybindings = useAtomValue(primaryServerKeybindingsAtom);  const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);  const currentView = viewStack.at(-1) ?? null;  const [browseGeneration, setBrowseGeneration] = useState(0);  const [addProjectEnvironmentId, setAddProjectEnvironmentId] = useState<EnvironmentId | null>(    null,  );  const [isPickingProjectFolder, setIsPickingProjectFolder] = useState(false);  const [addProjectCloneFlow, setAddProjectCloneFlow] = useState<AddProjectCloneFlow | null>(null);  const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false);  const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false);  const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;   const addProjectEnvironmentOptions = useMemo(() => {    const options = environments.map((environment): AddProjectEnvironmentOption => {      const isPrimary = environment.entry.target._tag === "PrimaryConnectionTarget";      return {        environmentId: environment.environmentId,        label: resolveEnvironmentOptionLabel({          isPrimary,          environmentId: environment.environmentId,          runtimeLabel: environment.label,        }),        isPrimary,      };    });     options.sort((left, right) => {      if (left.isPrimary !== right.isPrimary) {        return left.isPrimary ? -1 : 1;      }      return left.label.localeCompare(right.label);    });     return options;

Lines 1–500 of 1747.