Refactor mobile remote state into dedicated stores

- Split connection, catalog, composer, selection, and git state
- Move image previews to a shared viewer component
- Add ws client/runtime plumbing for remote environment handling
This commit is contained in:
Julius Marminge committed 2026-04-13 14:44:02 -07:00
1 parent e6d1d725f9
commit 87d12d72a1
51 files changed
+4034 -3329

No files matched your search

+3 -3
View File
@@ -16,8 +16,6 @@
"@expo-google-fonts/dm-sans": "^0.4.2",
"@gorhom/bottom-sheet": "^5",
"@legendapp/list": "^3.0.0-beta.44",
"@react-native-async-storage/async-storage": "2.2.0",
"@react-native-masked-view/masked-view": "0.3.2",
"@react-native-menu/menu": "^2.0.0",
"@sethwebster/react-ethereal-input": "^0.4.0",
"@shopify/flash-list": "2.0.2",
@@ -50,13 +48,15 @@
"react-native": "0.83.4",
"react-native-css": "3.0.7",
"react-native-gesture-handler": "~2.30.0",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.20.7",
"react-native-markdown-display": "^7.0.2",
"react-native-reanimated": "4.2.1",
"react-native-safe-area-context": "~5.6.2",
"react-native-screens": "~4.23.0",
"react-native-svg": "15.15.3",
"react-native-worklets": "0.7.2"
"react-native-worklets": "0.7.2",
"zustand": "^5.0.12"
},
"devDependencies": {
"@tailwindcss/postcss": "4.1.12",
+8 -14
View File
@@ -15,10 +15,13 @@ import { SafeAreaProvider } from "react-native-safe-area-context";
import { LoadingScreen } from "../components/LoadingScreen";
import { makeAppPalette } from "../lib/theme";
import { RemoteAppStateProvider, useRemoteApp } from "../state/remote-app-state-provider";
import {
useRemoteEnvironmentBootstrap,
useRemoteEnvironmentState,
} from "../state/use-remote-environment-registry";
function AppNavigator() {
const app = useRemoteApp();
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
const isDarkMode = useColorScheme() !== "light";
const palette = makeAppPalette(isDarkMode);
@@ -40,14 +43,10 @@ function AppNavigator() {
sheetGrabberVisible: true,
};
if (app.isLoadingSavedConnection) {
if (isLoadingSavedConnection) {
return <LoadingScreen message="Loading remote workspace…" />;
}
if (app.reconnectingScreenVisible) {
return <LoadingScreen message="Reconnecting…" />;
}
return (
<>
<StatusBar
@@ -78,19 +77,14 @@ export default function RootLayout() {
DMSans_500Medium,
DMSans_700Bold,
});
useRemoteEnvironmentBootstrap();
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<BottomSheetModalProvider>
<SafeAreaProvider>
<RemoteAppStateProvider>
{fontsLoaded ? (
<AppNavigator />
) : (
<LoadingScreen message="Loading remote workspace…" />
)}
</RemoteAppStateProvider>
{fontsLoaded ? <AppNavigator /> : <LoadingScreen message="Loading remote workspace…" />}
</SafeAreaProvider>
</BottomSheetModalProvider>
</KeyboardProvider>
+4 -4
View File
@@ -7,16 +7,16 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { makeAppPalette } from "../../lib/theme";
import { useRemoteApp } from "../../state/remote-app-state-provider";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
export default function NewTaskRoute() {
const app = useRemoteApp();
const { projects, threads } = useRemoteCatalog();
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const insets = useSafeAreaInsets();
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects: app.projects, threads: app.threads }),
[app.projects, app.threads],
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
);
const items = useMemo(
() =>
@@ -32,11 +32,18 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
}
return (
<ScrollView horizontal showsHorizontalScrollIndicator={false} keyboardShouldPersistTaps="always" style={{ flexGrow: 0 }}>
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
keyboardShouldPersistTaps="always"
style={{ flexGrow: 0 }}
>
<View style={{ flexDirection: "row", gap: 10 }}>
{props.attachments.map((image) => (
<View key={image.id} style={{ position: "relative" }}>
<Pressable onPress={props.onPressImage ? () => props.onPressImage!(image.previewUri) : undefined}>
<Pressable
onPress={props.onPressImage ? () => props.onPressImage!(image.previewUri) : undefined}
>
<Image
source={{ uri: image.previewUri }}
style={{
@@ -45,15 +45,13 @@ export function GlassSafeAreaView({
gap: 10,
}}
>
<View style={{ alignItems: "flex-start", justifyContent: "center" }}>
{leftSlot}
</View>
<View style={{ flex: 1, alignItems: "center", justifyContent: "center", overflow: "hidden" }}>
<View style={{ alignItems: "flex-start", justifyContent: "center" }}>{leftSlot}</View>
<View
style={{ flex: 1, alignItems: "center", justifyContent: "center", overflow: "hidden" }}
>
{centerSlot}
</View>
<View style={{ alignItems: "flex-end", justifyContent: "center" }}>
{rightSlot}
</View>
<View style={{ alignItems: "flex-end", justifyContent: "center" }}>{rightSlot}</View>
</View>
</GlassSurface>
</View>
@@ -12,7 +12,7 @@ import {
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import type { ConnectedEnvironmentSummary } from "../../state/use-remote-app-state";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
import {
@@ -6,8 +6,8 @@ import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanim
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { useRemoteApp } from "../../state/remote-app-state-provider";
import type { ConnectedEnvironmentSummary } from "../../state/use-remote-app-state";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
import { makeConnectionSheetPalette as makePalette } from "./connection-sheet-shared";
@@ -173,11 +173,12 @@ function EnvironmentRow(props: {
}
export function ConnectionsRouteScreen() {
const app = useRemoteApp();
const { connectedEnvironments, onRemoveEnvironmentPress, onUpdateEnvironment } =
useRemoteConnections();
const insets = useSafeAreaInsets();
const isDarkMode = useColorScheme() === "dark";
const palette = makePalette(isDarkMode);
const hasEnvironments = app.connectedEnvironments.length > 0;
const hasEnvironments = connectedEnvironments.length > 0;
const [expandedId, setExpandedId] = useState<string | null>(null);
const handleToggle = useCallback((environmentId: string) => {
@@ -223,7 +224,7 @@ export function ConnectionsRouteScreen() {
className="overflow-hidden rounded-[24px]"
style={{ backgroundColor: palette.card }}
>
{app.connectedEnvironments.map((environment, index) => (
{connectedEnvironments.map((environment, index) => (
<View
key={environment.environmentId}
collapsable={false}
@@ -236,8 +237,8 @@ export function ConnectionsRouteScreen() {
environment={environment}
expanded={expandedId === environment.environmentId}
onToggle={() => handleToggle(environment.environmentId)}
onRemove={app.onRemoveEnvironmentPress}
onUpdate={app.onUpdateEnvironment}
onRemove={onRemoveEnvironmentPress}
onUpdate={onUpdateEnvironment}
palette={palette}
/>
</View>
@@ -9,7 +9,7 @@ import { AppText as Text, AppTextInput as TextInput } from "../../components/App
import { ErrorBanner } from "../../components/ErrorBanner";
import { dismissRoute } from "../../lib/routes";
import { extractPairingUrlFromQrPayload } from "../../lib/pairingQr";
import { useRemoteApp } from "../../state/remote-app-state-provider";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import {
buildPairingUrl,
ConnectionSheetButton as SheetButton,
@@ -18,7 +18,13 @@ import {
} from "./connection-sheet-shared";
export function NewConnectionRouteScreen() {
const app = useRemoteApp();
const {
connectionError,
connectionPairingUrl,
connectionState,
onChangeConnectionPairingUrl,
onConnectPress,
} = useRemoteConnections();
const router = useRouter();
const params = useLocalSearchParams<{ mode?: string }>();
const insets = useSafeAreaInsets();
@@ -32,19 +38,19 @@ export function NewConnectionRouteScreen() {
const [scannerLocked, setScannerLocked] = useState(false);
const connectDisabled =
isSubmitting || app.connectionState === "connecting" || hostInput.trim().length === 0;
isSubmitting || connectionState === "connecting" || hostInput.trim().length === 0;
useEffect(() => {
const { host, code } = parsePairingUrl(app.connectionInput.pairingUrl);
const { host, code } = parsePairingUrl(connectionPairingUrl);
setHostInput(host);
setCodeInput(code);
}, [app.connectionInput.pairingUrl]);
}, [connectionPairingUrl]);
useEffect(() => {
if (app.connectionError) {
if (connectionError) {
setIsSubmitting(false);
}
}, [app.connectionError]);
}, [connectionError]);
const handleHostChange = useCallback((value: string) => {
setHostInput(value);
@@ -89,7 +95,7 @@ export function NewConnectionRouteScreen() {
const { host, code } = parsePairingUrl(pairingUrl);
setHostInput(host);
setCodeInput(code);
app.onChangeConnectionPairingUrl(pairingUrl);
onChangeConnectionPairingUrl(pairingUrl);
setShowScanner(false);
} catch (error) {
Alert.alert(
@@ -102,7 +108,7 @@ export function NewConnectionRouteScreen() {
}, 600);
}
},
[app, scannerLocked],
[onChangeConnectionPairingUrl, scannerLocked],
);
const handleSubmit = useCallback(async () => {
@@ -110,13 +116,13 @@ export function NewConnectionRouteScreen() {
try {
const pairingUrl = buildPairingUrl(hostInput, codeInput);
app.onChangeConnectionPairingUrl(pairingUrl);
await app.onConnectPress(pairingUrl);
onChangeConnectionPairingUrl(pairingUrl);
await onConnectPress(pairingUrl);
dismissRoute(router);
} catch {
setIsSubmitting(false);
}
}, [app, codeInput, hostInput, router]);
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
return (
<View collapsable={false} style={{ flex: 1, backgroundColor: palette.sheet }}>
@@ -252,12 +258,12 @@ export function NewConnectionRouteScreen() {
/>
</View>
{app.connectionError ? <ErrorBanner message={app.connectionError} /> : null}
{connectionError ? <ErrorBanner message={connectionError} /> : null}
<SheetButton
icon="plus"
label={
isSubmitting || app.connectionState === "connecting" ? "Pairing…" : "Add backend"
isSubmitting || connectionState === "connecting" ? "Pairing…" : "Add backend"
}
disabled={connectDisabled}
palette={palette}
@@ -2,29 +2,31 @@ import { useFocusEffect, useRouter } from "expo-router";
import { useCallback } from "react";
import { buildThreadRoutePath } from "../../lib/routes";
import { useRemoteApp } from "../../state/remote-app-state-provider";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useThreadSelection } from "../../state/use-thread-selection";
import { HomeScreen } from "./HomeScreen";
export function HomeRouteScreen() {
const app = useRemoteApp();
const { connectionState, hasRemoteActivity, projects, threads } = useRemoteCatalog();
const { onBackFromThread, onSelectThread } = useThreadSelection();
const router = useRouter();
useFocusEffect(
useCallback(() => {
app.onBackFromThread();
}, [app]),
onBackFromThread();
}, [onBackFromThread]),
);
return (
<HomeScreen
projects={app.projects}
threads={app.threads}
connectionState={app.connectionState}
connectionPulse={app.hasRemoteActivity}
projects={projects}
threads={threads}
connectionState={connectionState}
connectionPulse={hasRemoteActivity}
onOpenConnectionEditor={() => router.push("/connections")}
onOpenNewTask={() => router.push("/new")}
onSelectThread={(thread) => {
app.onSelectThread(thread);
onSelectThread(thread);
router.push(buildThreadRoutePath(thread));
}}
showFloatingConnectionButton
@@ -18,7 +18,8 @@ import { ProviderIcon } from "../../components/ProviderIcon";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
import { buildThreadRoutePath } from "../../lib/routes";
import { makeAppPalette } from "../../lib/theme";
import { useRemoteApp } from "../../state/remote-app-state-provider";
import { useProjectActions } from "../../state/use-project-actions";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useNativePaste } from "../../hooks/useNativePaste";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
@@ -28,7 +29,8 @@ export function NewTaskDraftScreen(props: {
readonly projectId?: string;
};
}) {
const app = useRemoteApp();
const { projects } = useRemoteCatalog();
const { onCreateThreadWithOptions } = useProjectActions();
const flow = useNewTaskFlow();
const router = useRouter();
const isDarkMode = useColorScheme() === "dark";
@@ -46,7 +48,7 @@ export function NewTaskDraftScreen(props: {
useEffect(() => {
if (props.initialProjectRef?.environmentId && props.initialProjectRef?.projectId) {
const directProject =
app.projects.find(
projects.find(
(project) =>
project.environmentId === props.initialProjectRef?.environmentId &&
project.id === props.initialProjectRef?.projectId,
@@ -69,8 +71,8 @@ export function NewTaskDraftScreen(props: {
router.replace("/new");
}, [
app.projects,
logicalProjects,
projects,
props.initialProjectRef?.environmentId,
props.initialProjectRef?.projectId,
router,
@@ -308,7 +310,7 @@ export function NewTaskDraftScreen(props: {
async function handlePickImages(): Promise<void> {
const result = await pickComposerImages({ existingCount: flow.attachments.length });
if (result.images.length > 0) {
flow.setAttachments((current) => [...current, ...result.images]);
flow.appendAttachments(result.images);
}
}
@@ -320,7 +322,7 @@ export function NewTaskDraftScreen(props: {
existingCount: flow.attachments.length,
});
if (images.length > 0) {
flow.setAttachments((current) => [...current, ...images]);
flow.appendAttachments(images);
}
} catch (error) {
console.error("[native paste] error converting images", error);
@@ -360,7 +362,7 @@ export function NewTaskDraftScreen(props: {
? { ...flow.selectedModel, options: { fastMode: flow.fastMode || undefined } }
: flow.selectedModel;
const createdThread = await app.onCreateThreadWithOptions({
const createdThread = await onCreateThreadWithOptions({
project: flow.selectedProject,
modelSelection: modelWithOptions,
envMode: flow.workspaceMode,
@@ -466,11 +468,7 @@ export function NewTaskDraftScreen(props: {
<View style={{ paddingHorizontal: 16, paddingTop: 12 }}>
<ComposerAttachmentStrip
attachments={flow.attachments}
onRemove={(imageId) =>
flow.setAttachments((current) =>
current.filter((candidate) => candidate.id !== imageId),
)
}
onRemove={flow.removeAttachment}
imageSize={88}
imageBorderRadius={20}
/>
@@ -46,7 +46,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
<Pressable
key={option.label}
className={cx(
"rounded-full border px-3 py-2.5",
"rounded-full border px-3 py-2.5 ",
selected
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
: "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
@@ -1,6 +1,5 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import { MenuView } from "@react-native-menu/menu";
import { SymbolView } from "expo-symbols";
import type {
ModelSelection,
OrchestrationThread,
@@ -13,15 +12,14 @@ import { TextInputWrapper } from "expo-paste-input";
import type { ReactNode } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
Dimensions,
Image,
Modal,
Pressable as RNPressable,
Pressable,
TextInput as RNTextInput,
useColorScheme,
View,
type ViewStyle,
} from "react-native";
import ImageViewing from "react-native-image-viewing";
import { AppText as Text } from "../../components/AppText";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
@@ -115,16 +113,20 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const inputRef = useRef<RNTextInput>(null);
const [isFocused, setIsFocused] = useState(false);
const wasExpandedBeforePreviewRef = useRef(false);
const { onExpandedChange } = props;
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
const isExpanded = isFocused || previewImageUri !== null;
const isExpanded = isFocused;
const canSend = props.connectionState === "ready" && hasContent;
const onPressImage = useCallback((uri: string) => {
wasExpandedBeforePreviewRef.current = isFocused;
setPreviewImageUri(uri);
}, [isFocused]);
const onPressImage = useCallback(
(uri: string) => {
wasExpandedBeforePreviewRef.current = isFocused;
setPreviewImageUri(uri);
},
[isFocused],
);
const closePreview = useCallback(() => {
setPreviewImageUri(null);
@@ -134,8 +136,8 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}, []);
useEffect(() => {
props.onExpandedChange?.(isExpanded);
}, [isExpanded]);
onExpandedChange?.(isExpanded);
}, [isExpanded, onExpandedChange]);
const showStopAction =
props.selectedThread.session?.status === "running" ||
props.selectedThread.session?.status === "starting" ||
@@ -425,7 +427,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
{!isExpanded && props.draftAttachments.length > 0 ? (
<View style={{ flexDirection: "row", gap: 4, paddingLeft: 4 }}>
{props.draftAttachments.slice(0, 3).map((image) => (
<RNPressable key={image.id} onPress={() => onPressImage(image.previewUri)}>
<Pressable key={image.id} onPress={() => onPressImage(image.previewUri)}>
<Image
source={{ uri: image.previewUri }}
style={{
@@ -436,7 +438,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}}
resizeMode="cover"
/>
</RNPressable>
</Pressable>
))}
{props.draftAttachments.length > 3 ? (
<View
@@ -538,48 +540,14 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
) : null}
</View>
{/* Full-screen image preview modal */}
<Modal
<ImageViewing
images={previewImageUri ? [{ uri: previewImageUri }] : []}
imageIndex={0}
visible={previewImageUri !== null}
transparent={false}
animationType="fade"
presentationStyle="fullScreen"
onRequestClose={closePreview}
>
<View style={{ flex: 1, backgroundColor: "#000" }}>
<RNPressable
style={{ flex: 1, alignItems: "center", justifyContent: "center" }}
onPress={closePreview}
>
{previewImageUri ? (
<Image
source={{ uri: previewImageUri }}
style={{
width: Dimensions.get("window").width,
height: Dimensions.get("window").height * 0.75,
}}
resizeMode="contain"
/>
) : null}
</RNPressable>
<RNPressable
style={{
position: "absolute",
top: 60,
right: 20,
width: 36,
height: 36,
borderRadius: 18,
backgroundColor: "rgba(255,255,255,0.15)",
alignItems: "center",
justifyContent: "center",
}}
onPress={closePreview}
>
<SymbolView name="xmark" size={16} tintColor="#ffffff" type="monochrome" />
</RNPressable>
</View>
</Modal>
swipeToCloseEnabled
doubleTapToZoomEnabled
/>
</View>
);
});
+22 -62
View File
@@ -4,16 +4,9 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useState, useRef } from "react";
import Markdown from "react-native-markdown-display";
import {
Dimensions,
Image,
Modal,
Pressable,
ScrollView,
useColorScheme,
View,
} from "react-native";
import { Image, Pressable, ScrollView, useColorScheme, View } from "react-native";
import { TouchableOpacity } from "react-native-gesture-handler";
import ImageViewing from "react-native-image-viewing";
import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
@@ -502,12 +495,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}));
}, []);
const onPressImage = useCallback(
(uri: string, headers?: Record<string, string>) => {
setExpandedImage({ uri, headers });
},
[],
);
const onPressImage = useCallback((uri: string, headers?: Record<string, string>) => {
setExpandedImage({ uri, headers });
}, []);
const renderItem = useCallback(
(info: { item: ThreadFeedEntry; index: number }) =>
@@ -552,8 +542,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
);
}
const screenWidth = Dimensions.get("window").width;
return (
<View className="flex-1" style={{ minHeight: 0 }}>
<LegendList
@@ -566,7 +554,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
keyboardShouldPersistTaps="handled"
estimatedItemSize={80}
initialScrollAtEnd
maintainScrollAtEnd={{ onLayout: true, onItemLayout: true, onDataChange: true }}
maintainScrollAtEnd={{ on: { layout: true, itemLayout: true, dataChange: true } }}
maintainScrollAtEndThreshold={0.1}
maintainVisibleContentPosition
refreshing={props.refreshing ?? false}
@@ -578,51 +566,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}}
/>
{/* Full-screen image preview modal */}
<Modal
visible={expandedImage !== null}
transparent={false}
animationType="fade"
presentationStyle="fullScreen"
onRequestClose={() => setExpandedImage(null)}
>
<View style={{ flex: 1, backgroundColor: "#000" }}>
<Pressable
style={{ flex: 1, alignItems: "center", justifyContent: "center" }}
onPress={() => setExpandedImage(null)}
>
{expandedImage ? (
<Image
source={{
<ImageViewing
images={
expandedImage
? [
{
uri: expandedImage.uri,
...(expandedImage.headers ? { headers: expandedImage.headers } : {}),
}}
style={{
width: screenWidth,
height: Dimensions.get("window").height * 0.75,
}}
resizeMode="contain"
/>
) : null}
</Pressable>
<Pressable
style={{
position: "absolute",
top: 60,
right: 20,
width: 36,
height: 36,
borderRadius: 18,
backgroundColor: "rgba(255,255,255,0.15)",
alignItems: "center",
justifyContent: "center",
}}
onPress={() => setExpandedImage(null)}
>
<SymbolView name="xmark" size={16} tintColor="#ffffff" type="monochrome" />
</Pressable>
</View>
</Modal>
headers: expandedImage.headers,
},
]
: []
}
imageIndex={0}
visible={expandedImage !== null}
onRequestClose={() => setExpandedImage(null)}
swipeToCloseEnabled
doubleTapToZoomEnabled
/>
</View>
);
});
@@ -2,12 +2,22 @@ import { useLocalSearchParams, useRouter } from "expo-router";
import { useEffect, useMemo, useState } from "react";
import { ScrollView, useColorScheme, View } from "react-native";
import { useRemoteApp } from "../../state/remote-app-state-provider";
import { EmptyState } from "../../components/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen";
import { buildThreadRoutePath, dismissRoute } from "../../lib/routes";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { makeAppPalette } from "../../lib/theme";
import { connectionTone } from "../connection/connectionTone";
import { firstNonNull } from "../../state/remote-runtime-types";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import {
useRemoteConnectionStatus,
useRemoteEnvironmentState,
} from "../../state/use-remote-environment-registry";
import { useSelectedThreadCommands } from "../../state/use-selected-thread-commands";
import { useSelectedThreadGit } from "../../state/use-selected-thread-git";
import { useThreadComposerState } from "../../state/use-thread-composer-state";
import { useThreadSelection } from "../../state/use-thread-selection";
import { ThreadDetailScreen } from "./ThreadDetailScreen";
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
@@ -20,7 +30,22 @@ function firstRouteParam(value: string | string[] | undefined): string | null {
}
export function ThreadRouteScreen() {
const app = useRemoteApp();
const { isLoadingSavedConnection, environmentStateById } = useRemoteEnvironmentState();
const { connectionState, connectionError } = useRemoteConnectionStatus();
const { projects, threads } = useRemoteCatalog();
const {
onSelectThread,
selectedThread,
selectedEnvironmentConnection,
selectedEnvironmentRuntime,
} = useThreadSelection();
const composer = useThreadComposerState();
const git = useSelectedThreadGit();
const commands = useSelectedThreadCommands({
activePendingUserInput: composer.activePendingUserInput,
activePendingUserInputAnswers: composer.activePendingUserInputAnswers,
refreshSelectedThreadGitStatus: git.refreshSelectedThreadGitStatus,
});
const router = useRouter();
const colorScheme = useColorScheme();
const isDarkMode = colorScheme !== "light";
@@ -38,14 +63,13 @@ export function ThreadRouteScreen() {
}
return (
app.threads.find(
(thread) => thread.environmentId === environmentId && thread.id === threadId,
) ?? null
threads.find((thread) => thread.environmentId === environmentId && thread.id === threadId) ??
null
);
}, [app.threads, environmentId, threadId]);
}, [environmentId, threadId, threads]);
const selectedMatchesRoute =
app.selectedThread?.environmentId === environmentId && app.selectedThread?.id === threadId;
selectedThread?.environmentId === environmentId && selectedThread?.id === threadId;
useEffect(() => {
if (!routeThread) {
@@ -56,8 +80,8 @@ export function ThreadRouteScreen() {
return;
}
app.onSelectThread(routeThread);
}, [app, routeThread, selectedMatchesRoute]);
onSelectThread(routeThread);
}, [onSelectThread, routeThread, selectedMatchesRoute]);
if (!environmentId || !threadId) {
return <LoadingScreen message="Opening thread…" />;
@@ -65,9 +89,9 @@ export function ThreadRouteScreen() {
if (!routeThread) {
const stillHydrating =
app.isLoadingSavedConnection ||
app.connectionState === "connecting" ||
app.connectionState === "reconnecting";
isLoadingSavedConnection ||
connectionState === "connecting" ||
connectionState === "reconnecting";
if (stillHydrating) {
return <LoadingScreen message="Opening thread…" />;
@@ -92,74 +116,76 @@ export function ThreadRouteScreen() {
);
}
if (!selectedMatchesRoute || !app.selectedThread) {
if (!selectedMatchesRoute || !selectedThread) {
return <LoadingScreen message="Opening thread…" />;
}
const selectedThreadKey = scopedThreadKey(
app.selectedThread.environmentId,
app.selectedThread.id,
);
const selectedThreadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
const serverConfig =
selectedEnvironmentRuntime?.serverConfig ??
firstNonNull(Object.values(environmentStateById).map((runtime) => runtime.serverConfig));
return (
<View style={{ flex: 1 }}>
<ThreadDetailScreen
selectedThread={app.selectedThread}
screenTone={app.screenTone}
connectionError={app.connectionError}
httpBaseUrl={app.selectedEnvironmentBaseUrl}
bearerToken={app.selectedEnvironmentBearerToken}
selectedThreadFeed={app.selectedThreadFeed}
activeWorkDurationLabel={app.activeWorkDurationLabel}
activePendingApproval={app.activePendingApproval}
respondingApprovalId={app.respondingApprovalId}
activePendingUserInput={app.activePendingUserInput}
activePendingUserInputDrafts={app.activePendingUserInputDrafts}
activePendingUserInputAnswers={app.activePendingUserInputAnswers}
respondingUserInputId={app.respondingUserInputId}
draftMessage={app.draftMessage}
draftAttachments={app.draftAttachments}
connectionStateLabel={app.connectionState}
activeThreadBusy={app.activeThreadBusy}
selectedThreadGitStatus={app.selectedThreadGitStatus}
gitOperationLabel={app.gitOperationLabel}
selectedThreadQueueCount={app.selectedThreadQueueCount}
selectedThread={selectedThread}
screenTone={connectionTone(connectionState)}
connectionError={connectionError}
httpBaseUrl={selectedEnvironmentConnection?.httpBaseUrl ?? null}
bearerToken={selectedEnvironmentConnection?.bearerToken ?? null}
selectedThreadFeed={composer.selectedThreadFeed}
activeWorkDurationLabel={composer.activeWorkDurationLabel}
activePendingApproval={composer.activePendingApproval}
respondingApprovalId={commands.respondingApprovalId}
activePendingUserInput={composer.activePendingUserInput}
activePendingUserInputDrafts={composer.activePendingUserInputDrafts}
activePendingUserInputAnswers={composer.activePendingUserInputAnswers}
respondingUserInputId={commands.respondingUserInputId}
draftMessage={composer.draftMessage}
draftAttachments={composer.draftAttachments}
connectionStateLabel={connectionState}
activeThreadBusy={composer.activeThreadBusy}
selectedThreadGitStatus={git.selectedThreadGitStatus}
gitOperationLabel={git.gitOperationLabel}
selectedThreadQueueCount={composer.selectedThreadQueueCount}
onBack={() => dismissRoute(router)}
onOpenDrawer={() => setDrawerVisible(true)}
onOpenConnectionEditor={() => router.push("/connections")}
onChangeDraftMessage={app.onChangeDraftMessage}
onPickDraftImages={app.onPickDraftImages}
onNativePasteImages={app.onNativePasteImages}
onRemoveDraftImage={app.onRemoveDraftImage}
onRefresh={app.onRefresh}
onRefreshSelectedThreadGitStatus={app.onRefreshSelectedThreadGitStatus}
onListSelectedThreadBranches={app.onListSelectedThreadBranches}
onCheckoutSelectedThreadBranch={app.onCheckoutSelectedThreadBranch}
onCreateSelectedThreadBranch={app.onCreateSelectedThreadBranch}
onCreateSelectedThreadWorktree={app.onCreateSelectedThreadWorktree}
onPullSelectedThreadBranch={app.onPullSelectedThreadBranch}
onRunSelectedThreadGitAction={app.onRunSelectedThreadGitAction}
serverConfig={app.serverConfig}
onRenameThread={app.onRenameThread}
onStopThread={app.onStopThread}
onSendMessage={app.onSendMessage}
onUpdateThreadModelSelection={app.onUpdateThreadModelSelection}
onUpdateThreadRuntimeMode={app.onUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={app.onUpdateThreadInteractionMode}
onRespondToApproval={app.onRespondToApproval}
onSelectUserInputOption={app.onSelectUserInputOption}
onChangeUserInputCustomAnswer={app.onChangeUserInputCustomAnswer}
onSubmitUserInput={app.onSubmitUserInput}
onChangeDraftMessage={composer.onChangeDraftMessage}
onPickDraftImages={composer.onPickDraftImages}
onNativePasteImages={composer.onNativePasteImages}
onRemoveDraftImage={composer.onRemoveDraftImage}
onRefresh={commands.onRefresh}
onRefreshSelectedThreadGitStatus={async (options) => {
await git.refreshSelectedThreadGitStatus(options);
}}
onListSelectedThreadBranches={git.onListSelectedThreadBranches}
onCheckoutSelectedThreadBranch={git.onCheckoutSelectedThreadBranch}
onCreateSelectedThreadBranch={git.onCreateSelectedThreadBranch}
onCreateSelectedThreadWorktree={git.onCreateSelectedThreadWorktree}
onPullSelectedThreadBranch={git.onPullSelectedThreadBranch}
onRunSelectedThreadGitAction={git.onRunSelectedThreadGitAction}
serverConfig={serverConfig}
onRenameThread={commands.onRenameThread}
onStopThread={commands.onStopThread}
onSendMessage={composer.onSendMessage}
onUpdateThreadModelSelection={commands.onUpdateThreadModelSelection}
onUpdateThreadRuntimeMode={commands.onUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={commands.onUpdateThreadInteractionMode}
onRespondToApproval={commands.onRespondToApproval}
onSelectUserInputOption={composer.onSelectUserInputOption}
onChangeUserInputCustomAnswer={composer.onChangeUserInputCustomAnswer}
onSubmitUserInput={commands.onSubmitUserInput}
/>
<ThreadNavigationDrawer
visible={drawerVisible}
projects={app.projects}
threads={app.threads}
projects={projects}
threads={threads}
selectedThreadKey={selectedThreadKey}
onClose={() => setDrawerVisible(false)}
onSelectThread={(thread) => {
app.onSelectThread(thread);
onSelectThread(thread);
router.replace(buildThreadRoutePath(thread));
}}
onStartNewTask={() => router.push("/new")}
@@ -15,7 +15,8 @@ import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import type { ScopedMobileProject } from "../../lib/scopedEntities";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { useRemoteApp } from "../../state/remote-app-state-provider";
import { useProjectActions } from "../../state/use-project-actions";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
export type { ModelOption, ProviderGroup };
export type WorkspaceMode = "local" | "worktree";
@@ -90,9 +91,10 @@ type NewTaskFlowContextValue = {
readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
readonly selectBranch: (branch: GitBranch) => void;
readonly setPrompt: (value: string) => void;
readonly setAttachments: React.Dispatch<
React.SetStateAction<ReadonlyArray<DraftComposerImageAttachment>>
>;
readonly replaceAttachments: (attachments: ReadonlyArray<DraftComposerImageAttachment>) => void;
readonly appendAttachments: (attachments: ReadonlyArray<DraftComposerImageAttachment>) => void;
readonly removeAttachment: (imageId: string) => void;
readonly clearAttachments: () => void;
readonly setSubmitting: (value: boolean) => void;
readonly setBranchQuery: (value: string) => void;
readonly loadBranches: () => Promise<void>;
@@ -107,11 +109,12 @@ type NewTaskFlowContextValue = {
const NewTaskFlowContext = React.createContext<NewTaskFlowContextValue | null>(null);
export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const app = useRemoteApp();
const { projects, serverConfigByEnvironmentId, threads } = useRemoteCatalog();
const { onListProjectBranches } = useProjectActions();
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects: app.projects, threads: app.threads }),
[app.projects, app.threads],
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
);
const logicalProjects = useMemo(
() =>
@@ -128,7 +131,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
);
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState(
app.projects[0]?.environmentId ?? "",
projects[0]?.environmentId ?? "",
);
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
@@ -150,19 +153,41 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const [contextWindow, setContextWindow] = useState("1M");
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
const replaceAttachments = useCallback(
(nextAttachments: ReadonlyArray<DraftComposerImageAttachment>) => {
setAttachments(nextAttachments);
},
[],
);
const appendAttachments = useCallback(
(nextAttachments: ReadonlyArray<DraftComposerImageAttachment>) => {
setAttachments((current) => [...current, ...nextAttachments]);
},
[],
);
const removeAttachment = useCallback((imageId: string) => {
setAttachments((current) => current.filter((candidate) => candidate.id !== imageId));
}, []);
const clearAttachments = useCallback(() => {
setAttachments([]);
}, []);
const reset = useCallback(() => {
console.log("[new task flow] reset", {
defaultEnvironmentId: app.projects[0]?.environmentId ?? null,
projectCount: app.projects.length,
defaultEnvironmentId: projects[0]?.environmentId ?? null,
projectCount: projects.length,
});
setSelectedEnvironmentId(app.projects[0]?.environmentId ?? "");
setSelectedEnvironmentId(projects[0]?.environmentId ?? "");
setSelectedProjectKey(null);
setSelectedModelKey(null);
setWorkspaceMode("local");
setSelectedBranchName(null);
setSelectedWorktreePath(null);
setPrompt("");
setAttachments([]);
clearAttachments();
setSubmitting(false);
setBranchQuery("");
setBranchesLoading(false);
@@ -173,35 +198,35 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setFastMode(false);
setContextWindow("1M");
setExpandedProvider(null);
}, [app.projects]);
}, [clearAttachments, projects]);
useEffect(() => {
if (selectedEnvironmentId || app.projects.length === 0) {
if (selectedEnvironmentId || projects.length === 0) {
return;
}
console.log("[new task flow] initializing environment", {
environmentId: app.projects[0]!.environmentId,
environmentId: projects[0]!.environmentId,
});
setSelectedEnvironmentId(app.projects[0]!.environmentId);
}, [app.projects, selectedEnvironmentId]);
setSelectedEnvironmentId(projects[0]!.environmentId);
}, [projects, selectedEnvironmentId]);
const environments = useMemo(
() =>
[
...new Map(
app.projects.map((project) => [project.environmentId, project.environmentLabel]),
projects.map((project) => [project.environmentId, project.environmentLabel]),
).entries(),
].map(([environmentId, environmentLabel]) => ({
environmentId,
environmentLabel,
})),
[app.projects],
[projects],
);
const projectsForEnvironment = useMemo(
() => app.projects.filter((project) => project.environmentId === selectedEnvironmentId),
[app.projects, selectedEnvironmentId],
() => projects.filter((project) => project.environmentId === selectedEnvironmentId),
[projects, selectedEnvironmentId],
);
const selectedProject =
@@ -215,11 +240,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
() =>
buildModelOptions(
selectedProject
? (app.serverConfigByEnvironmentId[selectedProject.environmentId] ?? null)
? (serverConfigByEnvironmentId[selectedProject.environmentId] ?? null)
: null,
selectedProject?.defaultModelSelection ?? null,
),
[app.serverConfigByEnvironmentId, selectedProject],
[selectedProject, serverConfigByEnvironmentId],
);
const selectedModel =
@@ -276,7 +301,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setBranchesLoading(true);
try {
const branches = await app.onListProjectBranches(selectedProject);
const branches = await onListProjectBranches(selectedProject);
setAvailableBranches(branches);
if (workspaceMode === "worktree" && !selectedBranchName) {
@@ -291,7 +316,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
} finally {
setBranchesLoading(false);
}
}, [app, selectedBranchName, selectedProject, workspaceMode]);
}, [onListProjectBranches, selectedBranchName, selectedProject, workspaceMode]);
const value = useMemo<NewTaskFlowContextValue>(
() => ({
@@ -328,7 +353,10 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setWorkspaceMode,
selectBranch,
setPrompt,
setAttachments,
replaceAttachments,
appendAttachments,
removeAttachment,
clearAttachments,
setSubmitting,
setBranchQuery,
loadBranches,
@@ -356,6 +384,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
modelOptions,
prompt,
providerGroups,
replaceAttachments,
reset,
runtimeMode,
selectedBranchName,
@@ -371,6 +400,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
selectEnvironment,
submitting,
workspaceMode,
appendAttachments,
clearAttachments,
removeAttachment,
],
);
@@ -1,7 +1,7 @@
import type { ServerConfig as T3ServerConfig } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import type { StatusTone } from "../../components/StatusPill";
import { reverseCopy } from "../../lib/arrayCompat";
import type { ScopedMobileThread } from "../../lib/scopedEntities";
export function threadSortValue(thread: ScopedMobileThread): number {
@@ -56,16 +56,18 @@ export function messageImageUrl(httpBaseUrl: string | null, attachmentId: string
}
export function lastConversationLine(thread: ScopedMobileThread): string {
const candidate = reverseCopy(thread.messages).find(
const candidate = Arr.findLast(
thread.messages,
(message) => message.role === "user" || message.role === "assistant",
);
if (!candidate) {
if (candidate._tag === "None") {
return "No messages yet.";
}
const trimmed = candidate.text.trim();
const trimmed = candidate.value.text.trim();
if (trimmed.length === 0) {
return candidate.role === "assistant" ? "(empty assistant response)" : "(empty message)";
return candidate.value.role === "assistant" ? "(empty assistant response)" : "(empty message)";
}
return trimmed;
}
+4 -1
View File
@@ -1,3 +1,6 @@
import * as Effect from "effect/Effect";
import * as Random from "effect/Random";
export function newClientId(prefix: string): string {
return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
return `${prefix}-${Effect.runSync(Random.nextUUIDv4)}`;
}
-36
View File
@@ -1,36 +0,0 @@
import { describe, expect, it } from "vitest";
import { deriveMobileLayout } from "./mobileLayout";
describe("deriveMobileLayout", () => {
it("keeps phones in compact mode", () => {
expect(deriveMobileLayout({ width: 393, height: 852 })).toEqual({
variant: "compact",
usesSplitView: false,
listPaneWidth: null,
shellPadding: 0,
});
});
it("avoids split mode in short landscape phone layouts", () => {
expect(deriveMobileLayout({ width: 852, height: 393 }).variant).toBe("compact");
});
it("enables split mode on tablet-sized displays", () => {
expect(deriveMobileLayout({ width: 744, height: 1133 })).toMatchObject({
variant: "split",
usesSplitView: true,
listPaneWidth: 320,
shellPadding: 14,
});
});
it("caps the sidebar width on large tablets", () => {
expect(deriveMobileLayout({ width: 1366, height: 1024 })).toMatchObject({
variant: "split",
usesSplitView: true,
listPaneWidth: 420,
shellPadding: 20,
});
});
});
-37
View File
@@ -1,37 +0,0 @@
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
export type MobileLayoutVariant = "compact" | "split";
export interface MobileLayout {
readonly variant: MobileLayoutVariant;
readonly usesSplitView: boolean;
readonly listPaneWidth: number | null;
readonly shellPadding: number;
}
export function deriveMobileLayout(input: {
readonly width: number;
readonly height: number;
}): MobileLayout {
const { width, height } = input;
const shortestEdge = Math.min(width, height);
const wideEnoughForSplit = width >= 900 || (width >= 700 && shortestEdge >= 700);
if (!wideEnoughForSplit) {
return {
variant: "compact",
usesSplitView: false,
listPaneWidth: null,
shellPadding: 0,
};
}
return {
variant: "split",
usesSplitView: true,
listPaneWidth: clamp(Math.round(width * 0.34), 320, 420),
shellPadding: width >= 1180 ? 20 : 14,
};
}
+11 -17
View File
@@ -1,3 +1,4 @@
import * as Order from "effect/Order";
import type {
ChatAttachment,
MessageId,
@@ -7,7 +8,7 @@ import type {
OrchestrationThread,
ThreadId,
} from "@t3tools/contracts";
import { sortCopy } from "./arrayCompat";
import * as Arr from "effect/Array";
const MAX_THREAD_PROPOSED_PLANS = 200;
@@ -295,15 +296,15 @@ export function applyRealtimeEvent(
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => ({
...thread,
proposedPlans: sortCopy(
proposedPlans: Arr.sortWith(
[
...thread.proposedPlans.filter((proposedPlan) => {
return proposedPlan.id !== event.payload.proposedPlan.id;
}),
event.payload.proposedPlan,
],
(left, right) =>
left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
(s) => new Date(s.createdAt),
Order.Date,
).slice(-MAX_THREAD_PROPOSED_PLANS),
updatedAt: event.occurredAt,
})),
@@ -313,7 +314,7 @@ export function applyRealtimeEvent(
return {
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => {
const checkpoints = sortCopy(
const checkpoints = Arr.sortWith(
[
...thread.checkpoints.filter(
(checkpoint) => checkpoint.turnId !== event.payload.turnId,
@@ -328,7 +329,8 @@ export function applyRealtimeEvent(
completedAt: event.payload.completedAt,
},
],
(left, right) => left.checkpointTurnCount - right.checkpointTurnCount,
(s) => s.checkpointTurnCount,
Order.Number,
);
const latestTurnState =
@@ -365,21 +367,13 @@ export function applyRealtimeEvent(
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => ({
...thread,
activities: sortCopy(
activities: Arr.sortWith(
[
...thread.activities.filter((activity) => activity.id !== event.payload.activity.id),
event.payload.activity,
],
(left, right) => {
const leftSequence = left.sequence ?? Number.MIN_SAFE_INTEGER;
const rightSequence = right.sequence ?? Number.MIN_SAFE_INTEGER;
if (leftSequence !== rightSequence) {
return leftSequence - rightSequence;
}
return (
left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id)
);
},
(s) => new Date(s.createdAt),
Order.Date,
),
updatedAt: event.occurredAt,
})),
-755
View File
@@ -1,761 +1,6 @@
import {
type ClientOrchestrationCommand,
type GitCheckoutInput,
type GitCheckoutResult,
type GitCreateBranchInput,
type GitCreateBranchResult,
type GitCreateWorktreeInput,
type GitCreateWorktreeResult,
type GitListBranchesInput,
type GitListBranchesResult,
type GitPullInput,
type GitPullResult,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type GitStatusInput,
type GitStatusResult,
ORCHESTRATION_WS_METHODS,
type OrchestrationEvent,
type OrchestrationReadModel,
type ServerConfig,
WS_METHODS,
} from "@t3tools/contracts";
import {
RemoteEnvironmentAuthHttpError,
resolveRemoteWebSocketConnectionUrl,
} from "@t3tools/shared/remote";
import type { SavedRemoteConnection } from "./connection";
const REQUEST_TIMEOUT_MS = 60_000;
const PING_INTERVAL_MS = 5_000;
const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000] as const;
const EMPTY_HEADERS: ReadonlyArray<readonly [string, string]> = [];
const textDecoder = new TextDecoder();
type RpcRequestId = string;
type RpcRequestMessage = {
readonly _tag: "Request";
readonly id: RpcRequestId;
readonly tag: string;
readonly payload: unknown;
readonly headers: ReadonlyArray<readonly [string, string]>;
};
type RpcAckMessage = {
readonly _tag: "Ack";
readonly requestId: RpcRequestId;
};
type RpcPingMessage = {
readonly _tag: "Ping";
};
type RpcPongMessage = {
readonly _tag: "Pong";
};
type RpcChunkMessage = {
readonly _tag: "Chunk";
readonly requestId: RpcRequestId;
readonly values: ReadonlyArray<unknown>;
};
type RpcExitMessage = {
readonly _tag: "Exit";
readonly requestId: RpcRequestId;
readonly exit:
| {
readonly _tag: "Success";
readonly value: unknown;
}
| {
readonly _tag: "Failure";
readonly cause: unknown;
};
};
type RpcDefectMessage = {
readonly _tag: "Defect";
readonly defect: unknown;
};
type RpcInboundMessage =
| RpcAckMessage
| RpcChunkMessage
| RpcDefectMessage
| RpcExitMessage
| RpcPingMessage
| RpcPongMessage;
type PendingUnaryRequest = {
readonly kind: "unary";
readonly label: string;
readonly reject: (error: Error) => void;
readonly resolve: (value: unknown) => void;
readonly timeout: ReturnType<typeof setTimeout>;
};
type PendingStreamRequest = {
readonly kind: "stream";
readonly label: string;
readonly onChunk: (values: ReadonlyArray<unknown>) => void;
readonly onExit: (error?: Error) => void;
};
type PendingRequest = PendingStreamRequest | PendingUnaryRequest;
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function toMessage(error: unknown, fallback: string): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
if (typeof error === "string" && error.trim().length > 0) {
return error;
}
return fallback;
}
function extractRpcFailureMessage(error: unknown, fallback: string): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
if (typeof error === "string" && error.trim().length > 0) {
return error;
}
if (Array.isArray(error)) {
for (const entry of error) {
const message = extractRpcFailureMessage(entry, "");
if (message.length > 0) {
return message;
}
}
return fallback;
}
if (!isRecord(error)) {
return fallback;
}
for (const key of ["message", "defect", "error", "reason"] as const) {
const value = error[key];
if (typeof value === "string" && value.trim().length > 0) {
return value;
}
}
if ("cause" in error) {
const message = extractRpcFailureMessage(error.cause, "");
if (message.length > 0) {
return message;
}
}
try {
return JSON.stringify(error);
} catch {
return fallback;
}
}
function toRpcError(error: unknown, fallback: string): Error {
return new Error(extractRpcFailureMessage(error, fallback));
}
async function readWebSocketMessageData(data: unknown): Promise<string> {
if (typeof data === "string") {
return data;
}
if (data instanceof ArrayBuffer) {
return textDecoder.decode(data);
}
if (ArrayBuffer.isView(data)) {
return textDecoder.decode(data);
}
if (typeof Blob !== "undefined" && data instanceof Blob) {
return await data.text();
}
return String(data);
}
function parseRpcMessages(raw: string): ReadonlyArray<RpcInboundMessage> {
const decoded = JSON.parse(raw);
if (Array.isArray(decoded)) {
return decoded as ReadonlyArray<RpcInboundMessage>;
}
return [decoded as RpcInboundMessage];
}
export type RemoteClientConnectionState =
| "idle"
| "connecting"
| "ready"
| "reconnecting"
| "disconnected";
export type RemoteClientEvent =
| {
readonly type: "status";
readonly state: RemoteClientConnectionState;
readonly error?: string;
}
| { readonly type: "snapshot"; readonly snapshot: OrchestrationReadModel }
| { readonly type: "server-config"; readonly config: ServerConfig }
| { readonly type: "domain-event"; readonly event: OrchestrationEvent };
export class RemoteClient {
private socket: WebSocket | null = null;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private pingTimer: ReturnType<typeof setInterval> | null = null;
private reconnectAttempt = 0;
private awaitingPong = false;
private readonly listeners = new Set<(event: RemoteClientEvent) => void>();
private readonly pendingRequests = new Map<RpcRequestId, PendingRequest>();
private disposed = false;
private bootstrapped = false;
private bufferedDomainEvents: OrchestrationEvent[] = [];
private requestCounter = 0n;
private domainEventsRequestId: RpcRequestId | null = null;
private openGeneration = 0;
constructor(private readonly connection: SavedRemoteConnection) {}
addListener(listener: (event: RemoteClientEvent) => void): () => void {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
}
connect(): void {
this.disposed = false;
this.reconnectAttempt = 0;
this.clearReconnectTimer();
this.rejectPendingRequests(new Error("Reconnecting."));
this.closeSocket();
const generation = ++this.openGeneration;
void this.openWebSocket(generation);
}
disconnect(): void {
this.disposed = true;
this.bootstrapped = false;
this.bufferedDomainEvents = [];
this.domainEventsRequestId = null;
this.openGeneration += 1;
this.clearReconnectTimer();
this.stopPingLoop();
this.rejectPendingRequests(new Error("Remote connection closed."));
this.closeSocket();
this.emit({ type: "status", state: "idle" });
}
async refreshSnapshot(): Promise<OrchestrationReadModel> {
return await this.request(
ORCHESTRATION_WS_METHODS.getSnapshot,
{},
"Request timed out: getSnapshot",
);
}
async refreshServerConfig(): Promise<ServerConfig> {
return await this.request(
WS_METHODS.serverGetConfig,
{},
"Request timed out: server.getConfig",
);
}
async dispatchCommand(command: ClientOrchestrationCommand): Promise<void> {
await this.request(
ORCHESTRATION_WS_METHODS.dispatchCommand,
command,
"Request timed out: orchestration.dispatchCommand",
);
}
async gitRefreshStatus(input: GitStatusInput): Promise<GitStatusResult> {
return await this.request(
WS_METHODS.gitRefreshStatus,
input,
"Request timed out: git.refreshStatus",
);
}
async gitListBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
return await this.request(
WS_METHODS.gitListBranches,
input,
"Request timed out: git.listBranches",
);
}
async gitCreateBranch(input: GitCreateBranchInput): Promise<GitCreateBranchResult> {
return await this.request(
WS_METHODS.gitCreateBranch,
input,
"Request timed out: git.createBranch",
);
}
async gitCheckout(input: GitCheckoutInput): Promise<GitCheckoutResult> {
return await this.request(WS_METHODS.gitCheckout, input, "Request timed out: git.checkout");
}
async gitCreateWorktree(input: GitCreateWorktreeInput): Promise<GitCreateWorktreeResult> {
return await this.request(
WS_METHODS.gitCreateWorktree,
input,
"Request timed out: git.createWorktree",
);
}
async gitPull(input: GitPullInput): Promise<GitPullResult> {
return await this.request(WS_METHODS.gitPull, input, "Request timed out: git.pull");
}
async gitRunStackedAction(input: GitRunStackedActionInput): Promise<GitRunStackedActionResult> {
return await this.request(
WS_METHODS.gitRunStackedAction,
input,
"Request timed out: git.runStackedAction",
);
}
private emit(event: RemoteClientEvent): void {
for (const listener of this.listeners) {
try {
listener(event);
} catch {
// Ignore listener failures in the mobile client.
}
}
}
private async openWebSocket(generation: number): Promise<void> {
if (this.disposed || generation !== this.openGeneration) {
return;
}
this.emit({
type: "status",
state: this.reconnectAttempt > 0 ? "reconnecting" : "connecting",
});
let socketUrl: string;
try {
socketUrl = await resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: this.connection.wsBaseUrl,
httpBaseUrl: this.connection.httpBaseUrl,
bearerToken: this.connection.bearerToken,
});
} catch (error) {
if (this.disposed || generation !== this.openGeneration) {
return;
}
this.emit({
type: "status",
state: "disconnected",
error: toMessage(error, "Failed to prepare the remote websocket connection."),
});
if (error instanceof RemoteEnvironmentAuthHttpError && error.status === 401) {
return;
}
this.scheduleReconnect();
return;
}
if (this.disposed || generation !== this.openGeneration) {
return;
}
const socket = new WebSocket(socketUrl);
this.socket = socket;
socket.addEventListener("open", () => {
if (this.disposed || this.socket !== socket || generation !== this.openGeneration) {
socket.close();
return;
}
this.startPingLoop(socket);
void this.startSession(socket, generation);
});
socket.addEventListener("message", (event) => {
void this.handleSocketMessage(socket, event.data);
});
socket.addEventListener("error", () => {
// Close handles reconnect state and pending request cleanup.
});
socket.addEventListener("close", (event) => {
if (this.socket !== socket) {
return;
}
this.socket = null;
this.stopPingLoop();
this.bootstrapped = false;
this.bufferedDomainEvents = [];
this.domainEventsRequestId = null;
this.rejectPendingRequests(
new Error(
event.reason.trim().length > 0
? event.reason
: `Remote connection closed (${event.code}).`,
),
);
if (this.disposed) {
this.emit({ type: "status", state: "idle" });
return;
}
this.emit({
type: "status",
state: "disconnected",
error:
event.reason.trim().length > 0
? event.reason
: event.code === 1000
? undefined
: `Remote connection closed (${event.code}).`,
});
this.scheduleReconnect();
});
}
private async startSession(socket: WebSocket, generation: number): Promise<void> {
this.bootstrapped = false;
this.bufferedDomainEvents = [];
this.domainEventsRequestId = null;
this.subscribeToDomainEvents(socket);
try {
const [config, snapshot] = await Promise.all([
this.requestWithSocket<ServerConfig>(
socket,
WS_METHODS.serverGetConfig,
{},
"server.getConfig",
),
this.requestWithSocket<OrchestrationReadModel>(
socket,
ORCHESTRATION_WS_METHODS.getSnapshot,
{},
"orchestration.getSnapshot",
),
]);
if (this.socket !== socket || this.disposed || generation !== this.openGeneration) {
return;
}
const bufferedEvents = this.drainBufferedDomainEvents(snapshot.snapshotSequence);
this.bootstrapped = true;
this.reconnectAttempt = 0;
this.emit({ type: "server-config", config });
this.emit({ type: "snapshot", snapshot });
for (const event of bufferedEvents) {
this.emit({ type: "domain-event", event });
}
this.emit({ type: "status", state: "ready" });
} catch (error) {
if (this.socket !== socket || this.disposed || generation !== this.openGeneration) {
return;
}
this.emit({
type: "status",
state: "disconnected",
error: toMessage(error, "Failed to bootstrap remote connection."),
});
socket.close(1011, "Failed to bootstrap remote connection.");
}
}
private subscribeToDomainEvents(socket: WebSocket): void {
const requestId = this.createRequestId();
this.domainEventsRequestId = requestId;
this.pendingRequests.set(requestId, {
kind: "stream",
label: WS_METHODS.subscribeOrchestrationDomainEvents,
onChunk: (values) => {
for (const value of values) {
const event = value as OrchestrationEvent;
if (!this.bootstrapped) {
this.bufferedDomainEvents.push(event);
continue;
}
this.emit({ type: "domain-event", event });
}
},
onExit: (error) => {
if (this.domainEventsRequestId === requestId) {
this.domainEventsRequestId = null;
}
if (this.socket !== socket || this.disposed) {
return;
}
this.emit({
type: "status",
state: "disconnected",
error: toMessage(error, "Remote event stream disconnected."),
});
socket.close(1011, "Remote event stream disconnected.");
},
});
this.sendMessage(socket, {
_tag: "Request",
id: requestId,
tag: WS_METHODS.subscribeOrchestrationDomainEvents,
payload: {},
headers: EMPTY_HEADERS,
});
}
private async handleSocketMessage(socket: WebSocket, data: unknown): Promise<void> {
if (this.socket !== socket || this.disposed) {
return;
}
try {
const raw = await readWebSocketMessageData(data);
const messages = parseRpcMessages(raw);
for (const message of messages) {
if (this.socket !== socket || this.disposed) {
return;
}
this.handleInboundMessage(socket, message);
}
} catch (error) {
if (this.socket !== socket || this.disposed) {
return;
}
this.emit({
type: "status",
state: "disconnected",
error: toMessage(error, "Failed to decode remote message."),
});
socket.close(1003, "Failed to decode remote message.");
}
}
private handleInboundMessage(socket: WebSocket, message: RpcInboundMessage): void {
switch (message._tag) {
case "Pong": {
this.awaitingPong = false;
return;
}
case "Ping": {
this.sendMessage(socket, { _tag: "Pong" });
return;
}
case "Ack": {
return;
}
case "Defect": {
const error = toRpcError(message.defect, "Remote protocol defect.");
this.rejectPendingRequests(error);
this.emit({ type: "status", state: "disconnected", error: error.message });
socket.close(1011, error.message);
return;
}
case "Chunk": {
const pending = this.pendingRequests.get(message.requestId);
if (!pending || pending.kind !== "stream") {
return;
}
pending.onChunk(message.values);
this.sendMessage(socket, {
_tag: "Ack",
requestId: message.requestId,
});
return;
}
case "Exit": {
const pending = this.pendingRequests.get(message.requestId);
if (!pending) {
return;
}
this.pendingRequests.delete(message.requestId);
if (pending.kind === "unary") {
clearTimeout(pending.timeout);
if (message.exit._tag === "Success") {
pending.resolve(message.exit.value);
} else {
pending.reject(
toRpcError(message.exit.cause, `Remote request failed: ${pending.label}`),
);
}
return;
}
pending.onExit(
message.exit._tag === "Success"
? undefined
: toRpcError(message.exit.cause, `Remote stream failed: ${pending.label}`),
);
}
}
}
private drainBufferedDomainEvents(snapshotSequence: number): OrchestrationEvent[] {
const bufferedEvents = this.bufferedDomainEvents.filter(
(event) => event.sequence > snapshotSequence,
);
bufferedEvents.sort((left, right) => left.sequence - right.sequence);
this.bufferedDomainEvents = [];
return bufferedEvents;
}
private async request<T>(tag: string, payload: unknown, timeoutLabel: string): Promise<T> {
const socket = this.socket;
if (!socket || socket.readyState !== WebSocket.OPEN) {
throw new Error("Remote connection is not open yet.");
}
return await this.requestWithSocket<T>(socket, tag, payload, timeoutLabel);
}
private async requestWithSocket<T>(
socket: WebSocket,
tag: string,
payload: unknown,
timeoutLabel: string,
): Promise<T> {
const requestId = this.createRequestId();
return await new Promise<T>((resolve, reject) => {
if (this.socket !== socket || socket.readyState !== WebSocket.OPEN) {
reject(new Error("Remote connection is not open yet."));
return;
}
const timeout = setTimeout(() => {
if (!this.pendingRequests.has(requestId)) {
return;
}
this.pendingRequests.delete(requestId);
reject(new Error(timeoutLabel));
}, REQUEST_TIMEOUT_MS);
this.pendingRequests.set(requestId, {
kind: "unary",
label: tag,
timeout,
resolve: (value) => resolve(value as T),
reject,
});
try {
this.sendMessage(socket, {
_tag: "Request",
id: requestId,
tag,
payload,
headers: EMPTY_HEADERS,
});
} catch (error) {
clearTimeout(timeout);
this.pendingRequests.delete(requestId);
reject(toRpcError(error, `Failed to send remote request: ${tag}`));
}
});
}
private createRequestId(): RpcRequestId {
const requestId = this.requestCounter.toString();
this.requestCounter += 1n;
return requestId;
}
private sendMessage(
socket: WebSocket,
message: RpcAckMessage | RpcPingMessage | RpcPongMessage | RpcRequestMessage,
): void {
socket.send(JSON.stringify(message));
}
private rejectPendingRequests(error: Error): void {
for (const [requestId, pending] of this.pendingRequests) {
this.pendingRequests.delete(requestId);
if (pending.kind === "unary") {
clearTimeout(pending.timeout);
pending.reject(error);
continue;
}
pending.onExit(error);
}
}
private startPingLoop(socket: WebSocket): void {
this.stopPingLoop();
this.awaitingPong = false;
this.pingTimer = setInterval(() => {
if (this.socket !== socket || socket.readyState !== WebSocket.OPEN) {
this.stopPingLoop();
return;
}
if (this.awaitingPong) {
socket.close(1011, "Remote ping timed out.");
return;
}
this.awaitingPong = true;
this.sendMessage(socket, { _tag: "Ping" });
}, PING_INTERVAL_MS);
}
private stopPingLoop(): void {
if (this.pingTimer !== null) {
clearInterval(this.pingTimer);
this.pingTimer = null;
}
this.awaitingPong = false;
}
private scheduleReconnect(): void {
if (this.disposed || this.reconnectTimer !== null) {
return;
}
const delay =
RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)] ??
RECONNECT_DELAYS_MS[0];
this.reconnectAttempt += 1;
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
const generation = ++this.openGeneration;
void this.openWebSocket(generation);
}, delay);
}
private clearReconnectTimer(): void {
if (this.reconnectTimer !== null) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
}
private closeSocket(): void {
const socket = this.socket;
this.socket = null;
if (
socket &&
(socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)
) {
socket.close();
}
}
}
+11 -17
View File
@@ -1,6 +1,7 @@
import * as Order from "effect/Order";
import * as Arr from "effect/Array";
import type { RepositoryIdentity } from "@t3tools/contracts";
import { sortCopy } from "./arrayCompat";
import type { ScopedMobileProject, ScopedMobileThread } from "./scopedEntities";
import { scopedProjectKey } from "./scopedEntities";
@@ -76,12 +77,12 @@ export function groupProjectsByRepository(input: {
for (const project of input.projects) {
const key = deriveRepositoryGroupKey(project);
const projectKey = scopedProjectKey(project.environmentId, project.id);
const threads = sortCopy(threadsByProjectKey.get(projectKey) ?? [], (left, right) =>
compareIsoDateDescending(
left.updatedAt ?? left.createdAt,
right.updatedAt ?? right.createdAt,
),
const threads = Arr.sortWith(
threadsByProjectKey.get(projectKey) ?? [],
(s) => new Date(s.updatedAt ?? s.createdAt),
Order.Date,
);
const latestActivityAt = deriveProjectLatestActivity(project, threads);
const projectGroup: MobileRepositoryProjectGroup = {
key: projectKey,
@@ -116,20 +117,13 @@ export function groupProjectsByRepository(input: {
compareIsoDateDescending(existing.latestActivityAt, latestActivityAt) > 0
? latestActivityAt
: existing.latestActivityAt,
projects: sortCopy(
projects: Arr.sortWith(
[...existing.projects, projectGroup],
(left, right) =>
compareIsoDateDescending(left.latestActivityAt, right.latestActivityAt) ||
left.project.environmentLabel.localeCompare(right.project.environmentLabel) ||
left.project.title.localeCompare(right.project.title),
(s) => new Date(s.latestActivityAt),
Order.Date,
),
});
}
return sortCopy(
[...grouped.values()],
(left, right) =>
compareIsoDateDescending(left.latestActivityAt, right.latestActivityAt) ||
left.title.localeCompare(right.title),
);
return Arr.sortWith([...grouped.values()], (s) => new Date(s.latestActivityAt), Order.Date);
}
+1 -1
View File
@@ -1,6 +1,6 @@
import type { Router } from "expo-router";
import type { SelectedThreadRef } from "../state/use-remote-app-state";
import type { SelectedThreadRef } from "../state/remote-runtime-types";
import type { ScopedMobileThread } from "./scopedEntities";
type ThreadRouteInput =
+5 -115
View File
@@ -1,91 +1,21 @@
import { Platform } from "react-native";
import * as SecureStore from "expo-secure-store";
import type { SavedRemoteConnection } from "./connection";
const CONNECTIONS_KEY = "t3code:connections";
const memoryStorage = new Map<string, string>();
type AsyncStorageModule = typeof import("@react-native-async-storage/async-storage");
type AsyncStorageLike = Pick<AsyncStorageModule["default"], "getItem" | "setItem" | "removeItem">;
type SecureStoreModule = typeof import("expo-secure-store");
type SavedRemoteConnectionMetadata = Omit<SavedRemoteConnection, "bearerToken">;
let asyncStoragePromise: Promise<AsyncStorageLike | null> | null = null;
let secureStorePromise: Promise<SecureStoreModule | null> | null = null;
async function loadAsyncStorage(): Promise<AsyncStorageLike | null> {
if (!asyncStoragePromise) {
asyncStoragePromise = import("@react-native-async-storage/async-storage")
.then((module) => module.default)
.catch(() => null);
}
return await asyncStoragePromise;
}
async function loadSecureStore(): Promise<SecureStoreModule | null> {
if (Platform.OS === "web") {
return null;
}
if (!secureStorePromise) {
secureStorePromise = import("expo-secure-store").catch(() => null);
}
return await secureStorePromise;
}
async function readFallbackItem(key: string): Promise<string | null> {
return memoryStorage.get(key) ?? null;
}
async function writeFallbackItem(key: string, value: string): Promise<void> {
memoryStorage.set(key, value);
}
async function removeFallbackItem(key: string): Promise<void> {
memoryStorage.delete(key);
}
async function readStorageItem(key: string): Promise<string | null> {
const asyncStorage = await loadAsyncStorage();
if (!asyncStorage) {
return await readFallbackItem(key);
}
try {
return await asyncStorage.getItem(key);
} catch {
return await readFallbackItem(key);
}
return await SecureStore.getItemAsync(key);
}
async function writeStorageItem(key: string, value: string): Promise<void> {
const asyncStorage = await loadAsyncStorage();
if (!asyncStorage) {
await writeFallbackItem(key, value);
return;
}
try {
await asyncStorage.setItem(key, value);
} catch {
await writeFallbackItem(key, value);
}
await SecureStore.setItemAsync(key, value);
}
async function removeStorageItem(key: string): Promise<void> {
const asyncStorage = await loadAsyncStorage();
if (!asyncStorage) {
await removeFallbackItem(key);
return;
}
try {
await asyncStorage.removeItem(key);
} catch {
await removeFallbackItem(key);
}
await SecureStore.deleteItemAsync(key);
}
function connectionTokenKey(environmentId: string): string {
@@ -93,56 +23,16 @@ function connectionTokenKey(environmentId: string): string {
}
async function loadSecureToken(environmentId: string): Promise<string> {
const tokenKey = connectionTokenKey(environmentId);
if (Platform.OS === "web") {
return (await readStorageItem(tokenKey)) ?? "";
}
const secureStore = await loadSecureStore();
try {
if (secureStore) {
return (await secureStore.getItemAsync(tokenKey)) ?? "";
}
} catch {
// Fall through to async storage.
}
return (await readStorageItem(tokenKey)) ?? "";
return (await readStorageItem(connectionTokenKey(environmentId))) ?? "";
}
async function storeSecureToken(environmentId: string, token: string): Promise<void> {
const tokenKey = connectionTokenKey(environmentId);
if (token.trim().length === 0) {
if (Platform.OS === "web") {
await removeStorageItem(tokenKey);
return;
}
const secureStore = await loadSecureStore();
try {
await secureStore?.deleteItemAsync(tokenKey);
} catch {
// Ignore secure store cleanup failures and clear fallback storage.
}
await removeStorageItem(tokenKey);
return;
}
if (Platform.OS === "web") {
await writeStorageItem(tokenKey, token);
return;
}
const secureStore = await loadSecureStore();
try {
if (secureStore) {
await secureStore.setItemAsync(tokenKey, token);
return;
}
} catch {
// Fall through to async storage fallback.
}
await writeStorageItem(tokenKey, token);
}
+9 -36
View File
@@ -7,7 +7,8 @@ import type {
} from "@t3tools/contracts";
import type { DraftComposerImageAttachment } from "./composerImages";
import { sortCopy } from "./arrayCompat";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
export interface PendingApproval {
readonly requestId: ApprovalRequestId;
@@ -76,23 +77,6 @@ export type ThreadFeedEntry =
readonly activities: ReadonlyArray<ThreadFeedActivity>;
};
function compareActivitiesByOrder(
left: OrchestrationThreadActivity,
right: OrchestrationThreadActivity,
): number {
if (left.sequence !== undefined && right.sequence !== undefined) {
if (left.sequence !== right.sequence) {
return left.sequence - right.sequence;
}
} else if (left.sequence !== undefined) {
return 1;
} else if (right.sequence !== undefined) {
return -1;
}
return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
}
function requestKindFromRequestType(requestType: unknown): PendingApproval["requestKind"] | null {
switch (requestType) {
case "command_execution_approval":
@@ -230,14 +214,6 @@ function activityStatus(activity: OrchestrationThreadActivity): string | null {
return null;
}
function compareFeedEntries(left: RawThreadFeedEntry, right: RawThreadFeedEntry): number {
const byCreatedAt = left.createdAt.localeCompare(right.createdAt);
if (byCreatedAt !== 0) {
return byCreatedAt;
}
return left.id.localeCompare(right.id);
}
function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
if (entry.type !== "message") {
return false;
@@ -285,7 +261,7 @@ export function derivePendingApprovals(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): PendingApproval[] {
const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
const ordered = sortCopy(activities, compareActivitiesByOrder);
const ordered = Arr.sortWith(activities, (s) => new Date(s.createdAt), Order.Date);
for (const activity of ordered) {
const payload =
@@ -325,16 +301,14 @@ export function derivePendingApprovals(
}
}
return sortCopy([...openByRequestId.values()], (left, right) =>
left.createdAt.localeCompare(right.createdAt),
);
return Arr.sortWith([...openByRequestId.values()], (s) => new Date(s.createdAt), Order.Date);
}
export function derivePendingUserInputs(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): PendingUserInput[] {
const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
const ordered = sortCopy(activities, compareActivitiesByOrder);
const ordered = Arr.sortWith(activities, (s) => new Date(s.createdAt), Order.Date);
for (const activity of ordered) {
const payload =
@@ -371,9 +345,7 @@ export function derivePendingUserInputs(
}
}
return sortCopy([...openByRequestId.values()], (left, right) =>
left.createdAt.localeCompare(right.createdAt),
);
return Arr.sortWith(openByRequestId.values(), (s) => new Date(s.createdAt), Order.Date);
}
export function setPendingUserInputCustomAnswer(
@@ -416,7 +388,7 @@ export function buildThreadFeed(
const loadedMessages = options?.loadedMessages ?? thread.messages;
const oldestLoadedMessageCreatedAt =
options?.loadedMessages !== undefined ? (loadedMessages[0]?.createdAt ?? null) : null;
const entries = sortCopy(
const entries = Arr.sortWith(
[
...loadedMessages.map<RawThreadFeedEntry>((message) => ({
type: "message",
@@ -457,7 +429,8 @@ export function buildThreadFeed(
},
})),
],
compareFeedEntries,
(s) => new Date(s.createdAt),
Order.Date,
);
return groupAdjacentActivities(entries);
@@ -1,21 +0,0 @@
import React from "react";
import { type RemoteAppModel, useRemoteAppState } from "./use-remote-app-state";
const RemoteAppStateContext = React.createContext<RemoteAppModel | null>(null);
export function RemoteAppStateProvider(props: React.PropsWithChildren) {
const app = useRemoteAppState();
return (
<RemoteAppStateContext.Provider value={app}>{props.children}</RemoteAppStateContext.Provider>
);
}
export function useRemoteApp() {
const app = React.use(RemoteAppStateContext);
if (app === null) {
throw new Error("useRemoteApp must be used within RemoteAppStateProvider.");
}
return app;
}
@@ -0,0 +1,79 @@
import { useStore } from "zustand";
import { createStore } from "zustand/vanilla";
import type { SavedRemoteConnection } from "../lib/connection";
import {
defaultEnvironmentRuntimeState,
type EnvironmentRuntimeState,
} from "./remote-runtime-types";
export interface RemoteEnvironmentStoreState {
readonly isLoadingSavedConnection: boolean;
readonly connectionPairingUrl: string;
readonly pendingConnectionError: string | null;
readonly savedConnectionsById: Record<string, SavedRemoteConnection>;
readonly environmentStateById: Record<string, EnvironmentRuntimeState>;
readonly setIsLoadingSavedConnection: (value: boolean) => void;
readonly setConnectionPairingUrl: (pairingUrl: string) => void;
readonly clearConnectionPairingUrl: () => void;
readonly setPendingConnectionError: (message: string | null) => void;
readonly clearPendingConnectionError: () => void;
readonly replaceSavedConnections: (connections: Record<string, SavedRemoteConnection>) => void;
readonly upsertSavedConnection: (connection: SavedRemoteConnection) => void;
readonly removeSavedConnection: (environmentId: string) => void;
readonly patchEnvironmentRuntimeState: (
environmentId: string,
updater: (current: EnvironmentRuntimeState) => EnvironmentRuntimeState,
) => void;
readonly removeEnvironmentRuntimeState: (environmentId: string) => void;
}
export const remoteEnvironmentStore = createStore<RemoteEnvironmentStoreState>()((set) => ({
isLoadingSavedConnection: true,
connectionPairingUrl: "",
pendingConnectionError: null,
savedConnectionsById: {},
environmentStateById: {},
setIsLoadingSavedConnection: (value) => set({ isLoadingSavedConnection: value }),
setConnectionPairingUrl: (pairingUrl) => set({ connectionPairingUrl: pairingUrl }),
clearConnectionPairingUrl: () => set({ connectionPairingUrl: "" }),
setPendingConnectionError: (message) => set({ pendingConnectionError: message }),
clearPendingConnectionError: () => set({ pendingConnectionError: null }),
replaceSavedConnections: (connections) => set({ savedConnectionsById: connections }),
upsertSavedConnection: (connection) =>
set((state) => ({
savedConnectionsById: {
...state.savedConnectionsById,
[connection.environmentId]: connection,
},
})),
removeSavedConnection: (environmentId) =>
set((state) => {
const next = { ...state.savedConnectionsById };
delete next[environmentId];
return { savedConnectionsById: next };
}),
patchEnvironmentRuntimeState: (environmentId, updater) =>
set((state) => ({
environmentStateById: {
...state.environmentStateById,
[environmentId]: updater(
state.environmentStateById[environmentId] ?? defaultEnvironmentRuntimeState(),
),
},
})),
removeEnvironmentRuntimeState: (environmentId) =>
set((state) => {
const next = { ...state.environmentStateById };
delete next[environmentId];
return { environmentStateById: next };
}),
}));
export function useRemoteEnvironmentStore<T>(
selector: (state: RemoteEnvironmentStoreState) => T,
): T {
return useStore(remoteEnvironmentStore, selector);
}
@@ -0,0 +1,82 @@
import type { OrchestrationReadModel, ServerConfig as T3ServerConfig } from "@t3tools/contracts";
import type { EnvironmentConnection, WsRpcClient } from "@t3tools/client-runtime";
export type RemoteClientConnectionState =
| "idle"
| "connecting"
| "ready"
| "reconnecting"
| "disconnected";
export interface ConnectedEnvironmentSummary {
readonly environmentId: string;
readonly environmentLabel: string;
readonly displayUrl: string;
readonly connectionState: RemoteClientConnectionState;
readonly connectionError: string | null;
}
export interface SelectedThreadRef {
readonly environmentId: string;
readonly threadId: string;
}
export interface EnvironmentRuntimeState {
readonly connectionState: RemoteClientConnectionState;
readonly connectionError: string | null;
readonly snapshot: OrchestrationReadModel | null;
readonly serverConfig: T3ServerConfig | null;
}
export interface EnvironmentSession {
readonly client: WsRpcClient;
readonly connection: EnvironmentConnection;
}
export type GetEnvironmentClient = (environmentId: string) => WsRpcClient | null;
export function defaultEnvironmentRuntimeState(): EnvironmentRuntimeState {
return {
connectionState: "idle",
connectionError: null,
snapshot: null,
serverConfig: null,
};
}
export function firstNonNull<T>(values: ReadonlyArray<T | null | undefined>): T | null {
for (const value of values) {
if (value !== null && value !== undefined) {
return value;
}
}
return null;
}
export function deriveThreadTitleFromPrompt(value: string): string {
const trimmed = value.trim();
if (trimmed.length === 0) {
return "New thread";
}
const compact = trimmed.replace(/\s+/g, " ");
return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
}
export function deriveOverallConnectionState(
environments: ReadonlyArray<ConnectedEnvironmentSummary>,
): RemoteClientConnectionState {
if (environments.length === 0) {
return "idle";
}
if (environments.some((environment) => environment.connectionState === "ready")) {
return "ready";
}
if (environments.some((environment) => environment.connectionState === "reconnecting")) {
return "reconnecting";
}
if (environments.some((environment) => environment.connectionState === "connecting")) {
return "connecting";
}
return "disconnected";
}
@@ -0,0 +1,23 @@
import type { ApprovalRequestId } from "@t3tools/contracts";
import { useStore } from "zustand";
import { createStore } from "zustand/vanilla";
interface ThreadApprovalStoreState {
readonly respondingApprovalId: ApprovalRequestId | null;
readonly beginRespondingApproval: (requestId: ApprovalRequestId) => void;
readonly finishRespondingApproval: (requestId: ApprovalRequestId) => void;
}
export const threadApprovalStore = createStore<ThreadApprovalStoreState>()((set) => ({
respondingApprovalId: null,
beginRespondingApproval: (requestId) => set({ respondingApprovalId: requestId }),
finishRespondingApproval: (requestId) =>
set((state) => ({
respondingApprovalId:
state.respondingApprovalId === requestId ? null : state.respondingApprovalId,
})),
}));
export function useThreadApprovalStore<T>(selector: (state: ThreadApprovalStoreState) => T): T {
return useStore(threadApprovalStore, selector);
}
@@ -0,0 +1,123 @@
import type { ThreadId } from "@t3tools/contracts";
import { useStore } from "zustand";
import { createStore } from "zustand/vanilla";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { scopedThreadKey } from "../lib/scopedEntities";
import type { QueuedThreadMessage } from "../lib/threadActivity";
interface ThreadComposerStoreState {
readonly nowTick: number;
readonly draftMessageByThreadKey: Record<string, string>;
readonly draftAttachmentsByThreadKey: Record<string, ReadonlyArray<DraftComposerImageAttachment>>;
readonly dispatchingQueuedMessageId: string | null;
readonly queuedMessagesByThreadKey: Record<string, ReadonlyArray<QueuedThreadMessage>>;
readonly setNowTick: (tick: number) => void;
readonly setDraftMessage: (threadKey: string, value: string) => void;
readonly appendDraftAttachments: (
threadKey: string,
attachments: ReadonlyArray<DraftComposerImageAttachment>,
) => void;
readonly appendDraftMessage: (threadKey: string, value: string) => void;
readonly clearDraft: (threadKey: string) => void;
readonly removeDraftImage: (threadKey: string, imageId: string) => void;
readonly beginDispatchingQueuedMessage: (queuedMessageId: string) => void;
readonly finishDispatchingQueuedMessage: (queuedMessageId: string) => void;
readonly enqueueQueuedMessage: (message: QueuedThreadMessage) => void;
readonly removeQueuedMessage: (
environmentId: string,
threadId: ThreadId,
queuedMessageId: string,
) => void;
}
export const threadComposerStore = createStore<ThreadComposerStoreState>()((set) => ({
nowTick: Date.now(),
draftMessageByThreadKey: {},
draftAttachmentsByThreadKey: {},
dispatchingQueuedMessageId: null,
queuedMessagesByThreadKey: {},
setNowTick: (tick) => set({ nowTick: tick }),
setDraftMessage: (threadKey, value) =>
set((state) => ({
draftMessageByThreadKey: {
...state.draftMessageByThreadKey,
[threadKey]: value,
},
})),
appendDraftAttachments: (threadKey, attachments) =>
set((state) => ({
draftAttachmentsByThreadKey: {
...state.draftAttachmentsByThreadKey,
[threadKey]: [...(state.draftAttachmentsByThreadKey[threadKey] ?? []), ...attachments],
},
})),
appendDraftMessage: (threadKey, value) =>
set((state) => ({
draftMessageByThreadKey: {
...state.draftMessageByThreadKey,
[threadKey]: `${state.draftMessageByThreadKey[threadKey] ?? ""}${value}`,
},
})),
clearDraft: (threadKey) =>
set((state) => ({
draftMessageByThreadKey: {
...state.draftMessageByThreadKey,
[threadKey]: "",
},
draftAttachmentsByThreadKey: {
...state.draftAttachmentsByThreadKey,
[threadKey]: [],
},
})),
removeDraftImage: (threadKey, imageId) =>
set((state) => ({
draftAttachmentsByThreadKey: {
...state.draftAttachmentsByThreadKey,
[threadKey]: (state.draftAttachmentsByThreadKey[threadKey] ?? []).filter(
(image) => image.id !== imageId,
),
},
})),
beginDispatchingQueuedMessage: (queuedMessageId) =>
set({ dispatchingQueuedMessageId: queuedMessageId }),
finishDispatchingQueuedMessage: (queuedMessageId) =>
set((state) => ({
dispatchingQueuedMessageId:
state.dispatchingQueuedMessageId === queuedMessageId
? null
: state.dispatchingQueuedMessageId,
})),
enqueueQueuedMessage: (message) =>
set((state) => {
const threadKey = scopedThreadKey(message.environmentId, message.threadId);
return {
queuedMessagesByThreadKey: {
...state.queuedMessagesByThreadKey,
[threadKey]: [...(state.queuedMessagesByThreadKey[threadKey] ?? []), message],
},
};
}),
removeQueuedMessage: (environmentId, threadId, queuedMessageId) =>
set((state) => {
const threadKey = scopedThreadKey(environmentId, threadId);
const existing = state.queuedMessagesByThreadKey[threadKey];
if (!existing) {
return state;
}
const nextQueue = existing.filter((entry) => entry.id !== queuedMessageId);
const next = { ...state.queuedMessagesByThreadKey };
if (nextQueue.length === 0) {
delete next[threadKey];
} else {
next[threadKey] = nextQueue;
}
return { queuedMessagesByThreadKey: next };
}),
}));
export function useThreadComposerStore<T>(selector: (state: ThreadComposerStoreState) => T): T {
return useStore(threadComposerStore, selector);
}
+45
View File
@@ -0,0 +1,45 @@
import type { GitStatusResult } from "@t3tools/contracts";
import { useStore } from "zustand";
import { createStore } from "zustand/vanilla";
interface ThreadGitStoreState {
readonly gitStatusByThreadKey: Record<string, GitStatusResult | null>;
readonly gitOperationLabelByThreadKey: Record<string, string | null>;
readonly setThreadGitStatus: (threadKey: string, status: GitStatusResult | null) => void;
readonly setThreadGitOperationLabel: (threadKey: string, label: string | null) => void;
readonly clearThreadGitState: (threadKey: string) => void;
}
export const threadGitStore = createStore<ThreadGitStoreState>()((set) => ({
gitStatusByThreadKey: {},
gitOperationLabelByThreadKey: {},
setThreadGitStatus: (threadKey, status) =>
set((state) => ({
gitStatusByThreadKey: {
...state.gitStatusByThreadKey,
[threadKey]: status,
},
})),
setThreadGitOperationLabel: (threadKey, label) =>
set((state) => ({
gitOperationLabelByThreadKey: {
...state.gitOperationLabelByThreadKey,
[threadKey]: label,
},
})),
clearThreadGitState: (threadKey) =>
set((state) => {
const nextStatus = { ...state.gitStatusByThreadKey };
const nextLabel = { ...state.gitOperationLabelByThreadKey };
delete nextStatus[threadKey];
delete nextLabel[threadKey];
return {
gitStatusByThreadKey: nextStatus,
gitOperationLabelByThreadKey: nextLabel,
};
}),
}));
export function useThreadGitStore<T>(selector: (state: ThreadGitStoreState) => T): T {
return useStore(threadGitStore, selector);
}
@@ -0,0 +1,20 @@
import { useStore } from "zustand";
import { createStore } from "zustand/vanilla";
import type { SelectedThreadRef } from "./remote-runtime-types";
interface ThreadSelectionStoreState {
readonly selectedThreadRef: SelectedThreadRef | null;
readonly selectThreadRef: (threadRef: SelectedThreadRef) => void;
readonly clearSelectedThreadRef: () => void;
}
export const threadSelectionStore = createStore<ThreadSelectionStoreState>()((set) => ({
selectedThreadRef: null,
selectThreadRef: (threadRef) => set({ selectedThreadRef: threadRef }),
clearSelectedThreadRef: () => set({ selectedThreadRef: null }),
}));
export function useThreadSelectionStore<T>(selector: (state: ThreadSelectionStoreState) => T): T {
return useStore(threadSelectionStore, selector);
}
@@ -0,0 +1,63 @@
import type { ApprovalRequestId } from "@t3tools/contracts";
import { useStore } from "zustand";
import { createStore } from "zustand/vanilla";
import {
setPendingUserInputCustomAnswer,
type PendingUserInputDraftAnswer,
} from "../lib/threadActivity";
interface ThreadUserInputStoreState {
readonly userInputDraftsByRequestKey: Record<string, Record<string, PendingUserInputDraftAnswer>>;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly setUserInputDraftOption: (requestKey: string, questionId: string, label: string) => void;
readonly setUserInputDraftCustomAnswer: (
requestKey: string,
questionId: string,
customAnswer: string,
) => void;
readonly beginRespondingUserInput: (requestId: ApprovalRequestId) => void;
readonly finishRespondingUserInput: (requestId: ApprovalRequestId) => void;
}
export const threadUserInputStore = createStore<ThreadUserInputStoreState>()((set) => ({
userInputDraftsByRequestKey: {},
respondingUserInputId: null,
setUserInputDraftOption: (requestKey, questionId, label) =>
set((state) => ({
userInputDraftsByRequestKey: {
...state.userInputDraftsByRequestKey,
[requestKey]: {
...state.userInputDraftsByRequestKey[requestKey],
[questionId]: {
selectedOptionLabel: label,
},
},
},
})),
setUserInputDraftCustomAnswer: (requestKey, questionId, customAnswer) =>
set((state) => ({
userInputDraftsByRequestKey: {
...state.userInputDraftsByRequestKey,
[requestKey]: {
...state.userInputDraftsByRequestKey[requestKey],
[questionId]: setPendingUserInputCustomAnswer(
state.userInputDraftsByRequestKey[requestKey]?.[questionId],
customAnswer,
),
},
},
})),
beginRespondingUserInput: (requestId) => set({ respondingUserInputId: requestId }),
finishRespondingUserInput: (requestId) =>
set((state) => ({
respondingUserInputId:
state.respondingUserInputId === requestId ? null : state.respondingUserInputId,
})),
}));
export function useThreadUserInputStore<T>(selector: (state: ThreadUserInputStoreState) => T): T {
return useStore(threadUserInputStore, selector);
}
@@ -0,0 +1,279 @@
import { useCallback } from "react";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
MessageId,
ThreadId,
type GitBranch,
type ModelSelection,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import { sanitizeFeatureBranchName } from "@t3tools/shared/git";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { newClientId } from "../lib/clientId";
import type { ScopedMobileProject } from "../lib/scopedEntities";
import { buildTemporaryWorktreeBranchName } from "../lib/worktrees";
import { deriveThreadTitleFromPrompt } from "./remote-runtime-types";
import { useRemoteEnvironmentStore } from "./remote-environment-store";
import { useRemoteCatalog } from "./use-remote-catalog";
import { getEnvironmentClient, useRemoteEnvironmentState } from "./use-remote-environment-registry";
import { useThreadSelectionStore } from "./thread-selection-store";
function useRefreshRemoteData() {
const { savedConnectionsById } = useRemoteEnvironmentState();
const patchEnvironmentRuntimeState = useRemoteEnvironmentStore(
(state) => state.patchEnvironmentRuntimeState,
);
return useCallback(
async (environmentIds?: ReadonlyArray<string>) => {
const targets = environmentIds ?? Object.keys(savedConnectionsById);
await Promise.all(
targets.map(async (environmentId) => {
const client = getEnvironmentClient(environmentId);
if (!client) {
return;
}
try {
const [serverConfig, snapshot] = await Promise.all([
client.server.getConfig(),
client.orchestration.getSnapshot(),
]);
patchEnvironmentRuntimeState(environmentId, (current) => ({
...current,
serverConfig,
snapshot,
connectionError: null,
}));
} catch (error) {
patchEnvironmentRuntimeState(environmentId, (current) => ({
...current,
connectionError:
error instanceof Error ? error.message : "Failed to refresh remote data.",
}));
}
}),
);
},
[patchEnvironmentRuntimeState, savedConnectionsById],
);
}
export function useProjectActions() {
const { threads } = useRemoteCatalog();
const refreshRemoteData = useRefreshRemoteData();
const setPendingConnectionError = useRemoteEnvironmentStore(
(state) => state.setPendingConnectionError,
);
const selectThreadRef = useThreadSelectionStore((state) => state.selectThreadRef);
const onCreateThreadWithOptions = useCallback(
async (input: {
readonly project: ScopedMobileProject;
readonly modelSelection: ModelSelection;
readonly envMode: "local" | "worktree";
readonly branch: string | null;
readonly worktreePath: string | null;
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode;
readonly initialMessageText: string;
readonly initialAttachments: ReadonlyArray<DraftComposerImageAttachment>;
}) => {
const client = getEnvironmentClient(input.project.environmentId);
if (!client) {
return null;
}
const threadId = ThreadId.makeUnsafe(newClientId("thread"));
const createdAt = new Date().toISOString();
const initialMessageText = input.initialMessageText.trim();
const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
if (input.envMode === "worktree") {
if (!input.branch || initialMessageText.length === 0) {
return null;
}
await client.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe(newClientId("command")),
threadId,
message: {
messageId: MessageId.makeUnsafe(newClientId("message")),
role: "user",
text: initialMessageText,
attachments: input.initialAttachments,
},
modelSelection: input.modelSelection,
titleSeed: nextTitle,
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
bootstrap: {
createThread: {
projectId: input.project.id,
title: nextTitle,
modelSelection: input.modelSelection,
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
branch: input.branch,
worktreePath: null,
createdAt,
},
prepareWorktree: {
projectCwd: input.project.workspaceRoot,
baseBranch: input.branch,
branch: buildTemporaryWorktreeBranchName(),
},
runSetupScript: true,
},
createdAt: new Date().toISOString(),
});
} else {
await client.orchestration.dispatchCommand({
type: "thread.create",
commandId: CommandId.makeUnsafe(newClientId("command")),
threadId,
projectId: input.project.id,
title: nextTitle,
modelSelection: input.modelSelection,
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
branch: input.branch,
worktreePath: input.worktreePath,
createdAt,
});
if (initialMessageText.length > 0 || input.initialAttachments.length > 0) {
await client.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe(newClientId("command")),
threadId,
message: {
messageId: MessageId.makeUnsafe(newClientId("message")),
role: "user",
text: initialMessageText,
attachments: input.initialAttachments,
},
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
createdAt: new Date().toISOString(),
});
}
}
selectThreadRef({
environmentId: input.project.environmentId,
threadId,
});
await refreshRemoteData([input.project.environmentId]);
return {
environmentId: input.project.environmentId,
threadId,
};
},
[refreshRemoteData, selectThreadRef],
);
const onCreateThread = useCallback(
async (project: ScopedMobileProject) => {
const latestProjectThread =
threads.find(
(thread) =>
thread.environmentId === project.environmentId && thread.projectId === project.id,
) ?? null;
const modelSelection =
project.defaultModelSelection ?? latestProjectThread?.modelSelection ?? null;
if (!modelSelection) {
setPendingConnectionError("This project does not have a default model configured yet.");
return null;
}
return await onCreateThreadWithOptions({
project,
modelSelection,
envMode: "local",
branch: null,
worktreePath: null,
runtimeMode: DEFAULT_RUNTIME_MODE,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
initialMessageText: "",
initialAttachments: [],
});
},
[onCreateThreadWithOptions, setPendingConnectionError, threads],
);
const onListProjectBranches = useCallback(
async (project: ScopedMobileProject): Promise<ReadonlyArray<GitBranch>> => {
const client = getEnvironmentClient(project.environmentId);
if (!client) {
return [];
}
try {
const result = await client.git.listBranches({
cwd: project.workspaceRoot,
limit: 100,
});
return result.branches.filter((branch) => !branch.isRemote);
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to load branches.",
);
return [];
}
},
[setPendingConnectionError],
);
const onCreateProjectWorktree = useCallback(
async (
project: ScopedMobileProject,
nextWorktree: {
readonly baseBranch: string;
readonly newBranch: string;
},
): Promise<{
readonly branch: string;
readonly worktreePath: string;
} | null> => {
const client = getEnvironmentClient(project.environmentId);
if (!client) {
return null;
}
try {
const result = await client.git.createWorktree({
cwd: project.workspaceRoot,
branch: nextWorktree.baseBranch,
newBranch: sanitizeFeatureBranchName(nextWorktree.newBranch),
path: null,
});
return {
branch: result.worktree.branch,
worktreePath: result.worktree.path,
};
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to create worktree.",
);
return null;
}
},
[setPendingConnectionError],
);
return {
onCreateThread,
onCreateThreadWithOptions,
onListProjectBranches,
onCreateProjectWorktree,
onRefreshProjects: refreshRemoteData,
};
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,92 @@
import { useMemo } from "react";
import type { ServerConfig as T3ServerConfig } from "@t3tools/contracts";
import { sortCopy } from "../lib/arrayCompat";
import type { ScopedMobileProject, ScopedMobileThread } from "../lib/scopedEntities";
import {
deriveOverallConnectionState,
type RemoteClientConnectionState,
} from "./remote-runtime-types";
import {
useRemoteConnectionStatus,
useRemoteEnvironmentState,
} from "./use-remote-environment-registry";
export function useRemoteCatalog() {
const { connectedEnvironments, connectionState } = useRemoteConnectionStatus();
const { environmentStateById, savedConnectionsById } = useRemoteEnvironmentState();
const projects = useMemo<ReadonlyArray<ScopedMobileProject>>(
() =>
sortCopy(
Object.values(savedConnectionsById).flatMap((connection) =>
(environmentStateById[connection.environmentId]?.snapshot?.projects ?? [])
.filter((project) => project.deletedAt === null)
.map((project) =>
Object.assign({}, project, {
environmentId: connection.environmentId,
environmentLabel: connection.environmentLabel,
}),
),
),
(left, right) =>
left.title.localeCompare(right.title) ||
left.environmentLabel.localeCompare(right.environmentLabel),
),
[environmentStateById, savedConnectionsById],
);
const threads = useMemo<ReadonlyArray<ScopedMobileThread>>(
() =>
sortCopy(
Object.values(savedConnectionsById).flatMap((connection) =>
(environmentStateById[connection.environmentId]?.snapshot?.threads ?? [])
.filter((thread) => thread.deletedAt === null)
.map((thread) =>
Object.assign({}, thread, {
environmentId: connection.environmentId,
environmentLabel: connection.environmentLabel,
}),
),
),
(left, right) =>
new Date(right.updatedAt ?? right.createdAt).getTime() -
new Date(left.updatedAt ?? left.createdAt).getTime() ||
right.environmentLabel.localeCompare(left.environmentLabel),
),
[environmentStateById, savedConnectionsById],
);
const serverConfigByEnvironmentId = useMemo<Readonly<Record<string, T3ServerConfig | null>>>(
() =>
Object.fromEntries(
Object.entries(environmentStateById).map(([environmentId, runtime]) => [
environmentId,
runtime.serverConfig ?? null,
]),
),
[environmentStateById],
);
const overallConnectionState = useMemo<RemoteClientConnectionState>(
() => deriveOverallConnectionState(connectedEnvironments),
[connectedEnvironments],
);
const hasRemoteActivity = useMemo(
() =>
threads.some(
(thread) => thread.session?.status === "running" || thread.session?.status === "starting",
),
[threads],
);
return {
projects,
threads,
serverConfigByEnvironmentId,
connectionState: connectionState ?? overallConnectionState,
hasRemoteActivity,
};
}
@@ -0,0 +1,401 @@
import { useCallback, useEffect, useMemo } from "react";
import { Alert } from "react-native";
import {
createEnvironmentConnection,
createKnownEnvironment,
createWsRpcClient,
WsTransport,
} from "@t3tools/client-runtime";
import { EnvironmentId, type OrchestrationReadModel } from "@t3tools/contracts";
import { resolveRemoteWebSocketConnectionUrl } from "@t3tools/shared/remote";
import { useShallow } from "zustand/react/shallow";
import { sortCopy } from "../lib/arrayCompat";
import { type SavedRemoteConnection, bootstrapRemoteConnection } from "../lib/connection";
import { applyRealtimeEvent, requiresSnapshotRefresh } from "../lib/orchestration";
import { clearSavedConnection, loadSavedConnections, saveConnection } from "../lib/storage";
import {
firstNonNull,
type ConnectedEnvironmentSummary,
type EnvironmentSession,
type RemoteClientConnectionState,
} from "./remote-runtime-types";
import { remoteEnvironmentStore, useRemoteEnvironmentStore } from "./remote-environment-store";
import { useThreadSelectionStore } from "./thread-selection-store";
const environmentSessions = new Map<string, EnvironmentSession>();
function setEnvironmentConnectionStatus(
environmentId: string,
state: ConnectedEnvironmentSummary["connectionState"],
error?: string | null,
) {
remoteEnvironmentStore.getState().patchEnvironmentRuntimeState(environmentId, (current) => ({
...current,
connectionState: state,
connectionError: error === undefined ? current.connectionError : error,
}));
}
export function getEnvironmentClient(environmentId: string) {
return environmentSessions.get(environmentId)?.client ?? null;
}
export async function disconnectEnvironment(
environmentId: string,
options?: { readonly removeSaved?: boolean },
) {
const session = environmentSessions.get(environmentId);
environmentSessions.delete(environmentId);
await session?.connection.dispose();
remoteEnvironmentStore.getState().removeEnvironmentRuntimeState(environmentId);
if (options?.removeSaved) {
await clearSavedConnection(environmentId);
remoteEnvironmentStore.getState().removeSavedConnection(environmentId);
}
}
export async function connectSavedEnvironment(
connection: SavedRemoteConnection,
options?: { readonly persist?: boolean },
) {
await disconnectEnvironment(connection.environmentId);
if (options?.persist !== false) {
await saveConnection(connection);
}
const store = remoteEnvironmentStore.getState();
store.upsertSavedConnection(connection);
setEnvironmentConnectionStatus(connection.environmentId, "connecting", null);
const transport = new WsTransport(
() =>
resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: connection.wsBaseUrl,
httpBaseUrl: connection.httpBaseUrl,
bearerToken: connection.bearerToken,
}),
{
onAttempt: () => {
remoteEnvironmentStore
.getState()
.patchEnvironmentRuntimeState(connection.environmentId, (previous) => {
const nextState =
previous.connectionState === "ready" ||
previous.connectionState === "reconnecting" ||
previous.connectionState === "disconnected"
? "reconnecting"
: "connecting";
return {
...previous,
connectionState: nextState,
connectionError: null,
};
});
},
onError: (message) => {
setEnvironmentConnectionStatus(connection.environmentId, "disconnected", message);
},
onClose: (details) => {
const reason =
details.reason.trim().length > 0
? details.reason
: details.code === 1000
? null
: `Remote connection closed (${details.code}).`;
setEnvironmentConnectionStatus(connection.environmentId, "disconnected", reason);
},
},
);
const client = createWsRpcClient(transport);
const environmentConnection = createEnvironmentConnection({
kind: "saved",
knownEnvironment: {
...createKnownEnvironment({
id: connection.environmentId,
label: connection.environmentLabel,
source: "manual",
target: {
httpBaseUrl: connection.httpBaseUrl,
wsBaseUrl: connection.wsBaseUrl,
},
}),
environmentId: EnvironmentId.makeUnsafe(connection.environmentId),
},
client,
applyEventBatch: (events, environmentId) => {
remoteEnvironmentStore.getState().patchEnvironmentRuntimeState(environmentId, (runtime) => ({
...runtime,
snapshot: runtime.snapshot
? events.reduce(
(snapshot, event) => applyRealtimeEvent(snapshot, event),
runtime.snapshot,
)
: runtime.snapshot,
}));
if (events.some((event) => requiresSnapshotRefresh(event))) {
void environmentSessions
.get(environmentId)
?.client.orchestration.getSnapshot()
.then((snapshot: OrchestrationReadModel) => {
remoteEnvironmentStore
.getState()
.patchEnvironmentRuntimeState(environmentId, (runtime) => ({
...runtime,
snapshot,
}));
})
.catch(() => undefined);
}
},
syncSnapshot: (snapshot, environmentId) => {
remoteEnvironmentStore.getState().patchEnvironmentRuntimeState(environmentId, (runtime) => ({
...runtime,
snapshot,
connectionState: "ready",
connectionError: null,
}));
},
applyTerminalEvent: () => undefined,
onConfigSnapshot: (serverConfig) => {
remoteEnvironmentStore
.getState()
.patchEnvironmentRuntimeState(connection.environmentId, (runtime) => ({
...runtime,
serverConfig,
}));
},
});
environmentSessions.set(connection.environmentId, {
client,
connection: environmentConnection,
});
try {
await environmentConnection.ensureBootstrapped();
} catch (error) {
setEnvironmentConnectionStatus(
connection.environmentId,
"disconnected",
error instanceof Error ? error.message : "Failed to bootstrap remote connection.",
);
}
}
function deriveConnectedEnvironments(
savedConnectionsById: Record<string, SavedRemoteConnection>,
environmentStateById: ReturnType<typeof remoteEnvironmentStore.getState>["environmentStateById"],
): ReadonlyArray<ConnectedEnvironmentSummary> {
return sortCopy(
Object.values(savedConnectionsById).map((connection) => {
const runtime = environmentStateById[connection.environmentId];
return {
environmentId: connection.environmentId,
environmentLabel: connection.environmentLabel,
displayUrl: connection.displayUrl,
connectionState: runtime?.connectionState ?? "idle",
connectionError: runtime?.connectionError ?? null,
};
}),
(left, right) => left.environmentLabel.localeCompare(right.environmentLabel),
);
}
export function useRemoteEnvironmentBootstrap() {
const setIsLoadingSavedConnection = useRemoteEnvironmentStore(
(state) => state.setIsLoadingSavedConnection,
);
const replaceSavedConnections = useRemoteEnvironmentStore(
(state) => state.replaceSavedConnections,
);
useEffect(() => {
let cancelled = false;
void loadSavedConnections()
.then(async (connections) => {
if (cancelled) {
return;
}
replaceSavedConnections(
Object.fromEntries(
connections.map((connection) => [connection.environmentId, connection]),
),
);
await Promise.all(
connections.map((connection) =>
connectSavedEnvironment(connection, {
persist: false,
}),
),
);
})
.finally(() => {
if (!cancelled) {
setIsLoadingSavedConnection(false);
}
});
return () => {
cancelled = true;
for (const session of environmentSessions.values()) {
void session.connection.dispose();
}
environmentSessions.clear();
};
}, [replaceSavedConnections, setIsLoadingSavedConnection]);
}
export function useRemoteEnvironmentState() {
return useRemoteEnvironmentStore(
useShallow((state) => ({
isLoadingSavedConnection: state.isLoadingSavedConnection,
connectionPairingUrl: state.connectionPairingUrl,
pendingConnectionError: state.pendingConnectionError,
savedConnectionsById: state.savedConnectionsById,
environmentStateById: state.environmentStateById,
})),
);
}
export function useRemoteConnectionStatus() {
const { environmentStateById, pendingConnectionError, savedConnectionsById } =
useRemoteEnvironmentState();
const selectedThreadRef = useThreadSelectionStore((state) => state.selectedThreadRef);
const connectedEnvironments = useMemo(
() => deriveConnectedEnvironments(savedConnectionsById, environmentStateById),
[environmentStateById, savedConnectionsById],
);
const connectionState = useMemo<RemoteClientConnectionState>(() => {
if (connectedEnvironments.length === 0) {
return "idle";
}
if (connectedEnvironments.some((environment) => environment.connectionState === "ready")) {
return "ready";
}
if (
connectedEnvironments.some((environment) => environment.connectionState === "reconnecting")
) {
return "reconnecting";
}
if (connectedEnvironments.some((environment) => environment.connectionState === "connecting")) {
return "connecting";
}
return "disconnected";
}, [connectedEnvironments]);
const connectionError = useMemo(
() =>
firstNonNull([
pendingConnectionError,
selectedThreadRef
? environmentStateById[selectedThreadRef.environmentId]?.connectionError
: null,
...connectedEnvironments.map((environment) => environment.connectionError),
]),
[connectedEnvironments, environmentStateById, pendingConnectionError, selectedThreadRef],
);
return {
connectedEnvironments,
connectionState,
connectionError,
};
}
export function useRemoteConnections() {
const { connectionPairingUrl } = useRemoteEnvironmentState();
const { connectedEnvironments, connectionError, connectionState } = useRemoteConnectionStatus();
const setConnectionPairingUrl = useRemoteEnvironmentStore(
(state) => state.setConnectionPairingUrl,
);
const clearConnectionPairingUrl = useRemoteEnvironmentStore(
(state) => state.clearConnectionPairingUrl,
);
const onConnectPress = useCallback(
async (pairingUrl?: string) => {
try {
const nextPairingUrl = pairingUrl ?? connectionPairingUrl;
const connection = await bootstrapRemoteConnection({ pairingUrl: nextPairingUrl });
remoteEnvironmentStore.getState().clearPendingConnectionError();
await connectSavedEnvironment(connection);
clearConnectionPairingUrl();
} catch (error) {
remoteEnvironmentStore
.getState()
.setPendingConnectionError(
error instanceof Error ? error.message : "Failed to pair with the environment.",
);
throw error;
}
},
[clearConnectionPairingUrl, connectionPairingUrl],
);
const onUpdateEnvironment = useCallback(
async (
environmentId: string,
updates: { readonly label: string; readonly displayUrl: string },
) => {
const connection = remoteEnvironmentStore.getState().savedConnectionsById[environmentId];
if (!connection) {
return;
}
const updated: SavedRemoteConnection = {
...connection,
environmentLabel: updates.label.trim() || connection.environmentLabel,
displayUrl: updates.displayUrl.trim() || connection.displayUrl,
};
await saveConnection(updated);
remoteEnvironmentStore.getState().upsertSavedConnection(updated);
},
[],
);
const onRemoveEnvironmentPress = useCallback((environmentId: string) => {
const connection = remoteEnvironmentStore.getState().savedConnectionsById[environmentId];
if (!connection) {
return;
}
Alert.alert(
"Remove environment?",
`Disconnect and forget ${connection.environmentLabel} on this device.`,
[
{ text: "Cancel", style: "cancel" },
{
text: "Remove",
style: "destructive",
onPress: () => {
void disconnectEnvironment(environmentId, { removeSaved: true });
},
},
],
);
}, []);
return {
connectionPairingUrl,
connectionState,
connectionError,
connectedEnvironments,
connectedEnvironmentCount: connectedEnvironments.length,
onChangeConnectionPairingUrl: setConnectionPairingUrl,
onConnectPress,
onUpdateEnvironment,
onRemoveEnvironmentPress,
};
}
@@ -0,0 +1,282 @@
import { useCallback } from "react";
import {
ApprovalRequestId,
CommandId,
type ModelSelection,
type ProviderApprovalDecision,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import { newClientId } from "../lib/clientId";
import { useThreadSelection } from "./use-thread-selection";
import { useRemoteEnvironmentStore } from "./remote-environment-store";
import { getEnvironmentClient, useRemoteEnvironmentState } from "./use-remote-environment-registry";
import { useThreadApprovalStore } from "./thread-approval-store";
import { useThreadUserInputStore } from "./thread-user-input-store";
export function useSelectedThreadCommands(input: {
readonly activePendingUserInput: {
readonly requestId: ApprovalRequestId;
} | null;
readonly activePendingUserInputAnswers: Record<string, string> | null;
readonly refreshSelectedThreadGitStatus: (options?: {
readonly quiet?: boolean;
readonly cwd?: string | null;
}) => Promise<unknown>;
}) {
const { activePendingUserInput, activePendingUserInputAnswers, refreshSelectedThreadGitStatus } =
input;
const { selectedThread } = useThreadSelection();
const { savedConnectionsById } = useRemoteEnvironmentState();
const patchEnvironmentRuntimeState = useRemoteEnvironmentStore(
(state) => state.patchEnvironmentRuntimeState,
);
const beginRespondingApproval = useThreadApprovalStore((state) => state.beginRespondingApproval);
const finishRespondingApproval = useThreadApprovalStore(
(state) => state.finishRespondingApproval,
);
const respondingApprovalId = useThreadApprovalStore((state) => state.respondingApprovalId);
const beginRespondingUserInput = useThreadUserInputStore(
(state) => state.beginRespondingUserInput,
);
const finishRespondingUserInput = useThreadUserInputStore(
(state) => state.finishRespondingUserInput,
);
const respondingUserInputId = useThreadUserInputStore((state) => state.respondingUserInputId);
const onRefresh = useCallback(async () => {
const targets = selectedThread
? [selectedThread.environmentId]
: Object.keys(savedConnectionsById);
await Promise.all(
targets.map(async (environmentId) => {
const client = getEnvironmentClient(environmentId);
if (!client) {
return;
}
try {
const [serverConfig, snapshot] = await Promise.all([
client.server.getConfig(),
client.orchestration.getSnapshot(),
]);
patchEnvironmentRuntimeState(environmentId, (current) => ({
...current,
serverConfig,
snapshot,
connectionError: null,
}));
} catch (error) {
patchEnvironmentRuntimeState(environmentId, (current) => ({
...current,
connectionError:
error instanceof Error ? error.message : "Failed to refresh remote data.",
}));
}
}),
);
if (selectedThread) {
await refreshSelectedThreadGitStatus({ quiet: true });
}
}, [
patchEnvironmentRuntimeState,
refreshSelectedThreadGitStatus,
savedConnectionsById,
selectedThread,
]);
const onUpdateThreadModelSelection = useCallback(
async (modelSelection: ModelSelection) => {
if (!selectedThread) {
return;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return;
}
await client.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe(newClientId("command")),
threadId: selectedThread.id,
modelSelection,
});
},
[selectedThread],
);
const onUpdateThreadRuntimeMode = useCallback(
async (runtimeMode: RuntimeMode) => {
if (!selectedThread) {
return;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return;
}
await client.orchestration.dispatchCommand({
type: "thread.runtime-mode.set",
commandId: CommandId.makeUnsafe(newClientId("command")),
threadId: selectedThread.id,
runtimeMode,
createdAt: new Date().toISOString(),
});
},
[selectedThread],
);
const onUpdateThreadInteractionMode = useCallback(
async (interactionMode: ProviderInteractionMode) => {
if (!selectedThread) {
return;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return;
}
await client.orchestration.dispatchCommand({
type: "thread.interaction-mode.set",
commandId: CommandId.makeUnsafe(newClientId("command")),
threadId: selectedThread.id,
interactionMode,
createdAt: new Date().toISOString(),
});
},
[selectedThread],
);
const onStopThread = useCallback(async () => {
if (!selectedThread) {
return;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return;
}
if (
selectedThread.session?.status !== "running" &&
selectedThread.session?.status !== "starting"
) {
return;
}
await client.orchestration.dispatchCommand({
type: "thread.turn.interrupt",
commandId: CommandId.makeUnsafe(newClientId("command")),
threadId: selectedThread.id,
...(selectedThread.session?.activeTurnId
? { turnId: selectedThread.session.activeTurnId }
: {}),
createdAt: new Date().toISOString(),
});
}, [selectedThread]);
const onRenameThread = useCallback(
async (title: string) => {
if (!selectedThread) {
return;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return;
}
const trimmed = title.trim();
if (!trimmed || trimmed === selectedThread.title) {
return;
}
await client.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe(newClientId("command")),
threadId: selectedThread.id,
title: trimmed,
});
},
[selectedThread],
);
const onRespondToApproval = useCallback(
async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
if (!selectedThread) {
return;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return;
}
beginRespondingApproval(requestId);
try {
await client.orchestration.dispatchCommand({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe(newClientId("command")),
threadId: selectedThread.id,
requestId,
decision,
createdAt: new Date().toISOString(),
});
} finally {
finishRespondingApproval(requestId);
}
},
[beginRespondingApproval, finishRespondingApproval, selectedThread],
);
const onSubmitUserInput = useCallback(async () => {
if (!selectedThread || !activePendingUserInput || !activePendingUserInputAnswers) {
return;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return;
}
beginRespondingUserInput(activePendingUserInput.requestId);
try {
await client.orchestration.dispatchCommand({
type: "thread.user-input.respond",
commandId: CommandId.makeUnsafe(newClientId("command")),
threadId: selectedThread.id,
requestId: activePendingUserInput.requestId,
answers: activePendingUserInputAnswers,
createdAt: new Date().toISOString(),
});
} finally {
finishRespondingUserInput(activePendingUserInput.requestId);
}
}, [
activePendingUserInput,
activePendingUserInputAnswers,
beginRespondingUserInput,
finishRespondingUserInput,
selectedThread,
]);
return {
respondingApprovalId,
respondingUserInputId,
onRefresh,
onUpdateThreadModelSelection,
onUpdateThreadRuntimeMode,
onUpdateThreadInteractionMode,
onRenameThread,
onStopThread,
onRespondToApproval,
onSubmitUserInput,
};
}
@@ -0,0 +1,409 @@
import { useCallback, useEffect } from "react";
import {
buildGitActionProgressStages,
type GitActionRequestInput,
type WsRpcClient,
} from "@t3tools/client-runtime";
import {
CommandId,
type GitBranch,
type GitRunStackedActionResult,
ThreadId,
} from "@t3tools/contracts";
import {
dedupeRemoteBranchesWithLocalMatches,
sanitizeFeatureBranchName,
} from "@t3tools/shared/git";
import { newClientId } from "../lib/clientId";
import {
scopedThreadKey,
type ScopedMobileProject,
type ScopedMobileThread,
} from "../lib/scopedEntities";
import { useRemoteEnvironmentStore } from "./remote-environment-store";
import { useThreadSelection } from "./use-thread-selection";
import { getEnvironmentClient } from "./use-remote-environment-registry";
import { useThreadGitStore } from "./thread-git-store";
export function useSelectedThreadGit() {
const { selectedThread, selectedThreadProject } = useThreadSelection();
const setPendingConnectionError = useRemoteEnvironmentStore(
(state) => state.setPendingConnectionError,
);
const selectedThreadGitRootCwd = selectedThreadProject?.workspaceRoot ?? null;
const selectedThreadKey = selectedThread
? scopedThreadKey(selectedThread.environmentId, selectedThread.id)
: null;
const selectedThreadGitStatus = useThreadGitStore((state) =>
selectedThreadKey ? (state.gitStatusByThreadKey[selectedThreadKey] ?? null) : null,
);
const gitOperationLabel = useThreadGitStore((state) =>
selectedThreadKey ? (state.gitOperationLabelByThreadKey[selectedThreadKey] ?? null) : null,
);
const setThreadGitStatus = useThreadGitStore((state) => state.setThreadGitStatus);
const setThreadGitOperationLabel = useThreadGitStore((state) => state.setThreadGitOperationLabel);
const clearThreadGitState = useThreadGitStore((state) => state.clearThreadGitState);
const updateThreadGitContext = useCallback(
async (
thread: NonNullable<typeof selectedThread>,
nextState: {
readonly branch?: string | null;
readonly worktreePath?: string | null;
},
) => {
const client = getEnvironmentClient(thread.environmentId);
if (!client) {
return;
}
await client.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe(newClientId("command")),
threadId: ThreadId.makeUnsafe(thread.id),
...(nextState.branch !== undefined ? { branch: nextState.branch } : {}),
...(nextState.worktreePath !== undefined ? { worktreePath: nextState.worktreePath } : {}),
});
},
[],
);
const refreshSelectedThreadGitStatus = useCallback(
async (options?: { readonly quiet?: boolean; readonly cwd?: string | null }) => {
if (!selectedThread || !selectedThreadProject) {
if (selectedThreadKey) {
clearThreadGitState(selectedThreadKey);
}
return null;
}
const cwd =
options?.cwd ?? selectedThread.worktreePath ?? selectedThreadProject.workspaceRoot;
if (!cwd) {
if (selectedThreadKey) {
clearThreadGitState(selectedThreadKey);
}
return null;
}
if (!options?.quiet && selectedThreadKey) {
setThreadGitOperationLabel(selectedThreadKey, "Refreshing git status");
}
try {
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return null;
}
const status = await client.git.refreshStatus({ cwd });
if (selectedThreadKey) {
setThreadGitStatus(selectedThreadKey, status);
}
setPendingConnectionError(null);
return status;
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to refresh git status.";
setPendingConnectionError(message);
return null;
} finally {
if (!options?.quiet && selectedThreadKey) {
setThreadGitOperationLabel(selectedThreadKey, null);
}
}
},
[
clearThreadGitState,
selectedThreadKey,
selectedThread,
selectedThreadProject,
setPendingConnectionError,
setThreadGitOperationLabel,
setThreadGitStatus,
],
);
useEffect(() => {
if (!selectedThread || !selectedThreadProject) {
if (selectedThreadKey) {
clearThreadGitState(selectedThreadKey);
}
return;
}
void refreshSelectedThreadGitStatus({ quiet: true });
}, [
clearThreadGitState,
refreshSelectedThreadGitStatus,
selectedThreadKey,
selectedThread,
selectedThreadProject,
]);
const runSelectedThreadGitMutation = useCallback(
async <T>(
label: string,
operation: (input: {
readonly client: WsRpcClient;
readonly thread: ScopedMobileThread;
readonly project: ScopedMobileProject;
}) => Promise<T>,
): Promise<T | null> => {
if (!selectedThread || !selectedThreadProject) {
return null;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return null;
}
if (selectedThreadKey) {
setThreadGitOperationLabel(selectedThreadKey, label);
}
try {
setPendingConnectionError(null);
return await operation({
client,
thread: selectedThread,
project: selectedThreadProject,
});
} catch (error) {
setPendingConnectionError(error instanceof Error ? error.message : "Git action failed.");
return null;
} finally {
if (selectedThreadKey) {
setThreadGitOperationLabel(selectedThreadKey, null);
}
}
},
[
selectedThreadKey,
selectedThread,
selectedThreadProject,
setPendingConnectionError,
setThreadGitOperationLabel,
],
);
const onListSelectedThreadBranches = useCallback(async (): Promise<ReadonlyArray<GitBranch>> => {
if (!selectedThread || !selectedThreadProject || !selectedThreadGitRootCwd) {
return [];
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return [];
}
try {
const result = await client.git.listBranches({
cwd: selectedThreadGitRootCwd,
limit: 100,
});
return dedupeRemoteBranchesWithLocalMatches(result.branches).filter(
(branch) => !branch.isRemote,
);
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to load branches.",
);
return [];
}
}, [selectedThread, selectedThreadGitRootCwd, selectedThreadProject, setPendingConnectionError]);
const onListProjectBranches = useCallback(
async (project: ScopedMobileProject): Promise<ReadonlyArray<GitBranch>> => {
const client = getEnvironmentClient(project.environmentId);
if (!client) {
return [];
}
try {
const result = await client.git.listBranches({
cwd: project.workspaceRoot,
limit: 100,
});
return dedupeRemoteBranchesWithLocalMatches(result.branches).filter(
(branch) => !branch.isRemote,
);
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to load branches.",
);
return [];
}
},
[setPendingConnectionError],
);
const onCreateProjectWorktree = useCallback(
async (
project: ScopedMobileProject,
nextWorktree: {
readonly baseBranch: string;
readonly newBranch: string;
},
): Promise<{
readonly branch: string;
readonly worktreePath: string;
} | null> => {
const client = getEnvironmentClient(project.environmentId);
if (!client) {
return null;
}
try {
const result = await client.git.createWorktree({
cwd: project.workspaceRoot,
branch: nextWorktree.baseBranch,
newBranch: sanitizeFeatureBranchName(nextWorktree.newBranch),
path: null,
});
return {
branch: result.worktree.branch,
worktreePath: result.worktree.path,
};
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to create worktree.",
);
return null;
}
},
[setPendingConnectionError],
);
const onCheckoutSelectedThreadBranch = useCallback(
async (branch: string) => {
await runSelectedThreadGitMutation(
"Checking out branch",
async ({ client, thread, project }) => {
const cwd = thread.worktreePath ?? project.workspaceRoot;
const result = await client.git.checkout({ cwd, branch });
await updateThreadGitContext(thread, {
branch: result.branch,
worktreePath: thread.worktreePath,
});
await refreshSelectedThreadGitStatus({ quiet: true, cwd });
},
);
},
[refreshSelectedThreadGitStatus, runSelectedThreadGitMutation, updateThreadGitContext],
);
const onCreateSelectedThreadBranch = useCallback(
async (branch: string) => {
await runSelectedThreadGitMutation("Creating branch", async ({ client, thread, project }) => {
const cwd = thread.worktreePath ?? project.workspaceRoot;
const result = await client.git.createBranch({
cwd,
branch,
checkout: true,
});
await updateThreadGitContext(thread, {
branch: result.branch,
worktreePath: thread.worktreePath,
});
await refreshSelectedThreadGitStatus({ quiet: true, cwd });
});
},
[refreshSelectedThreadGitStatus, runSelectedThreadGitMutation, updateThreadGitContext],
);
const onCreateSelectedThreadWorktree = useCallback(
async (nextWorktree: { readonly baseBranch: string; readonly newBranch: string }) => {
await runSelectedThreadGitMutation(
"Creating worktree",
async ({ client, thread, project }) => {
const result = await client.git.createWorktree({
cwd: project.workspaceRoot,
branch: nextWorktree.baseBranch,
newBranch: sanitizeFeatureBranchName(nextWorktree.newBranch),
path: null,
});
await updateThreadGitContext(thread, {
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
await refreshSelectedThreadGitStatus({ quiet: true, cwd: result.worktree.path });
},
);
},
[refreshSelectedThreadGitStatus, runSelectedThreadGitMutation, updateThreadGitContext],
);
const onPullSelectedThreadBranch = useCallback(async () => {
await runSelectedThreadGitMutation(
"Pulling latest changes",
async ({ client, thread, project }) => {
const cwd = thread.worktreePath ?? project.workspaceRoot;
await client.git.pull({ cwd });
await refreshSelectedThreadGitStatus({ quiet: true, cwd });
},
);
}, [refreshSelectedThreadGitStatus, runSelectedThreadGitMutation]);
const onRunSelectedThreadGitAction = useCallback(
async (input: GitActionRequestInput): Promise<GitRunStackedActionResult | null> => {
const [firstStage] = buildGitActionProgressStages({
action: input.action,
hasCustomCommitMessage: Boolean(input.commitMessage?.trim()),
hasWorkingTreeChanges: selectedThreadGitStatus?.hasWorkingTreeChanges ?? false,
featureBranch: input.featureBranch ?? false,
shouldPushBeforePr:
input.action === "create_pr" &&
((selectedThreadGitStatus?.aheadCount ?? 0) > 0 ||
!(selectedThreadGitStatus?.hasUpstream ?? false)),
});
return await runSelectedThreadGitMutation(
firstStage ?? "Running git action",
async ({ client, thread, project }) => {
const cwd = thread.worktreePath ?? project.workspaceRoot;
const result = await client.git.runStackedAction({
actionId: newClientId("git-action"),
cwd,
action: input.action,
...(input.commitMessage ? { commitMessage: input.commitMessage } : {}),
...(input.featureBranch ? { featureBranch: input.featureBranch } : {}),
...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}),
});
if (result.branch.status === "created" && result.branch.name) {
await updateThreadGitContext(thread, {
branch: result.branch.name,
worktreePath: thread.worktreePath,
});
}
await refreshSelectedThreadGitStatus({ quiet: true, cwd });
return result;
},
);
},
[
refreshSelectedThreadGitStatus,
runSelectedThreadGitMutation,
selectedThreadGitStatus,
updateThreadGitContext,
],
);
return {
selectedThreadGitStatus,
gitOperationLabel,
refreshSelectedThreadGitStatus,
onListProjectBranches,
onCreateProjectWorktree,
onListSelectedThreadBranches,
onCheckoutSelectedThreadBranch,
onCreateSelectedThreadBranch,
onCreateSelectedThreadWorktree,
onPullSelectedThreadBranch,
onRunSelectedThreadGitAction,
};
}
@@ -0,0 +1,474 @@
import { useCallback, useEffect, useMemo } from "react";
import { ApprovalRequestId, CommandId, MessageId, ThreadId } from "@t3tools/contracts";
import { deriveActiveWorkStartedAt, formatElapsed } from "@t3tools/shared/orchestrationTiming";
import {
convertPastedImagesToAttachments,
pasteComposerClipboard,
pickComposerImages,
} from "../lib/composerImages";
import { applyOptimisticUserMessage } from "../lib/orchestration";
import type { ScopedMobileThread } from "../lib/scopedEntities";
import { scopedRequestKey, scopedThreadKey } from "../lib/scopedEntities";
import {
buildPendingUserInputAnswers,
buildThreadFeed,
derivePendingApprovals,
derivePendingUserInputs,
type QueuedThreadMessage,
} from "../lib/threadActivity";
import { newClientId } from "../lib/clientId";
import type { ConnectedEnvironmentSummary } from "./remote-runtime-types";
import { useRemoteEnvironmentStore } from "./remote-environment-store";
import { getEnvironmentClient, useRemoteConnectionStatus } from "./use-remote-environment-registry";
import { useRemoteCatalog } from "./use-remote-catalog";
import { useThreadSelection } from "./use-thread-selection";
import { useThreadComposerStore } from "./thread-composer-store";
import { useThreadUserInputStore } from "./thread-user-input-store";
function useWorkDurationTicker(
activeWorkStartedAt: string | null,
setNowTick: (tick: number) => void,
) {
useEffect(() => {
if (!activeWorkStartedAt) {
return;
}
setNowTick(Date.now());
const timer = setInterval(() => {
setNowTick(Date.now());
}, 1_000);
return () => clearInterval(timer);
}, [activeWorkStartedAt, setNowTick]);
}
function useQueueDrain(input: {
readonly dispatchingQueuedMessageId: string | null;
readonly queuedMessagesByThreadKey: Record<string, ReadonlyArray<QueuedThreadMessage>>;
readonly threads: ReadonlyArray<ScopedMobileThread>;
readonly environments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly sendQueuedMessage: (message: QueuedThreadMessage) => Promise<void>;
}) {
const {
dispatchingQueuedMessageId,
environments,
queuedMessagesByThreadKey,
sendQueuedMessage,
threads,
} = input;
useEffect(() => {
if (dispatchingQueuedMessageId !== null) {
return;
}
for (const [threadKey, queuedMessages] of Object.entries(queuedMessagesByThreadKey)) {
const nextQueuedMessage = queuedMessages[0];
if (!nextQueuedMessage) {
continue;
}
const thread = threads.find(
(candidate) => scopedThreadKey(candidate.environmentId, candidate.id) === threadKey,
);
if (!thread) {
continue;
}
const environment = environments.find(
(candidate) => candidate.environmentId === nextQueuedMessage.environmentId,
);
if (!environment || environment.connectionState !== "ready") {
continue;
}
const threadStatus = thread.session?.status;
if (threadStatus === "running" || threadStatus === "starting") {
continue;
}
void sendQueuedMessage(nextQueuedMessage);
return;
}
}, [
dispatchingQueuedMessageId,
environments,
queuedMessagesByThreadKey,
sendQueuedMessage,
threads,
]);
}
export function useThreadComposerState() {
const { connectedEnvironments } = useRemoteConnectionStatus();
const { threads } = useRemoteCatalog();
const { selectedThread } = useThreadSelection();
const patchEnvironmentRuntimeState = useRemoteEnvironmentStore(
(state) => state.patchEnvironmentRuntimeState,
);
const setPendingConnectionError = useRemoteEnvironmentStore(
(state) => state.setPendingConnectionError,
);
const nowTick = useThreadComposerStore((state) => state.nowTick);
const draftMessageByThreadKey = useThreadComposerStore((state) => state.draftMessageByThreadKey);
const draftAttachmentsByThreadKey = useThreadComposerStore(
(state) => state.draftAttachmentsByThreadKey,
);
const dispatchingQueuedMessageId = useThreadComposerStore(
(state) => state.dispatchingQueuedMessageId,
);
const queuedMessagesByThreadKey = useThreadComposerStore(
(state) => state.queuedMessagesByThreadKey,
);
const userInputDraftsByRequestKey = useThreadUserInputStore(
(state) => state.userInputDraftsByRequestKey,
);
const setNowTick = useThreadComposerStore((state) => state.setNowTick);
const beginDispatchingQueuedMessage = useThreadComposerStore(
(state) => state.beginDispatchingQueuedMessage,
);
const finishDispatchingQueuedMessage = useThreadComposerStore(
(state) => state.finishDispatchingQueuedMessage,
);
const enqueueQueuedMessage = useThreadComposerStore((state) => state.enqueueQueuedMessage);
const removeQueuedMessage = useThreadComposerStore((state) => state.removeQueuedMessage);
const setDraftMessage = useThreadComposerStore((state) => state.setDraftMessage);
const appendDraftAttachments = useThreadComposerStore((state) => state.appendDraftAttachments);
const appendDraftMessage = useThreadComposerStore((state) => state.appendDraftMessage);
const clearDraft = useThreadComposerStore((state) => state.clearDraft);
const removeDraftImage = useThreadComposerStore((state) => state.removeDraftImage);
const setUserInputDraftOption = useThreadUserInputStore((state) => state.setUserInputDraftOption);
const setUserInputDraftCustomAnswer = useThreadUserInputStore(
(state) => state.setUserInputDraftCustomAnswer,
);
const selectedThreadKey = selectedThread
? scopedThreadKey(selectedThread.environmentId, selectedThread.id)
: null;
const selectedRequestKey = selectedThread
? (requestId: ApprovalRequestId) => scopedRequestKey(selectedThread.environmentId, requestId)
: null;
const selectedThreadQueuedMessages = useMemo(
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
[queuedMessagesByThreadKey, selectedThreadKey],
);
const selectedThreadFeed = useMemo(
() =>
selectedThread
? buildThreadFeed(selectedThread, selectedThreadQueuedMessages, dispatchingQueuedMessageId)
: [],
[dispatchingQueuedMessageId, selectedThread, selectedThreadQueuedMessages],
);
const draftMessage = selectedThreadKey ? (draftMessageByThreadKey[selectedThreadKey] ?? "") : "";
const draftAttachments = selectedThreadKey
? (draftAttachmentsByThreadKey[selectedThreadKey] ?? [])
: [];
const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
const selectedThreadSessionActivity = useMemo(() => {
if (!selectedThread?.session) {
return null;
}
return {
orchestrationStatus: selectedThread.session.status,
activeTurnId: selectedThread.session.activeTurnId ?? undefined,
};
}, [selectedThread]);
const queuedSendStartedAt = selectedThreadQueuedMessages[0]?.createdAt ?? null;
const activeWorkStartedAt = useMemo(() => {
if (!selectedThread) {
return null;
}
return deriveActiveWorkStartedAt(
selectedThread.latestTurn,
selectedThreadSessionActivity,
queuedSendStartedAt,
);
}, [queuedSendStartedAt, selectedThread, selectedThreadSessionActivity]);
const activeWorkDurationLabel = useMemo(
() =>
activeWorkStartedAt
? formatElapsed(activeWorkStartedAt, new Date(nowTick).toISOString())
: null,
[activeWorkStartedAt, nowTick],
);
useWorkDurationTicker(activeWorkStartedAt, setNowTick);
const activePendingApprovals = useMemo(
() => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),
[selectedThread],
);
const activePendingApproval = activePendingApprovals[0] ?? null;
const activePendingUserInputs = useMemo(
() => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []),
[selectedThread],
);
const activePendingUserInput = activePendingUserInputs[0] ?? null;
const activePendingUserInputDrafts =
activePendingUserInput && selectedRequestKey
? (userInputDraftsByRequestKey[selectedRequestKey(activePendingUserInput.requestId)] ?? {})
: {};
const activePendingUserInputAnswers = activePendingUserInput
? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingUserInputDrafts)
: null;
const activeThreadBusy =
!!selectedThread &&
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
const sendQueuedMessage = useCallback(
async (queuedMessage: QueuedThreadMessage) => {
const client = getEnvironmentClient(queuedMessage.environmentId);
const thread = threads.find(
(candidate) =>
candidate.environmentId === queuedMessage.environmentId &&
candidate.id === queuedMessage.threadId,
);
if (!client || !thread) {
return;
}
beginDispatchingQueuedMessage(queuedMessage.id);
try {
await client.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe(queuedMessage.commandId),
threadId: ThreadId.makeUnsafe(queuedMessage.threadId),
message: {
messageId: MessageId.makeUnsafe(queuedMessage.messageId),
role: "user",
text: queuedMessage.text,
attachments: queuedMessage.attachments,
},
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
createdAt: queuedMessage.createdAt,
});
removeQueuedMessage(queuedMessage.environmentId, queuedMessage.threadId, queuedMessage.id);
patchEnvironmentRuntimeState(queuedMessage.environmentId, (runtime) => ({
...runtime,
snapshot: runtime.snapshot
? applyOptimisticUserMessage(runtime.snapshot, {
threadId: ThreadId.makeUnsafe(queuedMessage.threadId),
messageId: MessageId.makeUnsafe(queuedMessage.messageId),
text: queuedMessage.text,
attachments: queuedMessage.attachments,
createdAt: queuedMessage.createdAt,
})
: runtime.snapshot,
}));
} catch (error) {
removeQueuedMessage(queuedMessage.environmentId, queuedMessage.threadId, queuedMessage.id);
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to send message.",
);
} finally {
finishDispatchingQueuedMessage(queuedMessage.id);
}
},
[
beginDispatchingQueuedMessage,
finishDispatchingQueuedMessage,
patchEnvironmentRuntimeState,
removeQueuedMessage,
setPendingConnectionError,
threads,
],
);
useQueueDrain({
dispatchingQueuedMessageId,
queuedMessagesByThreadKey,
threads,
environments: connectedEnvironments,
sendQueuedMessage,
});
const onSendMessage = useCallback(() => {
if (!selectedThread) {
return;
}
const threadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
const text = (draftMessageByThreadKey[threadKey] ?? "").trim();
const attachments = draftAttachmentsByThreadKey[threadKey] ?? [];
if (text.length === 0 && attachments.length === 0) {
return;
}
const createdAt = new Date().toISOString();
enqueueQueuedMessage({
id: newClientId("queued-message"),
environmentId: selectedThread.environmentId,
threadId: selectedThread.id,
messageId: newClientId("message"),
commandId: newClientId("command"),
text,
attachments,
createdAt,
});
clearDraft(threadKey);
}, [
clearDraft,
draftAttachmentsByThreadKey,
draftMessageByThreadKey,
enqueueQueuedMessage,
selectedThread,
]);
const onSelectUserInputOption = useCallback(
(requestId: string, questionId: string, label: string) => {
if (!selectedThread) {
return;
}
const requestKey = scopedRequestKey(
selectedThread.environmentId,
requestId as ApprovalRequestId,
);
setUserInputDraftOption(requestKey, questionId, label);
},
[selectedThread, setUserInputDraftOption],
);
const onChangeUserInputCustomAnswer = useCallback(
(requestId: string, questionId: string, customAnswer: string) => {
if (!selectedThread) {
return;
}
const requestKey = scopedRequestKey(
selectedThread.environmentId,
requestId as ApprovalRequestId,
);
setUserInputDraftCustomAnswer(requestKey, questionId, customAnswer);
},
[selectedThread, setUserInputDraftCustomAnswer],
);
const onChangeDraftMessage = useCallback(
(value: string) => {
if (!selectedThread) {
return;
}
const threadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
setDraftMessage(threadKey, value);
},
[selectedThread, setDraftMessage],
);
const onPickDraftImages = useCallback(async () => {
if (!selectedThread) {
return;
}
const threadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
const result = await pickComposerImages({
existingCount: draftAttachmentsByThreadKey[threadKey]?.length ?? 0,
});
if (result.images.length > 0) {
appendDraftAttachments(threadKey, result.images);
}
if (result.error) {
setPendingConnectionError(result.error);
}
}, [
appendDraftAttachments,
draftAttachmentsByThreadKey,
selectedThread,
setPendingConnectionError,
]);
const onPasteIntoDraft = useCallback(async () => {
if (!selectedThread) {
return;
}
const threadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
const result = await pasteComposerClipboard({
existingCount: draftAttachmentsByThreadKey[threadKey]?.length ?? 0,
});
if (result.images.length > 0) {
appendDraftAttachments(threadKey, result.images);
}
if (result.text) {
appendDraftMessage(threadKey, result.text);
}
if (result.error) {
setPendingConnectionError(result.error);
}
}, [
appendDraftAttachments,
appendDraftMessage,
draftAttachmentsByThreadKey,
selectedThread,
setPendingConnectionError,
]);
const onNativePasteImages = useCallback(
async (uris: ReadonlyArray<string>) => {
if (!selectedThread || uris.length === 0) {
return;
}
const threadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
try {
const images = await convertPastedImagesToAttachments({
uris,
existingCount: draftAttachmentsByThreadKey[threadKey]?.length ?? 0,
});
if (images.length > 0) {
appendDraftAttachments(threadKey, images);
}
} catch (error) {
console.error("[native paste] error converting images", error);
}
},
[appendDraftAttachments, draftAttachmentsByThreadKey, selectedThread],
);
const onRemoveDraftImage = useCallback(
(imageId: string) => {
if (!selectedThread) {
return;
}
const threadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
removeDraftImage(threadKey, imageId);
},
[removeDraftImage, selectedThread],
);
return {
selectedThreadFeed,
selectedThreadQueueCount,
activeWorkDurationLabel,
activePendingApproval,
activePendingUserInput,
activePendingUserInputDrafts,
activePendingUserInputAnswers,
draftMessage,
draftAttachments,
activeThreadBusy,
onChangeDraftMessage,
onPickDraftImages,
onPasteIntoDraft,
onNativePasteImages,
onRemoveDraftImage,
onSendMessage,
onSelectUserInputOption,
onChangeUserInputCustomAnswer,
};
}
@@ -0,0 +1,106 @@
import { useCallback, useEffect, useMemo } from "react";
import type { SavedRemoteConnection } from "../lib/connection";
import type { ScopedMobileProject, ScopedMobileThread } from "../lib/scopedEntities";
import { useRemoteCatalog } from "./use-remote-catalog";
import { type EnvironmentRuntimeState } from "./remote-runtime-types";
import { useRemoteEnvironmentState } from "./use-remote-environment-registry";
import { useThreadSelectionStore } from "./thread-selection-store";
function deriveSelectedThread(
selectedThreadRef: { readonly environmentId: string; readonly threadId: string } | null,
threads: ReadonlyArray<ScopedMobileThread>,
): ScopedMobileThread | null {
if (!selectedThreadRef) {
return null;
}
return (
threads.find(
(thread) =>
thread.environmentId === selectedThreadRef.environmentId &&
thread.id === selectedThreadRef.threadId,
) ?? null
);
}
function deriveSelectedThreadProject(
selectedThread: ScopedMobileThread | null,
projects: ReadonlyArray<ScopedMobileProject>,
): ScopedMobileProject | null {
if (!selectedThread) {
return null;
}
return (
projects.find(
(project) =>
project.environmentId === selectedThread.environmentId &&
project.id === selectedThread.projectId,
) ?? null
);
}
export function useThreadSelection() {
const { projects, threads } = useRemoteCatalog();
const { environmentStateById, savedConnectionsById } = useRemoteEnvironmentState();
const selectedThreadRef = useThreadSelectionStore((state) => state.selectedThreadRef);
const selectThreadRef = useThreadSelectionStore((state) => state.selectThreadRef);
const clearSelectedThreadRef = useThreadSelectionStore((state) => state.clearSelectedThreadRef);
const selectedThread = useMemo(
() => deriveSelectedThread(selectedThreadRef, threads),
[selectedThreadRef, threads],
);
useEffect(() => {
if (!selectedThreadRef || selectedThread) {
return;
}
clearSelectedThreadRef();
}, [clearSelectedThreadRef, selectedThread, selectedThreadRef]);
const selectedThreadProject = useMemo(
() => deriveSelectedThreadProject(selectedThread, projects),
[projects, selectedThread],
);
const selectedEnvironmentConnection = selectedThread
? (savedConnectionsById[selectedThread.environmentId] ?? null)
: null;
const selectedEnvironmentRuntime = selectedThread
? (environmentStateById[selectedThread.environmentId] ?? null)
: null;
const onSelectThread = useCallback(
(thread: ScopedMobileThread) => {
selectThreadRef({
environmentId: thread.environmentId,
threadId: thread.id,
});
},
[selectThreadRef],
);
const onBackFromThread = useCallback(() => {
clearSelectedThreadRef();
}, [clearSelectedThreadRef]);
return {
selectedThreadRef,
selectThreadRef,
clearSelectedThreadRef,
selectedThread,
selectedThreadProject,
selectedEnvironmentConnection,
selectedEnvironmentRuntime,
onSelectThread,
onBackFromThread,
};
}
export type ThreadSelectionSnapshot = {
readonly savedConnectionsById: Record<string, SavedRemoteConnection>;
readonly environmentStateById: Record<string, EnvironmentRuntimeState>;
};
+1 -173
View File
@@ -1,173 +1 @@
import type {
EnvironmentId,
OrchestrationShellSnapshot,
OrchestrationShellStreamEvent,
ServerConfig,
ServerLifecycleWelcomePayload,
TerminalEvent,
} from "@t3tools/contracts";
import type { KnownEnvironment } from "@t3tools/client-runtime";
import type { WsRpcClient } from "~/rpc/wsRpcClient";
export interface EnvironmentConnection {
readonly kind: "primary" | "saved";
readonly environmentId: EnvironmentId;
readonly knownEnvironment: KnownEnvironment;
readonly client: WsRpcClient;
readonly ensureBootstrapped: () => Promise<void>;
readonly reconnect: () => Promise<void>;
readonly dispose: () => Promise<void>;
}
interface OrchestrationHandlers {
readonly applyShellEvent: (
event: OrchestrationShellStreamEvent,
environmentId: EnvironmentId,
) => void;
readonly syncShellSnapshot: (
snapshot: OrchestrationShellSnapshot,
environmentId: EnvironmentId,
) => void;
readonly applyTerminalEvent: (event: TerminalEvent, environmentId: EnvironmentId) => void;
}
interface EnvironmentConnectionInput extends OrchestrationHandlers {
readonly kind: "primary" | "saved";
readonly knownEnvironment: KnownEnvironment;
readonly client: WsRpcClient;
readonly refreshMetadata?: () => Promise<void>;
readonly onConfigSnapshot?: (config: ServerConfig) => void;
readonly onWelcome?: (payload: ServerLifecycleWelcomePayload) => void;
}
function createBootstrapGate() {
let resolve: (() => void) | null = null;
let reject: ((error: unknown) => void) | null = null;
let promise = new Promise<void>((nextResolve, nextReject) => {
resolve = nextResolve;
reject = nextReject;
});
return {
wait: () => promise,
resolve: () => {
resolve?.();
resolve = null;
reject = null;
},
reject: (error: unknown) => {
reject?.(error);
resolve = null;
reject = null;
},
reset: () => {
promise = new Promise<void>((nextResolve, nextReject) => {
resolve = nextResolve;
reject = nextReject;
});
},
};
}
export function createEnvironmentConnection(
input: EnvironmentConnectionInput,
): EnvironmentConnection {
const environmentId = input.knownEnvironment.environmentId;
if (!environmentId) {
throw new Error(
`Known environment ${input.knownEnvironment.label} is missing its environmentId.`,
);
}
let disposed = false;
const bootstrapGate = createBootstrapGate();
const observeEnvironmentIdentity = (nextEnvironmentId: EnvironmentId, source: string) => {
if (environmentId !== nextEnvironmentId) {
throw new Error(
`Environment connection ${environmentId} changed identity to ${nextEnvironmentId} via ${source}.`,
);
}
};
const unsubLifecycle = input.client.server.subscribeLifecycle(
(event: Parameters<Parameters<WsRpcClient["server"]["subscribeLifecycle"]>[0]>[0]) => {
if (event.type !== "welcome") {
return;
}
observeEnvironmentIdentity(
event.payload.environment.environmentId,
"server lifecycle welcome",
);
input.onWelcome?.(event.payload);
},
);
const unsubConfig = input.client.server.subscribeConfig(
(event: Parameters<Parameters<WsRpcClient["server"]["subscribeConfig"]>[0]>[0]) => {
if (event.type !== "snapshot") {
return;
}
observeEnvironmentIdentity(event.config.environment.environmentId, "server config snapshot");
input.onConfigSnapshot?.(event.config);
},
);
const unsubShell = input.client.orchestration.subscribeShell(
(item: Parameters<Parameters<WsRpcClient["orchestration"]["subscribeShell"]>[0]>[0]) => {
if (item.kind === "snapshot") {
input.syncShellSnapshot(item.snapshot, environmentId);
bootstrapGate.resolve();
return;
}
input.applyShellEvent(item, environmentId);
},
{
onResubscribe: () => {
if (disposed) {
return;
}
bootstrapGate.reset();
},
},
);
const unsubTerminalEvent = input.client.terminal.onEvent(
(event: Parameters<Parameters<WsRpcClient["terminal"]["onEvent"]>[0]>[0]) => {
input.applyTerminalEvent(event, environmentId);
},
);
const cleanup = () => {
disposed = true;
unsubShell();
unsubTerminalEvent();
unsubLifecycle();
unsubConfig();
};
return {
kind: input.kind,
environmentId,
knownEnvironment: input.knownEnvironment,
client: input.client,
ensureBootstrapped: () => bootstrapGate.wait(),
reconnect: async () => {
bootstrapGate.reset();
try {
await input.client.reconnect();
await input.refreshMetadata?.();
await bootstrapGate.wait();
} catch (error) {
bootstrapGate.reject(error);
throw error;
}
},
dispose: async () => {
cleanup();
await input.client.dispose();
},
};
}
export { createEnvironmentConnection, type EnvironmentConnection } from "@t3tools/client-runtime";
+6 -11
View File
@@ -48,8 +48,6 @@
"@expo-google-fonts/dm-sans": "^0.4.2",
"@gorhom/bottom-sheet": "^5",
"@legendapp/list": "^3.0.0-beta.44",
"@react-native-async-storage/async-storage": "2.2.0",
"@react-native-masked-view/masked-view": "0.3.2",
"@react-native-menu/menu": "^2.0.0",
"@sethwebster/react-ethereal-input": "^0.4.0",
"@shopify/flash-list": "2.0.2",
@@ -82,6 +80,7 @@
"react-native": "0.83.4",
"react-native-css": "3.0.7",
"react-native-gesture-handler": "~2.30.0",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.20.7",
"react-native-markdown-display": "^7.0.2",
"react-native-reanimated": "4.2.1",
@@ -89,6 +88,7 @@
"react-native-screens": "~4.23.0",
"react-native-svg": "15.15.3",
"react-native-worklets": "0.7.2",
"zustand": "^5.0.12",
},
"devDependencies": {
"@tailwindcss/postcss": "4.1.12",
@@ -187,6 +187,7 @@
"version": "0.0.0-alpha.1",
"dependencies": {
"@t3tools/contracts": "workspace:*",
"effect": "catalog:",
},
"devDependencies": {
"@effect/language-service": "catalog:",
@@ -971,10 +972,6 @@
"@radix-ui/react-use-layout-effect": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="],
"@react-native-async-storage/async-storage": ["@react-native-async-storage/[email protected]", "", { "dependencies": { "merge-options": "^3.0.4" }, "peerDependencies": { "react-native": "^0.0.0-0 || >=0.65 <1.0" } }, "sha512-gvRvjR5JAaUZF8tv2Kcq/Gbt3JHwbKFYfmb445rhOj6NUMx3qPLixmDx5pZAyb9at1bYvJ4/eTUipU5aki45xw=="],
"@react-native-masked-view/masked-view": ["@react-native-masked-view/[email protected]", "", { "peerDependencies": { "react": ">=16", "react-native": ">=0.57" } }, "sha512-XwuQoW7/GEgWRMovOQtX3A4PrXhyaZm0lVUiY8qJDvdngjLms9Cpdck6SmGAUNqQwcj2EadHC1HwL0bEyoa/SQ=="],
"@react-native-menu/menu": ["@react-native-menu/[email protected]", "", { "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-hb8Mirw6aKPGONhgo52IiNpwHtISVrgCT3rMdFX1qS7eOFNzOcQh8d2UDnaH5zVpxN+QuvWtaaiRMGFpIjzdtA=="],
"@react-native/assets-registry": ["@react-native/[email protected]", "", {}, "sha512-aqKtpbJDSQeSX/Dwv0yMe1/Rd2QfXi12lnyZDXNn/OEKz59u6+LuPBVgO/9CRyclHmdlvwg8c7PJ9eX2ZMnjWg=="],
@@ -1949,7 +1946,7 @@
"is-number": ["[email protected]", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="],
"is-plain-obj": ["is-plain-obj@2.1.0", "", {}, "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA=="],
"is-plain-obj": ["is-plain-obj@4.1.0", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="],
"is-promise": ["[email protected]", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
@@ -2141,8 +2138,6 @@
"merge-descriptors": ["[email protected]", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],
"merge-options": ["[email protected]", "", { "dependencies": { "is-plain-obj": "^2.1.0" } }, "sha512-2Sug1+knBjkaMsMgf1ctR1Ujx+Ayku4EdJN4Z+C2+JzoeF7A3OZ9KM2GY0CpQS51NR61LTurMJrRKPhSs3ZRTQ=="],
"merge-stream": ["[email protected]", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="],
"metro": ["[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/core": "^7.25.2", "@babel/generator": "^7.29.1", "@babel/parser": "^7.29.0", "@babel/template": "^7.28.6", "@babel/traverse": "^7.29.0", "@babel/types": "^7.29.0", "accepts": "^2.0.0", "chalk": "^4.0.0", "ci-info": "^2.0.0", "connect": "^3.6.5", "debug": "^4.4.0", "error-stack-parser": "^2.0.6", "flow-enums-runtime": "^0.0.6", "graceful-fs": "^4.2.4", "hermes-parser": "0.33.3", "image-size": "^1.0.2", "invariant": "^2.2.4", "jest-worker": "^29.7.0", "jsc-safe-url": "^0.2.2", "lodash.throttle": "^4.1.1", "metro-babel-transformer": "0.83.5", "metro-cache": "0.83.5", "metro-cache-key": "0.83.5", "metro-config": "0.83.5", "metro-core": "0.83.5", "metro-file-map": "0.83.5", "metro-resolver": "0.83.5", "metro-runtime": "0.83.5", "metro-source-map": "0.83.5", "metro-symbolicate": "0.83.5", "metro-transform-plugins": "0.83.5", "metro-transform-worker": "0.83.5", "mime-types": "^3.0.1", "nullthrows": "^1.1.1", "serialize-error": "^2.1.0", "source-map": "^0.5.6", "throat": "^5.0.0", "ws": "^7.5.10", "yargs": "^17.6.2" }, "bin": { "metro": "src/cli.js" } }, "sha512-BgsXevY1MBac/3ZYv/RfNFf/4iuW9X7f4H8ZNkiH+r667HD9sVujxcmu4jvEzGCAm4/WyKdZCuyhAcyhTHOucQ=="],
@@ -2469,6 +2464,8 @@
"react-native-gesture-handler": ["[email protected]", "", { "dependencies": { "@egjs/hammerjs": "^2.0.17", "hoist-non-react-statics": "^3.3.0", "invariant": "^2.2.4" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-xIUBDo5ktmJs++0fZlavQNvDEE4PsihWhSeJsJtoz4Q6p0MiTM9TgrTgfEgzRR36qGPytFoeq+ShLrVwGdpUdA=="],
"react-native-image-viewing": ["[email protected]", "", { "peerDependencies": { "react": ">=16.11.0", "react-native": ">=0.61.3" } }, "sha512-osWieG+p/d2NPbAyonOMubttajtYEYiRGQaJA54slFxZ69j1V4/dCmcrVQry47ktVKy8/qpFwCpW1eT6MH5T2Q=="],
"react-native-is-edge-to-edge": ["[email protected]", "", { "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-NIXU/iT5+ORyCc7p0z2nnlkouYKX425vuU1OEm6bMMtWWR9yvb+Xg5AZmImTKoF9abxCPqrKC3rOZsKzUYgYZA=="],
"react-native-keyboard-controller": ["[email protected]", "", { "dependencies": { "react-native-is-edge-to-edge": "^1.2.1" }, "peerDependencies": { "react": "*", "react-native": "*", "react-native-reanimated": ">=3.0.0" } }, "sha512-G8S5jz1FufPrcL1vPtReATx+jJhT/j+sTqxMIb30b1z7cYEfMlkIzOCyaHgf6IMB2KA9uBmnA5M6ve2A9Ou4kw=="],
@@ -3269,8 +3266,6 @@
"type-is/mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
"unified/is-plain-obj": ["[email protected]", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="],
"unifont/css-tree": ["[email protected]", "", { "dependencies": { "mdn-data": "2.27.1", "source-map-js": "^1.2.1" } }, "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA=="],
"unrun/rolldown": ["[email protected]", "", { "dependencies": { "@oxc-project/types": "=0.124.0", "@rolldown/pluginutils": "1.0.0-rc.15" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.0.0-rc.15", "@rolldown/binding-darwin-arm64": "1.0.0-rc.15", "@rolldown/binding-darwin-x64": "1.0.0-rc.15", "@rolldown/binding-freebsd-x64": "1.0.0-rc.15", "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.15", "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.15", "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.15", "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.15", "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.15", "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.15", "@rolldown/binding-linux-x64-musl": "1.0.0-rc.15", "@rolldown/binding-openharmony-arm64": "1.0.0-rc.15", "@rolldown/binding-wasm32-wasi": "1.0.0-rc.15", "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.15", "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.15" }, "bin": { "rolldown": "bin/cli.mjs" } }, "sha512-Ff31guA5zT6WjnGp0SXw76X6hzGRk/OQq2hE+1lcDe+lJdHSgnSX6nK3erbONHyCbpSj9a9E+uX/OvytZoWp2g=="],
+2 -1
View File
@@ -20,7 +20,8 @@
"test": "vitest run"
},
"dependencies": {
"@t3tools/contracts": "workspace:*"
"@t3tools/contracts": "workspace:*",
"effect": "catalog:"
},
"devDependencies": {
"@effect/language-service": "catalog:",
@@ -0,0 +1,531 @@
import type {
EnvironmentId,
OrchestrationEvent,
OrchestrationReadModel,
ServerConfig,
ServerLifecycleWelcomePayload,
TerminalEvent,
} from "@t3tools/contracts";
import type { KnownEnvironment } from "./knownEnvironment";
import type { WsRpcClient } from "./wsRpcClient";
type OrchestrationRecoveryReason = "bootstrap" | "replay-failed" | "resubscribe" | "sequence-gap";
interface OrchestrationRecoveryPhase {
readonly kind: "snapshot" | "replay";
readonly reason: OrchestrationRecoveryReason;
}
interface OrchestrationRecoveryState {
readonly latestSequence: number;
readonly highestObservedSequence: number;
readonly bootstrapped: boolean;
readonly pendingReplay: boolean;
readonly inFlight: OrchestrationRecoveryPhase | null;
}
interface ReplayRecoveryCompletion {
readonly replayMadeProgress: boolean;
readonly shouldReplay: boolean;
}
interface ReplayRetryTracker {
readonly attempts: number;
readonly latestSequence: number;
readonly highestObservedSequence: number;
}
const REPLAY_RECOVERY_RETRY_DELAY_MS = 100;
const MAX_NO_PROGRESS_REPLAY_RETRIES = 3;
export interface EnvironmentConnection {
readonly kind: "primary" | "saved";
readonly environmentId: EnvironmentId;
readonly knownEnvironment: KnownEnvironment;
readonly client: WsRpcClient;
readonly ensureBootstrapped: () => Promise<void>;
readonly reconnect: () => Promise<void>;
readonly dispose: () => Promise<void>;
}
interface OrchestrationHandlers {
readonly applyEventBatch: (
events: ReadonlyArray<OrchestrationEvent>,
environmentId: EnvironmentId,
) => void;
readonly syncSnapshot: (snapshot: OrchestrationReadModel, environmentId: EnvironmentId) => void;
readonly applyTerminalEvent: (event: TerminalEvent, environmentId: EnvironmentId) => void;
}
interface EnvironmentConnectionInput extends OrchestrationHandlers {
readonly kind: "primary" | "saved";
readonly knownEnvironment: KnownEnvironment;
readonly client: WsRpcClient;
readonly refreshMetadata?: () => Promise<void>;
readonly onConfigSnapshot?: (config: ServerConfig) => void;
readonly onWelcome?: (payload: ServerLifecycleWelcomePayload) => void;
}
function createOrchestrationRecoveryCoordinator() {
let state: OrchestrationRecoveryState = {
latestSequence: 0,
highestObservedSequence: 0,
bootstrapped: false,
pendingReplay: false,
inFlight: null,
};
let replayStartSequence: number | null = null;
const snapshotState = (): OrchestrationRecoveryState => ({
...state,
...(state.inFlight ? { inFlight: { ...state.inFlight } } : {}),
});
const observeSequence = (sequence: number) => {
state = {
...state,
highestObservedSequence: Math.max(state.highestObservedSequence, sequence),
};
};
const resolveReplayNeedAfterRecovery = () => {
const pendingReplayBeforeReset = state.pendingReplay;
const observedAhead = state.highestObservedSequence > state.latestSequence;
const shouldReplay = pendingReplayBeforeReset || observedAhead;
state = {
...state,
pendingReplay: false,
};
return {
shouldReplay,
pendingReplayBeforeReset,
observedAhead,
};
};
return {
getState(): OrchestrationRecoveryState {
return snapshotState();
},
classifyDomainEvent(sequence: number): "ignore" | "defer" | "recover" | "apply" {
observeSequence(sequence);
if (sequence <= state.latestSequence) {
return "ignore";
}
if (!state.bootstrapped || state.inFlight) {
state = {
...state,
pendingReplay: true,
};
return "defer";
}
if (sequence !== state.latestSequence + 1) {
state = {
...state,
pendingReplay: true,
};
return "recover";
}
return "apply";
},
markEventBatchApplied<T extends Readonly<{ sequence: number }>>(
events: ReadonlyArray<T>,
): ReadonlyArray<T> {
const nextEvents = events
.filter((event) => event.sequence > state.latestSequence)
.toSorted((left, right) => left.sequence - right.sequence);
if (nextEvents.length === 0) {
return [];
}
const latestSequence = nextEvents.at(-1)?.sequence ?? state.latestSequence;
state = {
...state,
latestSequence,
highestObservedSequence: Math.max(state.highestObservedSequence, latestSequence),
};
return nextEvents;
},
beginSnapshotRecovery(reason: OrchestrationRecoveryReason): boolean {
if (state.inFlight?.kind === "snapshot" || state.inFlight?.kind === "replay") {
state = {
...state,
pendingReplay: true,
};
return false;
}
state = {
...state,
inFlight: { kind: "snapshot", reason },
};
return true;
},
completeSnapshotRecovery(snapshotSequence: number): boolean {
state = {
...state,
latestSequence: Math.max(state.latestSequence, snapshotSequence),
highestObservedSequence: Math.max(
state.highestObservedSequence,
Math.max(state.latestSequence, snapshotSequence),
),
bootstrapped: true,
inFlight: null,
};
return resolveReplayNeedAfterRecovery().shouldReplay;
},
failSnapshotRecovery() {
state = {
...state,
inFlight: null,
};
},
beginReplayRecovery(reason: OrchestrationRecoveryReason): boolean {
if (!state.bootstrapped || state.inFlight?.kind === "snapshot") {
state = {
...state,
pendingReplay: true,
};
return false;
}
state = {
...state,
pendingReplay: false,
inFlight: { kind: "replay", reason },
};
replayStartSequence = state.latestSequence;
return true;
},
completeReplayRecovery(): ReplayRecoveryCompletion {
const replayMadeProgress =
replayStartSequence !== null && state.latestSequence > replayStartSequence;
replayStartSequence = null;
state = {
...state,
inFlight: null,
};
const replayResolution = resolveReplayNeedAfterRecovery();
return {
replayMadeProgress,
shouldReplay: replayResolution.shouldReplay,
};
},
failReplayRecovery() {
state = {
...state,
bootstrapped: false,
inFlight: null,
};
replayStartSequence = null;
},
};
}
function deriveReplayRetryDecision(input: {
readonly previousTracker: ReplayRetryTracker | null;
readonly completion: ReplayRecoveryCompletion;
readonly recoveryState: Pick<
OrchestrationRecoveryState,
"latestSequence" | "highestObservedSequence"
>;
readonly baseDelayMs: number;
readonly maxNoProgressRetries: number;
}): {
readonly shouldRetry: boolean;
readonly delayMs: number;
readonly tracker: ReplayRetryTracker | null;
} {
if (!input.completion.shouldReplay) {
return {
shouldRetry: false,
delayMs: 0,
tracker: null,
};
}
if (input.completion.replayMadeProgress) {
return {
shouldRetry: true,
delayMs: 0,
tracker: null,
};
}
const previousTracker = input.previousTracker;
const sameFrontier =
previousTracker !== null &&
previousTracker.latestSequence === input.recoveryState.latestSequence &&
previousTracker.highestObservedSequence === input.recoveryState.highestObservedSequence;
const attempts = sameFrontier && previousTracker !== null ? previousTracker.attempts + 1 : 1;
if (attempts > input.maxNoProgressRetries) {
return {
shouldRetry: false,
delayMs: 0,
tracker: null,
};
}
return {
shouldRetry: true,
delayMs: input.baseDelayMs * 2 ** (attempts - 1),
tracker: {
attempts,
latestSequence: input.recoveryState.latestSequence,
highestObservedSequence: input.recoveryState.highestObservedSequence,
},
};
}
function createSnapshotBootstrapController(input: {
readonly isBootstrapped: () => boolean;
readonly runSnapshotRecovery: (
reason: Extract<OrchestrationRecoveryReason, "bootstrap" | "replay-failed">,
) => Promise<void>;
}) {
let inFlight: Promise<void> | null = null;
return {
ensureSnapshotRecovery(
reason: Extract<OrchestrationRecoveryReason, "bootstrap" | "replay-failed">,
): Promise<void> {
if (input.isBootstrapped()) {
return Promise.resolve();
}
if (inFlight !== null) {
return inFlight;
}
const nextInFlight = input.runSnapshotRecovery(reason).finally(() => {
if (inFlight === nextInFlight) {
inFlight = null;
}
});
inFlight = nextInFlight;
return nextInFlight;
},
};
}
export function createEnvironmentConnection(
input: EnvironmentConnectionInput,
): EnvironmentConnection {
const recovery = createOrchestrationRecoveryCoordinator();
let replayRetryTracker: ReplayRetryTracker | null = null;
const pendingDomainEvents: OrchestrationEvent[] = [];
let flushPendingDomainEventsScheduled = false;
const environmentId = input.knownEnvironment.environmentId;
if (!environmentId) {
throw new Error(
`Known environment ${input.knownEnvironment.label} is missing its environmentId.`,
);
}
let disposed = false;
const observeEnvironmentIdentity = (nextEnvironmentId: EnvironmentId, source: string) => {
if (environmentId !== nextEnvironmentId) {
throw new Error(
`Environment connection ${environmentId} changed identity to ${nextEnvironmentId} via ${source}.`,
);
}
};
const flushPendingDomainEvents = () => {
flushPendingDomainEventsScheduled = false;
if (disposed || pendingDomainEvents.length === 0) {
return;
}
const events = pendingDomainEvents.splice(0, pendingDomainEvents.length);
const nextEvents = recovery.markEventBatchApplied(events);
if (nextEvents.length === 0) {
return;
}
input.applyEventBatch(nextEvents, environmentId);
};
const schedulePendingDomainEventFlush = () => {
if (flushPendingDomainEventsScheduled) {
return;
}
flushPendingDomainEventsScheduled = true;
queueMicrotask(flushPendingDomainEvents);
};
const runReplayRecovery = async (
reason: Extract<OrchestrationRecoveryReason, "sequence-gap" | "resubscribe">,
): Promise<void> => {
if (!recovery.beginReplayRecovery(reason)) {
return;
}
const fromSequenceExclusive = recovery.getState().latestSequence;
try {
const events = await input.client.orchestration.replayEvents({ fromSequenceExclusive });
if (!disposed) {
const nextEvents = recovery.markEventBatchApplied(events);
if (nextEvents.length > 0) {
input.applyEventBatch(nextEvents, environmentId);
}
}
} catch {
replayRetryTracker = null;
recovery.failReplayRecovery();
await snapshotBootstrap.ensureSnapshotRecovery("replay-failed");
return;
}
if (disposed) {
return;
}
const replayCompletion = recovery.completeReplayRecovery();
const retryDecision = deriveReplayRetryDecision({
previousTracker: replayRetryTracker,
completion: replayCompletion,
recoveryState: recovery.getState(),
baseDelayMs: REPLAY_RECOVERY_RETRY_DELAY_MS,
maxNoProgressRetries: MAX_NO_PROGRESS_REPLAY_RETRIES,
});
replayRetryTracker = retryDecision.tracker;
if (!retryDecision.shouldRetry) {
return;
}
if (retryDecision.delayMs > 0) {
await new Promise<void>((resolve) => {
setTimeout(resolve, retryDecision.delayMs);
});
if (disposed) {
return;
}
}
void runReplayRecovery(reason);
};
const runSnapshotRecovery = async (
reason: Extract<OrchestrationRecoveryReason, "bootstrap" | "replay-failed">,
): Promise<void> => {
const started = recovery.beginSnapshotRecovery(reason);
if (!started) {
return;
}
try {
const snapshot = await input.client.orchestration.getSnapshot();
if (!disposed) {
input.syncSnapshot(snapshot, environmentId);
if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) {
void runReplayRecovery("sequence-gap");
}
}
} catch (error) {
recovery.failSnapshotRecovery();
throw error;
}
};
const snapshotBootstrap = createSnapshotBootstrapController({
isBootstrapped: () => recovery.getState().bootstrapped,
runSnapshotRecovery,
});
const unsubLifecycle = input.client.server.subscribeLifecycle((event) => {
if (event.type !== "welcome") {
return;
}
observeEnvironmentIdentity(event.payload.environment.environmentId, "server lifecycle welcome");
input.onWelcome?.(event.payload);
});
const unsubConfig = input.client.server.subscribeConfig((event) => {
if (event.type !== "snapshot") {
return;
}
observeEnvironmentIdentity(event.config.environment.environmentId, "server config snapshot");
input.onConfigSnapshot?.(event.config);
});
const unsubDomainEvent = input.client.orchestration.onDomainEvent(
(event) => {
const action = recovery.classifyDomainEvent(event.sequence);
if (action === "apply") {
pendingDomainEvents.push(event);
schedulePendingDomainEventFlush();
return;
}
if (action === "ignore" || action === "defer") {
return;
}
flushPendingDomainEvents();
void runReplayRecovery("sequence-gap");
},
{
onResubscribe: () => {
if (disposed) {
return;
}
flushPendingDomainEvents();
void runReplayRecovery("resubscribe");
},
},
);
const unsubTerminalEvent = input.client.terminal.onEvent((event) => {
input.applyTerminalEvent(event, environmentId);
});
void snapshotBootstrap.ensureSnapshotRecovery("bootstrap").catch(() => undefined);
const cleanup = () => {
disposed = true;
flushPendingDomainEventsScheduled = false;
pendingDomainEvents.length = 0;
unsubDomainEvent();
unsubTerminalEvent();
unsubLifecycle();
unsubConfig();
};
return {
kind: input.kind,
environmentId,
knownEnvironment: input.knownEnvironment,
client: input.client,
ensureBootstrapped: () => snapshotBootstrap.ensureSnapshotRecovery("bootstrap"),
reconnect: async () => {
await input.client.reconnect();
await input.refreshMetadata?.();
await snapshotBootstrap.ensureSnapshotRecovery("bootstrap");
},
dispose: async () => {
cleanup();
await input.client.dispose();
},
};
}
+4
View File
@@ -1,3 +1,7 @@
export * from "./knownEnvironment";
export * from "./scoped";
export * from "./gitActions";
export * from "./wsRpcProtocol";
export * from "./wsTransport";
export * from "./wsRpcClient";
export * from "./environmentConnection";
+304
View File
@@ -0,0 +1,304 @@
import {
type GitActionProgressEvent,
type GitStatusLocalResult,
type GitStatusRemoteResult,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type GitStatusResult,
type GitStatusStreamEvent,
type LocalApi,
ORCHESTRATION_WS_METHODS,
type ServerSettingsPatch,
WS_METHODS,
} from "@t3tools/contracts";
import { Effect, Stream } from "effect";
import { type WsRpcProtocolClient } from "./wsRpcProtocol";
import { WsTransport } from "./wsTransport";
const EMPTY_GIT_STATUS_REMOTE: GitStatusRemoteResult = {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
pr: null,
};
function mergeGitStatusParts(
local: GitStatusLocalResult,
remote: GitStatusRemoteResult | null,
): GitStatusResult {
return {
...local,
...(remote ?? EMPTY_GIT_STATUS_REMOTE),
};
}
function toRemoteStatusPart(status: GitStatusResult): GitStatusRemoteResult {
return {
hasUpstream: status.hasUpstream,
aheadCount: status.aheadCount,
behindCount: status.behindCount,
pr: status.pr,
};
}
function toLocalStatusPart(status: GitStatusResult): GitStatusLocalResult {
return {
isRepo: status.isRepo,
...(status.hostingProvider ? { hostingProvider: status.hostingProvider } : {}),
hasOriginRemote: status.hasOriginRemote,
isDefaultBranch: status.isDefaultBranch,
branch: status.branch,
hasWorkingTreeChanges: status.hasWorkingTreeChanges,
workingTree: status.workingTree,
};
}
function applyGitStatusStreamEvent(
current: GitStatusResult | null,
event: GitStatusStreamEvent,
): GitStatusResult {
switch (event._tag) {
case "snapshot":
return mergeGitStatusParts(event.local, event.remote);
case "localUpdated":
return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
case "remoteUpdated":
if (current === null) {
return mergeGitStatusParts(
{
isRepo: true,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
},
event.remote,
);
}
return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
}
}
type RpcTag = keyof WsRpcProtocolClient & string;
type RpcMethod<TTag extends RpcTag> = WsRpcProtocolClient[TTag];
type RpcInput<TTag extends RpcTag> = Parameters<RpcMethod<TTag>>[0];
interface StreamSubscriptionOptions {
readonly onResubscribe?: () => void;
}
type RpcUnaryMethod<TTag extends RpcTag> =
RpcMethod<TTag> extends (input: any, options?: any) => Effect.Effect<infer TSuccess, any, any>
? (input: RpcInput<TTag>) => Promise<TSuccess>
: never;
type RpcUnaryNoArgMethod<TTag extends RpcTag> =
RpcMethod<TTag> extends (input: any, options?: any) => Effect.Effect<infer TSuccess, any, any>
? () => Promise<TSuccess>
: never;
type RpcStreamMethod<TTag extends RpcTag> =
RpcMethod<TTag> extends (input: any, options?: any) => Stream.Stream<infer TEvent, any, any>
? (listener: (event: TEvent) => void, options?: StreamSubscriptionOptions) => () => void
: never;
interface GitRunStackedActionOptions {
readonly onProgress?: (event: GitActionProgressEvent) => void;
}
export interface WsRpcClient {
readonly dispose: () => Promise<void>;
readonly reconnect: () => Promise<void>;
readonly terminal: {
readonly open: RpcUnaryMethod<typeof WS_METHODS.terminalOpen>;
readonly write: RpcUnaryMethod<typeof WS_METHODS.terminalWrite>;
readonly resize: RpcUnaryMethod<typeof WS_METHODS.terminalResize>;
readonly clear: RpcUnaryMethod<typeof WS_METHODS.terminalClear>;
readonly restart: RpcUnaryMethod<typeof WS_METHODS.terminalRestart>;
readonly close: RpcUnaryMethod<typeof WS_METHODS.terminalClose>;
readonly onEvent: RpcStreamMethod<typeof WS_METHODS.subscribeTerminalEvents>;
};
readonly projects: {
readonly searchEntries: RpcUnaryMethod<typeof WS_METHODS.projectsSearchEntries>;
readonly writeFile: RpcUnaryMethod<typeof WS_METHODS.projectsWriteFile>;
};
readonly shell: {
readonly openInEditor: (input: {
readonly cwd: Parameters<LocalApi["shell"]["openInEditor"]>[0];
readonly editor: Parameters<LocalApi["shell"]["openInEditor"]>[1];
}) => ReturnType<LocalApi["shell"]["openInEditor"]>;
};
readonly git: {
readonly pull: RpcUnaryMethod<typeof WS_METHODS.gitPull>;
readonly refreshStatus: RpcUnaryMethod<typeof WS_METHODS.gitRefreshStatus>;
readonly onStatus: (
input: RpcInput<typeof WS_METHODS.subscribeGitStatus>,
listener: (status: GitStatusResult) => void,
options?: StreamSubscriptionOptions,
) => () => void;
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Promise<GitRunStackedActionResult>;
readonly listBranches: RpcUnaryMethod<typeof WS_METHODS.gitListBranches>;
readonly createWorktree: RpcUnaryMethod<typeof WS_METHODS.gitCreateWorktree>;
readonly removeWorktree: RpcUnaryMethod<typeof WS_METHODS.gitRemoveWorktree>;
readonly createBranch: RpcUnaryMethod<typeof WS_METHODS.gitCreateBranch>;
readonly checkout: RpcUnaryMethod<typeof WS_METHODS.gitCheckout>;
readonly init: RpcUnaryMethod<typeof WS_METHODS.gitInit>;
readonly resolvePullRequest: RpcUnaryMethod<typeof WS_METHODS.gitResolvePullRequest>;
readonly preparePullRequestThread: RpcUnaryMethod<
typeof WS_METHODS.gitPreparePullRequestThread
>;
};
readonly server: {
readonly getConfig: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetConfig>;
readonly refreshProviders: RpcUnaryNoArgMethod<typeof WS_METHODS.serverRefreshProviders>;
readonly upsertKeybinding: RpcUnaryMethod<typeof WS_METHODS.serverUpsertKeybinding>;
readonly getSettings: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetSettings>;
readonly updateSettings: (
patch: ServerSettingsPatch,
) => ReturnType<RpcUnaryMethod<typeof WS_METHODS.serverUpdateSettings>>;
readonly subscribeConfig: RpcStreamMethod<typeof WS_METHODS.subscribeServerConfig>;
readonly subscribeLifecycle: RpcStreamMethod<typeof WS_METHODS.subscribeServerLifecycle>;
readonly subscribeAuthAccess: RpcStreamMethod<typeof WS_METHODS.subscribeAuthAccess>;
};
readonly orchestration: {
readonly getSnapshot: RpcUnaryNoArgMethod<typeof ORCHESTRATION_WS_METHODS.getSnapshot>;
readonly dispatchCommand: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.dispatchCommand>;
readonly getTurnDiff: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.getTurnDiff>;
readonly getFullThreadDiff: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.getFullThreadDiff>;
readonly replayEvents: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.replayEvents>;
readonly onDomainEvent: RpcStreamMethod<typeof WS_METHODS.subscribeOrchestrationDomainEvents>;
};
}
export function createWsRpcClient(transport: WsTransport): WsRpcClient {
return {
dispose: () => transport.dispose(),
reconnect: () => transport.reconnect(),
terminal: {
open: (input) => transport.request((client) => client[WS_METHODS.terminalOpen](input)),
write: (input) => transport.request((client) => client[WS_METHODS.terminalWrite](input)),
resize: (input) => transport.request((client) => client[WS_METHODS.terminalResize](input)),
clear: (input) => transport.request((client) => client[WS_METHODS.terminalClear](input)),
restart: (input) => transport.request((client) => client[WS_METHODS.terminalRestart](input)),
close: (input) => transport.request((client) => client[WS_METHODS.terminalClose](input)),
onEvent: (listener, options) =>
transport.subscribe(
(client) => client[WS_METHODS.subscribeTerminalEvents]({}),
listener,
options,
),
},
projects: {
searchEntries: (input) =>
transport.request((client) => client[WS_METHODS.projectsSearchEntries](input)),
writeFile: (input) =>
transport.request((client) => client[WS_METHODS.projectsWriteFile](input)),
},
shell: {
openInEditor: (input) =>
transport.request((client) => client[WS_METHODS.shellOpenInEditor](input)),
},
git: {
pull: (input) => transport.request((client) => client[WS_METHODS.gitPull](input)),
refreshStatus: (input) =>
transport.request((client) => client[WS_METHODS.gitRefreshStatus](input)),
onStatus: (input, listener, options) => {
let current: GitStatusResult | null = null;
return transport.subscribe(
(client) => client[WS_METHODS.subscribeGitStatus](input),
(event: GitStatusStreamEvent) => {
current = applyGitStatusStreamEvent(current, event);
listener(current);
},
options,
);
},
runStackedAction: async (input, options) => {
let result: GitRunStackedActionResult | null = null;
await transport.requestStream(
(client) => client[WS_METHODS.gitRunStackedAction](input),
(event) => {
options?.onProgress?.(event);
if (event.kind === "action_finished") {
result = event.result;
}
},
);
if (result) {
return result;
}
throw new Error("Git action stream completed without a final result.");
},
listBranches: (input) =>
transport.request((client) => client[WS_METHODS.gitListBranches](input)),
createWorktree: (input) =>
transport.request((client) => client[WS_METHODS.gitCreateWorktree](input)),
removeWorktree: (input) =>
transport.request((client) => client[WS_METHODS.gitRemoveWorktree](input)),
createBranch: (input) =>
transport.request((client) => client[WS_METHODS.gitCreateBranch](input)),
checkout: (input) => transport.request((client) => client[WS_METHODS.gitCheckout](input)),
init: (input) => transport.request((client) => client[WS_METHODS.gitInit](input)),
resolvePullRequest: (input) =>
transport.request((client) => client[WS_METHODS.gitResolvePullRequest](input)),
preparePullRequestThread: (input) =>
transport.request((client) => client[WS_METHODS.gitPreparePullRequestThread](input)),
},
server: {
getConfig: () => transport.request((client) => client[WS_METHODS.serverGetConfig]({})),
refreshProviders: () =>
transport.request((client) => client[WS_METHODS.serverRefreshProviders]({})),
upsertKeybinding: (input) =>
transport.request((client) => client[WS_METHODS.serverUpsertKeybinding](input)),
getSettings: () => transport.request((client) => client[WS_METHODS.serverGetSettings]({})),
updateSettings: (patch) =>
transport.request((client) => client[WS_METHODS.serverUpdateSettings]({ patch })),
subscribeConfig: (listener, options) =>
transport.subscribe(
(client) => client[WS_METHODS.subscribeServerConfig]({}),
listener,
options,
),
subscribeLifecycle: (listener, options) =>
transport.subscribe(
(client) => client[WS_METHODS.subscribeServerLifecycle]({}),
listener,
options,
),
subscribeAuthAccess: (listener, options) =>
transport.subscribe(
(client) => client[WS_METHODS.subscribeAuthAccess]({}),
listener,
options,
),
},
orchestration: {
getSnapshot: () =>
transport.request((client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})),
dispatchCommand: (input) =>
transport.request((client) => client[ORCHESTRATION_WS_METHODS.dispatchCommand](input)),
getTurnDiff: (input) =>
transport.request((client) => client[ORCHESTRATION_WS_METHODS.getTurnDiff](input)),
getFullThreadDiff: (input) =>
transport.request((client) => client[ORCHESTRATION_WS_METHODS.getFullThreadDiff](input)),
replayEvents: (input) =>
transport
.request((client) => client[ORCHESTRATION_WS_METHODS.replayEvents](input))
.then((events) => [...events]),
onDomainEvent: (listener, options) =>
transport.subscribe(
(client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}),
listener,
options,
),
},
};
}
@@ -0,0 +1,122 @@
import { WsRpcGroup } from "@t3tools/contracts";
import { Duration, Effect, Layer, Schedule } from "effect";
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
import * as Socket from "effect/unstable/socket/Socket";
export interface WsProtocolLifecycleHandlers {
readonly onAttempt?: (socketUrl: string) => void;
readonly onOpen?: () => void;
readonly onError?: (message: string) => void;
readonly onClose?: (details: { readonly code: number; readonly reason: string }) => void;
}
export const makeWsRpcProtocolClient = RpcClient.make(WsRpcGroup);
type RpcClientFactory = typeof makeWsRpcProtocolClient;
export type WsRpcProtocolClient =
RpcClientFactory extends Effect.Effect<infer Client, any, any> ? Client : never;
export type WsRpcProtocolSocketUrlProvider = string | (() => Promise<string>);
const WS_RECONNECT_DELAYS_MS = [250, 500, 1_000, 2_000, 4_000] as const;
function formatSocketErrorMessage(error: unknown): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
return String(error);
}
function resolveWsRpcSocketUrl(rawUrl: string): string {
const resolved = new URL(rawUrl);
if (resolved.protocol !== "ws:" && resolved.protocol !== "wss:") {
throw new Error(`Unsupported websocket transport URL protocol: ${resolved.protocol}`);
}
resolved.pathname = "/ws";
return resolved.toString();
}
function getWsReconnectDelayMsForRetry(retryCount: number): number | null {
return WS_RECONNECT_DELAYS_MS[retryCount] ?? null;
}
function defaultLifecycleHandlers(): Required<WsProtocolLifecycleHandlers> {
return {
onAttempt: () => undefined,
onOpen: () => undefined,
onError: () => undefined,
onClose: () => undefined,
};
}
export function createWsRpcProtocolLayer(
url: WsRpcProtocolSocketUrlProvider,
handlers?: WsProtocolLifecycleHandlers,
) {
const lifecycle = {
...defaultLifecycleHandlers(),
...handlers,
};
const resolvedUrl =
typeof url === "function"
? Effect.promise(() => url()).pipe(
Effect.map((rawUrl) => resolveWsRpcSocketUrl(rawUrl)),
Effect.tapError((error) =>
Effect.sync(() => {
lifecycle.onError(formatSocketErrorMessage(error));
}),
),
Effect.orDie,
)
: resolveWsRpcSocketUrl(url);
const trackingWebSocketConstructorLayer = Layer.succeed(
Socket.WebSocketConstructor,
(socketUrl, protocols) => {
lifecycle.onAttempt(socketUrl);
const socket = new globalThis.WebSocket(socketUrl, protocols);
socket.addEventListener(
"open",
() => {
lifecycle.onOpen();
},
{ once: true },
);
socket.addEventListener(
"error",
() => {
lifecycle.onError("Unable to connect to the T3 server WebSocket.");
},
{ once: true },
);
socket.addEventListener(
"close",
(event) => {
lifecycle.onClose({
code: event.code,
reason: event.reason,
});
},
{ once: true },
);
return socket;
},
);
const socketLayer = Socket.layerWebSocket(resolvedUrl).pipe(
Layer.provide(trackingWebSocketConstructorLayer),
);
const retryPolicy = Schedule.addDelay(Schedule.forever, (retryCount) =>
Effect.succeed(Duration.millis(getWsReconnectDelayMsForRetry(retryCount) ?? 0)),
);
const protocolLayer = Layer.effect(
RpcClient.Protocol,
RpcClient.makeProtocolSocket({
retryPolicy,
retryTransientErrors: true,
}),
);
return protocolLayer.pipe(Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson)));
}
+267
View File
@@ -0,0 +1,267 @@
import { Cause, Duration, Effect, Exit, ManagedRuntime, Scope, Stream } from "effect";
import { RpcClient } from "effect/unstable/rpc";
import {
createWsRpcProtocolLayer,
makeWsRpcProtocolClient,
type WsProtocolLifecycleHandlers,
type WsRpcProtocolClient,
type WsRpcProtocolSocketUrlProvider,
} from "./wsRpcProtocol";
interface SubscribeOptions {
readonly retryDelay?: Duration.Input;
readonly onResubscribe?: () => void;
}
const DEFAULT_SUBSCRIPTION_RETRY_DELAY = Duration.millis(250);
const NOOP: () => void = () => undefined;
interface TransportSession {
readonly clientPromise: Promise<WsRpcProtocolClient>;
readonly clientScope: Scope.Closeable;
readonly runtime: ManagedRuntime.ManagedRuntime<RpcClient.Protocol, never>;
}
function formatErrorMessage(error: unknown): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
return String(error);
}
function isTransportConnectionError(error: unknown): boolean {
const message = formatErrorMessage(error).toLowerCase();
return (
message.includes("connect") ||
message.includes("socket") ||
message.includes("websocket") ||
message.includes("closed") ||
message.includes("econn") ||
message.includes("network")
);
}
export class WsTransport {
private readonly url: WsRpcProtocolSocketUrlProvider;
private readonly lifecycleHandlers: WsProtocolLifecycleHandlers | undefined;
private disposed = false;
private reconnectChain: Promise<void> = Promise.resolve();
private session: TransportSession;
constructor(
url: WsRpcProtocolSocketUrlProvider,
lifecycleHandlers?: WsProtocolLifecycleHandlers,
) {
this.url = url;
this.lifecycleHandlers = lifecycleHandlers;
this.session = this.createSession();
}
async request<TSuccess>(
execute: (client: WsRpcProtocolClient) => Effect.Effect<TSuccess, Error, never>,
): Promise<TSuccess> {
if (this.disposed) {
throw new Error("Transport disposed");
}
const session = this.session;
const client = await session.clientPromise;
return await session.runtime.runPromise(Effect.suspend(() => execute(client)));
}
async requestStream<TValue>(
connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
listener: (value: TValue) => void,
): Promise<void> {
if (this.disposed) {
throw new Error("Transport disposed");
}
const session = this.session;
const client = await session.clientPromise;
await session.runtime.runPromise(
Stream.runForEach(connect(client), (value) =>
Effect.sync(() => {
try {
listener(value);
} catch {
// Ignore listener errors so the stream can finish cleanly.
}
}),
),
);
}
subscribe<TValue>(
connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
listener: (value: TValue) => void,
options?: SubscribeOptions,
): () => void {
if (this.disposed) {
return NOOP;
}
let active = true;
let hasReceivedValue = false;
const retryDelayMs = Duration.toMillis(
Duration.fromInputUnsafe(options?.retryDelay ?? DEFAULT_SUBSCRIPTION_RETRY_DELAY),
);
let cancelCurrentStream: () => void = NOOP;
void (async () => {
for (;;) {
if (!active || this.disposed) {
return;
}
try {
if (hasReceivedValue) {
try {
options?.onResubscribe?.();
} catch {
// Ignore reconnect hook failures so the stream can recover.
}
}
const session = this.session;
const runningStream = this.runStreamOnSession(
session,
connect,
listener,
() => active,
() => {
hasReceivedValue = true;
},
);
cancelCurrentStream = runningStream.cancel;
await runningStream.completed;
cancelCurrentStream = NOOP;
} catch (error) {
cancelCurrentStream = NOOP;
if (!active || this.disposed) {
return;
}
if (!isTransportConnectionError(error)) {
console.warn("WebSocket RPC subscription failed", {
error: formatErrorMessage(error),
});
return;
}
await sleep(retryDelayMs);
}
}
})();
return () => {
active = false;
cancelCurrentStream();
};
}
async reconnect() {
if (this.disposed) {
throw new Error("Transport disposed");
}
const reconnectOperation = this.reconnectChain.then(async () => {
if (this.disposed) {
throw new Error("Transport disposed");
}
const previousSession = this.session;
this.session = this.createSession();
await this.closeSession(previousSession);
});
this.reconnectChain = reconnectOperation.catch(() => undefined);
await reconnectOperation;
}
async dispose() {
if (this.disposed) {
return;
}
this.disposed = true;
await this.closeSession(this.session);
}
private closeSession(session: TransportSession) {
return session.runtime.runPromise(Scope.close(session.clientScope, Exit.void)).finally(() => {
session.runtime.dispose();
});
}
private createSession(): TransportSession {
const runtime = ManagedRuntime.make(createWsRpcProtocolLayer(this.url, this.lifecycleHandlers));
const clientScope = runtime.runSync(Scope.make());
return {
runtime,
clientScope,
clientPromise: runtime.runPromise(Scope.provide(clientScope)(makeWsRpcProtocolClient)),
};
}
private runStreamOnSession<TValue>(
session: TransportSession,
connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
listener: (value: TValue) => void,
isActive: () => boolean,
markValueReceived: () => void,
): {
readonly cancel: () => void;
readonly completed: Promise<void>;
} {
let resolveCompleted!: () => void;
let rejectCompleted!: (error: unknown) => void;
const completed = new Promise<void>((resolve, reject) => {
resolveCompleted = resolve;
rejectCompleted = reject;
});
const cancel = session.runtime.runCallback(
Effect.promise(() => session.clientPromise).pipe(
Effect.flatMap((client) =>
Stream.runForEach(connect(client), (value) =>
Effect.sync(() => {
if (!isActive()) {
return;
}
markValueReceived();
try {
listener(value);
} catch {
// Ignore listener errors so the stream stays live.
}
}),
),
),
),
{
onExit: (exit) => {
if (Exit.isSuccess(exit)) {
resolveCompleted();
return;
}
rejectCompleted(Cause.squash(exit.cause));
},
},
);
return {
cancel,
completed,
};
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}