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