Add mobile remote reconnect and thread sync handling

- add reconnect controls and connection error display
- subscribe thread detail state for remote updates
- tighten mobile thread feed insets and git sheet layout
This commit is contained in:
Julius Marminge committed 2026-04-13 14:44:02 -07:00
1 parent db30cdd26b
commit 67e212e681
45 files changed
+2226 -1661

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@
"@effect/atom-react": "catalog:",
"@expo-google-fonts/dm-sans": "^0.4.2",
"@gorhom/bottom-sheet": "^5",
"@legendapp/list": "^3.0.0-beta.44",
"@legendapp/list": "3.0.0-beta.44",
"@react-native-menu/menu": "^2.0.0",
"@sethwebster/react-ethereal-input": "^0.4.0",
"@shopify/flash-list": "2.0.2",
+1 -5
View File
@@ -95,11 +95,7 @@ export default function RootLayout() {
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
{fontsLoaded ? (
<AppNavigator />
) : (
<LoadingScreen message="Loading remote workspace…" />
)}
{fontsLoaded ? <AppNavigator /> : <LoadingScreen message="Loading remote workspace…" />}
</SafeAreaProvider>
</KeyboardProvider>
</GestureHandlerRootView>
@@ -8,7 +8,9 @@ export const unstable_settings = {
export default function GitSheetLayout() {
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
const headerBg = { backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor };
const headerBg = {
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
};
return (
<Stack
@@ -16,6 +16,7 @@ function EnvironmentRow(props: {
readonly environment: ConnectedEnvironmentSummary;
readonly expanded: boolean;
readonly onToggle: () => void;
readonly onReconnect: (environmentId: string) => void;
readonly onRemove: (environmentId: string) => void;
readonly onUpdate: (
environmentId: string,
@@ -40,7 +41,10 @@ function EnvironmentRow(props: {
return (
<Animated.View layout={LinearTransition.duration(250)} className="bg-card">
<Pressable className="flex-row items-center gap-3 px-4 py-3.5" onPress={props.onToggle}>
<Pressable
className="flex-row items-center gap-3 px-4 py-3.5 active:opacity-70"
onPress={props.onToggle}
>
<ConnectionStatusDot state={props.environment.connectionState} pulse={false} size={8} />
<View className="flex-1 gap-0.5">
@@ -53,6 +57,14 @@ function EnvironmentRow(props: {
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{props.environment.displayUrl}
</Text>
{props.environment.connectionError ? (
<Text
className="text-[12px] leading-[16px] text-rose-500 dark:text-rose-400"
numberOfLines={2}
>
{props.environment.connectionError}
</Text>
) : null}
</View>
<SymbolView
@@ -111,7 +123,7 @@ function EnvironmentRow(props: {
<View className="flex-row gap-2">
<Pressable
className="min-h-[42px] flex-1 flex-row items-center justify-center gap-1.5 rounded-[14px] bg-primary px-3.5 py-2.5"
className="min-h-[42px] flex-1 flex-row items-center justify-center gap-1.5 rounded-[14px] bg-primary px-3.5 py-2.5 active:opacity-70"
onPress={handleSave}
>
<SymbolView name="checkmark" size={13} tintColor={primaryFg} type="monochrome" />
@@ -124,7 +136,19 @@ function EnvironmentRow(props: {
</Pressable>
<Pressable
className="h-[42px] w-[42px] items-center justify-center rounded-[14px] border border-danger-border bg-danger"
className="h-[42px] w-[42px] items-center justify-center rounded-[14px] border border-input-border bg-input active:opacity-70"
onPress={() => props.onReconnect(props.environment.environmentId)}
>
<SymbolView
name="arrow.clockwise"
size={14}
tintColor={mutedColor}
type="monochrome"
/>
</Pressable>
<Pressable
className="h-[42px] w-[42px] items-center justify-center rounded-[14px] border border-danger-border bg-danger active:opacity-70"
onPress={() => props.onRemove(props.environment.environmentId)}
>
<SymbolView name="trash" size={14} tintColor={dangerFg} type="monochrome" />
@@ -137,8 +161,12 @@ function EnvironmentRow(props: {
}
export function ConnectionsRouteScreen() {
const { connectedEnvironments, onRemoveEnvironmentPress, onUpdateEnvironment } =
useRemoteConnections();
const {
connectedEnvironments,
onReconnectEnvironment,
onRemoveEnvironmentPress,
onUpdateEnvironment,
} = useRemoteConnections();
const insets = useSafeAreaInsets();
const hasEnvironments = connectedEnvironments.length > 0;
const [expandedId, setExpandedId] = useState<string | null>(null);
@@ -158,7 +186,7 @@ export function ConnectionsRouteScreen() {
title: "Backends",
headerRight: () => (
<Link href="/connections/new" asChild>
<Pressable className="h-10 w-10 items-center justify-center rounded-full bg-primary">
<Pressable className="h-10 w-10 items-center justify-center rounded-full bg-primary active:opacity-70">
<SymbolView
name="plus"
size={18}
@@ -196,6 +224,7 @@ export function ConnectionsRouteScreen() {
environment={environment}
expanded={expandedId === environment.environmentId}
onToggle={() => handleToggle(environment.environmentId)}
onReconnect={onReconnectEnvironment}
onRemove={onRemoveEnvironmentPress}
onUpdate={onUpdateEnvironment}
/>
@@ -209,20 +209,18 @@ export function ThreadDetailScreen(props: ThreadDetailScreenProps) {
{/* Feed area — KAV shrinks this when keyboard opens */}
<KeyboardAvoidingView behavior="padding" style={{ flex: 1 }}>
{showContent ? (
<View style={{ flex: 1, minHeight: 0 }}>
<ThreadFeed
threadId={props.selectedThread.id}
feed={props.selectedThreadFeed}
httpBaseUrl={props.httpBaseUrl}
bearerToken={props.bearerToken}
agentLabel={agentLabel}
contentBottomInset={composerOverlapHeight + 8}
layoutVariant={layoutVariant}
composerExpanded={composerExpanded}
refreshing={refreshing}
onRefresh={() => void handleRefresh()}
/>
</View>
<ThreadFeed
threadId={props.selectedThread.id}
feed={props.selectedThreadFeed}
httpBaseUrl={props.httpBaseUrl}
bearerToken={props.bearerToken}
agentLabel={agentLabel}
contentBottomInset={composerOverlapHeight + 8}
layoutVariant={layoutVariant}
composerExpanded={composerExpanded}
refreshing={refreshing}
onRefresh={() => void handleRefresh()}
/>
) : (
<View style={{ flex: 1 }} />
)}
@@ -7,6 +7,7 @@ import Markdown from "react-native-markdown-display";
import { Image, Pressable, ScrollView, View } from "react-native";
import { TouchableOpacity } from "react-native-gesture-handler";
import ImageViewing from "react-native-image-viewing";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
@@ -440,6 +441,8 @@ function renderFeedEntry(
);
}
const IOS_NAV_BAR_HEIGHT = 44;
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const listRef = useRef<LegendListRef>(null);
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -450,6 +453,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
headers?: Record<string, string>;
} | null>(null);
const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
const insets = useSafeAreaInsets();
const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const markdownStyles = useMarkdownStyles();
@@ -533,7 +538,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
return (
<ScrollView
style={{ flex: 1 }}
contentInsetAdjustmentBehavior="automatic"
contentInsetAdjustmentBehavior="never"
contentInset={{ top: topContentInset }}
contentOffset={{ x: 0, y: -topContentInset }}
scrollIndicatorInsets={{ top: topContentInset }}
contentContainerStyle={{
flexGrow: 1,
paddingHorizontal: horizontalPadding,
@@ -549,12 +557,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}
return (
<View className="flex-1" style={{ minHeight: 0 }}>
<>
<LegendList
ref={listRef}
key={props.threadId}
style={{ flex: 1 }}
contentInsetAdjustmentBehavior="automatic"
contentInsetAdjustmentBehavior="never"
contentInset={{ top: topContentInset }}
scrollIndicatorInsets={{ top: topContentInset }}
data={props.feed as ThreadFeedEntry[]}
renderItem={renderItem}
keyExtractor={(entry) => `${entry.type}:${entry.id}`}
@@ -567,8 +577,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
refreshing={props.refreshing ?? false}
onRefresh={props.onRefresh}
contentContainerStyle={{
paddingTop: 12,
paddingHorizontal: horizontalPadding,
paddingTop: 8,
paddingBottom: props.contentBottomInset ?? 18,
}}
/>
@@ -590,6 +600,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
swipeToCloseEnabled
doubleTapToZoomEnabled
/>
</View>
</>
);
});
@@ -19,6 +19,7 @@ import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git
import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
import { useSelectedThreadCommands } from "../../state/use-selected-thread-commands";
import { useThreadComposerState } from "../../state/use-thread-composer-state";
import { useThreadDetailSubscription } from "../../state/use-thread-detail-subscription";
import { useThreadSelection } from "../../state/use-thread-selection";
import { ThreadDetailScreen } from "./ThreadDetailScreen";
import { ThreadGitControls } from "./ThreadGitControls";
@@ -61,6 +62,8 @@ export function ThreadRouteScreen() {
const environmentId = firstRouteParam(params.environmentId);
const threadId = firstRouteParam(params.threadId);
useThreadDetailSubscription(environmentId, threadId);
/* ─── Native header theming ──────────────────────────────────────── */
const isDark = useColorScheme() === "dark";
const iconColor = String(useThemeColor("--color-icon"));
@@ -64,142 +64,140 @@ export function GitBranchesSheet() {
gap: 16,
}}
>
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
<Text
className="text-foreground-secondary text-[11px] font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
New branch
</Text>
<TextInput
value={newBranchName}
onChangeText={setNewBranchName}
placeholder="feature/mobile-polish"
className="rounded-[18px] px-3.5 py-3 font-sans text-[15px]"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<SheetActionButton
icon="plus"
label="Create & checkout"
tone="primary"
disabled={busy || newBranchName.trim().length === 0}
onPress={() => {
const branch = sanitizeFeatureBranchName(newBranchName.trim());
if (branch.length === 0) return;
void gitActions.onCreateSelectedThreadBranch(branch).then(() => {
setNewBranchName("");
router.dismiss();
});
}}
/>
</View>
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
<Text
className="text-foreground-secondary text-[11px] font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
New branch
</Text>
<TextInput
value={newBranchName}
onChangeText={setNewBranchName}
placeholder="feature/mobile-polish"
className="rounded-[18px] px-3.5 py-3 font-sans text-[15px]"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<SheetActionButton
icon="plus"
label="Create & checkout"
tone="primary"
disabled={busy || newBranchName.trim().length === 0}
onPress={() => {
const branch = sanitizeFeatureBranchName(newBranchName.trim());
if (branch.length === 0) return;
void gitActions.onCreateSelectedThreadBranch(branch).then(() => {
setNewBranchName("");
router.dismiss();
});
}}
/>
</View>
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
<Text
className="text-foreground-secondary text-[11px] font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
New worktree
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
<Text
className="text-foreground-secondary text-[11px] font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
New worktree
</Text>
<TextInput
value={worktreeBaseBranch}
onChangeText={setWorktreeBaseBranch}
placeholder="main"
className="rounded-[18px] px-3.5 py-3 font-sans text-[15px]"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<TextInput
value={worktreeBranchName}
onChangeText={setWorktreeBranchName}
placeholder="feature/mobile-thread"
className="rounded-[18px] px-3.5 py-3 font-sans text-[15px]"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<SheetActionButton
icon="square.split.2x1"
label="Create worktree"
tone="primary"
disabled={
busy || worktreeBaseBranch.trim().length === 0 || worktreeBranchName.trim().length === 0
}
onPress={() => {
const baseBranch = worktreeBaseBranch.trim();
const newBranch = worktreeBranchName.trim();
if (baseBranch.length === 0 || newBranch.length === 0) return;
void gitActions.onCreateSelectedThreadWorktree({ baseBranch, newBranch }).then(() => {
setWorktreeBranchName("");
router.dismiss();
});
}}
/>
</View>
<View className="gap-2">
<Text
className="text-foreground-secondary text-[11px] font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
Existing branches
</Text>
{branchesLoading ? (
<Text className="text-foreground-secondary text-[13px] font-medium">
Loading branches...
</Text>
<TextInput
value={worktreeBaseBranch}
onChangeText={setWorktreeBaseBranch}
placeholder="main"
className="rounded-[18px] px-3.5 py-3 font-sans text-[15px]"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<TextInput
value={worktreeBranchName}
onChangeText={setWorktreeBranchName}
placeholder="feature/mobile-thread"
className="rounded-[18px] px-3.5 py-3 font-sans text-[15px]"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<SheetActionButton
icon="square.split.2x1"
label="Create worktree"
tone="primary"
disabled={
busy || worktreeBaseBranch.trim().length === 0 || worktreeBranchName.trim().length === 0
}
onPress={() => {
const baseBranch = worktreeBaseBranch.trim();
const newBranch = worktreeBranchName.trim();
if (baseBranch.length === 0 || newBranch.length === 0) return;
void gitActions
.onCreateSelectedThreadWorktree({ baseBranch, newBranch })
.then(() => {
setWorktreeBranchName("");
) : null}
{!branchesLoading && availableBranches.length === 0 ? (
<Text className="text-foreground-secondary text-[13px] font-medium">
No local branches found.
</Text>
) : null}
{availableBranches.map((branch) => {
const disabled = disabledExistingBranches.has(branch.name);
const subtitle = branch.worktreePath
? branch.worktreePath === currentWorktreePath
? "Checked out in this thread"
: "Checked out in another worktree"
: branch.isDefault
? "Default branch"
: "Local branch";
return (
<Pressable
key={branch.name}
className="gap-1 rounded-[18px] border px-4 py-3"
disabled={busy || disabled}
style={{
borderColor: branch.current ? subtleStrongColor : borderColor,
opacity: busy || disabled ? 0.45 : 1,
}}
onPress={() => {
void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => {
router.dismiss();
});
}}
/>
</View>
<View className="gap-2">
<Text
className="text-foreground-secondary text-[11px] font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
Existing branches
</Text>
{branchesLoading ? (
<Text className="text-foreground-secondary text-[13px] font-medium">
Loading branches...
</Text>
) : null}
{!branchesLoading && availableBranches.length === 0 ? (
<Text className="text-foreground-secondary text-[13px] font-medium">
No local branches found.
</Text>
) : null}
{availableBranches.map((branch) => {
const disabled = disabledExistingBranches.has(branch.name);
const subtitle = branch.worktreePath
? branch.worktreePath === currentWorktreePath
? "Checked out in this thread"
: "Checked out in another worktree"
: branch.isDefault
? "Default branch"
: "Local branch";
return (
<Pressable
key={branch.name}
className="gap-1 rounded-[18px] border px-4 py-3"
disabled={busy || disabled}
style={{
borderColor: branch.current ? subtleStrongColor : borderColor,
opacity: busy || disabled ? 0.45 : 1,
}}
onPress={() => {
void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => {
router.dismiss();
});
}}
>
<View className="absolute inset-0 rounded-[18px] bg-card" />
<Text className="text-foreground text-[15px] font-t3-bold">{branch.name}</Text>
<Text className="text-foreground-secondary text-[12px] font-medium">{subtitle}</Text>
</Pressable>
);
})}
</View>
}}
>
<View className="absolute inset-0 rounded-[18px] bg-card" />
<Text className="text-foreground text-[15px] font-t3-bold">{branch.name}</Text>
<Text className="text-foreground-secondary text-[12px] font-medium">{subtitle}</Text>
</Pressable>
);
})}
</View>
</ScrollView>
);
}
@@ -70,173 +70,170 @@ export function GitCommitSheet() {
gap: 16,
}}
>
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
<View className="flex-row items-center justify-between gap-3">
<Text className="text-foreground-muted text-[13px] font-medium">Branch</Text>
<Text className="text-foreground text-[15px] font-t3-bold">
{gitStatus.data?.branch ?? "(detached HEAD)"}
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
<View className="flex-row items-center justify-between gap-3">
<Text className="text-foreground-muted text-[13px] font-medium">Branch</Text>
<Text className="text-foreground text-[15px] font-t3-bold">
{gitStatus.data?.branch ?? "(detached HEAD)"}
</Text>
</View>
{isDefaultBranch ? (
<Text
className="text-[12px] leading-[18px]"
style={{ color: isDarkMode ? "#fbbf24" : "#b45309" }}
>
Warning: this is the default branch.
</Text>
) : null}
</View>
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
<View className="flex-row items-center justify-between gap-3">
<View className="gap-1">
<Text className="text-foreground text-[16px] font-t3-bold">Files</Text>
<Text className="text-foreground-muted text-[12px] leading-[18px]">
{selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions}
</Text>
</View>
{isDefaultBranch ? (
<Text
className="text-[12px] leading-[18px]"
style={{ color: isDarkMode ? "#fbbf24" : "#b45309" }}
>
Warning: this is the default branch.
</Text>
) : null}
</View>
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
<View className="flex-row items-center justify-between gap-3">
<View className="gap-1">
<Text className="text-foreground text-[16px] font-t3-bold">Files</Text>
<Text className="text-foreground-muted text-[12px] leading-[18px]">
{selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions}
</Text>
</View>
<View className="flex-row items-center gap-2">
{!allSelected && isEditingFiles ? (
<Pressable
className="bg-subtle rounded-full px-3 py-2"
onPress={() => setExcludedFiles(new Set())}
>
<Text className="text-foreground text-[11px] font-t3-bold uppercase">Reset</Text>
</Pressable>
) : null}
<View className="flex-row items-center gap-2">
{!allSelected && isEditingFiles ? (
<Pressable
className="bg-subtle rounded-full px-3 py-2"
onPress={() => setIsEditingFiles((current) => !current)}
onPress={() => setExcludedFiles(new Set())}
>
<Text className="text-foreground text-[11px] font-t3-bold uppercase">
{isEditingFiles ? "Done" : "Edit"}
</Text>
<Text className="text-foreground text-[11px] font-t3-bold uppercase">Reset</Text>
</Pressable>
</View>
) : null}
<Pressable
className="bg-subtle rounded-full px-3 py-2"
onPress={() => setIsEditingFiles((current) => !current)}
>
<Text className="text-foreground text-[11px] font-t3-bold uppercase">
{isEditingFiles ? "Done" : "Edit"}
</Text>
</Pressable>
</View>
{allFiles.length === 0 ? (
<Text className="text-foreground-secondary text-[13px] leading-[19px]">
No changed files are available to commit.
</Text>
) : !isEditingFiles ? (
<View className="gap-2">
{selectedFilePreview.map((file) => (
<View key={file.path} className="flex-row items-center justify-between gap-3">
<Text
className="text-foreground flex-1 text-[13px] font-medium"
numberOfLines={1}
>
{file.path}
</Text>
<Text className="text-[12px] font-t3-bold" style={{ color: "#10b981" }}>
+{file.insertions}
</Text>
<Text className="text-[12px] font-t3-bold" style={{ color: "#f43f5e" }}>
-{file.deletions}
</Text>
</View>
))}
{selectedFiles.length > selectedFilePreview.length ? (
<Text className="text-foreground-muted text-[12px] leading-[17px]">
+{selectedFiles.length - selectedFilePreview.length} more files
</Text>
) : null}
</View>
) : (
<View className="gap-2">
{allFiles.map((file) => {
const included = !excludedFiles.has(file.path);
return (
<Pressable
key={file.path}
className="rounded-[18px] border px-4 py-3"
style={{
borderColor: included ? borderColor : borderSubtleColor,
}}
onPress={() => {
setExcludedFiles((current) => {
const next = new Set(current);
if (next.has(file.path)) {
next.delete(file.path);
} else {
next.add(file.path);
}
return next;
});
}}
>
<View
className={`absolute inset-0 rounded-[18px] ${included ? "bg-card" : "bg-subtle"}`}
/>
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-1">
<Text
selectable
className={`text-[13px] font-t3-bold ${included ? "text-foreground" : "text-foreground-muted"}`}
>
{file.path}
</Text>
{!included ? (
<Text className="text-foreground-muted text-[11px] leading-[16px]">
Excluded from this commit
</Text>
) : null}
</View>
<View className="items-end gap-1">
<Text className="text-[12px] font-t3-bold" style={{ color: "#10b981" }}>
+{file.insertions}
</Text>
<Text className="text-[12px] font-t3-bold" style={{ color: "#f43f5e" }}>
-{file.deletions}
</Text>
</View>
</View>
</Pressable>
);
})}
</View>
)}
</View>
<View className="gap-2">
<Text className="text-foreground text-[13px] font-t3-bold">Commit message</Text>
<TextInput
multiline
value={dialogCommitMessage}
onChangeText={setDialogCommitMessage}
placeholder="Leave empty to auto-generate"
textAlignVertical="top"
className="min-h-[128px] rounded-[20px] px-4 py-3.5 font-sans text-[15px]"
style={{
minHeight: 128,
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
{allFiles.length === 0 ? (
<Text className="text-foreground-secondary text-[13px] leading-[19px]">
No changed files are available to commit.
</Text>
) : !isEditingFiles ? (
<View className="gap-2">
{selectedFilePreview.map((file) => (
<View key={file.path} className="flex-row items-center justify-between gap-3">
<Text className="text-foreground flex-1 text-[13px] font-medium" numberOfLines={1}>
{file.path}
</Text>
<Text className="text-[12px] font-t3-bold" style={{ color: "#10b981" }}>
+{file.insertions}
</Text>
<Text className="text-[12px] font-t3-bold" style={{ color: "#f43f5e" }}>
-{file.deletions}
</Text>
</View>
))}
{selectedFiles.length > selectedFilePreview.length ? (
<Text className="text-foreground-muted text-[12px] leading-[17px]">
+{selectedFiles.length - selectedFilePreview.length} more files
</Text>
) : null}
</View>
) : (
<View className="gap-2">
{allFiles.map((file) => {
const included = !excludedFiles.has(file.path);
return (
<Pressable
key={file.path}
className="rounded-[18px] border px-4 py-3"
style={{
borderColor: included ? borderColor : borderSubtleColor,
}}
onPress={() => {
setExcludedFiles((current) => {
const next = new Set(current);
if (next.has(file.path)) {
next.delete(file.path);
} else {
next.add(file.path);
}
return next;
});
}}
>
<View
className={`absolute inset-0 rounded-[18px] ${included ? "bg-card" : "bg-subtle"}`}
/>
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-1">
<Text
selectable
className={`text-[13px] font-t3-bold ${included ? "text-foreground" : "text-foreground-muted"}`}
>
{file.path}
</Text>
{!included ? (
<Text className="text-foreground-muted text-[11px] leading-[16px]">
Excluded from this commit
</Text>
) : null}
</View>
<View className="items-end gap-1">
<Text className="text-[12px] font-t3-bold" style={{ color: "#10b981" }}>
+{file.insertions}
</Text>
<Text className="text-[12px] font-t3-bold" style={{ color: "#f43f5e" }}>
-{file.deletions}
</Text>
</View>
</View>
</Pressable>
);
})}
</View>
)}
</View>
<View className="gap-2">
<Text className="text-foreground text-[13px] font-t3-bold">Commit message</Text>
<TextInput
multiline
value={dialogCommitMessage}
onChangeText={setDialogCommitMessage}
placeholder="Leave empty to auto-generate"
textAlignVertical="top"
className="min-h-[128px] rounded-[20px] px-4 py-3.5 font-sans text-[15px]"
style={{
minHeight: 128,
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
</View>
<View className="flex-row gap-3">
<View className="flex-1">
<SheetActionButton
icon="arrow.branch"
label="Commit on new branch"
disabled={noneSelected || busy}
onPress={() => void runCommitAction(true)}
/>
</View>
<View className="flex-row gap-3">
<View className="flex-1">
<SheetActionButton
icon="arrow.branch"
label="Commit on new branch"
disabled={noneSelected || busy}
onPress={() => void runCommitAction(true)}
/>
</View>
<View className="flex-1">
<SheetActionButton
icon="checkmark.circle"
label="Commit"
tone="primary"
disabled={noneSelected || busy}
onPress={() => void runCommitAction(false)}
/>
</View>
<View className="flex-1">
<SheetActionButton
icon="checkmark.circle"
label="Commit"
tone="primary"
disabled={noneSelected || busy}
onPress={() => void runCommitAction(false)}
/>
</View>
</View>
</ScrollView>
);
}
@@ -81,10 +81,7 @@ export function GitConfirmSheet() {
}, [confirmAction, gitActions, gitState.selectedThreadBranches, includesCommit, params, router]);
return (
<View
collapsable={false}
className="flex-1 bg-sheet"
>
<View collapsable={false} className="flex-1 bg-sheet">
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
@@ -122,7 +122,16 @@ export function menuItemIconName(
return "arrow.up.right.circle";
}
export function statusSummary(gitStatus: { readonly isRepo?: boolean; readonly hasWorkingTreeChanges?: boolean; readonly workingTree?: { readonly files: readonly { readonly path: string }[] }; readonly aheadCount?: number; readonly behindCount?: number; readonly pr?: { readonly state?: string; readonly number?: number } | null } | null): string {
export function statusSummary(
gitStatus: {
readonly isRepo?: boolean;
readonly hasWorkingTreeChanges?: boolean;
readonly workingTree?: { readonly files: readonly { readonly path: string }[] };
readonly aheadCount?: number;
readonly behindCount?: number;
readonly pr?: { readonly state?: string; readonly number?: number } | null;
} | null,
): string {
if (!gitStatus) {
return "Loading branch status\u2026";
}
-104
View File
@@ -1,104 +0,0 @@
import { describe, expect, it } from "vitest";
import { EventId, ProjectId } from "@t3tools/contracts";
import type { OrchestrationReadModel } from "@t3tools/contracts";
import { applyRealtimeEvent } from "./orchestration";
const baseSnapshot: OrchestrationReadModel = {
snapshotSequence: 0,
updatedAt: "2026-04-01T00:00:00.000Z",
projects: [],
threads: [],
};
const baseEventFields = {
eventId: EventId.makeUnsafe("event-1"),
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
} as const;
describe("applyRealtimeEvent project identity handling", () => {
it("preserves repository identity on project.created", () => {
const next = applyRealtimeEvent(baseSnapshot, {
...baseEventFields,
sequence: 1,
occurredAt: "2026-04-01T01:00:00.000Z",
aggregateKind: "project",
aggregateId: ProjectId.makeUnsafe("project-1"),
type: "project.created",
payload: {
projectId: ProjectId.makeUnsafe("project-1"),
title: "T3 Code",
workspaceRoot: "/repo",
repositoryIdentity: {
canonicalKey: "github.com/t3tools/t3code",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "[email protected]:t3tools/t3code.git",
},
provider: "github",
owner: "t3tools",
name: "t3code",
},
defaultModelSelection: null,
scripts: [],
createdAt: "2026-04-01T01:00:00.000Z",
updatedAt: "2026-04-01T01:00:00.000Z",
},
});
expect(next.projects[0]?.repositoryIdentity?.canonicalKey).toBe("github.com/t3tools/t3code");
});
it("applies repository identity updates on project.meta-updated", () => {
const seeded = applyRealtimeEvent(baseSnapshot, {
...baseEventFields,
sequence: 1,
occurredAt: "2026-04-01T01:00:00.000Z",
aggregateKind: "project",
aggregateId: ProjectId.makeUnsafe("project-1"),
type: "project.created",
payload: {
projectId: ProjectId.makeUnsafe("project-1"),
title: "T3 Code",
workspaceRoot: "/repo",
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-04-01T01:00:00.000Z",
updatedAt: "2026-04-01T01:00:00.000Z",
},
});
const next = applyRealtimeEvent(seeded, {
...baseEventFields,
eventId: EventId.makeUnsafe("event-2"),
sequence: 2,
occurredAt: "2026-04-01T02:00:00.000Z",
aggregateKind: "project",
aggregateId: ProjectId.makeUnsafe("project-1"),
type: "project.meta-updated",
payload: {
projectId: ProjectId.makeUnsafe("project-1"),
repositoryIdentity: {
canonicalKey: "github.com/t3tools/t3code",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "[email protected]:t3tools/t3code.git",
},
provider: "github",
owner: "t3tools",
name: "t3code",
},
updatedAt: "2026-04-01T02:00:00.000Z",
},
});
expect(next.projects[0]?.repositoryIdentity?.canonicalKey).toBe("github.com/t3tools/t3code");
});
});
-449
View File
@@ -1,449 +0,0 @@
import * as Order from "effect/Order";
import type {
ChatAttachment,
MessageId,
OrchestrationEvent,
OrchestrationProject,
OrchestrationReadModel,
OrchestrationThread,
ThreadId,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
const MAX_THREAD_PROPOSED_PLANS = 200;
function updateThread(
snapshot: OrchestrationReadModel,
threadId: ThreadId,
updater: (
thread: OrchestrationReadModel["threads"][number],
) => OrchestrationReadModel["threads"][number],
): OrchestrationReadModel["threads"] {
return snapshot.threads.map((thread) => (thread.id === threadId ? updater(thread) : thread));
}
function updateProject(
snapshot: OrchestrationReadModel,
projectId: OrchestrationProject["id"],
updater: (project: OrchestrationProject) => OrchestrationProject,
): OrchestrationReadModel["projects"] {
return snapshot.projects.map((project) =>
project.id === projectId ? updater(project) : project,
);
}
function upsertProject(
snapshot: OrchestrationReadModel,
nextProject: OrchestrationProject,
): OrchestrationReadModel["projects"] {
const existing = snapshot.projects.find((project) => project.id === nextProject.id);
if (existing) {
return updateProject(snapshot, nextProject.id, () => nextProject);
}
return [...snapshot.projects, nextProject];
}
function upsertThread(
snapshot: OrchestrationReadModel,
nextThread: OrchestrationThread,
): OrchestrationReadModel["threads"] {
const existing = snapshot.threads.find((thread) => thread.id === nextThread.id);
if (existing) {
return updateThread(snapshot, nextThread.id, () => nextThread);
}
return [...snapshot.threads, nextThread];
}
export function applyRealtimeEvent(
snapshot: OrchestrationReadModel,
event: OrchestrationEvent,
): OrchestrationReadModel {
const nextBase: OrchestrationReadModel = {
...snapshot,
snapshotSequence: event.sequence,
updatedAt: event.occurredAt,
};
switch (event.type) {
case "project.created":
return {
...nextBase,
projects: upsertProject(nextBase, {
id: event.payload.projectId,
title: event.payload.title,
workspaceRoot: event.payload.workspaceRoot,
repositoryIdentity: event.payload.repositoryIdentity ?? null,
defaultModelSelection: event.payload.defaultModelSelection,
scripts: event.payload.scripts,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
deletedAt: null,
}),
};
case "project.meta-updated":
return {
...nextBase,
projects: updateProject(nextBase, event.payload.projectId, (project) => ({
...project,
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
...(event.payload.workspaceRoot !== undefined
? { workspaceRoot: event.payload.workspaceRoot }
: {}),
...(event.payload.repositoryIdentity !== undefined
? { repositoryIdentity: event.payload.repositoryIdentity }
: {}),
...(event.payload.defaultModelSelection !== undefined
? { defaultModelSelection: event.payload.defaultModelSelection }
: {}),
...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
updatedAt: event.payload.updatedAt,
})),
};
case "project.deleted":
return {
...nextBase,
projects: updateProject(nextBase, event.payload.projectId, (project) => ({
...project,
deletedAt: event.payload.deletedAt,
updatedAt: event.payload.deletedAt,
})),
};
case "thread.created":
return {
...nextBase,
threads: upsertThread(nextBase, {
id: event.payload.threadId,
projectId: event.payload.projectId,
title: event.payload.title,
modelSelection: event.payload.modelSelection,
runtimeMode: event.payload.runtimeMode,
interactionMode: event.payload.interactionMode,
branch: event.payload.branch,
worktreePath: event.payload.worktreePath,
latestTurn: null,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
archivedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
}),
};
case "thread.deleted":
return {
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => ({
...thread,
deletedAt: event.payload.deletedAt,
updatedAt: event.payload.deletedAt,
})),
};
case "thread.archived":
return {
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => ({
...thread,
archivedAt: event.payload.archivedAt,
updatedAt: event.payload.updatedAt,
})),
};
case "thread.unarchived":
return {
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => ({
...thread,
archivedAt: null,
updatedAt: event.payload.updatedAt,
})),
};
case "thread.meta-updated":
return {
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => ({
...thread,
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
...(event.payload.modelSelection !== undefined
? { modelSelection: event.payload.modelSelection }
: {}),
...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
...(event.payload.worktreePath !== undefined
? { worktreePath: event.payload.worktreePath }
: {}),
updatedAt: event.payload.updatedAt,
})),
};
case "thread.runtime-mode-set":
return {
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => ({
...thread,
runtimeMode: event.payload.runtimeMode,
updatedAt: event.payload.updatedAt,
})),
};
case "thread.interaction-mode-set":
return {
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => ({
...thread,
interactionMode: event.payload.interactionMode,
updatedAt: event.payload.updatedAt,
})),
};
case "thread.message-sent":
return {
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => {
const existing = thread.messages.find(
(message) => message.id === event.payload.messageId,
);
const nextMessages = existing
? thread.messages.map((message) =>
message.id === event.payload.messageId
? {
...message,
text: event.payload.streaming
? `${message.text}${event.payload.text}`
: event.payload.text.length > 0
? event.payload.text
: message.text,
turnId: event.payload.turnId,
streaming: event.payload.streaming,
updatedAt: event.payload.updatedAt,
...(event.payload.attachments
? { attachments: event.payload.attachments }
: {}),
}
: message,
)
: [
...thread.messages,
{
id: event.payload.messageId,
role: event.payload.role,
text: event.payload.text,
turnId: event.payload.turnId,
streaming: event.payload.streaming,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
...(event.payload.attachments ? { attachments: event.payload.attachments } : {}),
},
];
return {
...thread,
messages: nextMessages,
updatedAt: event.occurredAt,
};
}),
};
case "thread.turn-start-requested":
return {
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => ({
...thread,
updatedAt: event.occurredAt,
})),
};
case "thread.session-set":
return {
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => ({
...thread,
session: event.payload.session,
latestTurn:
event.payload.session.status === "running" &&
event.payload.session.activeTurnId !== null
? {
turnId: event.payload.session.activeTurnId,
state: "running",
requestedAt:
thread.latestTurn?.turnId === event.payload.session.activeTurnId
? thread.latestTurn.requestedAt
: event.payload.session.updatedAt,
startedAt:
thread.latestTurn?.turnId === event.payload.session.activeTurnId
? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt)
: event.payload.session.updatedAt,
completedAt: null,
assistantMessageId:
thread.latestTurn?.turnId === event.payload.session.activeTurnId
? thread.latestTurn.assistantMessageId
: null,
}
: thread.latestTurn,
updatedAt: event.occurredAt,
})),
};
case "thread.proposed-plan-upserted":
return {
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => ({
...thread,
proposedPlans: Arr.sortWith(
[
...thread.proposedPlans.filter((proposedPlan) => {
return proposedPlan.id !== event.payload.proposedPlan.id;
}),
event.payload.proposedPlan,
],
(s) => new Date(s.createdAt),
Order.Date,
).slice(-MAX_THREAD_PROPOSED_PLANS),
updatedAt: event.occurredAt,
})),
};
case "thread.turn-diff-completed":
return {
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => {
const checkpoints = Arr.sortWith(
[
...thread.checkpoints.filter(
(checkpoint) => checkpoint.turnId !== event.payload.turnId,
),
{
turnId: event.payload.turnId,
checkpointTurnCount: event.payload.checkpointTurnCount,
checkpointRef: event.payload.checkpointRef,
status: event.payload.status,
files: event.payload.files,
assistantMessageId: event.payload.assistantMessageId,
completedAt: event.payload.completedAt,
},
],
(s) => s.checkpointTurnCount,
Order.Number,
);
const latestTurnState =
event.payload.status === "error"
? "error"
: event.payload.status === "missing"
? "interrupted"
: "completed";
return {
...thread,
checkpoints,
latestTurn: {
turnId: event.payload.turnId,
state: latestTurnState,
requestedAt:
thread.latestTurn?.turnId === event.payload.turnId
? thread.latestTurn.requestedAt
: event.payload.completedAt,
startedAt:
thread.latestTurn?.turnId === event.payload.turnId
? (thread.latestTurn.startedAt ?? event.payload.completedAt)
: event.payload.completedAt,
completedAt: event.payload.completedAt,
assistantMessageId: event.payload.assistantMessageId,
},
updatedAt: event.occurredAt,
};
}),
};
case "thread.activity-appended":
return {
...nextBase,
threads: updateThread(nextBase, event.payload.threadId, (thread) => ({
...thread,
activities: Arr.sortWith(
[
...thread.activities.filter((activity) => activity.id !== event.payload.activity.id),
event.payload.activity,
],
(s) => new Date(s.createdAt),
Order.Date,
),
updatedAt: event.occurredAt,
})),
};
default:
return nextBase;
}
}
export function requiresSnapshotRefresh(event: OrchestrationEvent): boolean {
switch (event.type) {
case "project.created":
case "project.meta-updated":
case "project.deleted":
case "thread.created":
case "thread.deleted":
case "thread.archived":
case "thread.unarchived":
case "thread.meta-updated":
case "thread.runtime-mode-set":
case "thread.interaction-mode-set":
case "thread.message-sent":
case "thread.turn-start-requested":
case "thread.session-set":
case "thread.proposed-plan-upserted":
case "thread.turn-diff-completed":
case "thread.activity-appended":
return false;
default:
return true;
}
}
export function applyOptimisticUserMessage(
snapshot: OrchestrationReadModel,
input: {
readonly threadId: ThreadId;
readonly messageId: MessageId;
readonly text: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly createdAt: string;
},
): OrchestrationReadModel {
return {
...snapshot,
updatedAt: input.createdAt,
threads: updateThread(snapshot, input.threadId, (thread) => {
if (thread.messages.some((message) => message.id === input.messageId)) {
return thread;
}
return {
...thread,
updatedAt: input.createdAt,
messages: [
...thread.messages,
{
id: input.messageId,
role: "user",
text: input.text,
turnId: null,
streaming: false,
createdAt: input.createdAt,
updatedAt: input.createdAt,
...(input.attachments && input.attachments.length > 0
? { attachments: input.attachments }
: {}),
},
],
};
}),
};
}
+11 -8
View File
@@ -16,7 +16,6 @@ function makeProject(
scripts: [],
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
deletedAt: null,
...input,
};
}
@@ -43,6 +42,10 @@ function makeThread(
activities: [],
checkpoints: [],
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
};
}
@@ -66,14 +69,14 @@ describe("groupProjectsByRepository", () => {
makeProject({
environmentId: "env-local",
environmentLabel: "Local",
id: ProjectId.makeUnsafe("project-local"),
id: ProjectId.make("project-local"),
title: "T3 Code",
repositoryIdentity: repoIdentity,
}),
makeProject({
environmentId: "env-staging",
environmentLabel: "Staging",
id: ProjectId.makeUnsafe("project-staging"),
id: ProjectId.make("project-staging"),
title: "T3 Code",
repositoryIdentity: repoIdentity,
}),
@@ -83,8 +86,8 @@ describe("groupProjectsByRepository", () => {
makeThread({
environmentId: "env-staging",
environmentLabel: "Staging",
id: ThreadId.makeUnsafe("thread-2"),
projectId: ProjectId.makeUnsafe("project-staging"),
id: ThreadId.make("thread-2"),
projectId: ProjectId.make("project-staging"),
title: "Fix reconnect flow",
modelSelection: { provider: "codex", model: "gpt-5.4" },
updatedAt: "2026-04-02T12:00:00.000Z",
@@ -92,8 +95,8 @@ describe("groupProjectsByRepository", () => {
makeThread({
environmentId: "env-local",
environmentLabel: "Local",
id: ThreadId.makeUnsafe("thread-1"),
projectId: ProjectId.makeUnsafe("project-local"),
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-local"),
title: "Polish mobile shell",
modelSelection: { provider: "codex", model: "gpt-5.4" },
updatedAt: "2026-04-03T12:00:00.000Z",
@@ -121,7 +124,7 @@ describe("groupProjectsByRepository", () => {
makeProject({
environmentId: "env-local",
environmentLabel: "Local",
id: ProjectId.makeUnsafe("project-local"),
id: ProjectId.make("project-local"),
title: "Scratchpad",
}),
];
+16 -3
View File
@@ -1,19 +1,32 @@
import type {
ApprovalRequestId,
OrchestrationProject,
OrchestrationProjectShell,
OrchestrationThread,
OrchestrationThreadShell,
ProjectId,
ThreadId,
} from "@t3tools/contracts";
export interface ScopedMobileProject extends OrchestrationProject {
export interface ScopedMobileProject extends OrchestrationProjectShell {
readonly environmentId: string;
readonly environmentLabel: string;
}
export interface ScopedMobileThread extends OrchestrationThread {
/**
* Thread shape used throughout the mobile UI. Extends the lightweight shell
* type with the full-detail fields the composer and detail screen expect.
* The shell snapshot stubs these as empty arrays; `useThreadSelection`
* overlays real data from the per-thread `subscribeThread` subscription
* when a thread is selected.
*/
export interface ScopedMobileThread extends OrchestrationThreadShell {
readonly environmentId: string;
readonly environmentLabel: string;
readonly deletedAt: OrchestrationThread["deletedAt"];
readonly messages: OrchestrationThread["messages"];
readonly proposedPlans: OrchestrationThread["proposedPlans"];
readonly activities: OrchestrationThread["activities"];
readonly checkpoints: OrchestrationThread["checkpoints"];
}
export function scopedProjectKey(environmentId: string, projectId: ProjectId): string {
@@ -1,6 +1,7 @@
import { useStore } from "zustand";
import { createStore } from "zustand/vanilla";
import type { OrchestrationThread } from "@t3tools/contracts";
import type { SavedRemoteConnection } from "../lib/connection";
import {
defaultEnvironmentRuntimeState,
@@ -13,6 +14,8 @@ export interface RemoteEnvironmentStoreState {
readonly pendingConnectionError: string | null;
readonly savedConnectionsById: Record<string, SavedRemoteConnection>;
readonly environmentStateById: Record<string, EnvironmentRuntimeState>;
/** Full thread detail keyed by `${environmentId}:${threadId}`. */
readonly threadDetailByKey: Record<string, OrchestrationThread>;
readonly setIsLoadingSavedConnection: (value: boolean) => void;
readonly setConnectionPairingUrl: (pairingUrl: string) => void;
@@ -27,6 +30,8 @@ export interface RemoteEnvironmentStoreState {
updater: (current: EnvironmentRuntimeState) => EnvironmentRuntimeState,
) => void;
readonly removeEnvironmentRuntimeState: (environmentId: string) => void;
readonly setThreadDetail: (key: string, thread: OrchestrationThread) => void;
readonly removeThreadDetail: (key: string) => void;
}
export const remoteEnvironmentStore = createStore<RemoteEnvironmentStoreState>()((set) => ({
@@ -35,6 +40,7 @@ export const remoteEnvironmentStore = createStore<RemoteEnvironmentStoreState>()
pendingConnectionError: null,
savedConnectionsById: {},
environmentStateById: {},
threadDetailByKey: {},
setIsLoadingSavedConnection: (value) => set({ isLoadingSavedConnection: value }),
setConnectionPairingUrl: (pairingUrl) => set({ connectionPairingUrl: pairingUrl }),
@@ -70,6 +76,16 @@ export const remoteEnvironmentStore = createStore<RemoteEnvironmentStoreState>()
delete next[environmentId];
return { environmentStateById: next };
}),
setThreadDetail: (key, thread) =>
set((state) => ({
threadDetailByKey: { ...state.threadDetailByKey, [key]: thread },
})),
removeThreadDetail: (key) =>
set((state) => {
const next = { ...state.threadDetailByKey };
delete next[key];
return { threadDetailByKey: next };
}),
}));
export function useRemoteEnvironmentStore<T>(
@@ -1,4 +1,7 @@
import type { OrchestrationReadModel, ServerConfig as T3ServerConfig } from "@t3tools/contracts";
import type {
OrchestrationShellSnapshot,
ServerConfig as T3ServerConfig,
} from "@t3tools/contracts";
import type { EnvironmentConnection, WsRpcClient } from "@t3tools/client-runtime";
export type RemoteClientConnectionState =
@@ -24,7 +27,7 @@ export interface SelectedThreadRef {
export interface EnvironmentRuntimeState {
readonly connectionState: RemoteClientConnectionState;
readonly connectionError: string | null;
readonly snapshot: OrchestrationReadModel | null;
readonly snapshot: OrchestrationShellSnapshot | null;
readonly serverConfig: T3ServerConfig | null;
}
+7 -11
View File
@@ -42,14 +42,10 @@ function useRefreshRemoteData() {
}
try {
const [serverConfig, snapshot] = await Promise.all([
client.server.getConfig(),
client.orchestration.getSnapshot(),
]);
const serverConfig = await client.server.getConfig();
patchEnvironmentRuntimeState(environmentId, (current) => ({
...current,
serverConfig,
snapshot,
connectionError: null,
}));
} catch (error) {
@@ -91,7 +87,7 @@ export function useProjectActions() {
return null;
}
const threadId = ThreadId.makeUnsafe(uuidv4());
const threadId = ThreadId.make(uuidv4());
const createdAt = new Date().toISOString();
const initialMessageText = input.initialMessageText.trim();
const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
@@ -103,10 +99,10 @@ export function useProjectActions() {
await client.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe(uuidv4()),
commandId: CommandId.make(uuidv4()),
threadId,
message: {
messageId: MessageId.makeUnsafe(uuidv4()),
messageId: MessageId.make(uuidv4()),
role: "user",
text: initialMessageText,
attachments: input.initialAttachments,
@@ -138,7 +134,7 @@ export function useProjectActions() {
} else {
await client.orchestration.dispatchCommand({
type: "thread.create",
commandId: CommandId.makeUnsafe(uuidv4()),
commandId: CommandId.make(uuidv4()),
threadId,
projectId: input.project.id,
title: nextTitle,
@@ -153,10 +149,10 @@ export function useProjectActions() {
if (initialMessageText.length > 0 || input.initialAttachments.length > 0) {
await client.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe(uuidv4()),
commandId: CommandId.make(uuidv4()),
threadId,
message: {
messageId: MessageId.makeUnsafe(uuidv4()),
messageId: MessageId.make(uuidv4()),
role: "user",
text: initialMessageText,
attachments: input.initialAttachments,
+14 -12
View File
@@ -34,14 +34,13 @@ export function useRemoteCatalog() {
() =>
Arr.sort(
Object.values(savedConnectionsById).flatMap((connection) =>
(environmentStateById[connection.environmentId]?.snapshot?.projects ?? [])
.filter((project) => project.deletedAt === null)
.map((project) =>
(environmentStateById[connection.environmentId]?.snapshot?.projects ?? []).map(
(project) =>
Object.assign({}, project, {
environmentId: connection.environmentId,
environmentLabel: connection.environmentLabel,
}),
),
),
),
projectsSortOrder,
),
@@ -52,14 +51,17 @@ export function useRemoteCatalog() {
() =>
Arr.sort(
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,
}),
),
(environmentStateById[connection.environmentId]?.snapshot?.threads ?? []).map((thread) =>
Object.assign({}, thread, {
environmentId: connection.environmentId,
environmentLabel: connection.environmentLabel,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
}),
),
),
threadsSortOrder,
),
@@ -2,18 +2,18 @@ import { useCallback, useEffect, useMemo } from "react";
import { Alert } from "react-native";
import {
applyShellStreamEvent,
createEnvironmentConnection,
createKnownEnvironment,
createWsRpcClient,
WsTransport,
} from "@t3tools/client-runtime";
import { EnvironmentId, type OrchestrationReadModel } from "@t3tools/contracts";
import { EnvironmentId } from "@t3tools/contracts";
import { resolveRemoteWebSocketConnectionUrl } from "@t3tools/shared/remote";
import { useShallow } from "zustand/react/shallow";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { type SavedRemoteConnection, bootstrapRemoteConnection } from "../lib/connection";
import { applyRealtimeEvent, requiresSnapshotRefresh } from "../lib/orchestration";
import { clearSavedConnection, loadSavedConnections, saveConnection } from "../lib/storage";
import {
firstNonNull,
@@ -141,36 +141,22 @@ export async function connectSavedEnvironment(
wsBaseUrl: connection.wsBaseUrl,
},
}),
environmentId: EnvironmentId.makeUnsafe(connection.environmentId),
environmentId: EnvironmentId.make(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,
}));
applyShellEvent: (event, environmentId) => {
remoteEnvironmentStore.getState().patchEnvironmentRuntimeState(environmentId, (runtime) => {
if (!runtime.snapshot) {
return runtime;
}
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);
}
return {
...runtime,
snapshot: applyShellStreamEvent(runtime.snapshot, event),
};
});
},
syncSnapshot: (snapshot, environmentId) => {
syncShellSnapshot: (snapshot, environmentId) => {
remoteEnvironmentStore.getState().patchEnvironmentRuntimeState(environmentId, (runtime) => ({
...runtime,
snapshot,
@@ -241,7 +227,7 @@ export function useRemoteEnvironmentBootstrap() {
let cancelled = false;
void loadSavedConnections()
.then(async (connections) => {
.then((connections) => {
if (cancelled) {
return;
}
@@ -252,7 +238,9 @@ export function useRemoteEnvironmentBootstrap() {
),
);
await Promise.all(
setIsLoadingSavedConnection(false);
void Promise.all(
connections.map((connection) =>
connectSavedEnvironment(connection, {
persist: false,
@@ -260,7 +248,7 @@ export function useRemoteEnvironmentBootstrap() {
),
);
})
.finally(() => {
.catch(() => {
if (!cancelled) {
setIsLoadingSavedConnection(false);
}
@@ -388,6 +376,14 @@ export function useRemoteConnections() {
[],
);
const onReconnectEnvironment = useCallback((environmentId: string) => {
const connection = remoteEnvironmentStore.getState().savedConnectionsById[environmentId];
if (!connection) {
return;
}
void connectSavedEnvironment(connection, { persist: false });
}, []);
const onRemoveEnvironmentPress = useCallback((environmentId: string) => {
const connection = remoteEnvironmentStore.getState().savedConnectionsById[environmentId];
if (!connection) {
@@ -418,6 +414,7 @@ export function useRemoteConnections() {
connectedEnvironmentCount: connectedEnvironments.length,
onChangeConnectionPairingUrl: setConnectionPairingUrl,
onConnectPress,
onReconnectEnvironment,
onUpdateEnvironment,
onRemoveEnvironmentPress,
};
@@ -59,14 +59,10 @@ export function useSelectedThreadCommands(input: {
}
try {
const [serverConfig, snapshot] = await Promise.all([
client.server.getConfig(),
client.orchestration.getSnapshot(),
]);
const serverConfig = await client.server.getConfig();
patchEnvironmentRuntimeState(environmentId, (current) => ({
...current,
serverConfig,
snapshot,
connectionError: null,
}));
} catch (error) {
@@ -102,7 +98,7 @@ export function useSelectedThreadCommands(input: {
await client.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe(uuidv4()),
commandId: CommandId.make(uuidv4()),
threadId: selectedThread.id,
modelSelection,
});
@@ -123,7 +119,7 @@ export function useSelectedThreadCommands(input: {
await client.orchestration.dispatchCommand({
type: "thread.runtime-mode.set",
commandId: CommandId.makeUnsafe(uuidv4()),
commandId: CommandId.make(uuidv4()),
threadId: selectedThread.id,
runtimeMode,
createdAt: new Date().toISOString(),
@@ -145,7 +141,7 @@ export function useSelectedThreadCommands(input: {
await client.orchestration.dispatchCommand({
type: "thread.interaction-mode.set",
commandId: CommandId.makeUnsafe(uuidv4()),
commandId: CommandId.make(uuidv4()),
threadId: selectedThread.id,
interactionMode,
createdAt: new Date().toISOString(),
@@ -173,7 +169,7 @@ export function useSelectedThreadCommands(input: {
await client.orchestration.dispatchCommand({
type: "thread.turn.interrupt",
commandId: CommandId.makeUnsafe(uuidv4()),
commandId: CommandId.make(uuidv4()),
threadId: selectedThread.id,
...(selectedThread.session?.activeTurnId
? { turnId: selectedThread.session.activeTurnId }
@@ -200,7 +196,7 @@ export function useSelectedThreadCommands(input: {
await client.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe(uuidv4()),
commandId: CommandId.make(uuidv4()),
threadId: selectedThread.id,
title: trimmed,
});
@@ -223,7 +219,7 @@ export function useSelectedThreadCommands(input: {
try {
await client.orchestration.dispatchCommand({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe(uuidv4()),
commandId: CommandId.make(uuidv4()),
threadId: selectedThread.id,
requestId,
decision,
@@ -250,7 +246,7 @@ export function useSelectedThreadCommands(input: {
try {
await client.orchestration.dispatchCommand({
type: "thread.user-input.respond",
commandId: CommandId.makeUnsafe(uuidv4()),
commandId: CommandId.make(uuidv4()),
threadId: selectedThread.id,
requestId: activePendingUserInput.requestId,
answers: activePendingUserInputAnswers,
@@ -44,8 +44,8 @@ export function useSelectedThreadGitActions() {
await client.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe(uuidv4()),
threadId: ThreadId.makeUnsafe(thread.id),
commandId: CommandId.make(uuidv4()),
threadId: ThreadId.make(thread.id),
...(nextState.branch !== undefined ? { branch: nextState.branch } : {}),
...(nextState.worktreePath !== undefined ? { worktreePath: nextState.worktreePath } : {}),
});
@@ -8,7 +8,6 @@ import {
pasteComposerClipboard,
pickComposerImages,
} from "../lib/composerImages";
import { applyOptimisticUserMessage } from "../lib/orchestration";
import type { ScopedMobileThread } from "../lib/scopedEntities";
import { scopedRequestKey, scopedThreadKey } from "../lib/scopedEntities";
import {
@@ -106,9 +105,7 @@ export function useThreadComposerState() {
const { connectedEnvironments } = useRemoteConnectionStatus();
const { threads } = useRemoteCatalog();
const { selectedThread } = useThreadSelection();
const patchEnvironmentRuntimeState = useRemoteEnvironmentStore(
(state) => state.patchEnvironmentRuntimeState,
);
const setPendingConnectionError = useRemoteEnvironmentStore(
(state) => state.setPendingConnectionError,
);
@@ -242,10 +239,10 @@ export function useThreadComposerState() {
try {
await client.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe(queuedMessage.commandId),
threadId: ThreadId.makeUnsafe(queuedMessage.threadId),
commandId: CommandId.make(queuedMessage.commandId),
threadId: ThreadId.make(queuedMessage.threadId),
message: {
messageId: MessageId.makeUnsafe(queuedMessage.messageId),
messageId: MessageId.make(queuedMessage.messageId),
role: "user",
text: queuedMessage.text,
attachments: queuedMessage.attachments,
@@ -260,18 +257,6 @@ export function useThreadComposerState() {
queuedMessage.threadId,
queuedMessage.messageId,
);
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,
@@ -288,7 +273,6 @@ export function useThreadComposerState() {
[
beginDispatchingQueuedMessage,
finishDispatchingQueuedMessage,
patchEnvironmentRuntimeState,
removeQueuedMessage,
setPendingConnectionError,
threads,
@@ -319,8 +303,8 @@ export function useThreadComposerState() {
enqueueQueuedMessage({
environmentId: selectedThread.environmentId,
threadId: selectedThread.id,
messageId: MessageId.makeUnsafe(uuidv4()),
commandId: CommandId.makeUnsafe(uuidv4()),
messageId: MessageId.make(uuidv4()),
commandId: CommandId.make(uuidv4()),
text,
attachments,
createdAt,
@@ -0,0 +1,100 @@
import { useEffect } from "react";
import { applyThreadDetailEvent } from "@t3tools/client-runtime";
import { ThreadId } from "@t3tools/contracts";
import { scopedThreadKey } from "../lib/scopedEntities";
import { remoteEnvironmentStore } from "./remote-environment-store";
import { getEnvironmentClient } from "./use-remote-environment-registry";
/**
* Subscribe to full thread detail (messages, activities, checkpoints, etc.)
* for the given environment + thread. The subscription is torn down when the
* component unmounts or the identifiers change.
*
* Received snapshots and incremental events are written into
* `remoteEnvironmentStore.threadDetailByKey` so that `useThreadSelection` can
* merge them over the shell stubs.
*/
export function useThreadDetailSubscription(
environmentId: string | null,
threadId: string | null,
): void {
useEffect(() => {
if (!environmentId || !threadId) {
return;
}
const brandedThreadId = ThreadId.make(threadId);
const key = scopedThreadKey(environmentId, brandedThreadId);
let unsubscribe: (() => void) | null = null;
let disposed = false;
function attach() {
if (disposed) {
return;
}
const client = getEnvironmentClient(environmentId!);
if (!client) {
return;
}
unsubscribe = client.orchestration.subscribeThread({ threadId: brandedThreadId }, (item) => {
if (disposed) {
return;
}
const store = remoteEnvironmentStore.getState();
if (item.kind === "snapshot") {
store.setThreadDetail(key, item.snapshot.thread);
return;
}
const current = store.threadDetailByKey[key];
if (!current) {
return;
}
const result = applyThreadDetailEvent(current, item.event);
if (result.kind === "updated") {
store.setThreadDetail(key, result.thread);
} else if (result.kind === "deleted") {
store.removeThreadDetail(key);
}
});
}
attach();
// If the client isn't available yet (still connecting), retry when the
// connection state changes via a simple polling interval that clears once
// attached. This avoids coupling to the connection listener API.
let retryTimer: ReturnType<typeof setInterval> | null = null;
if (!unsubscribe) {
retryTimer = setInterval(() => {
if (disposed) {
if (retryTimer) clearInterval(retryTimer);
return;
}
if (unsubscribe) {
if (retryTimer) clearInterval(retryTimer);
return;
}
attach();
if (unsubscribe && retryTimer) {
clearInterval(retryTimer);
retryTimer = null;
}
}, 500);
}
return () => {
disposed = true;
if (retryTimer) clearInterval(retryTimer);
unsubscribe?.();
remoteEnvironmentStore.getState().removeThreadDetail(key);
};
}, [environmentId, threadId]);
}
+27 -4
View File
@@ -2,8 +2,10 @@ import { useCallback, useEffect, useMemo } from "react";
import type { SavedRemoteConnection } from "../lib/connection";
import type { ScopedMobileProject, ScopedMobileThread } from "../lib/scopedEntities";
import { scopedThreadKey } from "../lib/scopedEntities";
import { useRemoteCatalog } from "./use-remote-catalog";
import { type EnvironmentRuntimeState } from "./remote-runtime-types";
import { useRemoteEnvironmentStore } from "./remote-environment-store";
import { useRemoteEnvironmentState } from "./use-remote-environment-registry";
import { useThreadSelectionStore } from "./thread-selection-store";
@@ -48,10 +50,31 @@ export function useThreadSelection() {
const selectThreadRef = useThreadSelectionStore((state) => state.selectThreadRef);
const clearSelectedThreadRef = useThreadSelectionStore((state) => state.clearSelectedThreadRef);
const selectedThread = useMemo(
() => deriveSelectedThread(selectedThreadRef, threads),
[selectedThreadRef, threads],
);
const threadDetailByKey = useRemoteEnvironmentStore((state) => state.threadDetailByKey);
const selectedThread = useMemo(() => {
const shell = deriveSelectedThread(selectedThreadRef, threads);
if (!shell) {
return null;
}
const key = scopedThreadKey(shell.environmentId, shell.id);
const detail = threadDetailByKey[key];
if (!detail) {
return shell;
}
return {
...shell,
messages: detail.messages,
proposedPlans: detail.proposedPlans,
activities: detail.activities,
checkpoints: detail.checkpoints,
latestTurn: detail.latestTurn,
session: detail.session,
deletedAt: detail.deletedAt,
};
}, [selectedThreadRef, threadDetailByKey, threads]);
useEffect(() => {
if (!selectedThreadRef || selectedThread) {
+5 -5
View File
@@ -1,10 +1,10 @@
// NOTE: This file is generated by uniwind and it should not be edited manually.
/// <reference types="uniwind/types" />
declare module 'uniwind' {
export interface UniwindConfig {
themes: readonly ['light', 'dark']
}
declare module "uniwind" {
export interface UniwindConfig {
themes: readonly ["light", "dark"];
}
}
export {}
export {};
+9 -10
View File
@@ -1,4 +1,9 @@
import { WsRpcGroup } from "@t3tools/contracts";
import {
DEFAULT_RECONNECT_BACKOFF,
getReconnectDelayMs,
type WsProtocolLifecycleHandlers,
} from "@t3tools/client-runtime";
import { Duration, Effect, Layer, Schedule } from "effect";
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
import * as Socket from "effect/unstable/socket/Socket";
@@ -9,20 +14,13 @@ import {
trackRpcRequestSent,
} from "./requestLatencyState";
import {
getWsReconnectDelayMsForRetry,
recordWsConnectionAttempt,
recordWsConnectionClosed,
recordWsConnectionErrored,
recordWsConnectionOpened,
WS_RECONNECT_MAX_RETRIES,
} from "./wsConnectionState";
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 type { WsProtocolLifecycleHandlers };
export const makeWsRpcProtocolClient = RpcClient.make(WsRpcGroup);
type RpcClientFactory = typeof makeWsRpcProtocolClient;
@@ -142,8 +140,9 @@ export function createWsRpcProtocolLayer(
const socketLayer = Socket.layerWebSocket(resolvedUrl).pipe(
Layer.provide(trackingWebSocketConstructorLayer),
);
const retryPolicy = Schedule.addDelay(Schedule.recurs(WS_RECONNECT_MAX_RETRIES), (retryCount) =>
Effect.succeed(Duration.millis(getWsReconnectDelayMsForRetry(retryCount) ?? 0)),
const retryPolicy = Schedule.addDelay(
Schedule.recurs(DEFAULT_RECONNECT_BACKOFF.maxRetries!),
(retryCount) => Effect.succeed(Duration.millis(getReconnectDelayMs(retryCount) ?? 0)),
);
const protocolLayer = Layer.effect(
RpcClient.Protocol,
+4 -23
View File
@@ -1,23 +1,4 @@
const TRANSPORT_ERROR_PATTERNS = [
/\bSocketCloseError\b/i,
/\bSocketOpenError\b/i,
/Unable to connect to the T3 server WebSocket\./i,
/\bping timeout\b/i,
] as const;
export function isTransportConnectionErrorMessage(message: string | null | undefined): boolean {
if (typeof message !== "string") {
return false;
}
const normalizedMessage = message.trim();
if (normalizedMessage.length === 0) {
return false;
}
return TRANSPORT_ERROR_PATTERNS.some((pattern) => pattern.test(normalizedMessage));
}
export function sanitizeThreadErrorMessage(message: string | null | undefined): string | null {
return isTransportConnectionErrorMessage(message) ? null : (message ?? null);
}
export {
isTransportConnectionErrorMessage,
sanitizeThreadErrorMessage,
} from "@t3tools/client-runtime";
+6 -12
View File
@@ -1,4 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
import { DEFAULT_RECONNECT_BACKOFF, getReconnectDelayMs } from "@t3tools/client-runtime";
import { Atom } from "effect/unstable/reactivity";
import { appAtomRegistry } from "./atomRegistry";
@@ -6,10 +7,10 @@ import { appAtomRegistry } from "./atomRegistry";
export type WsConnectionUiState = "connected" | "connecting" | "error" | "offline" | "reconnecting";
export type WsReconnectPhase = "attempting" | "exhausted" | "idle" | "waiting";
export const WS_RECONNECT_INITIAL_DELAY_MS = 1_000;
export const WS_RECONNECT_BACKOFF_FACTOR = 2;
export const WS_RECONNECT_MAX_DELAY_MS = 64_000;
export const WS_RECONNECT_MAX_RETRIES = 7;
export const WS_RECONNECT_INITIAL_DELAY_MS = DEFAULT_RECONNECT_BACKOFF.initialDelayMs;
export const WS_RECONNECT_BACKOFF_FACTOR = DEFAULT_RECONNECT_BACKOFF.backoffFactor;
export const WS_RECONNECT_MAX_DELAY_MS = DEFAULT_RECONNECT_BACKOFF.maxDelayMs;
export const WS_RECONNECT_MAX_RETRIES = DEFAULT_RECONNECT_BACKOFF.maxRetries!;
export const WS_RECONNECT_MAX_ATTEMPTS = WS_RECONNECT_MAX_RETRIES + 1;
export interface WsConnectionStatus {
@@ -158,14 +159,7 @@ export function useWsConnectionStatus(): WsConnectionStatus {
}
export function getWsReconnectDelayMsForRetry(retryIndex: number): number | null {
if (!Number.isInteger(retryIndex) || retryIndex < 0 || retryIndex >= WS_RECONNECT_MAX_RETRIES) {
return null;
}
return Math.min(
Math.round(WS_RECONNECT_INITIAL_DELAY_MS * WS_RECONNECT_BACKOFF_FACTOR ** retryIndex),
WS_RECONNECT_MAX_DELAY_MS,
);
return getReconnectDelayMs(retryIndex);
}
function applyDisconnectState(
+2 -101
View File
@@ -9,6 +9,7 @@ import {
type ServerSettingsPatch,
WS_METHODS,
} from "@t3tools/contracts";
import type { WsRpcClient } from "@t3tools/client-runtime";
import { applyGitStatusStreamEvent } from "@t3tools/shared/git";
import { Effect, Stream } from "effect";
@@ -16,107 +17,7 @@ import { type WsRpcProtocolClient } from "./protocol";
import { resetWsReconnectBackoff } from "./wsConnectionState";
import { WsTransport } from "./wsTransport";
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;
type RpcInputStreamMethod<TTag extends RpcTag> =
RpcMethod<TTag> extends (input: any, options?: any) => Stream.Stream<infer TEvent, any, any>
? (
input: RpcInput<TTag>,
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 dispatchCommand: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.dispatchCommand>;
readonly getTurnDiff: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.getTurnDiff>;
readonly getFullThreadDiff: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.getFullThreadDiff>;
readonly subscribeShell: RpcStreamMethod<typeof ORCHESTRATION_WS_METHODS.subscribeShell>;
readonly subscribeThread: RpcInputStreamMethod<typeof ORCHESTRATION_WS_METHODS.subscribeThread>;
};
}
export type { WsRpcClient };
export function createWsRpcClient(transport: WsTransport): WsRpcClient {
return {
+2 -1
View File
@@ -48,7 +48,7 @@
"@effect/atom-react": "catalog:",
"@expo-google-fonts/dm-sans": "^0.4.2",
"@gorhom/bottom-sheet": "^5",
"@legendapp/list": "^3.0.0-beta.44",
"@legendapp/list": "3.0.0-beta.44",
"@react-native-menu/menu": "^2.0.0",
"@sethwebster/react-ethereal-input": "^0.4.0",
"@shopify/flash-list": "2.0.2",
@@ -186,6 +186,7 @@
"version": "0.0.0-alpha.1",
"dependencies": {
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"effect": "catalog:",
},
"devDependencies": {
+1
View File
@@ -21,6 +21,7 @@
},
"dependencies": {
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"effect": "catalog:"
},
"devDependencies": {
@@ -1,48 +1,15 @@
import type {
EnvironmentId,
OrchestrationEvent,
OrchestrationReadModel,
OrchestrationShellSnapshot,
OrchestrationShellStreamEvent,
ServerConfig,
ServerLifecycleWelcomePayload,
TerminalEvent,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import * as Option from "effect/Option";
import { pipe } from "effect/Function";
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;
@@ -54,11 +21,14 @@ export interface EnvironmentConnection {
}
interface OrchestrationHandlers {
readonly applyEventBatch: (
events: ReadonlyArray<OrchestrationEvent>,
readonly applyShellEvent: (
event: OrchestrationShellStreamEvent,
environmentId: EnvironmentId,
) => void;
readonly syncShellSnapshot: (
snapshot: OrchestrationShellSnapshot,
environmentId: EnvironmentId,
) => void;
readonly syncSnapshot: (snapshot: OrchestrationReadModel, environmentId: EnvironmentId) => void;
readonly applyTerminalEvent: (event: TerminalEvent, environmentId: EnvironmentId) => void;
}
@@ -71,273 +41,9 @@ interface EnvironmentConnectionInput extends OrchestrationHandlers {
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 = pipe(
events,
Arr.filter((event) => event.sequence > state.latestSequence),
Arr.sortWith((event) => event.sequence, Order.Number),
);
if (nextEvents.length === 0) {
return [];
}
const latestSequence = Arr.last(nextEvents).pipe(
Option.map((event) => event.sequence),
Option.getOrElse(() => 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) {
@@ -347,6 +53,19 @@ export function createEnvironmentConnection(
}
let disposed = false;
let bootstrapped = false;
let bootstrapResolve: (() => void) | null = null;
let bootstrapPromise: Promise<void> | null = null;
const resetBootstrapGate = () => {
bootstrapped = false;
bootstrapPromise = new Promise<void>((resolve) => {
bootstrapResolve = resolve;
});
};
// Initialize the bootstrap gate so ensureBootstrapped can await it.
resetBootstrapGate();
const observeEnvironmentIdentity = (nextEnvironmentId: EnvironmentId, source: string) => {
if (environmentId !== nextEnvironmentId) {
@@ -356,110 +75,6 @@ export function createEnvironmentConnection(
}
};
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;
@@ -478,21 +93,21 @@ export function createEnvironmentConnection(
input.onConfigSnapshot?.(event.config);
});
const unsubDomainEvent = input.client.orchestration.onDomainEvent(
(event) => {
const action = recovery.classifyDomainEvent(event.sequence);
if (action === "apply") {
pendingDomainEvents.push(event);
schedulePendingDomainEventFlush();
const unsubShell = input.client.orchestration.subscribeShell(
(item) => {
if (disposed) {
return;
}
if (action === "ignore" || action === "defer") {
if (item.kind === "snapshot") {
input.syncShellSnapshot(item.snapshot, environmentId);
bootstrapped = true;
bootstrapResolve?.();
bootstrapResolve = null;
return;
}
flushPendingDomainEvents();
void runReplayRecovery("sequence-gap");
input.applyShellEvent(item, environmentId);
},
{
onResubscribe: () => {
@@ -500,8 +115,9 @@ export function createEnvironmentConnection(
return;
}
flushPendingDomainEvents();
void runReplayRecovery("resubscribe");
// The server will re-emit a snapshot on resubscribe, so reset the
// bootstrap gate so reconnect callers can await the fresh snapshot.
resetBootstrapGate();
},
},
);
@@ -510,13 +126,9 @@ export function createEnvironmentConnection(
input.applyTerminalEvent(event, environmentId);
});
void snapshotBootstrap.ensureSnapshotRecovery("bootstrap").catch(() => undefined);
const cleanup = () => {
disposed = true;
flushPendingDomainEventsScheduled = false;
pendingDomainEvents.length = 0;
unsubDomainEvent();
unsubShell();
unsubTerminalEvent();
unsubLifecycle();
unsubConfig();
@@ -527,11 +139,20 @@ export function createEnvironmentConnection(
environmentId,
knownEnvironment: input.knownEnvironment,
client: input.client,
ensureBootstrapped: () => snapshotBootstrap.ensureSnapshotRecovery("bootstrap"),
ensureBootstrapped: () => {
if (bootstrapped) {
return Promise.resolve();
}
return bootstrapPromise ?? Promise.resolve();
},
reconnect: async () => {
await input.client.reconnect();
await input.refreshMetadata?.();
await snapshotBootstrap.ensureSnapshotRecovery("bootstrap");
// After reconnect the shell subscription's onResubscribe fires, which
// resets the bootstrap gate. Wait for the server to push a fresh snapshot.
if (bootstrapPromise) {
await bootstrapPromise;
}
},
dispose: async () => {
cleanup();
+4
View File
@@ -1,9 +1,13 @@
export * from "./knownEnvironment";
export * from "./reconnectBackoff";
export * from "./scoped";
export * from "./shellSnapshotReducer";
export * from "./threadDetailReducer";
export * from "./gitActions";
export * from "./gitActionState";
export * from "./gitBranchState";
export * from "./gitStatusState";
export * from "./transportError";
export * from "./wsRpcProtocol";
export * from "./wsTransport";
export * from "./wsRpcClient";
@@ -0,0 +1,65 @@
import { describe, expect, it } from "vitest";
import {
DEFAULT_RECONNECT_BACKOFF,
getReconnectDelayMs,
type ReconnectBackoffConfig,
} from "./reconnectBackoff";
describe("getReconnectDelayMs", () => {
it("returns exponential delays with default config", () => {
expect(getReconnectDelayMs(0)).toBe(1_000);
expect(getReconnectDelayMs(1)).toBe(2_000);
expect(getReconnectDelayMs(2)).toBe(4_000);
expect(getReconnectDelayMs(3)).toBe(8_000);
expect(getReconnectDelayMs(4)).toBe(16_000);
expect(getReconnectDelayMs(5)).toBe(32_000);
expect(getReconnectDelayMs(6)).toBe(64_000);
});
it("returns null when retry index exceeds maxRetries", () => {
expect(getReconnectDelayMs(7)).toBeNull();
expect(getReconnectDelayMs(100)).toBeNull();
});
it("returns null for negative indices", () => {
expect(getReconnectDelayMs(-1)).toBeNull();
});
it("returns null for non-integer indices", () => {
expect(getReconnectDelayMs(1.5)).toBeNull();
});
it("caps delay at maxDelayMs", () => {
const config: ReconnectBackoffConfig = {
initialDelayMs: 10_000,
backoffFactor: 10,
maxDelayMs: 30_000,
maxRetries: 5,
};
expect(getReconnectDelayMs(0, config)).toBe(10_000);
expect(getReconnectDelayMs(1, config)).toBe(30_000); // 100_000 capped to 30_000
expect(getReconnectDelayMs(2, config)).toBe(30_000); // 1_000_000 capped to 30_000
});
it("supports unlimited retries when maxRetries is null", () => {
const config: ReconnectBackoffConfig = {
...DEFAULT_RECONNECT_BACKOFF,
maxRetries: null,
};
expect(getReconnectDelayMs(0, config)).toBe(1_000);
expect(getReconnectDelayMs(50, config)).toBe(64_000); // capped at maxDelayMs
expect(getReconnectDelayMs(100, config)).toBe(64_000);
});
});
describe("DEFAULT_RECONNECT_BACKOFF", () => {
it("has sensible defaults", () => {
expect(DEFAULT_RECONNECT_BACKOFF.initialDelayMs).toBe(1_000);
expect(DEFAULT_RECONNECT_BACKOFF.backoffFactor).toBe(2);
expect(DEFAULT_RECONNECT_BACKOFF.maxDelayMs).toBe(64_000);
expect(DEFAULT_RECONNECT_BACKOFF.maxRetries).toBe(7);
});
});
@@ -0,0 +1,47 @@
/**
* Configuration for exponential reconnect backoff.
*/
export interface ReconnectBackoffConfig {
/** Base delay in milliseconds before the first retry. */
readonly initialDelayMs: number;
/** Multiplier applied per retry (exponential factor). */
readonly backoffFactor: number;
/** Hard upper bound on delay in milliseconds. */
readonly maxDelayMs: number;
/** Maximum number of retries (0-based). `null` means unlimited. */
readonly maxRetries: number | null;
}
/**
* Sensible defaults for WebSocket reconnect backoff.
*
* - 1 s initial delay, doubling each retry, capped at 64 s, up to 7 retries.
*/
export const DEFAULT_RECONNECT_BACKOFF: ReconnectBackoffConfig = {
initialDelayMs: 1_000,
backoffFactor: 2,
maxDelayMs: 64_000,
maxRetries: 7,
};
/**
* Calculate the reconnect delay for a given retry index using exponential
* backoff. Returns `null` when `retryIndex` exceeds the configured maximum.
*/
export function getReconnectDelayMs(
retryIndex: number,
config: ReconnectBackoffConfig = DEFAULT_RECONNECT_BACKOFF,
): number | null {
if (!Number.isInteger(retryIndex) || retryIndex < 0) {
return null;
}
if (config.maxRetries !== null && retryIndex >= config.maxRetries) {
return null;
}
return Math.min(
Math.round(config.initialDelayMs * config.backoffFactor ** retryIndex),
config.maxDelayMs,
);
}
@@ -0,0 +1,163 @@
import { describe, expect, it } from "vitest";
import { ProjectId, ThreadId } from "@t3tools/contracts";
import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts";
import { applyShellStreamEvent } from "./shellSnapshotReducer";
const baseSnapshot: OrchestrationShellSnapshot = {
snapshotSequence: 0,
projects: [],
threads: [],
updatedAt: "2026-04-01T00:00:00.000Z",
};
const stubProject = {
id: ProjectId.make("project-1"),
title: "Test Project",
workspaceRoot: "/workspace/test",
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
} as const;
const stubThread = {
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Test Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access" as const,
interactionMode: "default" as const,
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
archivedAt: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
session: null,
} as const;
describe("applyShellStreamEvent", () => {
describe("project-upserted", () => {
it("adds a new project", () => {
const event: OrchestrationShellStreamEvent = {
kind: "project-upserted",
sequence: 1,
project: stubProject,
};
const next = applyShellStreamEvent(baseSnapshot, event);
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.id).toBe("project-1");
expect(next.snapshotSequence).toBe(1);
});
it("updates an existing project", () => {
const snapshotWithProject: OrchestrationShellSnapshot = {
...baseSnapshot,
projects: [stubProject],
};
const updatedProject = { ...stubProject, title: "Updated Title" };
const event: OrchestrationShellStreamEvent = {
kind: "project-upserted",
sequence: 2,
project: updatedProject,
};
const next = applyShellStreamEvent(snapshotWithProject, event);
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.title).toBe("Updated Title");
expect(next.snapshotSequence).toBe(2);
});
});
describe("project-removed", () => {
it("removes a project by id", () => {
const snapshotWithProject: OrchestrationShellSnapshot = {
...baseSnapshot,
projects: [stubProject],
};
const event: OrchestrationShellStreamEvent = {
kind: "project-removed",
sequence: 3,
projectId: ProjectId.make("project-1"),
};
const next = applyShellStreamEvent(snapshotWithProject, event);
expect(next.projects).toHaveLength(0);
expect(next.snapshotSequence).toBe(3);
});
});
describe("thread-upserted", () => {
it("adds a new thread", () => {
const event: OrchestrationShellStreamEvent = {
kind: "thread-upserted",
sequence: 4,
thread: stubThread,
};
const next = applyShellStreamEvent(baseSnapshot, event);
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.id).toBe("thread-1");
expect(next.snapshotSequence).toBe(4);
});
it("updates an existing thread", () => {
const snapshotWithThread: OrchestrationShellSnapshot = {
...baseSnapshot,
threads: [stubThread],
};
const updatedThread = { ...stubThread, title: "Updated Thread" };
const event: OrchestrationShellStreamEvent = {
kind: "thread-upserted",
sequence: 5,
thread: updatedThread,
};
const next = applyShellStreamEvent(snapshotWithThread, event);
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.title).toBe("Updated Thread");
});
});
describe("thread-removed", () => {
it("removes a thread by id", () => {
const snapshotWithThread: OrchestrationShellSnapshot = {
...baseSnapshot,
threads: [stubThread],
};
const event: OrchestrationShellStreamEvent = {
kind: "thread-removed",
sequence: 6,
threadId: ThreadId.make("thread-1"),
};
const next = applyShellStreamEvent(snapshotWithThread, event);
expect(next.threads).toHaveLength(0);
expect(next.snapshotSequence).toBe(6);
});
});
it("returns original snapshot for unrecognized event kinds", () => {
const unknownEvent = { kind: "unknown-future-event", sequence: 99 } as any;
const next = applyShellStreamEvent(baseSnapshot, unknownEvent);
expect(next).toBe(baseSnapshot);
});
});
@@ -0,0 +1,43 @@
import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts";
/**
* Apply a single shell stream event to an existing snapshot, returning a new
* snapshot with the event's changes applied. This is a pure reducer that both
* web and mobile can use to keep their local shell snapshot in sync.
*
* Returns the original snapshot reference unchanged if the event is not
* recognized (forward-compatible).
*/
export function applyShellStreamEvent(
snapshot: OrchestrationShellSnapshot,
event: OrchestrationShellStreamEvent,
): OrchestrationShellSnapshot {
switch (event.kind) {
case "project-upserted": {
const projects = snapshot.projects.some((p) => p.id === event.project.id)
? snapshot.projects.map((p) => (p.id === event.project.id ? event.project : p))
: [...snapshot.projects, event.project];
return { ...snapshot, projects, snapshotSequence: event.sequence };
}
case "project-removed":
return {
...snapshot,
projects: snapshot.projects.filter((p) => p.id !== event.projectId),
snapshotSequence: event.sequence,
};
case "thread-upserted": {
const threads = snapshot.threads.some((t) => t.id === event.thread.id)
? snapshot.threads.map((t) => (t.id === event.thread.id ? event.thread : t))
: [...snapshot.threads, event.thread];
return { ...snapshot, threads, snapshotSequence: event.sequence };
}
case "thread-removed":
return {
...snapshot,
threads: snapshot.threads.filter((t) => t.id !== event.threadId),
snapshotSequence: event.sequence,
};
default:
return snapshot;
}
}
@@ -0,0 +1,568 @@
import { describe, expect, it } from "vitest";
import {
CheckpointRef,
CommandId,
EventId,
MessageId,
ProjectId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import type { OrchestrationEvent, OrchestrationThread } from "@t3tools/contracts";
import { applyThreadDetailEvent } from "./threadDetailReducer";
const baseEventFields = {
eventId: EventId.make("event-1"),
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
} as const;
const baseThread: OrchestrationThread = {
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Test Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
archivedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
};
describe("applyThreadDetailEvent", () => {
describe("project events", () => {
it("returns unchanged for project.created", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 1,
occurredAt: "2026-04-01T01:00:00.000Z",
aggregateKind: "project",
aggregateId: ProjectId.make("project-1"),
type: "project.created",
payload: {
projectId: ProjectId.make("project-1"),
title: "T3 Code",
workspaceRoot: "/repo",
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-04-01T01:00:00.000Z",
updatedAt: "2026-04-01T01:00:00.000Z",
deletedAt: null,
},
} as any);
expect(result.kind).toBe("unchanged");
});
});
describe("thread.created", () => {
it("creates a fresh thread", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 1,
occurredAt: "2026-04-01T01:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-2"),
type: "thread.created",
payload: {
threadId: ThreadId.make("thread-2"),
projectId: ProjectId.make("project-1"),
title: "New Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
createdAt: "2026-04-01T01:00:00.000Z",
updatedAt: "2026-04-01T01:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.id).toBe("thread-2");
expect(result.thread.title).toBe("New Thread");
expect(result.thread.branch).toBe("main");
expect(result.thread.messages).toEqual([]);
expect(result.thread.session).toBeNull();
}
});
});
describe("thread.deleted", () => {
it("returns deleted signal", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 2,
occurredAt: "2026-04-01T02:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.deleted",
payload: {
threadId: ThreadId.make("thread-1"),
deletedAt: "2026-04-01T02:00:00.000Z",
},
});
expect(result.kind).toBe("deleted");
});
});
describe("thread.archived / thread.unarchived", () => {
it("sets archivedAt", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 3,
occurredAt: "2026-04-01T03:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.archived",
payload: {
threadId: ThreadId.make("thread-1"),
archivedAt: "2026-04-01T03:00:00.000Z",
updatedAt: "2026-04-01T03:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.archivedAt).toBe("2026-04-01T03:00:00.000Z");
}
});
it("clears archivedAt", () => {
const archivedThread = { ...baseThread, archivedAt: "2026-04-01T03:00:00.000Z" };
const result = applyThreadDetailEvent(archivedThread, {
...baseEventFields,
sequence: 4,
occurredAt: "2026-04-01T04:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.unarchived",
payload: {
threadId: ThreadId.make("thread-1"),
updatedAt: "2026-04-01T04:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.archivedAt).toBeNull();
}
});
});
describe("thread.meta-updated", () => {
it("patches title and branch", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 5,
occurredAt: "2026-04-01T05:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.meta-updated",
payload: {
threadId: ThreadId.make("thread-1"),
title: "Updated Title",
branch: "feature/demo",
updatedAt: "2026-04-01T05:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.title).toBe("Updated Title");
expect(result.thread.branch).toBe("feature/demo");
// Model selection should be unchanged since it wasn't in the payload
expect(result.thread.modelSelection).toEqual(baseThread.modelSelection);
}
});
});
describe("thread.message-sent", () => {
it("appends a new message", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 6,
occurredAt: "2026-04-01T06:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.message-sent",
payload: {
threadId: ThreadId.make("thread-1"),
messageId: MessageId.make("msg-1"),
role: "user",
text: "Hello, world!",
turnId: null,
streaming: false,
createdAt: "2026-04-01T06:00:00.000Z",
updatedAt: "2026-04-01T06:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.messages).toHaveLength(1);
expect(result.thread.messages[0]?.text).toBe("Hello, world!");
}
});
it("appends text for streaming messages", () => {
const threadWithMessage: OrchestrationThread = {
...baseThread,
messages: [
{
id: MessageId.make("msg-2"),
role: "assistant",
text: "Hello",
turnId: TurnId.make("turn-1"),
streaming: true,
createdAt: "2026-04-01T06:00:00.000Z",
updatedAt: "2026-04-01T06:00:00.000Z",
},
],
};
const result = applyThreadDetailEvent(threadWithMessage, {
...baseEventFields,
sequence: 7,
occurredAt: "2026-04-01T06:01:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.message-sent",
payload: {
threadId: ThreadId.make("thread-1"),
messageId: MessageId.make("msg-2"),
role: "assistant",
text: ", world!",
turnId: TurnId.make("turn-1"),
streaming: true,
createdAt: "2026-04-01T06:00:00.000Z",
updatedAt: "2026-04-01T06:01:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.messages).toHaveLength(1);
expect(result.thread.messages[0]?.text).toBe("Hello, world!");
}
});
it("updates latestTurn for assistant messages with a turn", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 8,
occurredAt: "2026-04-01T07:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.message-sent",
payload: {
threadId: ThreadId.make("thread-1"),
messageId: MessageId.make("msg-3"),
role: "assistant",
text: "Done.",
turnId: TurnId.make("turn-1"),
streaming: false,
createdAt: "2026-04-01T07:00:00.000Z",
updatedAt: "2026-04-01T07:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.latestTurn?.turnId).toBe("turn-1");
expect(result.thread.latestTurn?.state).toBe("completed");
expect(result.thread.latestTurn?.assistantMessageId).toBe("msg-3");
}
});
});
describe("thread.session-set", () => {
it("updates session and latestTurn for a running session", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 9,
occurredAt: "2026-04-01T08:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.session-set",
payload: {
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.make("turn-1"),
lastError: null,
updatedAt: "2026-04-01T08:00:00.000Z",
},
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.session?.status).toBe("running");
expect(result.thread.latestTurn?.turnId).toBe("turn-1");
expect(result.thread.latestTurn?.state).toBe("running");
}
});
});
describe("thread.session-stop-requested", () => {
it("marks session as stopped", () => {
const threadWithSession: OrchestrationThread = {
...baseThread,
session: {
threadId: ThreadId.make("thread-1"),
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.make("turn-1"),
lastError: null,
updatedAt: "2026-04-01T08:00:00.000Z",
},
};
const result = applyThreadDetailEvent(threadWithSession, {
...baseEventFields,
sequence: 10,
occurredAt: "2026-04-01T09:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.session-stop-requested",
payload: {
threadId: ThreadId.make("thread-1"),
createdAt: "2026-04-01T09:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.session?.status).toBe("stopped");
expect(result.thread.session?.activeTurnId).toBeNull();
}
});
it("returns unchanged when no session exists", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 10,
occurredAt: "2026-04-01T09:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.session-stop-requested",
payload: {
threadId: ThreadId.make("thread-1"),
createdAt: "2026-04-01T09:00:00.000Z",
},
});
expect(result.kind).toBe("unchanged");
});
});
describe("thread.proposed-plan-upserted", () => {
it("adds a proposed plan", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 11,
occurredAt: "2026-04-01T10:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.proposed-plan-upserted",
payload: {
threadId: ThreadId.make("thread-1"),
proposedPlan: {
id: "plan-1",
turnId: TurnId.make("turn-1"),
planMarkdown: "## Plan\n- Do stuff",
implementedAt: null,
implementationThreadId: null,
createdAt: "2026-04-01T10:00:00.000Z",
updatedAt: "2026-04-01T10:00:00.000Z",
},
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.proposedPlans).toHaveLength(1);
expect(result.thread.proposedPlans[0]?.id).toBe("plan-1");
}
});
});
describe("thread.activity-appended", () => {
it("adds an activity", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 12,
occurredAt: "2026-04-01T11:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.activity-appended",
payload: {
threadId: ThreadId.make("thread-1"),
activity: {
id: EventId.make("activity-1"),
tone: "tool",
kind: "file-edit",
summary: "Edited src/index.ts",
payload: {},
turnId: TurnId.make("turn-1"),
createdAt: "2026-04-01T11:00:00.000Z",
},
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.activities).toHaveLength(1);
expect(result.thread.activities[0]?.kind).toBe("file-edit");
}
});
});
describe("thread.turn-diff-completed", () => {
it("adds a checkpoint and updates latestTurn", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 13,
occurredAt: "2026-04-01T12:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.turn-diff-completed",
payload: {
threadId: ThreadId.make("thread-1"),
turnId: TurnId.make("turn-1"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.make("ref-1"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("msg-3"),
completedAt: "2026-04-01T12:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.checkpoints).toHaveLength(1);
expect(result.thread.latestTurn?.turnId).toBe("turn-1");
expect(result.thread.latestTurn?.state).toBe("completed");
}
});
});
describe("thread.reverted", () => {
it("filters entities to retained turns", () => {
const threadWithData: OrchestrationThread = {
...baseThread,
messages: [
{
id: MessageId.make("msg-1"),
role: "user",
text: "First",
turnId: null,
streaming: false,
createdAt: "2026-04-01T01:00:00.000Z",
updatedAt: "2026-04-01T01:00:00.000Z",
},
{
id: MessageId.make("msg-2"),
role: "assistant",
text: "Response 1",
turnId: TurnId.make("turn-1"),
streaming: false,
createdAt: "2026-04-01T02:00:00.000Z",
updatedAt: "2026-04-01T02:00:00.000Z",
},
{
id: MessageId.make("msg-3"),
role: "assistant",
text: "Response 2",
turnId: TurnId.make("turn-2"),
streaming: false,
createdAt: "2026-04-01T03:00:00.000Z",
updatedAt: "2026-04-01T03:00:00.000Z",
},
],
checkpoints: [
{
turnId: TurnId.make("turn-1"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.make("ref-1"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("msg-2"),
completedAt: "2026-04-01T02:00:00.000Z",
},
{
turnId: TurnId.make("turn-2"),
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.make("ref-2"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("msg-3"),
completedAt: "2026-04-01T03:00:00.000Z",
},
],
};
const result = applyThreadDetailEvent(threadWithData, {
...baseEventFields,
sequence: 14,
occurredAt: "2026-04-01T04:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.reverted",
payload: {
threadId: ThreadId.make("thread-1"),
turnCount: 1,
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
// turn-2 checkpoint is filtered out (turnCount 2 > revert target 1)
expect(result.thread.checkpoints).toHaveLength(1);
expect(result.thread.checkpoints[0]?.turnId).toBe("turn-1");
// msg-3 (turn-2) is filtered, msg-1 (no turn) and msg-2 (turn-1) remain
expect(result.thread.messages).toHaveLength(2);
expect(result.thread.latestTurn?.turnId).toBe("turn-1");
}
});
});
describe("no-op events", () => {
it("returns unchanged for approval-response-requested", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 15,
occurredAt: "2026-04-01T13:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.approval-response-requested",
payload: {
threadId: ThreadId.make("thread-1"),
requestId: "req-1",
decision: "approve",
createdAt: "2026-04-01T13:00:00.000Z",
},
} as any);
expect(result.kind).toBe("unchanged");
});
});
});
@@ -0,0 +1,519 @@
import type {
MessageId,
OrchestrationCheckpointSummary,
OrchestrationEvent,
OrchestrationLatestTurn,
OrchestrationMessage,
OrchestrationThread,
OrchestrationThreadActivity,
TurnId,
} from "@t3tools/contracts";
/**
* Retention limits for collections within a thread.
* These prevent unbounded growth of in-memory thread state.
*/
export interface ThreadDetailRetentionLimits {
readonly maxMessages: number;
readonly maxProposedPlans: number;
readonly maxCheckpoints: number;
readonly maxActivities: number;
}
export const DEFAULT_THREAD_DETAIL_LIMITS: ThreadDetailRetentionLimits = {
maxMessages: 512,
maxProposedPlans: 64,
maxCheckpoints: 256,
maxActivities: 128,
};
export type ThreadDetailReducerResult =
| { readonly kind: "updated"; readonly thread: OrchestrationThread }
| { readonly kind: "deleted" }
| { readonly kind: "unchanged" };
/**
* Apply a single orchestration event to an `OrchestrationThread`, returning
* the updated thread, a deletion signal, or an "unchanged" marker when the
* event doesn't affect this thread.
*
* This is a pure reducer operating on contract types. UI-specific mapping
* (e.g. resolving attachment preview URLs, normalising model slugs, adding
* scoped fields like `environmentId`) is the caller's responsibility.
*/
export function applyThreadDetailEvent(
thread: OrchestrationThread,
event: OrchestrationEvent,
limits: ThreadDetailRetentionLimits = DEFAULT_THREAD_DETAIL_LIMITS,
): ThreadDetailReducerResult {
switch (event.type) {
// ── Project events (irrelevant to thread detail) ────────────────
case "project.created":
case "project.meta-updated":
case "project.deleted":
return { kind: "unchanged" };
// ── Thread lifecycle ────────────────────────────────────────────
case "thread.created":
return {
kind: "updated",
thread: {
id: event.payload.threadId,
projectId: event.payload.projectId,
title: event.payload.title,
modelSelection: event.payload.modelSelection,
runtimeMode: event.payload.runtimeMode,
interactionMode: event.payload.interactionMode,
branch: event.payload.branch,
worktreePath: event.payload.worktreePath,
latestTurn: null,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
archivedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
};
case "thread.deleted":
return { kind: "deleted" };
case "thread.archived":
return {
kind: "updated",
thread: {
...thread,
archivedAt: event.payload.archivedAt,
updatedAt: event.payload.updatedAt,
},
};
case "thread.unarchived":
return {
kind: "updated",
thread: { ...thread, archivedAt: null, updatedAt: event.payload.updatedAt },
};
// ── Thread metadata ─────────────────────────────────────────────
case "thread.meta-updated":
return {
kind: "updated",
thread: {
...thread,
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
...(event.payload.modelSelection !== undefined
? { modelSelection: event.payload.modelSelection }
: {}),
...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
...(event.payload.worktreePath !== undefined
? { worktreePath: event.payload.worktreePath }
: {}),
updatedAt: event.payload.updatedAt,
},
};
case "thread.runtime-mode-set":
return {
kind: "updated",
thread: {
...thread,
runtimeMode: event.payload.runtimeMode,
updatedAt: event.payload.updatedAt,
},
};
case "thread.interaction-mode-set":
return {
kind: "updated",
thread: {
...thread,
interactionMode: event.payload.interactionMode,
updatedAt: event.payload.updatedAt,
},
};
// ── Turn lifecycle ──────────────────────────────────────────────
case "thread.turn-start-requested":
return {
kind: "updated",
thread: {
...thread,
...(event.payload.modelSelection !== undefined
? { modelSelection: event.payload.modelSelection }
: {}),
runtimeMode: event.payload.runtimeMode,
interactionMode: event.payload.interactionMode,
updatedAt: event.occurredAt,
},
};
case "thread.turn-interrupt-requested": {
if (event.payload.turnId === undefined) {
return { kind: "unchanged" };
}
const latestTurn = thread.latestTurn;
if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) {
return { kind: "unchanged" };
}
return {
kind: "updated",
thread: {
...thread,
latestTurn: {
...latestTurn,
state: "interrupted",
startedAt: latestTurn.startedAt ?? event.payload.createdAt,
completedAt: latestTurn.completedAt ?? event.payload.createdAt,
},
updatedAt: event.occurredAt,
},
};
}
// ── Messages ────────────────────────────────────────────────────
case "thread.message-sent": {
const message: OrchestrationMessage = {
id: event.payload.messageId,
role: event.payload.role,
text: event.payload.text,
...(event.payload.attachments !== undefined
? { attachments: event.payload.attachments }
: {}),
turnId: event.payload.turnId,
streaming: event.payload.streaming,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
};
const existingMessage = thread.messages.find((entry) => entry.id === message.id);
const messages = existingMessage
? thread.messages.map((entry) =>
entry.id !== message.id
? entry
: {
...entry,
text: message.streaming
? `${entry.text}${message.text}`
: message.text.length > 0
? message.text
: entry.text,
streaming: message.streaming,
...(message.turnId !== undefined ? { turnId: message.turnId } : {}),
...(message.streaming ? {} : { updatedAt: message.updatedAt }),
...(message.attachments !== undefined
? { attachments: message.attachments }
: {}),
},
)
: [...thread.messages, message];
const cappedMessages = messages.slice(-limits.maxMessages);
// Update latestTurn for assistant messages bound to a turn.
const latestTurn: OrchestrationThread["latestTurn"] =
event.payload.role === "assistant" &&
event.payload.turnId !== null &&
(thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
? {
turnId: event.payload.turnId,
state: event.payload.streaming
? "running"
: thread.latestTurn?.state === "interrupted"
? "interrupted"
: thread.latestTurn?.state === "error"
? "error"
: "completed",
requestedAt:
thread.latestTurn?.turnId === event.payload.turnId
? thread.latestTurn.requestedAt
: event.payload.createdAt,
startedAt:
thread.latestTurn?.turnId === event.payload.turnId
? (thread.latestTurn.startedAt ?? event.payload.createdAt)
: event.payload.createdAt,
completedAt: event.payload.streaming
? thread.latestTurn?.turnId === event.payload.turnId
? (thread.latestTurn.completedAt ?? null)
: null
: event.payload.updatedAt,
assistantMessageId: event.payload.messageId,
}
: thread.latestTurn;
// Rebind checkpoint assistant message IDs for assistant messages.
const checkpoints =
event.payload.role === "assistant" && event.payload.turnId !== null
? rebindCheckpointAssistantMessage(
thread.checkpoints,
event.payload.turnId,
event.payload.messageId,
)
: thread.checkpoints;
return {
kind: "updated",
thread: {
...thread,
messages: cappedMessages,
checkpoints,
latestTurn,
updatedAt: event.occurredAt,
},
};
}
// ── Session ─────────────────────────────────────────────────────
case "thread.session-set": {
const latestTurn: OrchestrationLatestTurn | null =
event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
? {
turnId: event.payload.session.activeTurnId,
state: "running",
requestedAt:
thread.latestTurn?.turnId === event.payload.session.activeTurnId
? thread.latestTurn.requestedAt
: event.payload.session.updatedAt,
startedAt:
thread.latestTurn?.turnId === event.payload.session.activeTurnId
? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt)
: event.payload.session.updatedAt,
completedAt: null,
assistantMessageId:
thread.latestTurn?.turnId === event.payload.session.activeTurnId
? thread.latestTurn.assistantMessageId
: null,
}
: thread.latestTurn;
return {
kind: "updated",
thread: {
...thread,
session: event.payload.session,
latestTurn,
updatedAt: event.occurredAt,
},
};
}
case "thread.session-stop-requested":
return thread.session === null
? { kind: "unchanged" }
: {
kind: "updated",
thread: {
...thread,
session: {
...thread.session,
status: "stopped",
activeTurnId: null,
updatedAt: event.payload.createdAt,
},
updatedAt: event.occurredAt,
},
};
// ── Proposed plans ──────────────────────────────────────────────
case "thread.proposed-plan-upserted": {
const proposedPlan = event.payload.proposedPlan;
const proposedPlans = [
...thread.proposedPlans.filter((entry) => entry.id !== proposedPlan.id),
proposedPlan,
]
.toSorted(
(left, right) =>
left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
)
.slice(-limits.maxProposedPlans);
return {
kind: "updated",
thread: { ...thread, proposedPlans, updatedAt: event.occurredAt },
};
}
// ── Checkpoints / turn diffs ────────────────────────────────────
case "thread.turn-diff-completed": {
const checkpoint: OrchestrationCheckpointSummary = {
turnId: event.payload.turnId,
checkpointTurnCount: event.payload.checkpointTurnCount,
checkpointRef: event.payload.checkpointRef,
status: event.payload.status,
files: event.payload.files,
assistantMessageId: event.payload.assistantMessageId,
completedAt: event.payload.completedAt,
};
const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
// Don't overwrite a non-missing checkpoint with a missing one.
if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
return { kind: "unchanged" };
}
const checkpoints = [
...thread.checkpoints.filter((entry) => entry.turnId !== checkpoint.turnId),
checkpoint,
]
.toSorted(
(left, right) =>
(left.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER) -
(right.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER),
)
.slice(-limits.maxCheckpoints);
const latestTurn =
thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId
? {
turnId: event.payload.turnId,
state: checkpointStatusToTurnState(event.payload.status),
requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt,
startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt,
completedAt: event.payload.completedAt,
assistantMessageId: event.payload.assistantMessageId,
}
: thread.latestTurn;
return {
kind: "updated",
thread: { ...thread, checkpoints, latestTurn, updatedAt: event.occurredAt },
};
}
// ── Revert ──────────────────────────────────────────────────────
case "thread.reverted": {
const checkpoints = thread.checkpoints
.filter(
(entry) =>
entry.checkpointTurnCount !== undefined &&
entry.checkpointTurnCount <= event.payload.turnCount,
)
.toSorted(
(left, right) =>
(left.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER) -
(right.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER),
)
.slice(-limits.maxCheckpoints);
const retainedTurnIds = new Set(checkpoints.map((entry) => entry.turnId));
const messages = retainMessagesAfterRevert(
thread.messages,
retainedTurnIds,
event.payload.turnCount,
).slice(-limits.maxMessages);
const proposedPlans = thread.proposedPlans
.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId))
.slice(-limits.maxProposedPlans);
const activities = thread.activities.filter(
(activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId),
);
const latestCheckpoint = checkpoints.at(-1) ?? null;
return {
kind: "updated",
thread: {
...thread,
checkpoints,
messages,
proposedPlans,
activities,
latestTurn:
latestCheckpoint === null
? null
: {
turnId: latestCheckpoint.turnId,
state: checkpointStatusToTurnState(
latestCheckpoint.status as "ready" | "missing" | "error",
),
requestedAt: latestCheckpoint.completedAt,
startedAt: latestCheckpoint.completedAt,
completedAt: latestCheckpoint.completedAt,
assistantMessageId: latestCheckpoint.assistantMessageId ?? null,
},
updatedAt: event.occurredAt,
},
};
}
// ── Activities ──────────────────────────────────────────────────
case "thread.activity-appended": {
const activities = [
...thread.activities.filter((activity) => activity.id !== event.payload.activity.id),
event.payload.activity,
]
.toSorted(compareActivities)
.slice(-limits.maxActivities);
return {
kind: "updated",
thread: { ...thread, activities, updatedAt: event.occurredAt },
};
}
// ── Events that don't mutate thread state directly ──────────────
case "thread.approval-response-requested":
case "thread.user-input-response-requested":
case "thread.checkpoint-revert-requested":
return { kind: "unchanged" };
}
// Forward-compatible: ignore unrecognized event types.
return { kind: "unchanged" };
}
// ── Helpers ──────────────────────────────────────────────────────────
function checkpointStatusToTurnState(
status: "ready" | "missing" | "error",
): OrchestrationLatestTurn["state"] {
switch (status) {
case "ready":
return "completed";
case "error":
return "error";
case "missing":
return "completed";
}
}
function compareActivities(
left: OrchestrationThreadActivity,
right: OrchestrationThreadActivity,
): number {
const sequenceLeft = left.sequence ?? Number.MAX_SAFE_INTEGER;
const sequenceRight = right.sequence ?? Number.MAX_SAFE_INTEGER;
if (sequenceLeft !== sequenceRight) {
return sequenceLeft - sequenceRight;
}
return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
}
function rebindCheckpointAssistantMessage(
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
turnId: TurnId,
messageId: MessageId,
): OrchestrationCheckpointSummary[] {
return checkpoints.map((entry) =>
entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry,
);
}
function retainMessagesAfterRevert(
messages: ReadonlyArray<OrchestrationMessage>,
retainedTurnIds: ReadonlySet<string>,
turnCount: number,
): OrchestrationMessage[] {
// Keep messages that belong to a retained turn, plus system messages and
// messages without a turn binding (pre-turn-0 user messages).
return messages.filter((message) => {
if (message.role === "system") {
return true;
}
if (message.turnId === null) {
return true;
}
return retainedTurnIds.has(message.turnId);
});
}
@@ -0,0 +1,50 @@
import { describe, expect, it } from "vitest";
import { isTransportConnectionErrorMessage, sanitizeThreadErrorMessage } from "./transportError";
describe("isTransportConnectionErrorMessage", () => {
it("returns true for SocketCloseError", () => {
expect(isTransportConnectionErrorMessage("SocketCloseError: connection reset")).toBe(true);
});
it("returns true for SocketOpenError", () => {
expect(isTransportConnectionErrorMessage("SocketOpenError: ECONNREFUSED")).toBe(true);
});
it("returns true for the T3 server WebSocket message", () => {
expect(isTransportConnectionErrorMessage("Unable to connect to the T3 server WebSocket.")).toBe(
true,
);
});
it("returns true for ping timeout", () => {
expect(isTransportConnectionErrorMessage("ping timeout")).toBe(true);
});
it("returns false for business logic errors", () => {
expect(isTransportConnectionErrorMessage("Thread not found")).toBe(false);
expect(isTransportConnectionErrorMessage("Invalid model selection")).toBe(false);
});
it("returns false for null, undefined, and empty strings", () => {
expect(isTransportConnectionErrorMessage(null)).toBe(false);
expect(isTransportConnectionErrorMessage(undefined)).toBe(false);
expect(isTransportConnectionErrorMessage("")).toBe(false);
expect(isTransportConnectionErrorMessage(" ")).toBe(false);
});
});
describe("sanitizeThreadErrorMessage", () => {
it("strips transport errors", () => {
expect(sanitizeThreadErrorMessage("SocketCloseError: oops")).toBeNull();
});
it("preserves non-transport errors", () => {
expect(sanitizeThreadErrorMessage("Thread not found")).toBe("Thread not found");
});
it("returns null for null/undefined", () => {
expect(sanitizeThreadErrorMessage(null)).toBeNull();
expect(sanitizeThreadErrorMessage(undefined)).toBeNull();
});
});
@@ -0,0 +1,33 @@
const TRANSPORT_ERROR_PATTERNS = [
/\bSocketCloseError\b/i,
/\bSocketOpenError\b/i,
/Unable to connect to the T3 server WebSocket\./i,
/\bping timeout\b/i,
] as const;
/**
* Test whether an error message originates from a transport-level connection
* failure (socket close, socket open, ping timeout, etc.) rather than a
* business-logic error.
*/
export function isTransportConnectionErrorMessage(message: string | null | undefined): boolean {
if (typeof message !== "string") {
return false;
}
const normalizedMessage = message.trim();
if (normalizedMessage.length === 0) {
return false;
}
return TRANSPORT_ERROR_PATTERNS.some((pattern) => pattern.test(normalizedMessage));
}
/**
* Strip transport connection errors from user-facing error messages.
* Returns `null` for transport errors so the UI can distinguish between
* real errors and transient connection issues.
*/
export function sanitizeThreadErrorMessage(message: string | null | undefined): string | null {
return isTransportConnectionErrorMessage(message) ? null : (message ?? null);
}
+20 -78
View File
@@ -1,7 +1,5 @@
import {
type GitActionProgressEvent,
type GitStatusLocalResult,
type GitStatusRemoteResult,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type GitStatusResult,
@@ -11,76 +9,12 @@ import {
type ServerSettingsPatch,
WS_METHODS,
} from "@t3tools/contracts";
import { applyGitStatusStreamEvent } from "@t3tools/shared/git";
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];
@@ -104,6 +38,15 @@ type RpcStreamMethod<TTag extends RpcTag> =
? (listener: (event: TEvent) => void, options?: StreamSubscriptionOptions) => () => void
: never;
type RpcInputStreamMethod<TTag extends RpcTag> =
RpcMethod<TTag> extends (input: any, options?: any) => Stream.Stream<infer TEvent, any, any>
? (
input: RpcInput<TTag>,
listener: (event: TEvent) => void,
options?: StreamSubscriptionOptions,
) => () => void
: never;
interface GitRunStackedActionOptions {
readonly onProgress?: (event: GitActionProgressEvent) => void;
}
@@ -166,12 +109,11 @@ export interface WsRpcClient {
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>;
readonly subscribeShell: RpcStreamMethod<typeof ORCHESTRATION_WS_METHODS.subscribeShell>;
readonly subscribeThread: RpcInputStreamMethod<typeof ORCHESTRATION_WS_METHODS.subscribeThread>;
};
}
@@ -281,21 +223,21 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
),
},
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) =>
subscribeShell: (listener, options) =>
transport.subscribe(
(client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}),
(client) => client[ORCHESTRATION_WS_METHODS.subscribeShell]({}),
listener,
options,
),
subscribeThread: (input, listener, options) =>
transport.subscribe(
(client) => client[ORCHESTRATION_WS_METHODS.subscribeThread](input),
listener,
options,
),
+19 -8
View File
@@ -3,6 +3,12 @@ import { Duration, Effect, Layer, Schedule } from "effect";
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
import * as Socket from "effect/unstable/socket/Socket";
import {
DEFAULT_RECONNECT_BACKOFF,
getReconnectDelayMs,
type ReconnectBackoffConfig,
} from "./reconnectBackoff";
export interface WsProtocolLifecycleHandlers {
readonly onAttempt?: (socketUrl: string) => void;
readonly onOpen?: () => void;
@@ -10,14 +16,17 @@ export interface WsProtocolLifecycleHandlers {
readonly onClose?: (details: { readonly code: number; readonly reason: string }) => void;
}
export interface WsRpcProtocolOptions {
/** Backoff configuration for reconnect retries. */
readonly backoff?: ReconnectBackoffConfig;
}
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;
@@ -36,10 +45,6 @@ function resolveWsRpcSocketUrl(rawUrl: string): string {
return resolved.toString();
}
function getWsReconnectDelayMsForRetry(retryCount: number): number | null {
return WS_RECONNECT_DELAYS_MS[retryCount] ?? null;
}
function defaultLifecycleHandlers(): Required<WsProtocolLifecycleHandlers> {
return {
onAttempt: () => undefined,
@@ -52,11 +57,14 @@ function defaultLifecycleHandlers(): Required<WsProtocolLifecycleHandlers> {
export function createWsRpcProtocolLayer(
url: WsRpcProtocolSocketUrlProvider,
handlers?: WsProtocolLifecycleHandlers,
options?: WsRpcProtocolOptions,
) {
const lifecycle = {
...defaultLifecycleHandlers(),
...handlers,
};
const backoff = options?.backoff ?? DEFAULT_RECONNECT_BACKOFF;
const resolvedUrl =
typeof url === "function"
? Effect.promise(() => url()).pipe(
@@ -107,8 +115,11 @@ export function createWsRpcProtocolLayer(
const socketLayer = Socket.layerWebSocket(resolvedUrl).pipe(
Layer.provide(trackingWebSocketConstructorLayer),
);
const retryPolicy = Schedule.addDelay(Schedule.forever, (retryCount) =>
Effect.succeed(Duration.millis(getWsReconnectDelayMsForRetry(retryCount) ?? 0)),
const baseSchedule =
backoff.maxRetries === null ? Schedule.forever : Schedule.recurs(backoff.maxRetries);
const retryPolicy = Schedule.addDelay(baseSchedule, (retryCount) =>
Effect.succeed(Duration.millis(getReconnectDelayMs(retryCount, backoff) ?? 0)),
);
const protocolLayer = Layer.effect(
RpcClient.Protocol,
+18 -15
View File
@@ -1,6 +1,7 @@
import { Cause, Duration, Effect, Exit, ManagedRuntime, Scope, Stream } from "effect";
import { RpcClient } from "effect/unstable/rpc";
import { isTransportConnectionErrorMessage } from "./transportError";
import {
createWsRpcProtocolLayer,
makeWsRpcProtocolClient,
@@ -31,22 +32,11 @@ function formatErrorMessage(error: unknown): string {
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 hasReportedTransportDisconnect = false;
private reconnectChain: Promise<void> = Promise.resolve();
private session: TransportSession;
@@ -116,6 +106,7 @@ export class WsTransport {
return;
}
const session = this.session;
try {
if (hasReceivedValue) {
try {
@@ -125,13 +116,13 @@ export class WsTransport {
}
}
const session = this.session;
const runningStream = this.runStreamOnSession(
session,
connect,
listener,
() => active,
() => {
this.hasReportedTransportDisconnect = false;
hasReceivedValue = true;
},
);
@@ -144,13 +135,25 @@ export class WsTransport {
return;
}
if (!isTransportConnectionError(error)) {
// Skip retry if the session has already been replaced by a reconnect.
if (session !== this.session) {
continue;
}
const formattedError = formatErrorMessage(error);
if (!isTransportConnectionErrorMessage(formattedError)) {
console.warn("WebSocket RPC subscription failed", {
error: formatErrorMessage(error),
error: formattedError,
});
return;
}
if (!this.hasReportedTransportDisconnect) {
console.warn("WebSocket RPC subscription disconnected", {
error: formattedError,
});
}
this.hasReportedTransportDisconnect = true;
await sleep(retryDelayMs);
}
}