diff --git a/apps/mobile/src/app/new/_layout.tsx b/apps/mobile/src/app/new/_layout.tsx index 7205e74509..658a367a1b 100644 --- a/apps/mobile/src/app/new/_layout.tsx +++ b/apps/mobile/src/app/new/_layout.tsx @@ -18,6 +18,10 @@ export default function NewTaskLayout() { }} > + diff --git a/apps/mobile/src/app/new/add-project/_layout.tsx b/apps/mobile/src/app/new/add-project/_layout.tsx new file mode 100644 index 0000000000..14131df0ab --- /dev/null +++ b/apps/mobile/src/app/new/add-project/_layout.tsx @@ -0,0 +1,17 @@ +import { Stack } from "expo-router"; +import { useThemeColor } from "../../../lib/useThemeColor"; + +export default function AddProjectLayout() { + const sheetStyle = { + backgroundColor: useThemeColor("--color-sheet"), + }; + + return ( + + + + + + + ); +} diff --git a/apps/mobile/src/app/new/add-project/destination.tsx b/apps/mobile/src/app/new/add-project/destination.tsx new file mode 100644 index 0000000000..1916c68d6a --- /dev/null +++ b/apps/mobile/src/app/new/add-project/destination.tsx @@ -0,0 +1,12 @@ +import { Stack } from "expo-router"; + +import { AddProjectDestinationScreen } from "../../../features/projects/AddProjectScreen"; + +export default function AddProjectDestinationRoute() { + return ( + <> + + + + ); +} diff --git a/apps/mobile/src/app/new/add-project/index.tsx b/apps/mobile/src/app/new/add-project/index.tsx new file mode 100644 index 0000000000..e5577e3ea3 --- /dev/null +++ b/apps/mobile/src/app/new/add-project/index.tsx @@ -0,0 +1,12 @@ +import { Stack } from "expo-router"; + +import { AddProjectSourceScreen } from "../../../features/projects/AddProjectScreen"; + +export default function AddProjectRoute() { + return ( + <> + + + + ); +} diff --git a/apps/mobile/src/app/new/add-project/local.tsx b/apps/mobile/src/app/new/add-project/local.tsx new file mode 100644 index 0000000000..7577bc907b --- /dev/null +++ b/apps/mobile/src/app/new/add-project/local.tsx @@ -0,0 +1,12 @@ +import { Stack } from "expo-router"; + +import { AddProjectLocalFolderScreen } from "../../../features/projects/AddProjectScreen"; + +export default function AddProjectLocalRoute() { + return ( + <> + + + + ); +} diff --git a/apps/mobile/src/app/new/add-project/repository.tsx b/apps/mobile/src/app/new/add-project/repository.tsx new file mode 100644 index 0000000000..8c574e7e42 --- /dev/null +++ b/apps/mobile/src/app/new/add-project/repository.tsx @@ -0,0 +1,12 @@ +import { Stack } from "expo-router"; + +import { AddProjectRepositoryScreen } from "../../../features/projects/AddProjectScreen"; + +export default function AddProjectRepositoryRoute() { + return ( + <> + + + + ); +} diff --git a/apps/mobile/src/app/new/index.tsx b/apps/mobile/src/app/new/index.tsx index 18ae1c16e4..535a2676f8 100644 --- a/apps/mobile/src/app/new/index.tsx +++ b/apps/mobile/src/app/new/index.tsx @@ -142,13 +142,21 @@ export default function NewTaskRoute() { Add environment - ) : null} + ) : ( + router.push("/new/add-project")} + > + + Add new project + + + )} ) : ( {items.map((item, index) => { const isFirst = index === 0; - const isLast = index === items.length - 1; return ( @@ -198,6 +206,33 @@ export default function NewTaskRoute() { ); })} + router.push("/new/add-project")} + > + + + + + + Add new project + + + + )} diff --git a/apps/mobile/src/components/SourceControlIcon.tsx b/apps/mobile/src/components/SourceControlIcon.tsx new file mode 100644 index 0000000000..b1d4918037 --- /dev/null +++ b/apps/mobile/src/components/SourceControlIcon.tsx @@ -0,0 +1,99 @@ +import Svg, { Defs, LinearGradient, Path, Stop } from "react-native-svg"; + +export type SourceControlIconKind = "github" | "gitlab" | "bitbucket" | "azure-devops"; + +export function SourceControlIcon(props: { + readonly kind: SourceControlIconKind; + readonly size?: number; + readonly color?: string; +}) { + const size = props.size ?? 18; + + switch (props.kind) { + case "github": + return ( + + + + ); + case "gitlab": + return ( + + + + + + + ); + case "azure-devops": + return ( + + + + + + + + + + + + + + + + ); + case "bitbucket": + return ( + + + + + + + + + + + ); + } +} diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx new file mode 100644 index 0000000000..05e04e00e0 --- /dev/null +++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx @@ -0,0 +1,818 @@ +import { + addProjectRemoteSourceLabel, + addProjectRemoteSourcePathHint, + addProjectRemoteSourceProvider, + appendBrowsePathSegment, + buildAddProjectRemoteSourceReadiness, + buildProjectCreateCommand, + canNavigateUp, + ensureBrowseDirectoryPath, + findExistingAddProject, + getAddProjectInitialQuery, + getBrowseDirectoryPath, + getBrowseLeafPathSegment, + getBrowseParentPath, + hasTrailingPathSeparator, + inferProjectTitleFromPath, + isFilesystemBrowseQuery, + resolveAddProjectPath, + sortAddProjectProviderSources, + type AddProjectRemoteSource, +} from "@t3tools/client-runtime"; +import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { useLocalSearchParams, useRouter } from "expo-router"; +import { SymbolView } from "expo-symbols"; +import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react"; +import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; +import * as Arr from "effect/Array"; +import * as Order from "effect/Order"; + +import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText"; +import { ControlPill } from "../../components/ControlPill"; +import { ErrorBanner } from "../../components/ErrorBanner"; +import { SourceControlIcon } from "../../components/SourceControlIcon"; +import { useThemeColor } from "../../lib/useThemeColor"; +import { uuidv4 } from "../../lib/uuid"; +import { getEnvironmentClient } from "../../state/environment-session-registry"; +import { useFilesystemBrowse } from "../../state/use-filesystem-browse"; +import { useRemoteCatalog } from "../../state/use-remote-catalog"; +import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry"; +import { + refreshSourceControlDiscoveryForEnvironment, + useSourceControlDiscovery, +} from "../../state/use-source-control-discovery"; + +interface EnvironmentOption { + readonly environmentId: EnvironmentId; + readonly label: string; + readonly platform: string; + readonly baseDirectory: string | null; +} + +const environmentOptionOrder = Order.mapInput( + Order.Struct({ + label: Order.String, + }), + (environment: EnvironmentOption) => ({ label: environment.label }), +); + +const browseEntryOrder = Order.mapInput( + Order.String, + (entry: { readonly name: string }) => entry.name, +); + +function platformFromOs(os: string | null | undefined): string { + if (os === "windows") return "Win32"; + if (os === "darwin") return "MacIntel"; + if (os === "linux") return "Linux"; + return ""; +} + +function errorMessage(error: unknown): string { + return error instanceof Error && error.message.trim().length > 0 + ? error.message + : "An error occurred."; +} + +function stringParam(value: string | string[] | undefined): string | null { + if (Array.isArray(value)) return value[0] ?? null; + return value ?? null; +} + +function sourceFromParam(value: string | string[] | undefined): AddProjectRemoteSource { + const source = stringParam(value); + if ( + source === "url" || + source === "github" || + source === "gitlab" || + source === "bitbucket" || + source === "azure-devops" + ) { + return source; + } + return "url"; +} + +function SectionTitle(props: { readonly children: string }) { + return ( + + {props.children} + + ); +} + +function AddProjectShell(props: { + readonly title: string; + readonly closeToNew?: boolean; + readonly children: ReactNode; +}) { + const router = useRouter(); + const insets = useSafeAreaInsets(); + + return ( + + + router.back()} + /> + {props.title} + + + + + {props.children} + + + ); +} + +function ListSection(props: { readonly children: ReactNode }) { + return {props.children}; +} + +function ListRow(props: { + readonly title: string; + readonly subtitle?: string | null; + readonly icon: ReactNode; + readonly disabled?: boolean; + readonly selected?: boolean; + readonly isFirst?: boolean; + readonly right?: ReactNode; + readonly onPress?: () => void; +}) { + const borderColor = useThemeColor("--color-border-subtle"); + const chevronColor = useThemeColor("--color-chevron"); + + return ( + + + + {props.icon} + + + {props.title} + {props.subtitle ? ( + + {props.subtitle} + + ) : null} + + {"right" in props ? ( + props.right + ) : !props.disabled ? ( + + ) : null} + + + ); +} + +function useEnvironmentOptions(): ReadonlyArray { + const { serverConfigByEnvironmentId } = useRemoteCatalog(); + const { savedConnectionsById } = useRemoteEnvironmentState(); + + return useMemo>(() => { + const options = Object.values(savedConnectionsById).map((connection) => { + const config = serverConfigByEnvironmentId[connection.environmentId]; + return { + environmentId: connection.environmentId, + label: connection.environmentLabel, + platform: platformFromOs(config?.environment.platform.os ?? null), + baseDirectory: config?.settings.addProjectBaseDirectory ?? null, + }; + }); + return Arr.sort(options, environmentOptionOrder); + }, [savedConnectionsById, serverConfigByEnvironmentId]); +} + +function useSelectedEnvironment(): { + readonly environmentOptions: ReadonlyArray; + readonly selectedEnvironment: EnvironmentOption | null; + readonly setSelectedEnvironmentId: (environmentId: EnvironmentId) => void; +} { + const router = useRouter(); + const params = useLocalSearchParams<{ environmentId?: string }>(); + const environmentOptions = useEnvironmentOptions(); + const requestedEnvironmentId = stringParam(params.environmentId) as EnvironmentId | null; + const selectedEnvironment = + environmentOptions.find( + (environment) => environment.environmentId === requestedEnvironmentId, + ) ?? + environmentOptions[0] ?? + null; + + return { + environmentOptions, + selectedEnvironment, + setSelectedEnvironmentId: (environmentId) => router.setParams({ environmentId }), + }; +} + +function EmptyEnvironmentState() { + const router = useRouter(); + + return ( + + No environments connected + + Add an environment before adding a project. + + router.replace("/connections/new")} + className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70" + > + Add environment + + + ); +} + +function SourceControlRow(props: { + readonly source: AddProjectRemoteSource; + readonly selectedEnvironmentId: EnvironmentId; + readonly ready: boolean; + readonly hint: string; + readonly isFirst: boolean; +}) { + const router = useRouter(); + const iconColor = useThemeColor("--color-icon"); + const title = + props.source === "url" ? "Git URL" : `${addProjectRemoteSourceLabel(props.source)} repository`; + const subtitle = + props.source === "url" + ? "Clone from a remote URL" + : `Clone ${addProjectRemoteSourceLabel(props.source)} ${props.hint}`; + const icon = + props.source === "url" ? ( + + ) : ( + + ); + + if (!props.ready) { + return ( + + ); + } + + return ( + + router.push({ + pathname: "/new/add-project/repository", + params: { + environmentId: props.selectedEnvironmentId, + source: props.source, + }, + }) + } + /> + ); +} + +export function AddProjectSourceScreen() { + const router = useRouter(); + const accentColor = useThemeColor("--color-icon-muted"); + const iconColor = useThemeColor("--color-icon"); + const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } = + useSelectedEnvironment(); + const discoveryState = useSourceControlDiscovery(selectedEnvironment?.environmentId ?? null); + const readiness = useMemo( + () => buildAddProjectRemoteSourceReadiness(discoveryState.data), + [discoveryState.data], + ); + + useEffect(() => { + if (!selectedEnvironment) return; + void refreshSourceControlDiscoveryForEnvironment(selectedEnvironment.environmentId); + }, [selectedEnvironment]); + + return ( + + {environmentOptions.length === 0 ? : null} + + {environmentOptions.length > 1 ? ( + <> + Connected environments + + {environmentOptions.map((environment, index) => ( + + } + selected={environment.environmentId === selectedEnvironment?.environmentId} + isFirst={index === 0} + right={ + environment.environmentId === selectedEnvironment?.environmentId ? ( + + ) : null + } + onPress={() => setSelectedEnvironmentId(environment.environmentId)} + /> + ))} + + + ) : null} + + {selectedEnvironment ? ( + <> + Sources + + + } + isFirst + onPress={() => + router.push({ + pathname: "/new/add-project/local", + params: { environmentId: selectedEnvironment.environmentId }, + }) + } + /> + {(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map( + (candidate) => ( + + ), + )} + + {discoveryState.isPending ? : null} + + ) : null} + + ); +} + +function useCreateProject(environment: EnvironmentOption | null) { + const router = useRouter(); + const { projects } = useRemoteCatalog(); + + return useCallback( + async (workspaceRoot: string) => { + if (!environment) return; + const client = getEnvironmentClient(environment.environmentId); + if (!client) throw new Error("Environment API is not available."); + + const existing = findExistingAddProject({ + projects, + environmentId: environment.environmentId, + path: workspaceRoot, + }); + if (existing) { + Alert.alert("Project already exists", existing.title); + router.replace({ + pathname: "/new/draft", + params: { + environmentId: existing.environmentId, + projectId: existing.id, + title: existing.title, + }, + }); + return; + } + + const projectId = ProjectId.make(uuidv4()); + await client.orchestration.dispatchCommand( + buildProjectCreateCommand({ + commandId: CommandId.make(uuidv4()), + projectId, + workspaceRoot, + createdAt: new Date().toISOString(), + }), + ); + router.replace({ + pathname: "/new/draft", + params: { + environmentId: environment.environmentId, + projectId, + title: inferProjectTitleFromPath(workspaceRoot), + }, + }); + }, + [environment, projects, router], + ); +} + +function useEnvironmentFromParam(): EnvironmentOption | null { + const params = useLocalSearchParams<{ environmentId?: string }>(); + const environmentOptions = useEnvironmentOptions(); + const environmentId = stringParam(params.environmentId) as EnvironmentId | null; + return ( + environmentOptions.find((environment) => environment.environmentId === environmentId) ?? + environmentOptions[0] ?? + null + ); +} + +export function AddProjectRepositoryScreen() { + const router = useRouter(); + const params = useLocalSearchParams<{ environmentId?: string; source?: string }>(); + const environment = useEnvironmentFromParam(); + const source = sourceFromParam(params.source); + const primaryForeground = useThemeColor("--color-primary-foreground"); + const [repositoryInput, setRepositoryInput] = useState(""); + const [isSubmitting, setIsSubmitting] = useState(false); + const [error, setError] = useState(null); + + const lookupRepository = useCallback(async () => { + if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return; + setError(null); + setIsSubmitting(true); + try { + const provider = addProjectRemoteSourceProvider(source); + if (!provider) { + const remoteUrl = repositoryInput.trim(); + router.push({ + pathname: "/new/add-project/destination", + params: { + environmentId: environment.environmentId, + source, + remoteUrl, + repositoryTitle: remoteUrl, + }, + }); + return; + } + + const client = getEnvironmentClient(environment.environmentId); + if (!client) throw new Error("Environment API is not available."); + const repository = await client.sourceControl.lookupRepository({ + provider, + repository: repositoryInput.trim(), + }); + router.push({ + pathname: "/new/add-project/destination", + params: { + environmentId: environment.environmentId, + source, + remoteUrl: repository.sshUrl, + repositoryTitle: repository.nameWithOwner, + }, + }); + } catch (nextError) { + setError(errorMessage(nextError)); + } finally { + setIsSubmitting(false); + } + }, [environment, isSubmitting, repositoryInput, router, source]); + + return ( + + {error ? : null} + void lookupRepository()} + /> + void lookupRepository()} + className="h-11 items-center justify-center rounded-full bg-primary active:opacity-70 disabled:opacity-45" + > + {isSubmitting ? ( + + ) : ( + + {source === "url" ? "Continue" : "Lookup repository"} + + )} + + + ); +} + +function FolderBrowser(props: { + readonly environment: EnvironmentOption; + readonly pathInput: string; + readonly setPathInput: (path: string) => void; +}) { + const accentColor = useThemeColor("--color-icon-muted"); + const browseDirectoryPath = useMemo( + () => + isFilesystemBrowseQuery(props.pathInput, props.environment.platform) + ? getBrowseDirectoryPath(props.pathInput) + : "", + [props.environment.platform, props.pathInput], + ); + const browseFilterQuery = + browseDirectoryPath.length > 0 && !hasTrailingPathSeparator(props.pathInput) + ? getBrowseLeafPathSegment(props.pathInput).toLowerCase() + : ""; + const browseInput = useMemo( + () => (browseDirectoryPath.length > 0 ? { partialPath: browseDirectoryPath } : null), + [browseDirectoryPath], + ); + const browseState = useFilesystemBrowse(props.environment.environmentId, browseInput); + const visibleBrowseEntries = useMemo( + () => + Arr.sort( + Arr.filter( + browseState.data?.entries ?? [], + (entry) => + !entry.name.startsWith(".") && entry.name.toLowerCase().startsWith(browseFilterQuery), + ), + browseEntryOrder, + ), + [browseFilterQuery, browseState.data?.entries], + ); + const parentBrowsePath = getBrowseParentPath(browseDirectoryPath); + const canBrowseUpPath = canNavigateUp(browseDirectoryPath); + + return ( + <> + Browse folders + {browseState.error ? : null} + + {browseState.isPending && browseState.data === null ? ( + + + + ) : null} + {canBrowseUpPath ? ( + + } + isFirst + right={null} + onPress={() => { + if (parentBrowsePath) props.setPathInput(parentBrowsePath); + }} + /> + ) : null} + {visibleBrowseEntries.map((entry, index) => ( + } + isFirst={index === 0 && !canBrowseUpPath} + right={null} + onPress={() => + props.setPathInput( + browseDirectoryPath.length > 0 + ? appendBrowsePathSegment(browseDirectoryPath, entry.name) + : ensureBrowseDirectoryPath(entry.fullPath), + ) + } + /> + ))} + + + ); +} + +export function AddProjectLocalFolderScreen() { + const environment = useEnvironmentFromParam(); + const createProject = useCreateProject(environment); + const primaryForeground = useThemeColor("--color-primary-foreground"); + const [pathInput, setPathInput] = useState(() => + getAddProjectInitialQuery(environment?.baseDirectory), + ); + const [isSubmitting, setIsSubmitting] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + if (!environment) return; + setPathInput(getAddProjectInitialQuery(environment.baseDirectory)); + }, [environment]); + + const submitPath = useCallback(async () => { + if (!environment || isSubmitting) return; + setError(null); + const resolved = resolveAddProjectPath({ + rawPath: pathInput, + currentProjectCwd: null, + platform: environment.platform, + }); + if (!resolved.ok) { + setError(resolved.error); + return; + } + + setIsSubmitting(true); + try { + await createProject(resolved.path); + } catch (nextError) { + setError(errorMessage(nextError)); + } finally { + setIsSubmitting(false); + } + }, [createProject, environment, isSubmitting, pathInput]); + + return ( + + {error ? : null} + {environment ? ( + <> + void submitPath()} + /> + void submitPath()} + className="h-11 items-center justify-center rounded-full bg-primary active:opacity-70" + > + {isSubmitting ? ( + + ) : ( + Add project + )} + + + + ) : ( + + )} + + ); +} + +export function AddProjectDestinationScreen() { + const params = useLocalSearchParams<{ + environmentId?: string; + remoteUrl?: string; + repositoryTitle?: string; + }>(); + const environment = useEnvironmentFromParam(); + const createProject = useCreateProject(environment); + const primaryForeground = useThemeColor("--color-primary-foreground"); + const remoteUrl = stringParam(params.remoteUrl); + const repositoryTitle = stringParam(params.repositoryTitle); + const [pathInput, setPathInput] = useState(() => + getAddProjectInitialQuery(environment?.baseDirectory), + ); + const [isSubmitting, setIsSubmitting] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + if (!environment) return; + setPathInput(getAddProjectInitialQuery(environment.baseDirectory)); + }, [environment]); + + const submitPath = useCallback(async () => { + if (!environment || !remoteUrl || isSubmitting) return; + setError(null); + const resolved = resolveAddProjectPath({ + rawPath: pathInput, + currentProjectCwd: null, + platform: environment.platform, + }); + if (!resolved.ok) { + setError(resolved.error); + return; + } + + setIsSubmitting(true); + try { + const client = getEnvironmentClient(environment.environmentId); + if (!client) throw new Error("Environment API is not available."); + const result = await client.sourceControl.cloneRepository({ + remoteUrl, + destinationPath: resolved.path, + }); + await createProject(result.cwd); + } catch (nextError) { + setError(errorMessage(nextError)); + } finally { + setIsSubmitting(false); + } + }, [createProject, environment, isSubmitting, pathInput, remoteUrl]); + + return ( + + {error ? : null} + {repositoryTitle ? ( + + {repositoryTitle} + + {remoteUrl} + + + ) : null} + {environment ? ( + <> + void submitPath()} + /> + void submitPath()} + className="h-11 items-center justify-center rounded-full bg-primary active:opacity-70 disabled:opacity-45" + > + {isSubmitting ? ( + + ) : ( + + Clone project + + )} + + + + ) : ( + + )} + + ); +} diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index 0c713ec5df..fa02a8aeb0 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -438,14 +438,18 @@ export function NewTaskDraftScreen(props: { - void handleNativePaste(payload)}> + void handleNativePaste(payload)} + style={{ flex: 1 }} + > diff --git a/apps/mobile/src/state/use-filesystem-browse.ts b/apps/mobile/src/state/use-filesystem-browse.ts new file mode 100644 index 0000000000..e5ab77a80a --- /dev/null +++ b/apps/mobile/src/state/use-filesystem-browse.ts @@ -0,0 +1,82 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + EMPTY_FILESYSTEM_BROWSE_ATOM, + EMPTY_FILESYSTEM_BROWSE_STATE, + type FilesystemBrowseClient, + type FilesystemBrowseState, + type FilesystemBrowseTarget, + createFilesystemBrowseManager, + filesystemBrowseStateAtom, + getFilesystemBrowseTargetKey, +} from "@t3tools/client-runtime"; +import type { + EnvironmentId, + FilesystemBrowseInput, + FilesystemBrowseResult, +} from "@t3tools/contracts"; +import { useEffect, useMemo } from "react"; + +import { appAtomRegistry } from "./atom-registry"; +import { + getEnvironmentClient, + subscribeEnvironmentConnections, +} from "./environment-session-registry"; + +const filesystemBrowseManager = createFilesystemBrowseManager({ + getRegistry: () => appAtomRegistry, + getClient: (environmentId) => getEnvironmentClient(environmentId)?.filesystem ?? null, + subscribeClientChanges: subscribeEnvironmentConnections, +}); + +function filesystemBrowseTargetForEnvironment( + environmentId: EnvironmentId | null, + input: FilesystemBrowseInput | null, +): FilesystemBrowseTarget { + return { key: environmentId, input }; +} + +export function refreshFilesystemBrowseForEnvironment( + environmentId: EnvironmentId | null, + input: FilesystemBrowseInput | null, + client?: FilesystemBrowseClient | null, +): Promise { + return filesystemBrowseManager.refresh( + filesystemBrowseTargetForEnvironment(environmentId, input), + client ?? undefined, + ); +} + +export function invalidateFilesystemBrowseForEnvironment( + environmentId: EnvironmentId | null, + input: FilesystemBrowseInput | null, +): void { + filesystemBrowseManager.invalidate(filesystemBrowseTargetForEnvironment(environmentId, input)); +} + +export function resetFilesystemBrowseState(): void { + filesystemBrowseManager.reset(); +} + +export function resetFilesystemBrowseStateForTests(): void { + resetFilesystemBrowseState(); +} + +export function useFilesystemBrowse( + environmentId: EnvironmentId | null, + input: FilesystemBrowseInput | null, +): FilesystemBrowseState { + const target = useMemo( + () => filesystemBrowseTargetForEnvironment(environmentId, input), + [environmentId, input], + ); + + useEffect(() => { + return filesystemBrowseManager.watch(target); + }, [target]); + + const targetKey = getFilesystemBrowseTargetKey(target); + const state = useAtomValue( + targetKey !== null ? filesystemBrowseStateAtom(targetKey) : EMPTY_FILESYSTEM_BROWSE_ATOM, + ); + return targetKey === null ? EMPTY_FILESYSTEM_BROWSE_STATE : state; +} diff --git a/apps/web/src/lib/projectPaths.ts b/apps/web/src/lib/projectPaths.ts index 4b823dff93..da0233ccfb 100644 --- a/apps/web/src/lib/projectPaths.ts +++ b/apps/web/src/lib/projectPaths.ts @@ -1,259 +1,17 @@ -import { - isExplicitRelativePath, - isUncPath, - isWindowsAbsolutePath, - isWindowsDrivePath, -} from "@t3tools/shared/path"; -import { isWindowsPlatform } from "./utils"; - -function isRootPath(value: string): boolean { - return value === "/" || value === "\\" || /^[a-zA-Z]:[/\\]?$/.test(value); -} - -function getAbsolutePathKind(value: string): "unix" | "windows" | null { - if (isWindowsDrivePath(value) || isUncPath(value)) { - return "windows"; - } - - if (value.startsWith("/")) { - return "unix"; - } - - return null; -} - -function trimTrailingPathSeparators(value: string): string { - if (value.length === 0 || isRootPath(value)) { - return value; - } - - const trimmed = - getAbsolutePathKind(value) === "unix" - ? value.replace(/\/+$/g, "") - : value.replace(/[\\/]+$/g, ""); - if (trimmed.length === 0) { - return value; - } - - return /^[a-zA-Z]:$/.test(trimmed) ? `${trimmed}\\` : trimmed; -} - -function preferredPathSeparator(value: string): "/" | "\\" { - const absolutePathKind = getAbsolutePathKind(value); - if (absolutePathKind === "windows") { - return "\\"; - } - if (absolutePathKind === "unix") { - return "/"; - } - - return value.includes("\\") ? "\\" : "/"; -} - -export function hasTrailingPathSeparator(value: string): boolean { - return (getAbsolutePathKind(value) === "unix" ? /\/$/ : /[\\/]$/).test(value); -} - -export { isExplicitRelativePath as isExplicitRelativeProjectPath }; - -function splitPathSegments(value: string, separator: "/" | "\\"): string[] { - return value.split(separator === "/" ? /\/+/ : /[\\/]+/).filter(Boolean); -} - -function getLastPathSeparatorIndex(value: string): number { - if (getAbsolutePathKind(value) === "unix") { - return value.lastIndexOf("/"); - } - - return Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\")); -} - -function splitAbsolutePath(value: string): { - root: string; - separator: "/" | "\\"; - segments: string[]; -} | null { - if (isWindowsDrivePath(value)) { - const root = `${value.slice(0, 2)}\\`; - const segments = splitPathSegments(value.slice(root.length), "\\"); - return { root, separator: "\\", segments }; - } - if (isUncPath(value)) { - const segments = splitPathSegments(value, "\\"); - const [server, share, ...rest] = segments; - if (!server || !share) { - return null; - } - return { - root: `\\\\${server}\\${share}\\`, - separator: "\\", - segments: rest, - }; - } - if (value.startsWith("/")) { - return { - root: "/", - separator: "/", - segments: splitPathSegments(value.slice(1), "/"), - }; - } - return null; -} - -export function isFilesystemBrowseQuery( - value: string, - platform = typeof navigator === "undefined" ? "" : navigator.platform, -): boolean { - const allowWindowsPaths = isWindowsPlatform(platform); - return ( - value.startsWith("./") || - value.startsWith("../") || - value.startsWith(".\\") || - value.startsWith("..\\") || - value.startsWith("/") || - value.startsWith("~/") || - (allowWindowsPaths && isWindowsAbsolutePath(value)) - ); -} - -export function isUnsupportedWindowsProjectPath(value: string, platform: string): boolean { - return isWindowsAbsolutePath(value) && !isWindowsPlatform(platform); -} - -export function normalizeProjectPathForDispatch(value: string): string { - return trimTrailingPathSeparators(value.trim()); -} - -export function resolveProjectPathForDispatch(value: string, cwd?: string | null): string { - const trimmedValue = value.trim(); - if (!isExplicitRelativePath(trimmedValue) || !cwd) { - return normalizeProjectPathForDispatch(trimmedValue); - } - - const absoluteBase = splitAbsolutePath(normalizeProjectPathForDispatch(cwd)); - if (!absoluteBase) { - return normalizeProjectPathForDispatch(trimmedValue); - } - - const nextSegments = [...absoluteBase.segments]; - for (const segment of trimmedValue.split(/[\\/]+/)) { - if (segment.length === 0 || segment === ".") { - continue; - } - if (segment === "..") { - nextSegments.pop(); - continue; - } - nextSegments.push(segment); - } - - const joinedPath = nextSegments.join(absoluteBase.separator); - if (joinedPath.length === 0) { - return normalizeProjectPathForDispatch(absoluteBase.root); - } - - return normalizeProjectPathForDispatch(`${absoluteBase.root}${joinedPath}`); -} - -export function normalizeProjectPathForComparison(value: string): string { - const normalized = normalizeProjectPathForDispatch(value); - if (isWindowsDrivePath(normalized) || normalized.startsWith("\\\\")) { - return normalized.replaceAll("/", "\\").toLowerCase(); - } - return normalized; -} - -export function findProjectByPath( - projects: ReadonlyArray, - candidatePath: string, -): T | undefined { - const normalizedCandidate = normalizeProjectPathForComparison(candidatePath); - if (normalizedCandidate.length === 0) { - return undefined; - } - - return projects.find( - (project) => normalizeProjectPathForComparison(project.cwd) === normalizedCandidate, - ); -} - -export function inferProjectTitleFromPath(value: string): string { - const normalized = normalizeProjectPathForDispatch(value); - const absolutePath = splitAbsolutePath(normalized); - if (absolutePath) { - return absolutePath.segments.findLast(Boolean) ?? normalized; - } - - const segments = normalized.split(/[/\\]/); - return segments.findLast(Boolean) ?? normalized; -} - -export function appendBrowsePathSegment(currentPath: string, segment: string): string { - const separator = preferredPathSeparator(currentPath); - return `${getBrowseDirectoryPath(currentPath)}${segment}${separator}`; -} - -export function getBrowseLeafPathSegment(currentPath: string): string { - const lastSeparatorIndex = getLastPathSeparatorIndex(currentPath); - return currentPath.slice(lastSeparatorIndex + 1); -} - -export function getBrowseDirectoryPath(currentPath: string): string { - if (hasTrailingPathSeparator(currentPath)) { - return currentPath; - } - - const lastSeparatorIndex = getLastPathSeparatorIndex(currentPath); - if (lastSeparatorIndex < 0) { - return currentPath; - } - - return currentPath.slice(0, lastSeparatorIndex + 1); -} - -export function ensureBrowseDirectoryPath(currentPath: string): string { - const trimmed = currentPath.trim(); - if (trimmed.length === 0) { - return trimmed; - } - - if (hasTrailingPathSeparator(trimmed)) { - return trimmed; - } - - return `${trimmed}${preferredPathSeparator(trimmed)}`; -} - -export function getBrowseParentPath(currentPath: string): string | null { - const trimmed = trimTrailingPathSeparators(currentPath); - const absolutePath = splitAbsolutePath(trimmed); - if (absolutePath) { - if (absolutePath.segments.length === 0) { - return null; - } - - if (absolutePath.segments.length === 1) { - return absolutePath.root; - } - - const parentSegments = absolutePath.segments.slice(0, -1).join(absolutePath.separator); - return `${absolutePath.root}${parentSegments}${absolutePath.separator}`; - } - - const separator = preferredPathSeparator(currentPath); - const lastSeparatorIndex = getLastPathSeparatorIndex(trimmed); - - if (lastSeparatorIndex < 0) { - return null; - } - - if (lastSeparatorIndex === 2 && /^[a-zA-Z]:/.test(trimmed)) { - return `${trimmed.slice(0, 2)}${separator}`; - } - - return trimmed.slice(0, lastSeparatorIndex + 1); -} - -export function canNavigateUp(currentPath: string): boolean { - return hasTrailingPathSeparator(currentPath) && getBrowseParentPath(currentPath) !== null; -} +export { + appendBrowsePathSegment, + canNavigateUp, + ensureBrowseDirectoryPath, + findProjectByPath, + getBrowseDirectoryPath, + getBrowseLeafPathSegment, + getBrowseParentPath, + hasTrailingPathSeparator, + inferProjectTitleFromPath, + isExplicitRelativeProjectPath, + isFilesystemBrowseQuery, + isUnsupportedWindowsProjectPath, + normalizeProjectPathForComparison, + normalizeProjectPathForDispatch, + resolveProjectPathForDispatch, +} from "@t3tools/client-runtime"; diff --git a/packages/client-runtime/src/addProject.test.ts b/packages/client-runtime/src/addProject.test.ts new file mode 100644 index 0000000000..9bc2fd61ab --- /dev/null +++ b/packages/client-runtime/src/addProject.test.ts @@ -0,0 +1,146 @@ +import { describe, expect, it } from "vitest"; +import { + EnvironmentId, + ProjectId, + CommandId, + SourceControlDiscoveryResult, +} from "@t3tools/contracts"; +import * as Option from "effect/Option"; + +import { + buildAddProjectRemoteSourceReadiness, + buildProjectCreateCommand, + findExistingAddProject, + getAddProjectInitialQuery, + resolveAddProjectPath, + sortAddProjectProviderSources, +} from "./addProject.ts"; +import type { EnvironmentScopedProjectShell } from "./shellTypes.ts"; + +describe("add project shared logic", () => { + it("resolves initial browse paths from settings", () => { + expect(getAddProjectInitialQuery("")).toBe("~/"); + expect(getAddProjectInitialQuery("/work")).toBe("/work/"); + expect(getAddProjectInitialQuery("C:\\work")).toBe("C:\\work\\"); + }); + + it("rejects unsupported windows paths on non-windows environments", () => { + expect( + resolveAddProjectPath({ + rawPath: "C:\\repo", + platform: "MacIntel", + currentProjectCwd: null, + }), + ).toEqual({ + ok: false, + error: "Windows-style paths are only supported on Windows environments.", + }); + }); + + it("resolves relative paths from the active project cwd", () => { + expect( + resolveAddProjectPath({ + rawPath: "../next", + platform: "Linux", + currentProjectCwd: "/work/current", + }), + ).toEqual({ ok: true, path: "/work/next" }); + }); + + it("marks authenticated source control providers as ready", () => { + const discovery: SourceControlDiscoveryResult = { + versionControlSystems: [], + sourceControlProviders: [ + { + kind: "github", + label: "GitHub", + status: "available", + installHint: "Install gh", + version: Option.some("1.0.0"), + detail: Option.none(), + auth: { + status: "authenticated", + account: Option.some("octo"), + host: Option.some("github.com"), + detail: Option.none(), + }, + }, + { + kind: "gitlab", + label: "GitLab", + status: "available", + installHint: "Install glab", + version: Option.some("1.0.0"), + detail: Option.none(), + auth: { + status: "unauthenticated", + account: Option.none(), + host: Option.none(), + detail: Option.some("Run glab auth login"), + }, + }, + ], + }; + + const readiness = buildAddProjectRemoteSourceReadiness(discovery); + expect(readiness.url.ready).toBe(true); + expect(readiness.github.ready).toBe(true); + expect(readiness.gitlab).toEqual({ ready: false, hint: "Run glab auth login" }); + expect(sortAddProjectProviderSources(readiness)[0]).toBe("github"); + }); + + it("finds existing projects by normalized path in the target environment", () => { + const env = EnvironmentId.make("env"); + const other = EnvironmentId.make("other"); + const projects: EnvironmentScopedProjectShell[] = [ + { + environmentId: other, + id: ProjectId.make("same-path-other-env"), + title: "Other", + workspaceRoot: "/repo", + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + }, + { + environmentId: env, + id: ProjectId.make("project"), + title: "Repo", + workspaceRoot: "/repo/", + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + }, + ]; + + expect(findExistingAddProject({ projects, environmentId: env, path: "/repo" })?.id).toBe( + "project", + ); + }); + + it("builds the existing project.create command shape", () => { + expect( + buildProjectCreateCommand({ + commandId: CommandId.make("command"), + projectId: ProjectId.make("project"), + workspaceRoot: "/work/repo", + createdAt: "2026-01-01T00:00:00.000Z", + }), + ).toMatchObject({ + type: "project.create", + commandId: "command", + projectId: "project", + title: "repo", + workspaceRoot: "/work/repo", + createWorkspaceRootIfMissing: true, + defaultModelSelection: { + instanceId: "codex", + model: "gpt-5.4", + }, + }); + }); +}); diff --git a/packages/client-runtime/src/addProject.ts b/packages/client-runtime/src/addProject.ts new file mode 100644 index 0000000000..fb4e599317 --- /dev/null +++ b/packages/client-runtime/src/addProject.ts @@ -0,0 +1,224 @@ +import type { + CommandId, + EnvironmentId, + OrchestrationCommand, + ProjectId, + SourceControlDiscoveryResult, + SourceControlProviderKind, + SourceControlRepositoryInfo, +} from "@t3tools/contracts"; +import { DEFAULT_MODEL, ProviderInstanceId } from "@t3tools/contracts"; +import * as Arr from "effect/Array"; +import * as Option from "effect/Option"; +import * as Order from "effect/Order"; + +import { + ensureBrowseDirectoryPath, + findProjectByPath, + inferProjectTitleFromPath, + isExplicitRelativeProjectPath, + isUnsupportedWindowsProjectPath, + resolveProjectPathForDispatch, +} from "./projectPaths.ts"; +import type { EnvironmentScopedProjectShell } from "./shellTypes.ts"; + +export type AddProjectRemoteProviderKind = Extract< + SourceControlProviderKind, + "github" | "gitlab" | "bitbucket" | "azure-devops" +>; +export type AddProjectRemoteSource = AddProjectRemoteProviderKind | "url"; + +export type AddProjectRemoteSourceReadiness = Record< + AddProjectRemoteSource, + { readonly ready: boolean; readonly hint: string | null } +>; + +export 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; + }; + +export const ADD_PROJECT_REMOTE_SOURCES: ReadonlyArray = [ + "url", + "github", + "gitlab", + "bitbucket", + "azure-devops", +]; + +export const ADD_PROJECT_REMOTE_PROVIDER_SOURCES: ReadonlyArray = [ + "github", + "gitlab", + "bitbucket", + "azure-devops", +]; + +export function addProjectRemoteSourceLabel(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"; + } +} + +export function addProjectRemoteSourcePathHint(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"; + } +} + +export function addProjectRemoteSourceProvider( + source: AddProjectRemoteSource, +): AddProjectRemoteProviderKind | null { + return source === "url" ? null : source; +} + +export function sortAddProjectProviderSources( + readinessBySource: AddProjectRemoteSourceReadiness, +): ReadonlyArray { + return Arr.sort( + ADD_PROJECT_REMOTE_PROVIDER_SOURCES, + Order.mapInput( + Order.Struct({ + ready: Order.flip(Order.Boolean), + label: Order.String, + }), + (source: AddProjectRemoteProviderKind) => ({ + ready: readinessBySource[source].ready, + label: addProjectRemoteSourceLabel(source), + }), + ), + ); +} + +export function buildAddProjectRemoteSourceReadiness( + discovery: SourceControlDiscoveryResult | null, +): AddProjectRemoteSourceReadiness { + const unavailable = { + ready: false, + hint: "Provider status unavailable. Open Source Control settings and rescan.", + } as const; + const readiness: AddProjectRemoteSourceReadiness = { + url: { ready: true, hint: null }, + github: unavailable, + gitlab: unavailable, + bitbucket: unavailable, + "azure-devops": unavailable, + }; + + if (!discovery) { + return readiness; + } + + const providerByKind = new Map( + discovery.sourceControlProviders.map((provider) => [provider.kind, provider]), + ); + for (const source of ADD_PROJECT_REMOTE_SOURCES) { + const kind = addProjectRemoteSourceProvider(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 Source Control settings for setup guidance.`, + }; + continue; + } + readiness[source] = { ready: true, hint: null }; + } + return readiness; +} + +export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string { + const trimmed = baseDirectory?.trim() ?? ""; + return trimmed.length === 0 ? "~/" : ensureBrowseDirectoryPath(trimmed); +} + +export function resolveAddProjectPath(input: { + readonly rawPath: string; + readonly currentProjectCwd?: string | null; + readonly platform: string; +}): { readonly ok: true; readonly path: string } | { readonly ok: false; readonly error: string } { + const rawPath = input.rawPath.trim(); + if (rawPath.length === 0) { + return { ok: false, error: "Enter a project path." }; + } + if (isUnsupportedWindowsProjectPath(rawPath, input.platform)) { + return { ok: false, error: "Windows-style paths are only supported on Windows environments." }; + } + if (isExplicitRelativeProjectPath(rawPath) && !input.currentProjectCwd) { + return { ok: false, error: "Relative paths require an active project in this environment." }; + } + const path = resolveProjectPathForDispatch(rawPath, input.currentProjectCwd); + return path.length === 0 ? { ok: false, error: "Enter a project path." } : { ok: true, path }; +} + +export function findExistingAddProject(input: { + readonly projects: ReadonlyArray; + readonly environmentId: EnvironmentId; + readonly path: string; +}): EnvironmentScopedProjectShell | null { + return ( + findProjectByPath( + input.projects.filter((project) => project.environmentId === input.environmentId), + input.path, + ) ?? null + ); +} + +export function buildProjectCreateCommand(input: { + readonly commandId: CommandId; + readonly projectId: ProjectId; + readonly workspaceRoot: string; + readonly createdAt: string; +}): Extract { + return { + type: "project.create", + commandId: input.commandId, + projectId: input.projectId, + title: inferProjectTitleFromPath(input.workspaceRoot), + workspaceRoot: input.workspaceRoot, + createWorkspaceRootIfMissing: true, + defaultModelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: DEFAULT_MODEL, + }, + createdAt: input.createdAt, + }; +} diff --git a/packages/client-runtime/src/filesystemBrowseState.test.ts b/packages/client-runtime/src/filesystemBrowseState.test.ts new file mode 100644 index 0000000000..c2fe0da181 --- /dev/null +++ b/packages/client-runtime/src/filesystemBrowseState.test.ts @@ -0,0 +1,119 @@ +import { assert, beforeEach, it } from "vitest"; +import type { FilesystemBrowseResult } from "@t3tools/contracts"; +import { AtomRegistry } from "effect/unstable/reactivity"; + +import { + EMPTY_FILESYSTEM_BROWSE_STATE, + createFilesystemBrowseManager, +} from "./filesystemBrowseState.ts"; + +const ROOT_RESULT: FilesystemBrowseResult = { + parentPath: "/Users/julius", + entries: [ + { + name: "code", + fullPath: "/Users/julius/code", + }, + ], +}; + +let registry = AtomRegistry.make(); + +beforeEach(() => { + registry.dispose(); + registry = AtomRegistry.make(); +}); + +function unresolvedBrowse() { + throw new Error("Browse resolver was not initialized."); +} + +function flushAsyncWork(): Promise { + return Promise.resolve().then(() => undefined); +} + +it("stores browsed folder data in an atom snapshot", async () => { + const manager = createFilesystemBrowseManager({ + getRegistry: () => registry, + getClient: () => ({ + browse: async () => ROOT_RESULT, + }), + }); + + assert.deepStrictEqual( + manager.getSnapshot({ key: null, input: null }), + EMPTY_FILESYSTEM_BROWSE_STATE, + ); + + const target = { key: "env-1", input: { partialPath: "~" } }; + const result = await manager.refresh(target); + + assert.strictEqual(result, ROOT_RESULT); + assert.deepStrictEqual(manager.getSnapshot(target), { + data: ROOT_RESULT, + error: null, + isPending: false, + }); +}); + +it("deduplicates in-flight browse refreshes by target input", async () => { + let resolveBrowse: (result: FilesystemBrowseResult) => void = unresolvedBrowse; + let calls = 0; + const target = { key: "env-1", input: { partialPath: "~" } }; + const manager = createFilesystemBrowseManager({ + getRegistry: () => registry, + getClient: () => ({ + browse: () => { + calls += 1; + return new Promise((resolve) => { + resolveBrowse = resolve; + }); + }, + }), + }); + + const first = manager.refresh(target); + const second = manager.refresh(target); + + assert.strictEqual(first, second); + assert.strictEqual(calls, 1); + assert.deepStrictEqual(manager.getSnapshot(target), { + data: null, + error: null, + isPending: true, + }); + + resolveBrowse(ROOT_RESULT); + await first; + + assert.deepStrictEqual(manager.getSnapshot(target), { + data: ROOT_RESULT, + error: null, + isPending: false, + }); +}); + +it("keeps fresh watched browse results on remount", async () => { + let browseCalls = 0; + const target = { key: "env-1", input: { partialPath: "~" } }; + const manager = createFilesystemBrowseManager({ + getRegistry: () => registry, + getClient: () => ({ + browse: async () => { + browseCalls += 1; + return ROOT_RESULT; + }, + }), + staleTimeMs: 60_000, + }); + + const firstUnwatch = manager.watch(target); + await flushAsyncWork(); + firstUnwatch(); + + const secondUnwatch = manager.watch(target); + await flushAsyncWork(); + secondUnwatch(); + + assert.strictEqual(browseCalls, 1); +}); diff --git a/packages/client-runtime/src/filesystemBrowseState.ts b/packages/client-runtime/src/filesystemBrowseState.ts new file mode 100644 index 0000000000..b1c72966d4 --- /dev/null +++ b/packages/client-runtime/src/filesystemBrowseState.ts @@ -0,0 +1,339 @@ +import type { FilesystemBrowseInput, FilesystemBrowseResult } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import { Atom, type AtomRegistry } from "effect/unstable/reactivity"; + +export interface FilesystemBrowseState { + readonly data: FilesystemBrowseResult | null; + readonly error: string | null; + readonly isPending: boolean; +} + +export interface FilesystemBrowseTarget { + readonly key: TKey | null; + readonly input: FilesystemBrowseInput | null; +} + +export interface FilesystemBrowseClient { + readonly browse: (input: FilesystemBrowseInput) => Promise; +} + +interface WatchedEntry { + refCount: number; + teardown: () => void; +} + +export const EMPTY_FILESYSTEM_BROWSE_STATE = Object.freeze({ + data: null, + error: null, + isPending: false, +}); + +const INITIAL_FILESYSTEM_BROWSE_STATE = Object.freeze({ + data: null, + error: null, + isPending: true, +}); + +const knownFilesystemBrowseKeys = new Set(); + +export const filesystemBrowseStateAtom = Atom.family((targetKey: string) => { + knownFilesystemBrowseKeys.add(targetKey); + return Atom.make(INITIAL_FILESYSTEM_BROWSE_STATE).pipe( + Atom.keepAlive, + Atom.withLabel(`filesystem-browse:${targetKey}`), + ); +}); + +export const EMPTY_FILESYSTEM_BROWSE_ATOM = Atom.make(EMPTY_FILESYSTEM_BROWSE_STATE).pipe( + Atom.keepAlive, + Atom.withLabel("filesystem-browse:null"), +); + +const NOOP: () => void = () => undefined; +const DEFAULT_STALE_TIME_MS = 30_000; +const DEFAULT_IDLE_TTL_MS = 5 * 60_000; + +export function getFilesystemBrowseTargetKey( + target: FilesystemBrowseTarget, +): string | null { + const key = target.key; + const input = target.input; + if (!key || !input || input.partialPath.length === 0) { + return null; + } + + return JSON.stringify([key, input.cwd ?? null, input.partialPath]); +} + +export interface FilesystemBrowseManagerConfig { + readonly getRegistry: () => AtomRegistry.AtomRegistry; + readonly getClient: (key: TKey) => FilesystemBrowseClient | null; + readonly subscribeClientChanges?: (listener: () => void) => () => void; + readonly staleTimeMs?: number; + readonly idleTtlMs?: number; +} + +export function createFilesystemBrowseManager( + config: FilesystemBrowseManagerConfig, +) { + const refreshInFlight = new Map< + string, + { + readonly client: FilesystemBrowseClient; + readonly promise: Promise; + } + >(); + const refreshVersions = new Map(); + const watched = new Map(); + const refreshTargets = new Map>(); + const staleTimeMs = config.staleTimeMs ?? DEFAULT_STALE_TIME_MS; + const idleTtlMs = config.idleTtlMs ?? DEFAULT_IDLE_TTL_MS; + + const watchedRefreshAtom = Atom.family((targetKey: string) => + Atom.make(() => + Effect.promise(() => { + const target = refreshTargets.get(targetKey); + return target ? refresh(target) : Promise.resolve(null); + }), + ).pipe( + Atom.swr({ + staleTime: staleTimeMs, + revalidateOnMount: true, + }), + Atom.setIdleTTL(idleTtlMs), + Atom.withLabel(`filesystem-browse:watched-refresh:${targetKey}`), + ), + ); + + function getRefreshVersion(targetKey: string): number { + return refreshVersions.get(targetKey) ?? 0; + } + + function bumpRefreshVersion(targetKey: string): void { + refreshVersions.set(targetKey, getRefreshVersion(targetKey) + 1); + } + + function setState(targetKey: string, nextState: FilesystemBrowseState): void { + config.getRegistry().set(filesystemBrowseStateAtom(targetKey), nextState); + } + + function markPending(targetKey: string): void { + const current = config.getRegistry().get(filesystemBrowseStateAtom(targetKey)); + const next: FilesystemBrowseState = + current.data === null + ? INITIAL_FILESYSTEM_BROWSE_STATE + : { + data: current.data, + error: null, + isPending: true, + }; + + if ( + current.data === next.data && + current.error === next.error && + current.isPending === next.isPending + ) { + return; + } + + setState(targetKey, next); + } + + function setData(targetKey: string, data: FilesystemBrowseResult): void { + setState(targetKey, { + data, + error: null, + isPending: false, + }); + } + + function setError(targetKey: string, error: unknown): void { + const current = config.getRegistry().get(filesystemBrowseStateAtom(targetKey)); + setState(targetKey, { + data: current.data, + error: error instanceof Error ? error.message : "Failed to browse folder.", + isPending: false, + }); + } + + function refresh( + target: FilesystemBrowseTarget, + client?: FilesystemBrowseClient, + ): Promise { + const targetKey = getFilesystemBrowseTargetKey(target); + if (targetKey === null || target.key === null || target.input === null) { + return Promise.resolve(null); + } + refreshTargets.set(targetKey, target); + + const resolvedClient = client ?? config.getClient(target.key); + if (!resolvedClient) { + setError(targetKey, new Error("Filesystem browser client is unavailable.")); + return Promise.resolve(getSnapshot(target).data); + } + + const existing = refreshInFlight.get(targetKey); + if (existing) { + if (!client || existing.client === resolvedClient) { + return existing.promise; + } + return existing.promise.then(() => refresh(target, resolvedClient)); + } + + markPending(targetKey); + const refreshVersion = getRefreshVersion(targetKey); + const promise = resolvedClient.browse(target.input).then( + (result) => { + if (getRefreshVersion(targetKey) === refreshVersion) { + setData(targetKey, result); + } + return result; + }, + (error: unknown) => { + if (getRefreshVersion(targetKey) === refreshVersion) { + setError(targetKey, error); + } + return getSnapshot(target).data; + }, + ); + + let tracked: Promise; + tracked = promise.finally(() => { + if (refreshInFlight.get(targetKey)?.promise === tracked) { + refreshInFlight.delete(targetKey); + } + }); + refreshInFlight.set(targetKey, { + client: resolvedClient, + promise: tracked, + }); + return tracked; + } + + function invalidate(target?: FilesystemBrowseTarget): void { + if (!target) { + reset(); + return; + } + + const targetKey = getFilesystemBrowseTargetKey(target); + if (targetKey === null) { + return; + } + + bumpRefreshVersion(targetKey); + refreshInFlight.delete(targetKey); + setState(targetKey, INITIAL_FILESYSTEM_BROWSE_STATE); + } + + function getSnapshot(target: FilesystemBrowseTarget): FilesystemBrowseState { + const targetKey = getFilesystemBrowseTargetKey(target); + if (targetKey === null) { + return EMPTY_FILESYSTEM_BROWSE_STATE; + } + + return config.getRegistry().get(filesystemBrowseStateAtom(targetKey)); + } + + function watch( + target: FilesystemBrowseTarget, + client?: FilesystemBrowseClient, + ): () => void { + const targetKey = getFilesystemBrowseTargetKey(target); + if (targetKey === null || target.key === null) { + return NOOP; + } + refreshTargets.set(targetKey, target); + + const existing = watched.get(targetKey); + if (existing) { + existing.refCount += 1; + return () => unwatch(targetKey); + } + + let teardown: () => void; + + if (client) { + void refresh(target, client); + teardown = NOOP; + } else if (config.subscribeClientChanges) { + let currentClient: FilesystemBrowseClient | null = null; + + const sync = () => { + const resolved = config.getClient(target.key!); + if (!resolved) { + currentClient = null; + markPending(targetKey); + return; + } + + if (currentClient === resolved) { + return; + } + + const isClientReplacement = currentClient !== null; + currentClient = resolved; + refreshWatchedTarget(targetKey, target, isClientReplacement ? resolved : undefined); + }; + + const unsubChanges = config.subscribeClientChanges(sync); + sync(); + teardown = unsubChanges; + } else { + if (!config.getClient(target.key)) { + return NOOP; + } + refreshWatchedTarget(targetKey, target); + teardown = NOOP; + } + + watched.set(targetKey, { refCount: 1, teardown }); + return () => unwatch(targetKey); + } + + function unwatch(targetKey: string): void { + const entry = watched.get(targetKey); + if (!entry) { + return; + } + + entry.refCount -= 1; + if (entry.refCount > 0) { + return; + } + + entry.teardown(); + watched.delete(targetKey); + } + + function refreshWatchedTarget( + targetKey: string, + target: FilesystemBrowseTarget, + client?: FilesystemBrowseClient, + ): void { + refreshTargets.set(targetKey, target); + const registry = config.getRegistry(); + void registry.get(watchedRefreshAtom(targetKey)); + if (client) { + void refresh(target, client); + } + } + + function reset(): void { + refreshInFlight.clear(); + watched.clear(); + refreshTargets.clear(); + for (const targetKey of knownFilesystemBrowseKeys) { + bumpRefreshVersion(targetKey); + setState(targetKey, INITIAL_FILESYSTEM_BROWSE_STATE); + } + } + + return { + refresh, + invalidate, + getSnapshot, + watch, + reset, + }; +} diff --git a/packages/client-runtime/src/index.ts b/packages/client-runtime/src/index.ts index 94d0787b97..2353bb26ac 100644 --- a/packages/client-runtime/src/index.ts +++ b/packages/client-runtime/src/index.ts @@ -2,6 +2,9 @@ export * from "./advertisedEndpoint.ts"; export * from "./knownEnvironment.ts"; export * from "./reconnectBackoff.ts"; export * from "./scoped.ts"; +export * from "./projectPaths.ts"; +export * from "./addProject.ts"; +export * from "./filesystemBrowseState.ts"; export * from "./sourceControlDiscoveryState.ts"; export * from "./environmentRuntimeState.ts"; export * from "./shellTypes.ts"; diff --git a/packages/client-runtime/src/projectPaths.ts b/packages/client-runtime/src/projectPaths.ts new file mode 100644 index 0000000000..a4d2c7e19e --- /dev/null +++ b/packages/client-runtime/src/projectPaths.ts @@ -0,0 +1,221 @@ +import { + isExplicitRelativePath, + isUncPath, + isWindowsAbsolutePath, + isWindowsDrivePath, +} from "@t3tools/shared/path"; + +function isWindowsPlatform(platform: string): boolean { + return /^win(dows)?/i.test(platform); +} + +function isRootPath(value: string): boolean { + return value === "/" || value === "\\" || /^[a-zA-Z]:[/\\]?$/.test(value); +} + +function getAbsolutePathKind(value: string): "unix" | "windows" | null { + if (isWindowsDrivePath(value) || isUncPath(value)) { + return "windows"; + } + if (value.startsWith("/")) { + return "unix"; + } + return null; +} + +function trimTrailingPathSeparators(value: string): string { + if (value.length === 0 || isRootPath(value)) { + return value; + } + const trimmed = + getAbsolutePathKind(value) === "unix" + ? value.replace(/\/+$/g, "") + : value.replace(/[\\/]+$/g, ""); + if (trimmed.length === 0) { + return value; + } + return /^[a-zA-Z]:$/.test(trimmed) ? `${trimmed}\\` : trimmed; +} + +function preferredPathSeparator(value: string): "/" | "\\" { + const absolutePathKind = getAbsolutePathKind(value); + if (absolutePathKind === "windows") return "\\"; + if (absolutePathKind === "unix") return "/"; + return value.includes("\\") ? "\\" : "/"; +} + +export function hasTrailingPathSeparator(value: string): boolean { + return (getAbsolutePathKind(value) === "unix" ? /\/$/ : /[\\/]$/).test(value); +} + +export { isExplicitRelativePath as isExplicitRelativeProjectPath }; + +function splitPathSegments(value: string, separator: "/" | "\\"): string[] { + return value.split(separator === "/" ? /\/+/ : /[\\/]+/).filter(Boolean); +} + +function getLastPathSeparatorIndex(value: string): number { + if (getAbsolutePathKind(value) === "unix") { + return value.lastIndexOf("/"); + } + return Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\")); +} + +function splitAbsolutePath(value: string): { + root: string; + separator: "/" | "\\"; + segments: string[]; +} | null { + if (isWindowsDrivePath(value)) { + const root = `${value.slice(0, 2)}\\`; + const segments = splitPathSegments(value.slice(root.length), "\\"); + return { root, separator: "\\", segments }; + } + if (isUncPath(value)) { + const segments = splitPathSegments(value, "\\"); + const [server, share, ...rest] = segments; + if (!server || !share) return null; + return { + root: `\\\\${server}\\${share}\\`, + separator: "\\", + segments: rest, + }; + } + if (value.startsWith("/")) { + return { + root: "/", + separator: "/", + segments: splitPathSegments(value.slice(1), "/"), + }; + } + return null; +} + +export function isFilesystemBrowseQuery(value: string, platform = ""): boolean { + const allowWindowsPaths = isWindowsPlatform(platform); + return ( + value.startsWith("./") || + value.startsWith("../") || + value.startsWith(".\\") || + value.startsWith("..\\") || + value.startsWith("/") || + value.startsWith("~/") || + (allowWindowsPaths && isWindowsAbsolutePath(value)) + ); +} + +export function isUnsupportedWindowsProjectPath(value: string, platform: string): boolean { + return isWindowsAbsolutePath(value) && !isWindowsPlatform(platform); +} + +export function normalizeProjectPathForDispatch(value: string): string { + return trimTrailingPathSeparators(value.trim()); +} + +export function resolveProjectPathForDispatch(value: string, cwd?: string | null): string { + const trimmedValue = value.trim(); + if (!isExplicitRelativePath(trimmedValue) || !cwd) { + return normalizeProjectPathForDispatch(trimmedValue); + } + + const absoluteBase = splitAbsolutePath(normalizeProjectPathForDispatch(cwd)); + if (!absoluteBase) { + return normalizeProjectPathForDispatch(trimmedValue); + } + + const nextSegments = [...absoluteBase.segments]; + for (const segment of trimmedValue.split(/[\\/]+/)) { + if (segment.length === 0 || segment === ".") continue; + if (segment === "..") { + nextSegments.pop(); + continue; + } + nextSegments.push(segment); + } + + const joinedPath = nextSegments.join(absoluteBase.separator); + return normalizeProjectPathForDispatch( + joinedPath.length === 0 ? absoluteBase.root : `${absoluteBase.root}${joinedPath}`, + ); +} + +export function normalizeProjectPathForComparison(value: string): string { + const normalized = normalizeProjectPathForDispatch(value); + if (isWindowsDrivePath(normalized) || normalized.startsWith("\\\\")) { + return normalized.replaceAll("/", "\\").toLowerCase(); + } + return normalized; +} + +export function findProjectByPath( + projects: ReadonlyArray, + candidatePath: string, +): T | undefined { + const normalizedCandidate = normalizeProjectPathForComparison(candidatePath); + if (normalizedCandidate.length === 0) { + return undefined; + } + return projects.find((project) => { + const cwd = project.workspaceRoot ?? project.cwd; + return cwd ? normalizeProjectPathForComparison(cwd) === normalizedCandidate : false; + }); +} + +export function inferProjectTitleFromPath(value: string): string { + const normalized = normalizeProjectPathForDispatch(value); + const absolutePath = splitAbsolutePath(normalized); + if (absolutePath) { + return absolutePath.segments.findLast(Boolean) ?? normalized; + } + const segments = normalized.split(/[/\\]/); + return segments.findLast(Boolean) ?? normalized; +} + +export function appendBrowsePathSegment(currentPath: string, segment: string): string { + const separator = preferredPathSeparator(currentPath); + return `${getBrowseDirectoryPath(currentPath)}${segment}${separator}`; +} + +export function getBrowseLeafPathSegment(currentPath: string): string { + const lastSeparatorIndex = getLastPathSeparatorIndex(currentPath); + return currentPath.slice(lastSeparatorIndex + 1); +} + +export function getBrowseDirectoryPath(currentPath: string): string { + if (hasTrailingPathSeparator(currentPath)) { + return currentPath; + } + const lastSeparatorIndex = getLastPathSeparatorIndex(currentPath); + return lastSeparatorIndex < 0 ? currentPath : currentPath.slice(0, lastSeparatorIndex + 1); +} + +export function ensureBrowseDirectoryPath(currentPath: string): string { + const trimmed = currentPath.trim(); + if (trimmed.length === 0 || hasTrailingPathSeparator(trimmed)) { + return trimmed; + } + return `${trimmed}${preferredPathSeparator(trimmed)}`; +} + +export function getBrowseParentPath(currentPath: string): string | null { + const trimmed = trimTrailingPathSeparators(currentPath); + const absolutePath = splitAbsolutePath(trimmed); + if (absolutePath) { + if (absolutePath.segments.length === 0) return null; + if (absolutePath.segments.length === 1) return absolutePath.root; + const parentSegments = absolutePath.segments.slice(0, -1).join(absolutePath.separator); + return `${absolutePath.root}${parentSegments}${absolutePath.separator}`; + } + + const separator = preferredPathSeparator(currentPath); + const lastSeparatorIndex = getLastPathSeparatorIndex(trimmed); + if (lastSeparatorIndex < 0) return null; + if (lastSeparatorIndex === 2 && /^[a-zA-Z]:/.test(trimmed)) { + return `${trimmed.slice(0, 2)}${separator}`; + } + return trimmed.slice(0, lastSeparatorIndex + 1); +} + +export function canNavigateUp(currentPath: string): boolean { + return hasTrailingPathSeparator(currentPath) && getBrowseParentPath(currentPath) !== null; +} diff --git a/packages/shared/src/observability.test.ts b/packages/shared/src/observability.test.ts index 5e9894550a..2943bf46a4 100644 --- a/packages/shared/src/observability.test.ts +++ b/packages/shared/src/observability.test.ts @@ -1,9 +1,11 @@ import { assert, describe, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Arr from "effect/Array"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; +import * as Order from "effect/Order"; import * as Path from "effect/Path"; import * as References from "effect/References"; import * as Schema from "effect/Schema"; @@ -170,12 +172,13 @@ describe("observability", () => { } yield* sink.close(); - const matchingFiles = (yield* fileSystem.readDirectory(tempDir)) - .filter( + const matchingFiles = Arr.sort( + (yield* fileSystem.readDirectory(tempDir)).filter( (entry) => entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."), - ) - .toSorted(); + ), + Order.String, + ); assert.equal( matchingFiles.some((entry) => entry === "shared.trace.ndjson.1"),