Add mobile project onboarding flow

- Add new project screens for local folders and remote repositories
- Support source-control provider lookup, clone destination selection, and folder browsing
- Extract shared add-project path helpers and add coverage for the new runtime logic
This commit is contained in:
Julius Marminge committed 2026-05-21 18:30:24 -07:00
1 parent 1e929ad74f
commit 907f4d7501
19 files changed
+2189 -269

No files matched your search

+4
View File
@@ -18,6 +18,10 @@ export default function NewTaskLayout() {
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen
name="add-project"
options={{ animation: "slide_from_right", headerShown: false }}
/>
<Stack.Screen name="draft" options={{ animation: "slide_from_right" }} />
</Stack>
</NewTaskFlowProvider>
@@ -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 (
<Stack screenOptions={{ headerShown: false, contentStyle: sheetStyle }}>
<Stack.Screen name="index" options={{ animation: "slide_from_right" }} />
<Stack.Screen name="repository" options={{ animation: "slide_from_right" }} />
<Stack.Screen name="destination" options={{ animation: "slide_from_right" }} />
<Stack.Screen name="local" options={{ animation: "slide_from_right" }} />
</Stack>
);
}
@@ -0,0 +1,12 @@
import { Stack } from "expo-router";
import { AddProjectDestinationScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectDestinationRoute() {
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<AddProjectDestinationScreen />
</>
);
}
@@ -0,0 +1,12 @@
import { Stack } from "expo-router";
import { AddProjectSourceScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectRoute() {
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<AddProjectSourceScreen />
</>
);
}
@@ -0,0 +1,12 @@
import { Stack } from "expo-router";
import { AddProjectLocalFolderScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectLocalRoute() {
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<AddProjectLocalFolderScreen />
</>
);
}
@@ -0,0 +1,12 @@
import { Stack } from "expo-router";
import { AddProjectRepositoryScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectRepositoryRoute() {
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<AddProjectRepositoryScreen />
</>
);
}
+39 -4
View File
@@ -142,13 +142,21 @@ export default function NewTaskRoute() {
Add environment
</Text>
</Pressable>
) : null}
) : (
<Pressable
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
onPress={() => router.push("/new/add-project")}
>
<Text className="text-[13px] font-t3-bold text-primary-foreground">
Add new project
</Text>
</Pressable>
)}
</View>
) : (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{items.map((item, index) => {
const isFirst = index === 0;
const isLast = index === items.length - 1;
return (
<Link
@@ -172,8 +180,8 @@ export default function NewTaskRoute() {
borderTopColor: borderSubtleColor,
borderTopLeftRadius: isFirst ? 24 : 0,
borderTopRightRadius: isFirst ? 24 : 0,
borderBottomLeftRadius: isLast ? 24 : 0,
borderBottomRightRadius: isLast ? 24 : 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0,
}}
>
<View className="flex-row items-center justify-between gap-3">
@@ -198,6 +206,33 @@ export default function NewTaskRoute() {
</Link>
);
})}
<Pressable
className="bg-card"
style={{
paddingHorizontal: 16,
paddingVertical: 18,
borderTopWidth: 1,
borderTopColor: borderSubtleColor,
borderBottomLeftRadius: 24,
borderBottomRightRadius: 24,
}}
onPress={() => router.push("/new/add-project")}
>
<View className="flex-row items-center justify-between gap-3">
<View className="h-[22px] w-[22px] items-center justify-center rounded-full bg-subtle">
<SymbolView name="plus" size={13} tintColor={accentColor} type="monochrome" />
</View>
<View className="flex-1">
<Text className="text-[18px] font-t3-bold">Add new project</Text>
</View>
<SymbolView
name="chevron.right"
size={14}
tintColor={chevronColor}
type="monochrome"
/>
</View>
</Pressable>
</View>
)}
</ScrollView>
@@ -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 (
<Svg width={size} height={size} viewBox="0 0 16 16" fill="none">
<Path
fillRule="evenodd"
clipRule="evenodd"
d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82A7.68 7.68 0 0 1 8.02 3.86c.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8Z"
fill={props.color ?? "#24292F"}
/>
</Svg>
);
case "gitlab":
return (
<Svg width={size} height={size} viewBox="0 0 32 32" fill="none">
<Path
d="m31.46 12.78-.04-.12-4.35-11.35A1.14 1.14 0 0 0 25.94.6c-.24 0-.47.1-.66.24-.19.15-.33.36-.39.6l-2.94 9h-11.9l-2.94-9A1.14 1.14 0 0 0 6.07.58a1.15 1.15 0 0 0-1.14.72L.58 12.68l-.05.11a8.1 8.1 0 0 0 2.68 9.34l.02.01.04.03 6.63 4.97 3.28 2.48 2 1.52a1.35 1.35 0 0 0 1.62 0l2-1.52 3.28-2.48 6.67-5h.02a8.09 8.09 0 0 0 2.7-9.36Z"
fill="#E24329"
/>
<Path
d="m31.46 12.78-.04-.12a14.75 14.75 0 0 0-5.86 2.64l-9.55 7.24 6.09 4.6 6.67-5h.02a8.09 8.09 0 0 0 2.67-9.36Z"
fill="#FC6D26"
/>
<Path
d="m9.9 27.14 3.28 2.48 2 1.52a1.35 1.35 0 0 0 1.62 0l2-1.52 3.28-2.48-6.1-4.6-6.07 4.6Z"
fill="#FCA326"
/>
<Path
d="M6.44 15.3a14.71 14.71 0 0 0-5.86-2.63l-.05.12a8.1 8.1 0 0 0 2.68 9.34l.02.01.04.03 6.63 4.97 6.1-4.6-9.56-7.24Z"
fill="#FC6D26"
/>
</Svg>
);
case "azure-devops":
return (
<Svg width={size} height={size} viewBox="0 0 96 96">
<Defs>
<LinearGradient id="azure-a" x1="42.83" x2="15.79" y1="12.69" y2="92.57">
<Stop offset="0" stopColor="#114A8B" />
<Stop offset="1" stopColor="#0669BC" />
</LinearGradient>
<LinearGradient id="azure-b" x1="47.84" x2="77.52" y1="10.36" y2="89.44">
<Stop offset="0" stopColor="#3CCBF4" />
<Stop offset="1" stopColor="#2892DF" />
</LinearGradient>
</Defs>
<Path
fill="url(#azure-a)"
d="M33.34 6.54h26.04l-27.03 80.1a4.15 4.15 0 0 1-3.94 2.81H8.15a4.14 4.14 0 0 1-3.93-5.47L29.4 9.38a4.15 4.15 0 0 1 3.94-2.83z"
/>
<Path
fill="#0078D4"
d="M71.17 60.26H29.88a1.91 1.91 0 0 0-1.3 3.31l26.53 24.76a4.17 4.17 0 0 0 2.85 1.13h23.38z"
/>
<Path
fill="url(#azure-b)"
d="M66.6 9.36a4.14 4.14 0 0 0-3.93-2.82H33.65a4.15 4.15 0 0 1 3.93 2.82l25.18 74.62a4.15 4.15 0 0 1-3.93 5.48h29.02a4.15 4.15 0 0 0 3.93-5.48z"
/>
</Svg>
);
case "bitbucket":
return (
<Svg width={size} height={size} viewBox="8.4 14.39 2481.29 2231.21">
<Defs>
<LinearGradient
id="bitbucket-a"
x1="945.1094"
y1="1524.8389"
x2="944.4923"
y2="1524.1893"
gradientTransform="matrix(1996.6343 0 0 -1480.3047 -1884485.625 2258195)"
>
<Stop offset="0.18" stopColor="#0052CC" />
<Stop offset="1" stopColor="#2684FF" />
</LinearGradient>
</Defs>
<Path
fill="#2684FF"
d="M88.92,14.4C45.02,13.83,8.97,48.96,8.41,92.86c-0.06,4.61,0.28,9.22,1.02,13.77l337.48,2048.72 c8.68,51.75,53.26,89.8,105.74,90.24h1619.03c39.38,0.5,73.19-27.9,79.49-66.78l337.49-2071.78c7.03-43.34-22.41-84.17-65.75-91.2 c-4.55-0.74-9.15-1.08-13.76-1.02L88.92,14.4z M1509.99,1495.09H993.24l-139.92-731h781.89L1509.99,1495.09z"
/>
<Path
fill="url(#bitbucket-a)"
d="M2379.27,763.06h-745.5l-125.12,730.42H992.31l-609.67,723.67c19.32,16.71,43.96,26,69.5,26.21h1618.13 c39.35,0.51,73.14-27.88,79.44-66.72L2379.27,763.06z"
/>
</Svg>
);
}
}
@@ -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 (
<Text
className="px-1 text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.7 }}
>
{props.children}
</Text>
);
}
function AddProjectShell(props: {
readonly title: string;
readonly closeToNew?: boolean;
readonly children: ReactNode;
}) {
const router = useRouter();
const insets = useSafeAreaInsets();
return (
<View className="flex-1 bg-sheet">
<View className="flex-row items-center justify-between px-5 pb-1 pt-3">
<ControlPill
icon={props.closeToNew ? "xmark" : "chevron.left"}
onPress={() => router.back()}
/>
<Text className="text-[17px] font-t3-bold">{props.title}</Text>
<View className="h-11 w-11" />
</View>
<ScrollView
keyboardShouldPersistTaps="handled"
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
paddingHorizontal: 18,
paddingTop: 8,
paddingBottom: Math.max(insets.bottom, 18) + 18,
gap: 10,
}}
>
{props.children}
</ScrollView>
</View>
);
}
function ListSection(props: { readonly children: ReactNode }) {
return <View className="overflow-hidden rounded-2xl bg-card">{props.children}</View>;
}
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 (
<Pressable
disabled={props.disabled}
onPress={props.onPress}
className="bg-card px-3.5 py-2.5 active:opacity-70"
style={{
opacity: props.disabled ? 0.45 : 1,
borderTopWidth: props.isFirst ? 0 : 1,
borderTopColor: borderColor,
}}
>
<View className="flex-row items-center gap-3">
<View
className={
props.selected
? "h-7 w-7 items-center justify-center rounded-full bg-primary"
: "h-7 w-7 items-center justify-center"
}
>
{props.icon}
</View>
<View className="flex-1 gap-0.5">
<Text className="text-[15px] font-t3-bold">{props.title}</Text>
{props.subtitle ? (
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={2}>
{props.subtitle}
</Text>
) : null}
</View>
{"right" in props ? (
props.right
) : !props.disabled ? (
<SymbolView name="chevron.right" size={13} tintColor={chevronColor} type="monochrome" />
) : null}
</View>
</Pressable>
);
}
function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
const { serverConfigByEnvironmentId } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
return useMemo<ReadonlyArray<EnvironmentOption>>(() => {
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<EnvironmentOption>;
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 (
<View className="items-center gap-3 rounded-2xl bg-card px-5 py-8">
<Text className="text-center text-[17px] font-t3-bold">No environments connected</Text>
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
Add an environment before adding a project.
</Text>
<Pressable
onPress={() => router.replace("/connections/new")}
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
>
<Text className="text-[13px] font-t3-bold text-primary-foreground">Add environment</Text>
</Pressable>
</View>
);
}
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" ? (
<SymbolView name="link" size={17} tintColor={iconColor} type="monochrome" />
) : (
<SourceControlIcon kind={props.source} size={18} color={String(iconColor)} />
);
if (!props.ready) {
return (
<ListRow title={title} subtitle={props.hint} icon={icon} disabled isFirst={props.isFirst} />
);
}
return (
<ListRow
title={title}
subtitle={subtitle}
icon={icon}
isFirst={props.isFirst}
onPress={() =>
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 (
<AddProjectShell title="Add project" closeToNew>
{environmentOptions.length === 0 ? <EmptyEnvironmentState /> : null}
{environmentOptions.length > 1 ? (
<>
<SectionTitle>Connected environments</SectionTitle>
<ListSection>
{environmentOptions.map((environment, index) => (
<ListRow
key={environment.environmentId}
title={environment.label}
subtitle={environment.environmentId}
icon={
<SymbolView
name="server.rack"
size={17}
tintColor={iconColor}
type="monochrome"
/>
}
selected={environment.environmentId === selectedEnvironment?.environmentId}
isFirst={index === 0}
right={
environment.environmentId === selectedEnvironment?.environmentId ? (
<SymbolView
name="checkmark"
size={14}
tintColor={iconColor}
type="monochrome"
/>
) : null
}
onPress={() => setSelectedEnvironmentId(environment.environmentId)}
/>
))}
</ListSection>
</>
) : null}
{selectedEnvironment ? (
<>
<SectionTitle>Sources</SectionTitle>
<ListSection>
<ListRow
title="Local folder"
subtitle="Browse a folder on disk"
icon={
<SymbolView
name="folder.badge.plus"
size={17}
tintColor={iconColor}
type="monochrome"
/>
}
isFirst
onPress={() =>
router.push({
pathname: "/new/add-project/local",
params: { environmentId: selectedEnvironment.environmentId },
})
}
/>
{(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(
(candidate) => (
<SourceControlRow
key={candidate}
source={candidate}
selectedEnvironmentId={selectedEnvironment.environmentId}
ready={readiness[candidate].ready}
hint={
readiness[candidate].ready
? addProjectRemoteSourcePathHint(candidate)
: (readiness[candidate].hint ?? "")
}
isFirst={false}
/>
),
)}
</ListSection>
{discoveryState.isPending ? <ActivityIndicator color={accentColor} /> : null}
</>
) : null}
</AddProjectShell>
);
}
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<string | null>(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 (
<AddProjectShell title={source === "url" ? "Git URL" : addProjectRemoteSourceLabel(source)}>
{error ? <ErrorBanner message={error} /> : null}
<TextInput
className="h-12 min-h-12 rounded-xl px-3 py-0 text-[15px] leading-[20px]"
value={repositoryInput}
onChangeText={setRepositoryInput}
autoCapitalize="none"
autoCorrect={false}
placeholder={
source === "url"
? "https://github.com/org/repo.git"
: addProjectRemoteSourcePathHint(source)
}
returnKeyType="next"
onSubmitEditing={() => void lookupRepository()}
/>
<Pressable
disabled={isSubmitting || repositoryInput.trim().length === 0}
onPress={() => void lookupRepository()}
className="h-11 items-center justify-center rounded-full bg-primary active:opacity-70 disabled:opacity-45"
>
{isSubmitting ? (
<ActivityIndicator color={String(primaryForeground)} />
) : (
<Text className="text-[14px] font-t3-bold text-primary-foreground">
{source === "url" ? "Continue" : "Lookup repository"}
</Text>
)}
</Pressable>
</AddProjectShell>
);
}
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 (
<>
<SectionTitle>Browse folders</SectionTitle>
{browseState.error ? <ErrorBanner message={browseState.error} /> : null}
<ListSection>
{browseState.isPending && browseState.data === null ? (
<View className="items-center py-5">
<ActivityIndicator color={accentColor} />
</View>
) : null}
{canBrowseUpPath ? (
<ListRow
title=".."
icon={
<SymbolView
name="arrow.turn.left.up"
size={17}
tintColor={accentColor}
type="monochrome"
/>
}
isFirst
right={null}
onPress={() => {
if (parentBrowsePath) props.setPathInput(parentBrowsePath);
}}
/>
) : null}
{visibleBrowseEntries.map((entry, index) => (
<ListRow
key={entry.fullPath}
title={entry.name}
icon={<SymbolView name="folder" size={17} tintColor={accentColor} type="monochrome" />}
isFirst={index === 0 && !canBrowseUpPath}
right={null}
onPress={() =>
props.setPathInput(
browseDirectoryPath.length > 0
? appendBrowsePathSegment(browseDirectoryPath, entry.name)
: ensureBrowseDirectoryPath(entry.fullPath),
)
}
/>
))}
</ListSection>
</>
);
}
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<string | null>(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 (
<AddProjectShell title="Local folder">
{error ? <ErrorBanner message={error} /> : null}
{environment ? (
<>
<TextInput
className="h-12 min-h-12 rounded-xl px-3 py-0 text-[15px] leading-[20px]"
value={pathInput}
onChangeText={setPathInput}
autoCapitalize="none"
autoCorrect={false}
placeholder="~/projects/my-app"
returnKeyType="done"
onSubmitEditing={() => void submitPath()}
/>
<Pressable
disabled={isSubmitting}
onPress={() => void submitPath()}
className="h-11 items-center justify-center rounded-full bg-primary active:opacity-70"
>
{isSubmitting ? (
<ActivityIndicator color={String(primaryForeground)} />
) : (
<Text className="text-[14px] font-t3-bold text-primary-foreground">Add project</Text>
)}
</Pressable>
<FolderBrowser
environment={environment}
pathInput={pathInput}
setPathInput={setPathInput}
/>
</>
) : (
<EmptyEnvironmentState />
)}
</AddProjectShell>
);
}
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<string | null>(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 (
<AddProjectShell title="Clone destination">
{error ? <ErrorBanner message={error} /> : null}
{repositoryTitle ? (
<View className="rounded-xl bg-card px-3.5 py-2.5">
<Text className="text-[14px] font-t3-bold">{repositoryTitle}</Text>
<Text className="mt-0.5 text-[12px] text-foreground-muted" numberOfLines={2}>
{remoteUrl}
</Text>
</View>
) : null}
{environment ? (
<>
<TextInput
className="h-12 min-h-12 rounded-xl px-3 py-0 text-[15px] leading-[20px]"
value={pathInput}
onChangeText={setPathInput}
autoCapitalize="none"
autoCorrect={false}
placeholder="~/projects/my-app"
returnKeyType="done"
onSubmitEditing={() => void submitPath()}
/>
<Pressable
disabled={isSubmitting || !remoteUrl}
onPress={() => void submitPath()}
className="h-11 items-center justify-center rounded-full bg-primary active:opacity-70 disabled:opacity-45"
>
{isSubmitting ? (
<ActivityIndicator color={String(primaryForeground)} />
) : (
<Text className="text-[14px] font-t3-bold text-primary-foreground">
Clone project
</Text>
)}
</Pressable>
<FolderBrowser
environment={environment}
pathInput={pathInput}
setPathInput={setPathInput}
/>
</>
) : (
<EmptyEnvironmentState />
)}
</AddProjectShell>
);
}
@@ -438,14 +438,18 @@ export function NewTaskDraftScreen(props: {
</View>
<View style={{ flex: 1, paddingHorizontal: 20, paddingTop: 8 }}>
<TextInputWrapper onPaste={(payload) => void handleNativePaste(payload)}>
<TextInputWrapper
onPaste={(payload) => void handleNativePaste(payload)}
style={{ flex: 1 }}
>
<TextInput
multiline
value={flow.prompt}
onChangeText={flow.setPrompt}
placeholder={`Describe a coding task in ${selectedProject.title}`}
textAlignVertical="top"
className="flex-1 border-0 bg-transparent text-[18px] leading-[28px]"
className="h-full flex-1 border-0 bg-transparent text-[18px] leading-[28px]"
style={{ flex: 1 }}
/>
</TextInputWrapper>
</View>
@@ -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<EnvironmentId>({
getRegistry: () => appAtomRegistry,
getClient: (environmentId) => getEnvironmentClient(environmentId)?.filesystem ?? null,
subscribeClientChanges: subscribeEnvironmentConnections,
});
function filesystemBrowseTargetForEnvironment(
environmentId: EnvironmentId | null,
input: FilesystemBrowseInput | null,
): FilesystemBrowseTarget<EnvironmentId> {
return { key: environmentId, input };
}
export function refreshFilesystemBrowseForEnvironment(
environmentId: EnvironmentId | null,
input: FilesystemBrowseInput | null,
client?: FilesystemBrowseClient | null,
): Promise<FilesystemBrowseResult | null> {
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;
}
+17 -259
View File
@@ -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<T extends { cwd: string }>(
projects: ReadonlyArray<T>,
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";
@@ -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",
},
});
});
});
+224
View File
@@ -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<AddProjectRemoteSource> = [
"url",
"github",
"gitlab",
"bitbucket",
"azure-devops",
];
export const ADD_PROJECT_REMOTE_PROVIDER_SOURCES: ReadonlyArray<AddProjectRemoteProviderKind> = [
"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<AddProjectRemoteProviderKind> {
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<EnvironmentScopedProjectShell>;
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<OrchestrationCommand, { type: "project.create" }> {
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,
};
}
@@ -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<void> {
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<FilesystemBrowseResult>((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);
});
@@ -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<TKey extends string = string> {
readonly key: TKey | null;
readonly input: FilesystemBrowseInput | null;
}
export interface FilesystemBrowseClient {
readonly browse: (input: FilesystemBrowseInput) => Promise<FilesystemBrowseResult>;
}
interface WatchedEntry {
refCount: number;
teardown: () => void;
}
export const EMPTY_FILESYSTEM_BROWSE_STATE = Object.freeze<FilesystemBrowseState>({
data: null,
error: null,
isPending: false,
});
const INITIAL_FILESYSTEM_BROWSE_STATE = Object.freeze<FilesystemBrowseState>({
data: null,
error: null,
isPending: true,
});
const knownFilesystemBrowseKeys = new Set<string>();
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<TKey extends string>(
target: FilesystemBrowseTarget<TKey>,
): 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<TKey extends string = string> {
readonly getRegistry: () => AtomRegistry.AtomRegistry;
readonly getClient: (key: TKey) => FilesystemBrowseClient | null;
readonly subscribeClientChanges?: (listener: () => void) => () => void;
readonly staleTimeMs?: number;
readonly idleTtlMs?: number;
}
export function createFilesystemBrowseManager<TKey extends string = string>(
config: FilesystemBrowseManagerConfig<TKey>,
) {
const refreshInFlight = new Map<
string,
{
readonly client: FilesystemBrowseClient;
readonly promise: Promise<FilesystemBrowseResult | null>;
}
>();
const refreshVersions = new Map<string, number>();
const watched = new Map<string, WatchedEntry>();
const refreshTargets = new Map<string, FilesystemBrowseTarget<TKey>>();
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<TKey>,
client?: FilesystemBrowseClient,
): Promise<FilesystemBrowseResult | null> {
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<FilesystemBrowseResult | null>;
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<TKey>): 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<TKey>): FilesystemBrowseState {
const targetKey = getFilesystemBrowseTargetKey(target);
if (targetKey === null) {
return EMPTY_FILESYSTEM_BROWSE_STATE;
}
return config.getRegistry().get(filesystemBrowseStateAtom(targetKey));
}
function watch(
target: FilesystemBrowseTarget<TKey>,
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<TKey>,
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,
};
}
+3
View File
@@ -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";
+221
View File
@@ -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<T extends { workspaceRoot?: string; cwd?: string }>(
projects: ReadonlyArray<T>,
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;
}
+7 -4
View File
@@ -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"),