2094 lines · 70.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 {  type DesktopWslState,  type EnvironmentId,  type FilesystemBrowseResult,  type ProjectId,  type SourceControlDiscoveryResult,  type SourceControlProviderKind,  type SourceControlRepositoryInfo,  PRIMARY_LOCAL_ENVIRONMENT_ID,} 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 { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";import { useHandleNewThread } from "../hooks/useHandleNewThread";import { useClientSettings } from "../hooks/useSettings";import { readLocalApi } from "../localApi";import { desktopLocalBackendId } from "../connection/desktopLocal";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, usePrimaryEnvironmentId } from "../state/environments";import { useProjects, useThreadShells } from "../state/entities";import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";import {  appendBrowsePathSegment,  canNavigateUp,  ensureBrowseDirectoryPath,  findProjectByPath,  getBrowseDirectoryPath,  getBrowseLeafPathSegment,  getBrowseParentPath,  hasTrailingPathSeparator,  inferProjectTitleFromPath,  isExplicitRelativeProjectPath,  isFilesystemBrowseQuery,  isUnsupportedWindowsProjectPath,  resolveProjectPathForDispatch,} from "../lib/projectPaths";import { onOpenCommandPalette } from "../commandPaletteBus";import { isTerminalFocused } from "../lib/terminalFocus";import { getLatestThreadForProject, sortThreads } from "../lib/threadSort";import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";import {  applyWslEnvironmentConfiguration,  parseWslUncPath,  resolveProjectPickerTarget,  resolveWslProjectSelection,} from "../wslPaths";import {  ADDON_ICON_CLASS,  buildBrowseGroups,  buildProjectActionItems,  buildRootGroups,  buildThreadActionItems,  enumerateCommandPaletteItems,  type CommandPaletteActionItem,  type CommandPaletteSubmenuItem,  type CommandPaletteView,  filterBrowseEntries,  filterCommandPaletteGroups,  getCommandPaletteInputPlaceholder,  getCommandPaletteMode,  ITEM_ICON_CLASS,  RECENT_THREAD_LIMIT,} from "./CommandPalette.logic";import { orderItemsByPreferredIds, sortLogicalProjectsForSidebar } from "./Sidebar.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, primaryServerProvidersAtom } from "../state/server";import { resolveDefaultProviderModelSelection } from "../providerInstances";import { resolveShortcutCommand, threadJumpIndexFromCommand } 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";import { getProjectOrderKey, selectProjectGroupingSettings } from "../logicalProject";import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";import {  buildSidebarProjectPickerEntries,  buildSidebarProjectSnapshots,} from "../sidebarProjectGrouping"; 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" | "new-thread-in";} 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: "OpenNewThreadIn" }  | { 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 "OpenNewThreadIn":      return { open: true, openIntent: { kind: "new-thread-in" } };    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 openNewThreadIn = useCallback(() => dispatch({ _tag: "OpenNewThreadIn" }), []);  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]);   useEffect(    () =>      onOpenCommandPalette((detail) => {        if (detail.open === "new-thread-in") {          openNewThreadIn();        } else if (detail.open === "add-project") {          openAddProject();        } else {          setOpen(true);        }      }),    [openAddProject, openNewThreadIn, setOpen],  );   return (    <ComposerHandleContext value={composerHandleRef}>      <CommandDialog open={state.open} onOpenChange={setOpen}>        {children}        <CommandPaletteDialog          open={state.open}          openIntent={state.openIntent}          setOpen={setOpen}          clearOpenIntent={clearOpenIntent}        />      </CommandDialog>    </ComposerHandleContext>  );} 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 clientSettings = useClientSettings();  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 desktopLocalBootstraps = useDesktopLocalBootstraps();  const primaryEnvironmentId = usePrimaryEnvironmentId();  const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =    useHandleNewThread();  const projects = useProjects();  const projectOrder = useUiStateStore((store) => store.projectOrder);  const threads = useThreadShells();  const keybindings = useAtomValue(primaryServerKeybindingsAtom);

Lines 1–500 of 2094.