Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7294763bfe |
No files matched your search
@@ -44,7 +44,7 @@ function resolveAppVariant(value: string | undefined): AppVariant {
|
||||
case "production":
|
||||
return value;
|
||||
default:
|
||||
return "production";
|
||||
return "development";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,10 +18,6 @@ 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>
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { Stack } from "expo-router";
|
||||
|
||||
import { AddProjectDestinationScreen } from "../../../features/projects/AddProjectScreen";
|
||||
|
||||
export default function AddProjectDestinationRoute() {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={{ headerShown: false }} />
|
||||
<AddProjectDestinationScreen />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { Stack } from "expo-router";
|
||||
|
||||
import { AddProjectSourceScreen } from "../../../features/projects/AddProjectScreen";
|
||||
|
||||
export default function AddProjectRoute() {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={{ headerShown: false }} />
|
||||
<AddProjectSourceScreen />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { Stack } from "expo-router";
|
||||
|
||||
import { AddProjectLocalFolderScreen } from "../../../features/projects/AddProjectScreen";
|
||||
|
||||
export default function AddProjectLocalRoute() {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={{ headerShown: false }} />
|
||||
<AddProjectLocalFolderScreen />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { Stack } from "expo-router";
|
||||
|
||||
import { AddProjectRepositoryScreen } from "../../../features/projects/AddProjectScreen";
|
||||
|
||||
export default function AddProjectRepositoryRoute() {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={{ headerShown: false }} />
|
||||
<AddProjectRepositoryScreen />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -142,21 +142,13 @@ export default function NewTaskRoute() {
|
||||
Add environment
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : (
|
||||
<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>
|
||||
)}
|
||||
) : null}
|
||||
</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
|
||||
@@ -180,8 +172,8 @@ export default function NewTaskRoute() {
|
||||
borderTopColor: borderSubtleColor,
|
||||
borderTopLeftRadius: isFirst ? 24 : 0,
|
||||
borderTopRightRadius: isFirst ? 24 : 0,
|
||||
borderBottomLeftRadius: 0,
|
||||
borderBottomRightRadius: 0,
|
||||
borderBottomLeftRadius: isLast ? 24 : 0,
|
||||
borderBottomRightRadius: isLast ? 24 : 0,
|
||||
}}
|
||||
>
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
@@ -206,33 +198,6 @@ 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>
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,818 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,12 @@ import {
|
||||
} from "../diffs/nativeReviewDiffHighlighter";
|
||||
import type { NativeReviewDiffRow } from "../diffs/nativeReviewDiffSurface";
|
||||
import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";
|
||||
import { resolveReviewHighlighterEnginePreference } from "./reviewHighlighterEngine";
|
||||
|
||||
const CONFIGURED_ENGINE: NativeReviewDiffHighlightEngine = resolveReviewHighlighterEnginePreference(
|
||||
process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ??
|
||||
(process.env.NODE_ENV === "test" ? "javascript" : "native"),
|
||||
);
|
||||
|
||||
interface NativeReviewVisibleRange {
|
||||
readonly firstRowIndex: number;
|
||||
@@ -68,7 +74,7 @@ export function useNativeReviewDiffHighlighting(input: {
|
||||
|
||||
const abortController = new AbortController();
|
||||
const requestRange = visibleRangeRef.current;
|
||||
const engine: NativeReviewDiffHighlightEngine = "native";
|
||||
const engine: NativeReviewDiffHighlightEngine = CONFIGURED_ENGINE;
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import { DEFAULT_TERMINAL_ID, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { memo, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { getEnvironmentClient } from "../../state/environment-session-registry";
|
||||
import {
|
||||
attachTerminalSession,
|
||||
useTerminalSession,
|
||||
useTerminalSessionTarget,
|
||||
} from "../../state/use-terminal-session";
|
||||
import { TerminalSurface } from "./NativeTerminalSurface";
|
||||
import { hasNativeTerminalSurface } from "./nativeTerminalModule";
|
||||
import { terminalDebugLog } from "./terminalDebugLog";
|
||||
|
||||
interface ThreadTerminalPanelProps {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly cwd: string;
|
||||
readonly worktreePath: string | null;
|
||||
readonly visible: boolean;
|
||||
readonly onClose: () => void;
|
||||
}
|
||||
|
||||
const DEFAULT_TERMINAL_COLS = 80;
|
||||
const DEFAULT_TERMINAL_ROWS = 24;
|
||||
|
||||
export const ThreadTerminalPanel = memo(function ThreadTerminalPanel(
|
||||
props: ThreadTerminalPanelProps,
|
||||
) {
|
||||
const nativeTerminalAvailable = hasNativeTerminalSurface();
|
||||
const terminalId = DEFAULT_TERMINAL_ID;
|
||||
const target = useTerminalSessionTarget({
|
||||
environmentId: props.environmentId,
|
||||
threadId: props.threadId,
|
||||
terminalId,
|
||||
});
|
||||
const terminal = useTerminalSession(target);
|
||||
const [lastGridSize, setLastGridSize] = useState({
|
||||
cols: DEFAULT_TERMINAL_COLS,
|
||||
rows: DEFAULT_TERMINAL_ROWS,
|
||||
});
|
||||
const lastGridSizeRef = useRef(lastGridSize);
|
||||
lastGridSizeRef.current = lastGridSize;
|
||||
|
||||
const terminalKey = `${props.environmentId}:${props.threadId}:${terminalId}`;
|
||||
const isRunning = terminal.status === "running" || terminal.status === "starting";
|
||||
|
||||
useEffect(() => {
|
||||
if (!props.visible) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(props.environmentId);
|
||||
if (!client) {
|
||||
terminalDebugLog("panel:attach-skip", {
|
||||
reason: "no-environment-client",
|
||||
environmentId: props.environmentId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
terminalDebugLog("panel:attach", {
|
||||
environmentId: props.environmentId,
|
||||
threadId: props.threadId,
|
||||
terminalId,
|
||||
});
|
||||
|
||||
return attachTerminalSession({
|
||||
environmentId: props.environmentId,
|
||||
client,
|
||||
terminal: {
|
||||
threadId: props.threadId,
|
||||
terminalId,
|
||||
cwd: props.cwd,
|
||||
worktreePath: props.worktreePath,
|
||||
cols: lastGridSizeRef.current.cols,
|
||||
rows: lastGridSizeRef.current.rows,
|
||||
},
|
||||
});
|
||||
}, [
|
||||
props.cwd,
|
||||
props.environmentId,
|
||||
props.threadId,
|
||||
props.worktreePath,
|
||||
props.visible,
|
||||
terminalId,
|
||||
]);
|
||||
|
||||
const handleInput = useCallback(
|
||||
(data: string) => {
|
||||
const client = getEnvironmentClient(props.environmentId);
|
||||
if (!client || !isRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
void client.terminal.write({
|
||||
threadId: props.threadId,
|
||||
terminalId,
|
||||
data,
|
||||
});
|
||||
},
|
||||
[isRunning, props.environmentId, props.threadId, terminalId],
|
||||
);
|
||||
|
||||
const handleResize = useCallback(
|
||||
(size: { readonly cols: number; readonly rows: number }) => {
|
||||
if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLastGridSize(size);
|
||||
const client = getEnvironmentClient(props.environmentId);
|
||||
if (!client || !isRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
void client.terminal.resize({
|
||||
threadId: props.threadId,
|
||||
terminalId,
|
||||
cols: size.cols,
|
||||
rows: size.rows,
|
||||
});
|
||||
},
|
||||
[
|
||||
isRunning,
|
||||
lastGridSize.cols,
|
||||
lastGridSize.rows,
|
||||
props.environmentId,
|
||||
props.threadId,
|
||||
terminalId,
|
||||
],
|
||||
);
|
||||
|
||||
if (!props.visible) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="absolute inset-x-3 bottom-28 top-28 overflow-hidden rounded-[8px] border border-white/10 bg-neutral-950 shadow-2xl">
|
||||
<View className="flex-row items-center justify-between border-b border-white/10 px-3 py-2">
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="font-t3-bold text-[13px] text-neutral-100" numberOfLines={1}>
|
||||
Terminal
|
||||
</Text>
|
||||
<Text className="text-[11px] text-neutral-500" numberOfLines={1}>
|
||||
{nativeTerminalAvailable ? "Native Ghostty surface" : "Text fallback active"}
|
||||
</Text>
|
||||
</View>
|
||||
<View className="flex-row items-center gap-2">
|
||||
{terminal.error ? (
|
||||
<Text className="max-w-44 text-right text-[11px] text-red-300" numberOfLines={1}>
|
||||
{terminal.error}
|
||||
</Text>
|
||||
) : null}
|
||||
<Pressable
|
||||
className="h-8 w-8 items-center justify-center rounded-[8px] bg-white/10"
|
||||
onPress={props.onClose}
|
||||
>
|
||||
<SymbolView name="xmark" size={13} tintColor="#e5e5e5" type="monochrome" />
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
<TerminalSurface
|
||||
terminalKey={terminalKey}
|
||||
buffer={terminal.buffer}
|
||||
isRunning={isRunning}
|
||||
onInput={handleInput}
|
||||
onResize={handleResize}
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
@@ -725,7 +725,6 @@ export function ThreadTerminalRouteScreen() {
|
||||
router,
|
||||
selectedThread?.environmentId,
|
||||
selectedThread?.id,
|
||||
selectedThreadDetail?.worktreePath,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
terminalId,
|
||||
]);
|
||||
|
||||
@@ -438,18 +438,14 @@ export function NewTaskDraftScreen(props: {
|
||||
</View>
|
||||
|
||||
<View style={{ flex: 1, paddingHorizontal: 20, paddingTop: 8 }}>
|
||||
<TextInputWrapper
|
||||
onPaste={(payload) => void handleNativePaste(payload)}
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
<TextInputWrapper onPaste={(payload) => void handleNativePaste(payload)}>
|
||||
<TextInput
|
||||
multiline
|
||||
value={flow.prompt}
|
||||
onChangeText={flow.setPrompt}
|
||||
placeholder={`Describe a coding task in ${selectedProject.title}`}
|
||||
textAlignVertical="top"
|
||||
className="h-full flex-1 border-0 bg-transparent text-[18px] leading-[28px]"
|
||||
style={{ flex: 1 }}
|
||||
className="flex-1 border-0 bg-transparent text-[18px] leading-[28px]"
|
||||
/>
|
||||
</TextInputWrapper>
|
||||
</View>
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -2602,9 +2602,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
cwd: "/tmp/repo",
|
||||
},
|
||||
layers: {
|
||||
vcsDriver: {
|
||||
isInsideWorkTree: () => Effect.succeed(true),
|
||||
},
|
||||
gitManager: {
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
invalidateRemoteStatus: () => Effect.void,
|
||||
@@ -2741,21 +2738,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
createRef: (input) => Effect.succeed({ refName: input.refName }),
|
||||
switchRef: (input) => Effect.succeed({ refName: input.refName }),
|
||||
},
|
||||
vcsStatusBroadcaster: {
|
||||
refreshStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
}),
|
||||
},
|
||||
reviewService: {
|
||||
getDiffPreview: (input) =>
|
||||
Effect.succeed({
|
||||
|
||||
@@ -16,15 +16,9 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { LegendList, type LegendListRef } from "@legendapp/list/react";
|
||||
import { FileDiff } from "@pierre/diffs/react";
|
||||
import { deriveTimelineEntries, formatElapsed } from "../../session-logic";
|
||||
import { type TurnDiffSummary } from "../../types";
|
||||
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
|
||||
import {
|
||||
getRenderablePatch,
|
||||
resolveDiffThemeName,
|
||||
resolveFileDiffPath,
|
||||
} from "../../lib/diffRendering";
|
||||
import ChatMarkdown from "../ChatMarkdown";
|
||||
import {
|
||||
BotIcon,
|
||||
@@ -73,11 +67,6 @@ import {
|
||||
} from "./userMessageTerminalContexts";
|
||||
import { SkillInlineText } from "./SkillInlineText";
|
||||
import { formatWorkspaceRelativePath } from "../../filePathDisplay";
|
||||
import {
|
||||
buildReviewCommentRenderablePatch,
|
||||
parseReviewCommentMessageSegments,
|
||||
type ReviewCommentContext,
|
||||
} from "../../reviewCommentContext";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Context — shared state consumed by every row component via Context.
|
||||
@@ -848,25 +837,6 @@ const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
terminalContexts: ParsedTerminalContextEntry[];
|
||||
skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
|
||||
}) {
|
||||
const reviewCommentSegments = parseReviewCommentMessageSegments(props.text);
|
||||
if (reviewCommentSegments.some((segment) => segment.kind === "review-comment")) {
|
||||
return (
|
||||
<div className="space-y-3 text-sm leading-relaxed text-foreground">
|
||||
{reviewCommentSegments.map((segment) =>
|
||||
segment.kind === "text" ? (
|
||||
segment.text.trim().length > 0 ? (
|
||||
<div key={segment.id} className="whitespace-pre-wrap wrap-break-word">
|
||||
<SkillInlineText text={segment.text.trim()} skills={props.skills} />
|
||||
</div>
|
||||
) : null
|
||||
) : (
|
||||
<UserMessageReviewCommentCard key={segment.comment.id} comment={segment.comment} />
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.terminalContexts.length > 0) {
|
||||
const hasEmbeddedInlineLabels = textContainsInlineTerminalContextLabels(
|
||||
props.text,
|
||||
@@ -960,49 +930,6 @@ const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
);
|
||||
});
|
||||
|
||||
function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentContext }) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const renderablePatch = getRenderablePatch(
|
||||
buildReviewCommentRenderablePatch(comment),
|
||||
`review-comment:${comment.id}`,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-2 rounded-lg border border-border/70 bg-background/70 p-3">
|
||||
<div className="space-y-1">
|
||||
<div className="text-xs font-medium text-foreground">
|
||||
{formatWorkspaceRelativePath(comment.filePath, ctx.workspaceRoot)}
|
||||
</div>
|
||||
<div className="text-[11px] text-muted-foreground">
|
||||
{comment.sectionTitle} · {comment.rangeLabel}
|
||||
</div>
|
||||
</div>
|
||||
{comment.text.length > 0 && (
|
||||
<div className="whitespace-pre-wrap wrap-break-word text-sm">
|
||||
<SkillInlineText text={comment.text} skills={ctx.skills} />
|
||||
</div>
|
||||
)}
|
||||
{renderablePatch?.kind === "files" &&
|
||||
renderablePatch.files.map((fileDiff) => (
|
||||
<FileDiff
|
||||
key={resolveFileDiffPath(fileDiff)}
|
||||
fileDiff={fileDiff}
|
||||
options={{
|
||||
collapsed: false,
|
||||
diffStyle: "unified",
|
||||
theme: resolveDiffThemeName(ctx.resolvedTheme),
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
{renderablePatch?.kind === "raw" && (
|
||||
<pre className="overflow-x-auto rounded-md bg-muted/40 p-2 text-xs">
|
||||
{renderablePatch.text}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Structural sharing — reuse old row references when data hasn't changed
|
||||
// so LegendList (and React) can skip re-rendering unchanged items.
|
||||
|
||||
@@ -239,28 +239,7 @@ describe("remote environment api", () => {
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
bearerToken: "bearer-token",
|
||||
}),
|
||||
).resolves.toBe("wss://remote.example.com/?wsToken=ws-token");
|
||||
});
|
||||
|
||||
it("preserves the caller-provided websocket path when minting a token", async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
token: "ws-token",
|
||||
expiresAt: "2026-05-01T12:05:00.000Z",
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
);
|
||||
globalThis.fetch = fetchMock as typeof fetch;
|
||||
|
||||
await expect(
|
||||
resolveRemoteWebSocketConnectionUrl({
|
||||
wsBaseUrl: "wss://remote.example.com/custom/socket?existing=1",
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
bearerToken: "bearer-token",
|
||||
}),
|
||||
).resolves.toBe("wss://remote.example.com/custom/socket?existing=1&wsToken=ws-token");
|
||||
).resolves.toBe("wss://remote.example.com/ws?wsToken=ws-token");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -72,7 +72,6 @@ function createTestClient() {
|
||||
clear: vi.fn(async () => undefined),
|
||||
restart: vi.fn(async () => undefined),
|
||||
close: vi.fn(async () => undefined),
|
||||
onEvent: vi.fn(() => () => undefined),
|
||||
onMetadata: vi.fn(() => () => undefined),
|
||||
},
|
||||
projects: {
|
||||
|
||||
@@ -269,17 +269,6 @@ describe("retainThreadDetailSubscription", () => {
|
||||
mockCreateEnvironmentConnection.mockImplementation((input) => {
|
||||
const reconnect = vi.fn(async () => undefined);
|
||||
mockConnectionReconnects.push(reconnect);
|
||||
queueMicrotask(() => {
|
||||
input.onConfigSnapshot?.({
|
||||
environment: {
|
||||
environmentId: input.knownEnvironment.environmentId,
|
||||
label: input.knownEnvironment.label,
|
||||
platform: { os: "darwin", arch: "arm64" },
|
||||
serverVersion: "0.0.0-test",
|
||||
capabilities: { repositoryIdentity: true },
|
||||
},
|
||||
});
|
||||
});
|
||||
return {
|
||||
kind: input.kind,
|
||||
environmentId: input.knownEnvironment.environmentId,
|
||||
@@ -449,13 +438,13 @@ describe("retainThreadDetailSubscription", () => {
|
||||
const stop = startEnvironmentConnectionService(new QueryClient());
|
||||
savedEnvironmentRegistryListener?.();
|
||||
await vi.waitFor(() => {
|
||||
expect(mockCreateEnvironmentConnection).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
listEnvironmentConnections().some(
|
||||
(connection) => connection.environmentId === environmentId,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
const createConnectionCallsBeforeReconnect = mockCreateEnvironmentConnection.mock.calls.length;
|
||||
|
||||
const release = retainThreadDetailSubscription(environmentId, threadId);
|
||||
expect(mockSubscribeThread).toHaveBeenCalledTimes(1);
|
||||
@@ -470,9 +459,7 @@ describe("retainThreadDetailSubscription", () => {
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
await reconnectPromise;
|
||||
await vi.waitFor(() => {
|
||||
expect(mockCreateEnvironmentConnection).toHaveBeenCalledTimes(
|
||||
createConnectionCallsBeforeReconnect + 1,
|
||||
);
|
||||
expect(mockCreateEnvironmentConnection).toHaveBeenCalledTimes(3);
|
||||
expect(mockSubscribeThread).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
@@ -499,33 +486,6 @@ describe("retainThreadDetailSubscription", () => {
|
||||
|
||||
const { resetEnvironmentServiceForTests, startEnvironmentConnectionService } =
|
||||
await import("./service");
|
||||
mockCreateEnvironmentConnection.mockImplementation((input) => {
|
||||
const reconnect = vi.fn(async () => undefined);
|
||||
mockConnectionReconnects.push(reconnect);
|
||||
queueMicrotask(() => {
|
||||
input.onConfigSnapshot?.({
|
||||
environment: {
|
||||
environmentId: input.knownEnvironment.environmentId,
|
||||
label: input.knownEnvironment.label,
|
||||
platform: { os: "darwin", arch: "arm64" },
|
||||
serverVersion: "0.0.0-test",
|
||||
capabilities: { repositoryIdentity: true },
|
||||
},
|
||||
});
|
||||
});
|
||||
return {
|
||||
kind: input.kind,
|
||||
environmentId: input.knownEnvironment.environmentId,
|
||||
knownEnvironment: input.knownEnvironment,
|
||||
client: {
|
||||
...input.client,
|
||||
isHeartbeatFresh: vi.fn(() => true),
|
||||
},
|
||||
ensureBootstrapped: vi.fn(async () => undefined),
|
||||
reconnect,
|
||||
dispose: vi.fn(async () => undefined),
|
||||
};
|
||||
});
|
||||
|
||||
const stop = startEnvironmentConnectionService(new QueryClient());
|
||||
expect(mockConnectionReconnects).toHaveLength(1);
|
||||
|
||||
@@ -1,17 +1,259 @@
|
||||
export {
|
||||
appendBrowsePathSegment,
|
||||
canNavigateUp,
|
||||
ensureBrowseDirectoryPath,
|
||||
findProjectByPath,
|
||||
getBrowseDirectoryPath,
|
||||
getBrowseLeafPathSegment,
|
||||
getBrowseParentPath,
|
||||
hasTrailingPathSeparator,
|
||||
inferProjectTitleFromPath,
|
||||
isExplicitRelativeProjectPath,
|
||||
isFilesystemBrowseQuery,
|
||||
isUnsupportedWindowsProjectPath,
|
||||
normalizeProjectPathForComparison,
|
||||
normalizeProjectPathForDispatch,
|
||||
resolveProjectPathForDispatch,
|
||||
} from "@t3tools/client-runtime";
|
||||
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;
|
||||
}
|
||||
@@ -31,11 +31,8 @@ function createWsRpcProtocolLayer(
|
||||
clearAllTrackedRpcRequests();
|
||||
recordWsConnectionErrored(message);
|
||||
},
|
||||
onClose: (details, context) => {
|
||||
onClose: (details) => {
|
||||
clearAllTrackedRpcRequests();
|
||||
if (context.intentional) {
|
||||
return;
|
||||
}
|
||||
recordWsConnectionClosed(details);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
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",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,224 +0,0 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
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);
|
||||
});
|
||||
@@ -1,339 +0,0 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -2,9 +2,6 @@ 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";
|
||||
|
||||
@@ -1,221 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -242,24 +242,16 @@ function latestTimestamp(left: string | null, right: string | null): string | nu
|
||||
return Date.parse(left) >= Date.parse(right) ? left : right;
|
||||
}
|
||||
|
||||
function isBufferTerminalStatus(buffer: TerminalBufferState): boolean {
|
||||
return (
|
||||
buffer.version > 0 &&
|
||||
(buffer.status === "exited" || buffer.status === "closed" || buffer.status === "error")
|
||||
);
|
||||
}
|
||||
|
||||
function combineSessionState(
|
||||
summary: TerminalSummary | null,
|
||||
buffer: TerminalBufferState,
|
||||
): TerminalSessionState {
|
||||
const bufferTerminal = isBufferTerminalStatus(buffer);
|
||||
return {
|
||||
summary,
|
||||
buffer: buffer.buffer,
|
||||
status: bufferTerminal ? buffer.status : (summary?.status ?? buffer.status),
|
||||
status: summary?.status ?? buffer.status,
|
||||
error: buffer.error,
|
||||
hasRunningSubprocess: bufferTerminal ? false : (summary?.hasRunningSubprocess ?? false),
|
||||
hasRunningSubprocess: summary?.hasRunningSubprocess ?? false,
|
||||
updatedAt: latestTimestamp(summary?.updatedAt ?? null, buffer.updatedAt),
|
||||
version: buffer.version,
|
||||
};
|
||||
|
||||
@@ -43,13 +43,12 @@ describe("createWsRpcClient", () => {
|
||||
reconnect: vi.fn(async () => {
|
||||
order.push("reconnect");
|
||||
}),
|
||||
isHeartbeatFresh: vi.fn(() => true),
|
||||
request: vi.fn(),
|
||||
requestStream: vi.fn(),
|
||||
subscribe: vi.fn(() => () => undefined),
|
||||
} satisfies Pick<
|
||||
WsTransport,
|
||||
"dispose" | "isHeartbeatFresh" | "reconnect" | "request" | "requestStream" | "subscribe"
|
||||
"dispose" | "reconnect" | "request" | "requestStream" | "subscribe"
|
||||
>;
|
||||
|
||||
const client = createWsRpcClient(transport as unknown as WsTransport, {
|
||||
@@ -62,26 +61,6 @@ describe("createWsRpcClient", () => {
|
||||
expect(order).toEqual(["beforeReconnect", "reconnect"]);
|
||||
});
|
||||
|
||||
it("delegates heartbeat freshness to the transport", () => {
|
||||
const isHeartbeatFresh = vi.fn(() => true);
|
||||
const transport = {
|
||||
dispose: vi.fn(async () => undefined),
|
||||
reconnect: vi.fn(async () => undefined),
|
||||
isHeartbeatFresh,
|
||||
request: vi.fn(),
|
||||
requestStream: vi.fn(),
|
||||
subscribe: vi.fn(() => () => undefined),
|
||||
} satisfies Pick<
|
||||
WsTransport,
|
||||
"dispose" | "isHeartbeatFresh" | "reconnect" | "request" | "requestStream" | "subscribe"
|
||||
>;
|
||||
|
||||
const client = createWsRpcClient(transport as unknown as WsTransport);
|
||||
|
||||
expect(client.isHeartbeatFresh()).toBe(true);
|
||||
expect(isHeartbeatFresh).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("reduces vcs status stream events into flat status snapshots", () => {
|
||||
const subscribe = vi.fn(<TValue>(_connect: unknown, listener: (value: TValue) => void) => {
|
||||
for (const event of [
|
||||
@@ -110,13 +89,12 @@ describe("createWsRpcClient", () => {
|
||||
const transport = {
|
||||
dispose: vi.fn(async () => undefined),
|
||||
reconnect: vi.fn(async () => undefined),
|
||||
isHeartbeatFresh: vi.fn(() => true),
|
||||
request: vi.fn(),
|
||||
requestStream: vi.fn(),
|
||||
subscribe,
|
||||
} satisfies Pick<
|
||||
WsTransport,
|
||||
"dispose" | "isHeartbeatFresh" | "reconnect" | "request" | "requestStream" | "subscribe"
|
||||
"dispose" | "reconnect" | "request" | "requestStream" | "subscribe"
|
||||
>;
|
||||
|
||||
const client = createWsRpcClient(transport as unknown as WsTransport);
|
||||
@@ -156,13 +134,12 @@ describe("createWsRpcClient", () => {
|
||||
const transport = {
|
||||
dispose: vi.fn(async () => undefined),
|
||||
reconnect: vi.fn(async () => undefined),
|
||||
isHeartbeatFresh: vi.fn(() => true),
|
||||
request: vi.fn(),
|
||||
requestStream: vi.fn(),
|
||||
subscribe,
|
||||
} satisfies Pick<
|
||||
WsTransport,
|
||||
"dispose" | "isHeartbeatFresh" | "reconnect" | "request" | "requestStream" | "subscribe"
|
||||
"dispose" | "reconnect" | "request" | "requestStream" | "subscribe"
|
||||
>;
|
||||
|
||||
const client = createWsRpcClient(transport as unknown as WsTransport);
|
||||
|
||||
@@ -125,9 +125,7 @@ export interface WsRpcClient {
|
||||
};
|
||||
readonly server: {
|
||||
readonly getConfig: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetConfig>;
|
||||
readonly refreshProviders: (
|
||||
input?: RpcInput<typeof WS_METHODS.serverRefreshProviders>,
|
||||
) => ReturnType<RpcUnaryMethod<typeof WS_METHODS.serverRefreshProviders>>;
|
||||
readonly refreshProviders: RpcUnaryNoArgMethod<typeof WS_METHODS.serverRefreshProviders>;
|
||||
readonly discoverSourceControl: RpcUnaryNoArgMethod<
|
||||
typeof WS_METHODS.serverDiscoverSourceControl
|
||||
>;
|
||||
@@ -173,7 +171,7 @@ export function createWsRpcClient(
|
||||
): WsRpcClient {
|
||||
return {
|
||||
dispose: () => transport.dispose(),
|
||||
isHeartbeatFresh: () => transport.isHeartbeatFresh(),
|
||||
isHeartbeatFresh: () => false,
|
||||
reconnect: async () => {
|
||||
options?.beforeReconnect?.();
|
||||
await transport.reconnect();
|
||||
@@ -280,8 +278,8 @@ export function createWsRpcClient(
|
||||
},
|
||||
server: {
|
||||
getConfig: () => transport.request((client) => client[WS_METHODS.serverGetConfig]({})),
|
||||
refreshProviders: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.serverRefreshProviders](input ?? {})),
|
||||
refreshProviders: () =>
|
||||
transport.request((client) => client[WS_METHODS.serverRefreshProviders]({})),
|
||||
discoverSourceControl: () =>
|
||||
transport.request((client) => client[WS_METHODS.serverDiscoverSourceControl]({})),
|
||||
updateProvider: (input) =>
|
||||
|
||||
@@ -15,34 +15,10 @@ import {
|
||||
export interface WsProtocolLifecycleHandlers {
|
||||
readonly getConnectionLabel?: () => string | null;
|
||||
readonly getVersionMismatchHint?: () => string | null;
|
||||
readonly isCloseIntentional?: () => boolean;
|
||||
readonly isActive?: () => boolean;
|
||||
readonly onAttempt?: (socketUrl: string) => void;
|
||||
readonly onOpen?: () => void;
|
||||
readonly onHeartbeatPing?: () => void;
|
||||
readonly onHeartbeatPong?: () => void;
|
||||
readonly onHeartbeatTimeout?: () => void;
|
||||
readonly onRequestStart?: (info: {
|
||||
readonly id: string;
|
||||
readonly tag: string;
|
||||
readonly stream: boolean;
|
||||
}) => void;
|
||||
readonly onRequestChunk?: (info: {
|
||||
readonly id: string;
|
||||
readonly tag: string;
|
||||
readonly chunkCount: number;
|
||||
}) => void;
|
||||
readonly onRequestExit?: (info: {
|
||||
readonly id: string;
|
||||
readonly tag: string;
|
||||
readonly stream: boolean;
|
||||
}) => void;
|
||||
readonly onRequestInterrupt?: (info: { readonly id: string; readonly tag?: string }) => void;
|
||||
readonly onError?: (message: string) => void;
|
||||
readonly onClose?: (
|
||||
details: { readonly code: number; readonly reason: string },
|
||||
context: { readonly intentional: boolean },
|
||||
) => void;
|
||||
readonly onClose?: (details: { readonly code: number; readonly reason: string }) => void;
|
||||
}
|
||||
|
||||
export interface WsRpcProtocolRequestTelemetry {
|
||||
@@ -87,107 +63,48 @@ function resolveWsRpcSocketUrl(rawUrl: string): string {
|
||||
return resolved.toString();
|
||||
}
|
||||
|
||||
type ResolvedLifecycleHandlers = Required<
|
||||
Pick<
|
||||
WsProtocolLifecycleHandlers,
|
||||
| "getConnectionLabel"
|
||||
| "getVersionMismatchHint"
|
||||
| "isCloseIntentional"
|
||||
| "isActive"
|
||||
| "onAttempt"
|
||||
| "onOpen"
|
||||
| "onHeartbeatPing"
|
||||
| "onHeartbeatPong"
|
||||
| "onHeartbeatTimeout"
|
||||
| "onError"
|
||||
| "onClose"
|
||||
>
|
||||
>;
|
||||
|
||||
function defaultLifecycleHandlers(): ResolvedLifecycleHandlers {
|
||||
function defaultLifecycleHandlers(): Required<WsProtocolLifecycleHandlers> {
|
||||
return {
|
||||
onAttempt: () => undefined,
|
||||
onOpen: () => undefined,
|
||||
onHeartbeatPing: () => undefined,
|
||||
onHeartbeatPong: () => undefined,
|
||||
onHeartbeatTimeout: () => undefined,
|
||||
onError: () => undefined,
|
||||
onClose: () => undefined,
|
||||
getConnectionLabel: () => null,
|
||||
getVersionMismatchHint: () => null,
|
||||
isCloseIntentional: () => false,
|
||||
isActive: () => true,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveLifecycleHandlers(
|
||||
handlers: WsProtocolLifecycleHandlers | undefined,
|
||||
telemetryLifecycle: WsProtocolLifecycleHandlers | undefined,
|
||||
): ResolvedLifecycleHandlers {
|
||||
const defaults = defaultLifecycleHandlers();
|
||||
const isActive = handlers?.isActive ?? telemetryLifecycle?.isActive ?? defaults.isActive;
|
||||
const isCloseIntentional =
|
||||
handlers?.isCloseIntentional ??
|
||||
telemetryLifecycle?.isCloseIntentional ??
|
||||
defaults.isCloseIntentional;
|
||||
): Required<WsProtocolLifecycleHandlers> {
|
||||
if (telemetryLifecycle === undefined) {
|
||||
return {
|
||||
...defaultLifecycleHandlers(),
|
||||
...handlers,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
getConnectionLabel: () =>
|
||||
handlers?.getConnectionLabel?.() ?? telemetryLifecycle?.getConnectionLabel?.() ?? null,
|
||||
handlers?.getConnectionLabel?.() ?? telemetryLifecycle.getConnectionLabel?.() ?? null,
|
||||
getVersionMismatchHint: () =>
|
||||
handlers?.getVersionMismatchHint?.() ??
|
||||
telemetryLifecycle?.getVersionMismatchHint?.() ??
|
||||
null,
|
||||
isActive,
|
||||
isCloseIntentional,
|
||||
handlers?.getVersionMismatchHint?.() ?? telemetryLifecycle.getVersionMismatchHint?.() ?? null,
|
||||
onAttempt: (socketUrl) => {
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
telemetryLifecycle?.onAttempt?.(socketUrl);
|
||||
telemetryLifecycle.onAttempt?.(socketUrl);
|
||||
handlers?.onAttempt?.(socketUrl);
|
||||
},
|
||||
onOpen: () => {
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
telemetryLifecycle?.onOpen?.();
|
||||
telemetryLifecycle.onOpen?.();
|
||||
handlers?.onOpen?.();
|
||||
},
|
||||
onHeartbeatPing: () => {
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
telemetryLifecycle?.onHeartbeatPing?.();
|
||||
handlers?.onHeartbeatPing?.();
|
||||
},
|
||||
onHeartbeatPong: () => {
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
telemetryLifecycle?.onHeartbeatPong?.();
|
||||
handlers?.onHeartbeatPong?.();
|
||||
},
|
||||
onHeartbeatTimeout: () => {
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
telemetryLifecycle?.onHeartbeatTimeout?.();
|
||||
handlers?.onHeartbeatTimeout?.();
|
||||
},
|
||||
onError: (message) => {
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
telemetryLifecycle?.onError?.(message);
|
||||
telemetryLifecycle.onError?.(message);
|
||||
handlers?.onError?.(message);
|
||||
},
|
||||
onClose: (details, context) => {
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
telemetryLifecycle?.onClose?.(details, context);
|
||||
handlers?.onClose?.(details, context);
|
||||
onClose: (details) => {
|
||||
telemetryLifecycle.onClose?.(details);
|
||||
handlers?.onClose?.(details);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -241,15 +158,10 @@ export function createWsRpcProtocolLayer(
|
||||
socket.addEventListener(
|
||||
"close",
|
||||
(event) => {
|
||||
lifecycle.onClose(
|
||||
{
|
||||
code: event.code,
|
||||
reason: event.reason,
|
||||
},
|
||||
{
|
||||
intentional: lifecycle.isCloseIntentional(),
|
||||
},
|
||||
);
|
||||
lifecycle.onClose({
|
||||
code: event.code,
|
||||
reason: event.reason,
|
||||
});
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
@@ -298,77 +210,6 @@ export function createWsRpcProtocolLayer(
|
||||
retryTransientErrors: true,
|
||||
}),
|
||||
);
|
||||
const requestHooksLayer = Layer.succeed(
|
||||
RpcClient.RequestHooks,
|
||||
RpcClient.RequestHooks.of({
|
||||
onRequestStart: (info) =>
|
||||
Effect.sync(() => {
|
||||
if (!lifecycle.isActive()) {
|
||||
return;
|
||||
}
|
||||
handlers?.onRequestStart?.({
|
||||
id: String(info.id),
|
||||
tag: info.tag,
|
||||
stream: info.stream,
|
||||
});
|
||||
}),
|
||||
onRequestChunk: (info) =>
|
||||
Effect.sync(() => {
|
||||
if (!lifecycle.isActive()) {
|
||||
return;
|
||||
}
|
||||
handlers?.onRequestChunk?.({
|
||||
id: String(info.id),
|
||||
tag: info.tag,
|
||||
chunkCount: info.chunkCount,
|
||||
});
|
||||
}),
|
||||
onRequestExit: (info) =>
|
||||
Effect.sync(() => {
|
||||
if (!lifecycle.isActive()) {
|
||||
return;
|
||||
}
|
||||
handlers?.onRequestExit?.({
|
||||
id: String(info.id),
|
||||
tag: info.tag,
|
||||
stream: info.stream,
|
||||
});
|
||||
}),
|
||||
onRequestInterrupt: (info) =>
|
||||
Effect.sync(() => {
|
||||
if (!lifecycle.isActive()) {
|
||||
return;
|
||||
}
|
||||
handlers?.onRequestInterrupt?.({
|
||||
id: String(info.id),
|
||||
...(info.tag === undefined ? {} : { tag: info.tag }),
|
||||
});
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const connectionHooksLayer = Layer.succeed(
|
||||
RpcClient.ConnectionHooks,
|
||||
RpcClient.ConnectionHooks.of({
|
||||
onConnect: Effect.void,
|
||||
onDisconnect: Effect.void,
|
||||
onPing: Effect.sync(() => {
|
||||
lifecycle.onHeartbeatPing();
|
||||
}),
|
||||
onPong: Effect.sync(() => {
|
||||
lifecycle.onHeartbeatPong();
|
||||
}),
|
||||
onPingTimeout: Effect.sync(() => {
|
||||
requestTelemetry?.onClearTrackedRequests?.();
|
||||
lifecycle.onHeartbeatTimeout();
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
return Layer.mergeAll(
|
||||
protocolLayer.pipe(
|
||||
Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson, connectionHooksLayer)),
|
||||
),
|
||||
requestHooksLayer,
|
||||
connectionHooksLayer,
|
||||
);
|
||||
return protocolLayer.pipe(Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson)));
|
||||
}
|
||||
@@ -202,111 +202,15 @@ describe("WsTransport", () => {
|
||||
socket.close(1012, "service restart");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onClose).toHaveBeenCalledWith(
|
||||
{
|
||||
code: 1012,
|
||||
reason: "service restart",
|
||||
},
|
||||
{
|
||||
intentional: false,
|
||||
},
|
||||
);
|
||||
expect(onClose).toHaveBeenCalledWith({
|
||||
code: 1012,
|
||||
reason: "service restart",
|
||||
});
|
||||
});
|
||||
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("tracks heartbeat freshness from websocket pongs", async () => {
|
||||
const nowSpy = vi.spyOn(performance, "now").mockReturnValue(1_000);
|
||||
const onHeartbeatPong = vi.fn();
|
||||
const transport = createTransport("ws://localhost:3020", { onHeartbeatPong });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
expect(transport.isHeartbeatFresh()).toBe(false);
|
||||
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
socket.serverMessage(JSON.stringify({ _tag: "Pong" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onHeartbeatPong).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
expect(transport.isHeartbeatFresh()).toBe(true);
|
||||
expect(transport.isHeartbeatFresh(500)).toBe(true);
|
||||
|
||||
nowSpy.mockReturnValue(1_501);
|
||||
expect(transport.isHeartbeatFresh(500)).toBe(false);
|
||||
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("clears heartbeat freshness when reconnecting", async () => {
|
||||
vi.spyOn(performance, "now").mockReturnValue(1_000);
|
||||
const onHeartbeatPong = vi.fn();
|
||||
const transport = createTransport("ws://localhost:3020", { onHeartbeatPong });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const firstSocket = getSocket();
|
||||
firstSocket.open();
|
||||
firstSocket.serverMessage(JSON.stringify({ _tag: "Pong" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onHeartbeatPong).toHaveBeenCalledOnce();
|
||||
});
|
||||
expect(transport.isHeartbeatFresh()).toBe(true);
|
||||
|
||||
await transport.reconnect();
|
||||
|
||||
expect(transport.isHeartbeatFresh()).toBe(false);
|
||||
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("does not report an intentional dispose as a close", async () => {
|
||||
const onClose = vi.fn();
|
||||
const transport = createTransport("ws://localhost:3020", { onClose });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
getSocket().open();
|
||||
await transport.dispose();
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores stale socket lifecycle events after reconnect starts a new session", async () => {
|
||||
const onClose = vi.fn();
|
||||
const transport = createTransport("ws://localhost:3020", { onClose });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const firstSocket = getSocket();
|
||||
firstSocket.open();
|
||||
|
||||
await transport.reconnect();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(2);
|
||||
});
|
||||
|
||||
firstSocket.close(1006, "stale close");
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("reconnects the websocket session without disposing the transport", async () => {
|
||||
const transport = createTransport("ws://localhost:3020");
|
||||
|
||||
@@ -741,8 +645,8 @@ describe("WsTransport", () => {
|
||||
});
|
||||
|
||||
it("does not retry stream subscriptions after application-level failures", async () => {
|
||||
const warnSpy = vi.fn();
|
||||
const transport = createTransport("ws://localhost:3020", undefined, { logWarning: warnSpy });
|
||||
const transport = createTransport("ws://localhost:3020");
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
let attempts = 0;
|
||||
|
||||
const unsubscribe = transport.subscribe(
|
||||
@@ -780,8 +684,8 @@ describe("WsTransport", () => {
|
||||
});
|
||||
|
||||
it("keeps retrying stream subscriptions after transport failures", async () => {
|
||||
const warnSpy = vi.fn();
|
||||
const transport = createTransport("ws://localhost:3020", undefined, { logWarning: warnSpy });
|
||||
const transport = createTransport("ws://localhost:3020");
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
let attempts = 0;
|
||||
|
||||
const unsubscribe = transport.subscribe(
|
||||
@@ -813,8 +717,8 @@ describe("WsTransport", () => {
|
||||
});
|
||||
|
||||
it("logs a transport disconnect once even when multiple subscriptions fail together", async () => {
|
||||
const warnSpy = vi.fn();
|
||||
const transport = createTransport("ws://localhost:3020", undefined, { logWarning: warnSpy });
|
||||
const transport = createTransport("ws://localhost:3020");
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
|
||||
const unsubscribeA = transport.subscribe(
|
||||
() => Stream.fail(new Error("SocketCloseError: 1006")),
|
||||
|
||||
@@ -31,7 +31,6 @@ export interface WsTransportOptions {
|
||||
url: WsRpcProtocolSocketUrlProvider,
|
||||
lifecycleHandlers?: WsProtocolLifecycleHandlers,
|
||||
) => Layer.Layer<RpcClient.Protocol, never, never>;
|
||||
readonly logWarning?: (message: string, metadata: { readonly error: string }) => void;
|
||||
/**
|
||||
* Invoked at the start of {@link WsTransport.reconnect} before the session is replaced.
|
||||
*/
|
||||
@@ -41,7 +40,6 @@ export interface WsTransportOptions {
|
||||
interface SubscribeOptions {
|
||||
readonly retryDelay?: Duration.Input;
|
||||
readonly onResubscribe?: () => void;
|
||||
readonly tag?: string;
|
||||
}
|
||||
|
||||
const DEFAULT_SUBSCRIPTION_RETRY_DELAY = Duration.millis(250);
|
||||
@@ -67,13 +65,6 @@ export class WsTransport {
|
||||
private readonly options: WsTransportOptions | undefined;
|
||||
private disposed = false;
|
||||
private hasReportedTransportDisconnect = false;
|
||||
private intentionalCloseDepth = 0;
|
||||
private nextSessionId = 0;
|
||||
private activeSessionId = 0;
|
||||
private lastHeartbeatPongAt: number | null = null;
|
||||
private readonly streamRequestStartListeners = new Set<
|
||||
(info: { readonly tag: string }) => void
|
||||
>();
|
||||
private reconnectChain: Promise<void> = Promise.resolve();
|
||||
private session: TransportSession;
|
||||
|
||||
@@ -138,22 +129,6 @@ export class WsTransport {
|
||||
Duration.fromInputUnsafe(options?.retryDelay ?? DEFAULT_SUBSCRIPTION_RETRY_DELAY),
|
||||
);
|
||||
let cancelCurrentStream: () => void = NOOP;
|
||||
const onStreamRequestStart = (info: { readonly tag: string }) => {
|
||||
if (
|
||||
!hasReceivedValue ||
|
||||
!active ||
|
||||
(options?.tag !== undefined && info.tag !== options.tag)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
options?.onResubscribe?.();
|
||||
} catch {
|
||||
// Ignore reconnect hook failures so the stream can recover.
|
||||
}
|
||||
};
|
||||
this.streamRequestStartListeners.add(onStreamRequestStart);
|
||||
|
||||
void (async () => {
|
||||
for (;;) {
|
||||
@@ -163,6 +138,14 @@ export class WsTransport {
|
||||
|
||||
const session = this.session;
|
||||
try {
|
||||
if (hasReceivedValue) {
|
||||
try {
|
||||
options?.onResubscribe?.();
|
||||
} catch {
|
||||
// Ignore reconnect hook failures so the stream can recover.
|
||||
}
|
||||
}
|
||||
|
||||
const runningStream = this.runStreamOnSession(
|
||||
session,
|
||||
connect,
|
||||
@@ -189,14 +172,18 @@ export class WsTransport {
|
||||
|
||||
const formattedError = formatErrorMessage(error);
|
||||
if (!isTransportConnectionErrorMessage(formattedError)) {
|
||||
this.logWarning("WebSocket RPC subscription failed", { error: formattedError });
|
||||
Effect.runSync(
|
||||
Effect.logWarning("WebSocket RPC subscription failed", { error: formattedError }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.hasReportedTransportDisconnect) {
|
||||
this.logWarning("WebSocket RPC subscription disconnected", {
|
||||
error: formattedError,
|
||||
});
|
||||
Effect.runSync(
|
||||
Effect.logWarning("WebSocket RPC subscription disconnected", {
|
||||
error: formattedError,
|
||||
}),
|
||||
);
|
||||
}
|
||||
this.hasReportedTransportDisconnect = true;
|
||||
await sleep(retryDelayMs);
|
||||
@@ -206,7 +193,6 @@ export class WsTransport {
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
this.streamRequestStartListeners.delete(onStreamRequestStart);
|
||||
cancelCurrentStream();
|
||||
};
|
||||
}
|
||||
@@ -227,7 +213,6 @@ export class WsTransport {
|
||||
// Ignore hook failures so reconnect can proceed.
|
||||
}
|
||||
|
||||
this.lastHeartbeatPongAt = null;
|
||||
const previousSession = this.session;
|
||||
this.session = this.createSession();
|
||||
await this.closeSession(previousSession);
|
||||
@@ -237,12 +222,6 @@ export class WsTransport {
|
||||
await reconnectOperation;
|
||||
}
|
||||
|
||||
isHeartbeatFresh(maxAgeMs = 15_000): boolean {
|
||||
return (
|
||||
this.lastHeartbeatPongAt !== null && performance.now() - this.lastHeartbeatPongAt <= maxAgeMs
|
||||
);
|
||||
}
|
||||
|
||||
async dispose() {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
@@ -253,43 +232,14 @@ export class WsTransport {
|
||||
}
|
||||
|
||||
private closeSession(session: TransportSession) {
|
||||
this.intentionalCloseDepth += 1;
|
||||
return session.runtime.runPromise(Scope.close(session.clientScope, Exit.void)).finally(() => {
|
||||
this.intentionalCloseDepth = Math.max(0, this.intentionalCloseDepth - 1);
|
||||
session.runtime.dispose();
|
||||
});
|
||||
}
|
||||
|
||||
private createSession(): TransportSession {
|
||||
const protocolFactory = this.options?.createProtocolLayer ?? createWsRpcProtocolLayer;
|
||||
const sessionId = this.nextSessionId + 1;
|
||||
this.nextSessionId = sessionId;
|
||||
this.activeSessionId = sessionId;
|
||||
const lifecycleHandlers = this.lifecycleHandlers;
|
||||
const protocolLayer = protocolFactory(this.url, {
|
||||
...lifecycleHandlers,
|
||||
isActive: () =>
|
||||
!this.disposed &&
|
||||
this.activeSessionId === sessionId &&
|
||||
(lifecycleHandlers?.isActive?.() ?? true),
|
||||
isCloseIntentional: () =>
|
||||
this.disposed ||
|
||||
this.intentionalCloseDepth > 0 ||
|
||||
lifecycleHandlers?.isCloseIntentional?.() === true,
|
||||
onHeartbeatPong: () => {
|
||||
this.lastHeartbeatPongAt = performance.now();
|
||||
lifecycleHandlers?.onHeartbeatPong?.();
|
||||
},
|
||||
onRequestStart: (info) => {
|
||||
lifecycleHandlers?.onRequestStart?.(info);
|
||||
if (!info.stream) {
|
||||
return;
|
||||
}
|
||||
for (const listener of this.streamRequestStartListeners) {
|
||||
listener({ tag: info.tag });
|
||||
}
|
||||
},
|
||||
});
|
||||
const protocolLayer = protocolFactory(this.url, this.lifecycleHandlers);
|
||||
const rootLayer = this.options?.tracingLayer
|
||||
? Layer.mergeAll(protocolLayer, this.options.tracingLayer)
|
||||
: protocolLayer;
|
||||
@@ -302,15 +252,6 @@ export class WsTransport {
|
||||
};
|
||||
}
|
||||
|
||||
private logWarning(message: string, metadata: { readonly error: string }) {
|
||||
const logWarning = this.options?.logWarning;
|
||||
if (logWarning) {
|
||||
logWarning(message, metadata);
|
||||
} else {
|
||||
Effect.runSync(Effect.logWarning(message, metadata));
|
||||
}
|
||||
}
|
||||
|
||||
private runStreamOnSession<TValue>(
|
||||
session: TransportSession,
|
||||
connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
|
||||
|
||||
@@ -44,7 +44,6 @@ describe("TerminalOpenInput", () => {
|
||||
expect(
|
||||
decodes(TerminalOpenInput, {
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
cwd: "/tmp/project",
|
||||
cols: 423,
|
||||
rows: 40,
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
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";
|
||||
@@ -172,13 +170,12 @@ describe("observability", () => {
|
||||
}
|
||||
yield* sink.close();
|
||||
|
||||
const matchingFiles = Arr.sort(
|
||||
(yield* fileSystem.readDirectory(tempDir)).filter(
|
||||
const matchingFiles = (yield* fileSystem.readDirectory(tempDir))
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
|
||||
),
|
||||
Order.String,
|
||||
);
|
||||
)
|
||||
.toSorted();
|
||||
|
||||
assert.equal(
|
||||
matchingFiles.some((entry) => entry === "shared.trace.ndjson.1"),
|
||||
|
||||
Reference in new issue
Block a user