diff --git a/.oxlintrc.json b/.oxlintrc.json
index 8ea8fbf2b8..e99dbb4c4d 100644
--- a/.oxlintrc.json
+++ b/.oxlintrc.json
@@ -6,7 +6,8 @@
"node_modules",
"bun.lock",
"*.tsbuildinfo",
- "**/routeTree.gen.ts"
+ "**/routeTree.gen.ts",
+ "apps/mobile/uniwind-types.d.ts"
],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"categories": {
@@ -15,6 +16,7 @@
"perf": "warn"
},
"rules": {
+ "unicorn/no-array-sort": "off",
"react-in-jsx-scope": "off",
"eslint/no-shadow": "off",
"eslint/no-await-in-loop": "off"
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index fe3bccdd5e..06f8482f86 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -57,8 +57,7 @@
"react-native-svg": "15.15.3",
"react-native-worklets": "0.7.2",
"tailwind-merge": "^3.5.0",
- "uniwind": "^1.6.2",
- "zustand": "^5.0.12"
+ "uniwind": "^1.6.2"
},
"devDependencies": {
"@types/react": "~19.2.10",
diff --git a/apps/mobile/src/app/+not-found.tsx b/apps/mobile/src/app/+not-found.tsx
index bdaa655684..124077b090 100644
--- a/apps/mobile/src/app/+not-found.tsx
+++ b/apps/mobile/src/app/+not-found.tsx
@@ -1,5 +1,5 @@
import { Link } from "expo-router";
-import { Pressable, ScrollView, StyleSheet, View } from "react-native";
+import { Pressable, ScrollView, StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
import { AppText as Text } from "../components/AppText";
diff --git a/apps/mobile/src/app/_layout.tsx b/apps/mobile/src/app/_layout.tsx
index 121e69299c..15ff31339f 100644
--- a/apps/mobile/src/app/_layout.tsx
+++ b/apps/mobile/src/app/_layout.tsx
@@ -1,5 +1,4 @@
import "../../global.css";
-
import {
DMSans_400Regular,
DMSans_500Medium,
@@ -14,18 +13,19 @@ import { SafeAreaProvider } from "react-native-safe-area-context";
import { useCSSVariable, useResolveClassNames } from "uniwind";
import { LoadingScreen } from "../components/LoadingScreen";
-import { AppAtomRegistryProvider } from "../state/atomRegistry";
+
import {
useRemoteEnvironmentBootstrap,
useRemoteEnvironmentState,
} from "../state/use-remote-environment-registry";
+import { RegistryContext } from "@effect/atom-react";
+import { appAtomRegistry } from "../state/atom-registry";
function AppNavigator() {
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
const colorScheme = useColorScheme();
const statusBarBg = useCSSVariable("--color-status-bar");
const sheetStyle = useResolveClassNames("bg-sheet");
- const screenStyle = useResolveClassNames("bg-screen");
const newTaskScreenOptions = {
contentStyle: sheetStyle,
@@ -91,7 +91,7 @@ export default function RootLayout() {
useRemoteEnvironmentBootstrap();
return (
-
+
@@ -99,6 +99,6 @@ export default function RootLayout() {
-
+
);
}
diff --git a/apps/mobile/src/components/ControlPill.tsx b/apps/mobile/src/components/ControlPill.tsx
index 3ebe9fada5..fbbba2691e 100644
--- a/apps/mobile/src/components/ControlPill.tsx
+++ b/apps/mobile/src/components/ControlPill.tsx
@@ -3,6 +3,7 @@ import { Pressable, View } from "react-native";
import { SymbolView } from "expo-symbols";
import { useThemeColor } from "../lib/useThemeColor";
+import { cn } from "../lib/cn";
import { AppText as Text } from "./AppText";
export function ControlPill(props: {
@@ -15,25 +16,10 @@ export function ControlPill(props: {
}) {
const variant = props.variant ?? "circle";
- const subtleBg = useThemeColor("--color-subtle");
- const subtleBgStrong = useThemeColor("--color-subtle-strong");
- const primaryBg = useThemeColor("--color-primary");
- const dangerBg = useThemeColor("--color-danger");
const iconColor = useThemeColor("--color-icon");
const iconSubtle = useThemeColor("--color-icon-subtle");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerFg = useThemeColor("--color-danger-foreground");
- const textColor = useThemeColor("--color-foreground");
- const textMuted = useThemeColor("--color-foreground-muted");
-
- const backgroundColor =
- variant === "primary"
- ? props.disabled
- ? subtleBgStrong
- : primaryBg
- : variant === "danger"
- ? dangerBg
- : subtleBg;
const iconTintColor =
variant === "primary"
? props.disabled
@@ -42,34 +28,40 @@ export function ControlPill(props: {
: variant === "danger"
? dangerFg
: iconColor;
- const labelColor = variant === "primary" ? (props.disabled ? textMuted : primaryFg) : textColor;
const isCircle =
variant === "circle" || variant === "danger" || (variant === "primary" && !props.label);
+ const containerClassName = cn(
+ isCircle
+ ? "h-11 w-11 items-center justify-center rounded-full"
+ : variant === "primary"
+ ? "h-11 flex-row items-center justify-center gap-2 rounded-full px-5"
+ : "h-11 flex-row items-center justify-center gap-2 rounded-full px-3.5",
+ variant === "primary"
+ ? props.disabled
+ ? "bg-subtle-strong"
+ : "bg-primary"
+ : variant === "danger"
+ ? "bg-danger"
+ : "bg-subtle",
+ );
+ const labelClassName = cn(
+ "text-center text-[12px] font-t3-bold",
+ variant === "primary"
+ ? props.disabled
+ ? "text-foreground-muted"
+ : "text-primary-foreground"
+ : "",
+ );
return (
-
+
{props.iconNode ? (
{props.iconNode}
) : props.icon ? (
) : null}
- {props.label ? (
-
- {props.label}
-
- ) : null}
+ {props.label ? {props.label} : null}
);
}
diff --git a/apps/mobile/src/components/ProviderIcon.tsx b/apps/mobile/src/components/ProviderIcon.tsx
index 0bf3c7f837..d62f8d9a4b 100644
--- a/apps/mobile/src/components/ProviderIcon.tsx
+++ b/apps/mobile/src/components/ProviderIcon.tsx
@@ -1,5 +1,5 @@
import { useColorScheme } from "react-native";
-import Svg, { Path } from "react-native-svg";
+import { Path, Svg } from "react-native-svg";
type ProviderIconProps = {
readonly provider: string | null | undefined;
diff --git a/apps/mobile/src/features/connection/connection-sheet-shared.tsx b/apps/mobile/src/features/connection/ConnectionSheetButton.tsx
similarity index 76%
rename from apps/mobile/src/features/connection/connection-sheet-shared.tsx
rename to apps/mobile/src/features/connection/ConnectionSheetButton.tsx
index f9ec97d663..1a03061e23 100644
--- a/apps/mobile/src/features/connection/connection-sheet-shared.tsx
+++ b/apps/mobile/src/features/connection/ConnectionSheetButton.tsx
@@ -5,41 +5,6 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
-export function parsePairingUrl(url: string): { host: string; code: string } {
- const trimmed = url.trim();
- if (!trimmed) return { host: "", code: "" };
-
- try {
- const parsed = new URL(trimmed);
- const hashParams = new URLSearchParams(parsed.hash.slice(1));
- const hashToken = hashParams.get("token");
- const queryToken = parsed.searchParams.get("token");
- const code = hashToken || queryToken || "";
-
- parsed.hash = "";
- parsed.search = "";
- parsed.pathname = "/";
- return { host: parsed.toString().replace(/\/$/, ""), code };
- } catch {
- return { host: trimmed, code: "" };
- }
-}
-
-export function buildPairingUrl(host: string, code: string): string {
- const h = host.trim();
- const c = code.trim();
- if (!h) return "";
- if (!c) return h;
-
- try {
- const url = new URL(h.includes("://") ? h : `https://${h}`);
- url.hash = new URLSearchParams([["token", c]]).toString();
- return url.toString();
- } catch {
- return `${h}#token=${c}`;
- }
-}
-
const CARD_SHADOW = Platform.select({
ios: {
shadowColor: "rgba(23,23,23,0.08)",
diff --git a/apps/mobile/src/features/connection/ConnectionStatusDot.tsx b/apps/mobile/src/features/connection/ConnectionStatusDot.tsx
index 2f9cbdbf26..60d86e0118 100644
--- a/apps/mobile/src/features/connection/ConnectionStatusDot.tsx
+++ b/apps/mobile/src/features/connection/ConnectionStatusDot.tsx
@@ -9,7 +9,7 @@ import Animated, {
withTiming,
} from "react-native-reanimated";
-import type { RemoteClientConnectionState } from "../../lib/remoteClient";
+import type { RemoteClientConnectionState } from "../../lib/connection";
function statusDotTone(state: RemoteClientConnectionState): {
readonly dotColor: string;
diff --git a/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx
index 47843999f5..bb6f1b3611 100644
--- a/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx
+++ b/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx
@@ -173,7 +173,6 @@ export function ConnectionsRouteScreen() {
const primaryFg = useThemeColor("--color-primary-foreground");
const accentColor = useThemeColor("--color-icon-muted");
- const mutedColor = useThemeColor("--color-icon-subtle");
const handleToggle = useCallback((environmentId: string) => {
setExpandedId((prev) => (prev === environmentId ? null : environmentId));
diff --git a/apps/mobile/src/features/connection/NewConnectionRouteScreen.tsx b/apps/mobile/src/features/connection/NewConnectionRouteScreen.tsx
index a650747443..85a7e587e2 100644
--- a/apps/mobile/src/features/connection/NewConnectionRouteScreen.tsx
+++ b/apps/mobile/src/features/connection/NewConnectionRouteScreen.tsx
@@ -9,13 +9,10 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ErrorBanner } from "../../components/ErrorBanner";
import { dismissRoute } from "../../lib/routes";
-import { extractPairingUrlFromQrPayload } from "./pairingQr";
+import { ConnectionSheetButton } from "./ConnectionSheetButton";
+import { extractPairingUrlFromQrPayload } from "./pairing";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
-import {
- buildPairingUrl,
- ConnectionSheetButton as SheetButton,
- parsePairingUrl,
-} from "./connection-sheet-shared";
+import { buildPairingUrl, parsePairingUrl } from "./pairing";
export function NewConnectionRouteScreen() {
const {
@@ -184,7 +181,7 @@ export function NewConnectionRouteScreen() {
Camera permission is required to scan a QR code.
- : null}
- {
it("trims raw pairing urls from qr payloads", () => {
diff --git a/apps/mobile/src/features/connection/pairing.ts b/apps/mobile/src/features/connection/pairing.ts
new file mode 100644
index 0000000000..2b4fa273d8
--- /dev/null
+++ b/apps/mobile/src/features/connection/pairing.ts
@@ -0,0 +1,57 @@
+const MOBILE_PAIRING_URL_PARAM = "pairingUrl";
+
+export function buildPairingUrl(host: string, code: string): string {
+ const h = host.trim();
+ const c = code.trim();
+ if (!h) return "";
+ if (!c) return h;
+
+ try {
+ const url = new URL(h.includes("://") ? h : `https://${h}`);
+ url.hash = new URLSearchParams([["token", c]]).toString();
+ return url.toString();
+ } catch {
+ return `${h}#token=${c}`;
+ }
+}
+
+export function parsePairingUrl(url: string): { host: string; code: string } {
+ const trimmed = url.trim();
+ if (!trimmed) return { host: "", code: "" };
+
+ try {
+ const parsed = new URL(trimmed);
+ const hashParams = new URLSearchParams(parsed.hash.slice(1));
+ const hashToken = hashParams.get("token");
+ const queryToken = parsed.searchParams.get("token");
+ const code = hashToken || queryToken || "";
+
+ parsed.hash = "";
+ parsed.search = "";
+ parsed.pathname = "/";
+ return { host: parsed.toString().replace(/\/$/, ""), code };
+ } catch {
+ return { host: trimmed, code: "" };
+ }
+}
+
+export function extractPairingUrlFromQrPayload(payload: string): string {
+ const trimmed = payload.trim();
+ if (!trimmed) {
+ throw new Error("Scanned QR code did not contain a pairing URL.");
+ }
+
+ try {
+ const url = new URL(trimmed);
+ if (url.protocol === "t3code:") {
+ const pairingUrl = url.searchParams.get(MOBILE_PAIRING_URL_PARAM)?.trim() ?? "";
+ if (pairingUrl.length > 0) {
+ return pairingUrl;
+ }
+ }
+ } catch {
+ // Treat non-URL payloads as raw pairing-url text so the normal input validation can decide.
+ }
+
+ return trimmed;
+}
diff --git a/apps/mobile/src/features/connection/pairingQr.ts b/apps/mobile/src/features/connection/pairingQr.ts
deleted file mode 100644
index fe5565fdc9..0000000000
--- a/apps/mobile/src/features/connection/pairingQr.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-const MOBILE_PAIRING_URL_PARAM = "pairingUrl";
-
-export function extractPairingUrlFromQrPayload(payload: string): string {
- const trimmed = payload.trim();
- if (!trimmed) {
- throw new Error("Scanned QR code did not contain a pairing URL.");
- }
-
- try {
- const url = new URL(trimmed);
- if (url.protocol === "t3code:") {
- const pairingUrl = url.searchParams.get(MOBILE_PAIRING_URL_PARAM)?.trim() ?? "";
- if (pairingUrl.length > 0) {
- return pairingUrl;
- }
- }
- } catch {
- // Treat non-URL payloads as raw pairing-url text so the normal input validation can decide.
- }
-
- return trimmed;
-}
diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx
index 2bb634481f..480c9587ac 100644
--- a/apps/mobile/src/features/home/HomeRouteScreen.tsx
+++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx
@@ -1,5 +1,5 @@
-import { Stack, useFocusEffect, useRouter } from "expo-router";
-import { useCallback, useState } from "react";
+import { Stack, useRouter } from "expo-router";
+import { useState } from "react";
import { Pressable, Text as RNText, View, useColorScheme } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -7,7 +7,6 @@ import { buildThreadRoutePath } from "../../lib/routes";
import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
-import { useThreadSelection } from "../../state/use-thread-selection";
import { HomeScreen } from "./HomeScreen";
/* ─── Connection pill label ──────────────────────────────────────────── */
@@ -25,7 +24,6 @@ const CONNECTION_LABEL: Record = {
export function HomeRouteScreen() {
const { connectionState, hasRemoteActivity, projects, threads } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
- const { onBackFromThread, onSelectThread } = useThreadSelection();
const router = useRouter();
const [searchQuery, setSearchQuery] = useState("");
@@ -33,12 +31,6 @@ export function HomeRouteScreen() {
const iconColor = String(useThemeColor("--color-icon"));
const secondaryFg = isDark ? "#a3a3a3" : "#525252";
- useFocusEffect(
- useCallback(() => {
- onBackFromThread();
- }, [onBackFromThread]),
- );
-
return (
<>
{
- onSelectThread(thread);
router.push(buildThreadRoutePath(thread));
}}
/>
diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx
index 2142b9806a..5388cd7788 100644
--- a/apps/mobile/src/features/home/HomeScreen.tsx
+++ b/apps/mobile/src/features/home/HomeScreen.tsx
@@ -1,4 +1,8 @@
-import type { GitStatusState } from "@t3tools/client-runtime";
+import type {
+ EnvironmentScopedProjectShell,
+ EnvironmentScopedThreadShell,
+ GitStatusState,
+} from "@t3tools/client-runtime";
import { SymbolView } from "expo-symbols";
import { useCallback, useMemo, useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
@@ -8,7 +12,6 @@ import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import type { SavedRemoteConnection } from "../../lib/connection";
-import type { ScopedMobileProject, ScopedMobileThread } from "../../lib/scopedEntities";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import { useGitStatus } from "../../state/use-git-status";
@@ -17,22 +20,22 @@ import { lastConversationLine, threadStatusTone } from "../threads/threadPresent
/* ─── Types ──────────────────────────────────────────────────────────── */
interface HomeScreenProps {
- readonly projects: ReadonlyArray;
- readonly threads: ReadonlyArray;
+ readonly projects: ReadonlyArray;
+ readonly threads: ReadonlyArray;
readonly savedConnectionsById: Readonly>;
readonly searchQuery: string;
- readonly onSelectThread: (thread: ScopedMobileThread) => void;
+ readonly onSelectThread: (thread: EnvironmentScopedThreadShell) => void;
}
interface ProjectGroup {
readonly key: string;
- readonly project: ScopedMobileProject;
- readonly threads: ReadonlyArray;
+ readonly project: EnvironmentScopedProjectShell;
+ readonly threads: ReadonlyArray;
}
/* ─── Status indicator colors ────────────────────────────────────────── */
-function statusColors(thread: ScopedMobileThread): { bg: string; fg: string } {
+function statusColors(thread: EnvironmentScopedThreadShell): { bg: string; fg: string } {
switch (thread.session?.status) {
case "running":
return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" };
@@ -52,7 +55,7 @@ const COLLAPSED_THREAD_LIMIT = 6;
/* ─── Project group header ───────────────────────────────────────────── */
function ProjectGroupLabel(props: {
- readonly project: ScopedMobileProject;
+ readonly project: EnvironmentScopedProjectShell;
readonly totalThreadCount: number;
readonly httpBaseUrl: string | null;
readonly bearerToken: string | null;
@@ -110,7 +113,7 @@ function gitSummaryParts(gitStatus: GitStatusState): ReadonlyArray {
/* ─── Thread row ─────────────────────────────────────────────────────── */
function ThreadRow(props: {
- readonly thread: ScopedMobileThread;
+ readonly thread: EnvironmentScopedThreadShell;
readonly projectCwd: string | null;
readonly onPress: () => void;
readonly isLast: boolean;
@@ -257,7 +260,7 @@ export function HomeScreen(props: HomeScreenProps) {
/* Group filtered threads by project */
const projectGroups = useMemo>(() => {
- const byProject = new Map();
+ const byProject = new Map();
for (const thread of filteredThreads) {
const key = scopedProjectKey(thread.environmentId, thread.projectId);
const existing = byProject.get(key);
diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
index 015649a8a1..21f9daa4d1 100644
--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
@@ -8,7 +8,7 @@ import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-re
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
-import type { ModelSelection } from "@t3tools/contracts";
+import { EnvironmentId, type ModelSelection } from "@t3tools/contracts";
import { CLAUDE_CODE_EFFORT_OPTIONS } from "@t3tools/contracts";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
@@ -18,10 +18,10 @@ import { ProviderIcon } from "../../components/ProviderIcon";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
import { buildThreadRoutePath } from "../../lib/routes";
-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";
+import { useProjectActions } from "./use-project-actions";
export function NewTaskDraftScreen(props: {
readonly initialProjectRef?: {
@@ -264,7 +264,7 @@ export function NewTaskDraftScreen(props: {
if (!event.startsWith("environment:")) {
return;
}
- flow.selectEnvironment(event.slice("environment:".length));
+ flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
}
function handleOptionsMenuAction(event: string) {
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
index 302cce9012..ae7535457b 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -27,9 +27,8 @@ import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStri
import { ControlPill } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
-import type { MobileLayoutVariant } from "../../lib/mobileLayout";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
-import type { RemoteClientConnectionState } from "../../lib/remoteClient";
+import type { RemoteClientConnectionState } from "../../lib/connection";
import { useNativePaste } from "../../hooks/useNativePaste";
/**
@@ -54,7 +53,6 @@ export interface ThreadComposerProps {
readonly serverConfig: T3ServerConfig | null;
readonly queueCount: number;
readonly activeThreadBusy: boolean;
- readonly layoutVariant?: MobileLayoutVariant;
readonly onChangeDraftMessage: (value: string) => void;
readonly onPickDraftImages: () => Promise;
readonly onNativePasteImages: (uris: ReadonlyArray) => Promise;
@@ -143,7 +141,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
props.selectedThread.session?.status === "running" ||
props.selectedThread.session?.status === "starting" ||
props.queueCount > 0;
- const isSplitLayout = props.layoutVariant === "split";
+
const sendLabel = props.activeThreadBusy || props.queueCount > 0 ? "Queue" : "Send";
const modelProvider = props.selectedThread.modelSelection?.provider ?? null;
const currentModelSelection = props.selectedThread.modelSelection;
@@ -345,13 +343,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 4 : 10),
}}
>
-
+
{/* Input surface — the pill/card IS the glass element */}
;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
readonly assistant: Record;
}
diff --git a/apps/mobile/src/features/threads/ThreadListScreen.tsx b/apps/mobile/src/features/threads/ThreadListScreen.tsx
deleted file mode 100644
index 1e3e80dcfc..0000000000
--- a/apps/mobile/src/features/threads/ThreadListScreen.tsx
+++ /dev/null
@@ -1,511 +0,0 @@
-import { SymbolView } from "expo-symbols";
-import { useCallback, useMemo, useRef, useState } from "react";
-import {
- Modal,
- Pressable,
- RefreshControl,
- ScrollView,
- View,
- useColorScheme,
- type View as RNView,
-} from "react-native";
-import Animated, { FadeInDown, LinearTransition } from "react-native-reanimated";
-import { useThemeColor } from "../../lib/useThemeColor";
-
-import { BrandMark } from "../../components/BrandMark";
-import { AppText as Text } from "../../components/AppText";
-import { EmptyState } from "../../components/EmptyState";
-import { GlassSafeAreaView } from "../../components/GlassSafeAreaView";
-import { StatusPill } from "../../components/StatusPill";
-import { cn } from "../../lib/cn";
-import type { MobileLayout } from "../../lib/mobileLayout";
-import {
- scopedThreadKey,
- type ScopedMobileProject,
- type ScopedMobileThread,
-} from "../../lib/scopedEntities";
-import type { RemoteClientConnectionState } from "../../lib/remoteClient";
-import { relativeTime } from "../../lib/time";
-import { groupProjectsByRepository, type MobileRepositoryGroup } from "../../lib/repositoryGroups";
-import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
-import { lastConversationLine, threadStatusTone } from "./threadPresentation";
-
-export interface ThreadListScreenProps {
- readonly heroTitle: string;
- readonly showBrandWordmark: boolean;
- readonly screenTone: {
- readonly label: string;
- readonly pillClassName: string;
- readonly textClassName: string;
- };
- readonly connectionState: RemoteClientConnectionState;
- readonly connectionPulse: boolean;
- readonly projects: ReadonlyArray;
- readonly threads: ReadonlyArray;
- readonly connectedEnvironmentCount: number;
- readonly hasClient: boolean;
- readonly hasServerConfig: boolean;
- readonly layout: MobileLayout;
- readonly hiddenThreadKey?: string | null;
- readonly selectedThreadKey?: string | null;
- readonly connectionError: string | null;
- readonly onOpenConnectionEditor: () => void;
- readonly onRefresh: () => Promise;
- readonly onCreateThread: (project: ScopedMobileProject) => Promise;
- readonly onSelectThread: (
- thread: ScopedMobileThread,
- sourceFrame: TransitionSourceFrame | null,
- ) => void;
-}
-
-export interface TransitionSourceFrame {
- readonly x: number;
- readonly y: number;
- readonly width: number;
- readonly height: number;
-}
-
-function ActionButton(props: {
- readonly icon: React.ComponentProps["name"];
- readonly label: string;
- readonly primary?: boolean;
- readonly onPress: () => void;
-}) {
- const primaryForeground = useThemeColor("--color-primary-foreground");
- const secondaryForeground = useThemeColor("--color-secondary-foreground");
- const tintColor = props.primary ? primaryForeground : secondaryForeground;
-
- return (
-
-
-
- {props.label}
-
-
- );
-}
-
-function StatCard(props: {
- readonly label: string;
- readonly value: string;
- readonly icon: React.ComponentProps["name"];
-}) {
- const foregroundSecondary = useThemeColor("--color-foreground-secondary");
-
- return (
-
-
-
-
- {props.label}
-
-
- {props.value}
-
- );
-}
-
-function ThreadRow(props: {
- readonly thread: ScopedMobileThread;
- readonly hidden?: boolean;
- readonly selected?: boolean;
- readonly onPress: (sourceFrame: TransitionSourceFrame | null) => void;
-}) {
- const isDarkMode = useColorScheme() === "dark";
- const cardColor = useThemeColor("--color-card");
- const borderColor = useThemeColor("--color-border");
- const containerRef = useRef(null);
- const tone = threadStatusTone(props.thread);
- const backgroundColor = props.selected
- ? isDarkMode
- ? "rgba(249,115,22,0.12)"
- : "rgba(249,115,22,0.09)"
- : cardColor;
- const resolvedBorderColor = props.selected
- ? isDarkMode
- ? "rgba(249,115,22,0.32)"
- : "rgba(249,115,22,0.28)"
- : borderColor;
-
- return (
- {
- containerRef.current?.measureInWindow((x, y, width, height) => {
- if (width > 0 && height > 0) {
- props.onPress({ x, y, width, height });
- return;
- }
- props.onPress(null);
- });
- }}
- >
-
-
- {props.thread.title}
-
- {lastConversationLine(props.thread)}
-
-
-
-
-
-
- {props.thread.environmentLabel} · {props.thread.modelSelection.provider} ·{" "}
- {relativeTime(props.thread.updatedAt ?? props.thread.createdAt)}
-
-
- );
-}
-
-function ProjectSection(props: {
- readonly project: ScopedMobileProject;
- readonly threads: ReadonlyArray;
- readonly hiddenThreadKey?: string | null;
- readonly selectedThreadKey?: string | null;
- readonly onCreateThread: (project: ScopedMobileProject) => Promise;
- readonly onSelectThread: (
- thread: ScopedMobileThread,
- sourceFrame: TransitionSourceFrame | null,
- ) => void;
-}) {
- const [expanded, setExpanded] = useState(false);
- const visibleThreads = expanded ? props.threads : props.threads.slice(0, 2);
- const hiddenCount = Math.max(props.threads.length - visibleThreads.length, 0);
-
- return (
-
-
-
-
- {props.project.environmentLabel}
-
-
- {props.project.workspaceRoot}
-
-
- void props.onCreateThread(props.project)}
- >
-
- New thread
-
-
-
-
- {props.threads.length === 0 ? (
-
- ) : (
-
- {visibleThreads.map((thread) => (
- props.onSelectThread(thread, sourceFrame)}
- />
- ))}
-
- {hiddenCount > 0 ? (
- setExpanded((current) => !current)}
- >
-
- {expanded ? "Show less" : `Show ${hiddenCount} more`}
-
-
- ) : null}
-
- )}
-
- );
-}
-
-function CreateThreadModal(props: {
- readonly group: MobileRepositoryGroup | null;
- readonly visible: boolean;
- readonly onClose: () => void;
- readonly onSelectProject: (project: ScopedMobileProject) => Promise;
-}) {
- if (!props.group) {
- return null;
- }
-
- return (
-
-
-
-
-
- New thread in {props.group.title}
-
-
- Choose which environment should own the new thread.
-
-
-
-
- {props.group.projects.map(({ project, threads }) => (
- {
- void props.onSelectProject(project).then(props.onClose);
- }}
- >
-
-
-
- {project.environmentLabel}
-
-
- {project.workspaceRoot}
-
-
-
-
- {threads.length} thread{threads.length === 1 ? "" : "s"}
-
-
-
-
- ))}
-
-
-
-
-
-
- );
-}
-
-export function ThreadListScreen(props: ThreadListScreenProps) {
- const borderColorValue = useThemeColor("--color-border");
- const repositoryGroups = useMemo(
- () => groupProjectsByRepository({ projects: props.projects, threads: props.threads }),
- [props.projects, props.threads],
- );
- const [createTarget, setCreateTarget] = useState(null);
- const [refreshing, setRefreshing] = useState(false);
- const isSplitLayout = props.layout.usesSplitView;
- const contentHorizontalPadding = isSplitLayout ? 18 : 20;
- const panelBorderColor = isSplitLayout ? borderColorValue : "transparent";
- const refreshThreads = props.onRefresh;
-
- const handleRefresh = useCallback(async (): Promise => {
- if (refreshing) {
- return;
- }
-
- setRefreshing(true);
- try {
- await refreshThreads();
- } finally {
- setRefreshing(false);
- }
- }, [refreshThreads, refreshing]);
-
- return (
-
-
- : null} />
-
-
- void handleRefresh()} />
- }
- contentContainerStyle={{
- gap: 16,
- paddingHorizontal: contentHorizontalPadding,
- paddingBottom: isSplitLayout ? 32 : 48,
- paddingTop: isSplitLayout ? 112 : 124,
- }}
- >
-
-
-
-
- {props.heroTitle}
-
-
- {isSplitLayout ? "Native workspace" : "Repo board"}
-
-
- {isSplitLayout
- ? "Keep your repositories visible while you move between active threads."
- : "Your connected repositories, grouped by identity across environments."}
-
-
-
-
-
-
-
-
-
-
-
-
-
- void handleRefresh()}
- />
-
-
-
- {repositoryGroups.length === 0 ? (
-
- ) : null}
-
- {repositoryGroups.map((group, index) => (
-
-
-
- {group.title}
- {group.subtitle ? (
-
- {group.subtitle}
-
- ) : null}
-
- {group.projectCount} environment{group.projectCount === 1 ? "" : "s"} ·{" "}
- {group.threadCount} active thread{group.threadCount === 1 ? "" : "s"}
-
-
-
- {
- if (group.projects.length === 1) {
- void props.onCreateThread(group.projects[0]!.project);
- return;
- }
- setCreateTarget(group);
- }}
- >
-
- New thread
-
-
-
-
-
- {group.projects.map(({ project, threads }) => (
-
- ))}
-
-
- ))}
-
-
- setCreateTarget(null)}
- onSelectProject={props.onCreateThread}
- />
-
- );
-}
diff --git a/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx b/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx
index 8fe5a6adcb..c6dbcb47a7 100644
--- a/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx
+++ b/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx
@@ -14,12 +14,18 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { StatusPill } from "../../components/StatusPill";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
-import type { ScopedMobileProject, ScopedMobileThread } from "../../lib/scopedEntities";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import { threadStatusTone } from "./threadPresentation";
+import {
+ EnvironmentScopedProjectShell,
+ EnvironmentScopedThreadShell,
+} from "@t3tools/client-runtime";
-function compareThreadActivity(left: ScopedMobileThread, right: ScopedMobileThread): number {
+function compareThreadActivity(
+ left: EnvironmentScopedThreadShell,
+ right: EnvironmentScopedThreadShell,
+): number {
return (
new Date(right.updatedAt ?? right.createdAt).getTime() -
new Date(left.updatedAt ?? left.createdAt).getTime() || left.title.localeCompare(right.title)
@@ -28,11 +34,11 @@ function compareThreadActivity(left: ScopedMobileThread, right: ScopedMobileThre
export function ThreadNavigationDrawer(props: {
readonly visible: boolean;
- readonly projects: ReadonlyArray;
- readonly threads: ReadonlyArray;
+ readonly projects: ReadonlyArray;
+ readonly threads: ReadonlyArray;
readonly selectedThreadKey: string | null;
readonly onClose: () => void;
- readonly onSelectThread: (thread: ScopedMobileThread) => void;
+ readonly onSelectThread: (thread: EnvironmentScopedThreadShell) => void;
readonly onStartNewTask: () => void;
}) {
const insets = useSafeAreaInsets();
@@ -59,7 +65,7 @@ export function ThreadNavigationDrawer(props: {
title: group.projects[0]?.project.title ?? group.title,
threads: group.projects
.flatMap((projectGroup) => projectGroup.threads)
- .sort(compareThreadActivity), // oxlint-disable-line eslint-plugin-unicorn/no-array-sort
+ .sort(compareThreadActivity),
})),
[repositoryGroups],
);
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index 97504ecc7b..c66ee0419f 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -1,5 +1,8 @@
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useState } from "react";
+import * as Arr from "effect/Array";
+import * as Option from "effect/Option";
+import { pipe } from "effect/Function";
import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
import { useGitStatus, gitStatusManager } from "../../state/use-git-status";
@@ -9,22 +12,22 @@ import { LoadingScreen } from "../../components/LoadingScreen";
import { buildThreadRoutePath } from "../../lib/routes";
import { scopedThreadKey } from "../../lib/scopedEntities";
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 { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
-import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
-import { useSelectedThreadCommands } from "../../state/use-selected-thread-commands";
-import { useThreadComposerState } from "../../state/use-thread-composer-state";
-import { useThreadDetailSubscription } from "../../state/use-thread-detail-subscription";
+import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { useThreadSelection } from "../../state/use-thread-selection";
import { ThreadDetailScreen } from "./ThreadDetailScreen";
import { ThreadGitControls } from "./ThreadGitControls";
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
import { screenTitle } from "./threadPresentation";
+import { useSelectedThreadCommands } from "./use-selected-thread-commands";
+import { useSelectedThreadGitActions } from "./use-selected-thread-git-actions";
+import { useSelectedThreadGitState } from "./use-selected-thread-git-state";
+import { useThreadComposerState } from "./use-thread-composer-state";
function firstRouteParam(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) {
@@ -35,16 +38,14 @@ function firstRouteParam(value: string | string[] | undefined): string | null {
}
export function ThreadRouteScreen() {
- const { isLoadingSavedConnection, environmentStateById } = useRemoteEnvironmentState();
- const { connectionState, connectionError } = useRemoteConnectionStatus();
+ const { isLoadingSavedConnection, environmentStateById, pendingConnectionError } =
+ useRemoteEnvironmentState();
+ const { connectionState, connectionError: aggregateConnectionError } =
+ useRemoteConnectionStatus();
const { projects, threads } = useRemoteCatalog();
- const {
- onSelectThread,
- selectedThread,
- selectedThreadProject,
- selectedEnvironmentConnection,
- selectedEnvironmentRuntime,
- } = useThreadSelection();
+ const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
+ useThreadSelection();
+ const selectedThreadDetail = useSelectedThreadDetail();
const composer = useThreadComposerState();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
@@ -61,8 +62,12 @@ export function ThreadRouteScreen() {
const [drawerVisible, setDrawerVisible] = useState(false);
const environmentId = firstRouteParam(params.environmentId);
const threadId = firstRouteParam(params.threadId);
-
- useThreadDetailSubscription(environmentId, threadId);
+ const routeEnvironmentRuntime = environmentId
+ ? (environmentStateById[environmentId] ?? null)
+ : null;
+ const routeConnectionState = routeEnvironmentRuntime?.connectionState ?? connectionState;
+ const routeConnectionError =
+ pendingConnectionError ?? routeEnvironmentRuntime?.connectionError ?? aggregateConnectionError;
/* ─── Native header theming ──────────────────────────────────────── */
const isDark = useColorScheme() === "dark";
@@ -90,41 +95,15 @@ export function ThreadRouteScreen() {
await handleRefreshGitStatus();
}, [commands, handleRefreshGitStatus]);
- const routeThread = useMemo(() => {
- if (!environmentId || !threadId) {
- return null;
- }
-
- return (
- threads.find((thread) => thread.environmentId === environmentId && thread.id === threadId) ??
- null
- );
- }, [environmentId, threadId, threads]);
-
- const selectedMatchesRoute =
- selectedThread?.environmentId === environmentId && selectedThread?.id === threadId;
-
- useEffect(() => {
- if (!routeThread) {
- return;
- }
-
- if (selectedMatchesRoute) {
- return;
- }
-
- onSelectThread(routeThread);
- }, [onSelectThread, routeThread, selectedMatchesRoute]);
-
if (!environmentId || !threadId) {
return ;
}
- if (!routeThread) {
+ if (!selectedThread) {
const stillHydrating =
isLoadingSavedConnection ||
- connectionState === "connecting" ||
- connectionState === "reconnecting";
+ routeConnectionState === "connecting" ||
+ routeConnectionState === "reconnecting";
if (stillHydrating) {
return ;
@@ -149,16 +128,24 @@ export function ThreadRouteScreen() {
);
}
- if (!selectedMatchesRoute || !selectedThread) {
+ if (!selectedThreadDetail) {
return ;
}
const selectedThreadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
const serverConfig =
- selectedEnvironmentRuntime?.serverConfig ??
- firstNonNull(Object.values(environmentStateById).map((runtime) => runtime.serverConfig));
+ routeEnvironmentRuntime?.serverConfig ??
+ pipe(
+ Object.values(environmentStateById),
+ Arr.map((runtime) => runtime.serverConfig),
+ Arr.findFirst((value) => value !== null),
+ Option.getOrNull,
+ );
- const headerSubtitle = [screenTitle(serverConfig, null), selectedThread.environmentLabel]
+ const headerSubtitle = [
+ screenTitle(serverConfig, null),
+ selectedEnvironmentConnection?.environmentLabel ?? null,
+ ]
.filter(Boolean)
.join(" · ");
@@ -189,7 +176,7 @@ export function ThreadRouteScreen() {
letterSpacing: -0.4,
}}
>
- {selectedThread.title}
+ {selectedThreadDetail.title}
setDrawerVisible(false)}
onSelectThread={(thread) => {
- onSelectThread(thread);
router.replace(buildThreadRoutePath(thread));
}}
onStartNewTask={() => router.push("/new")}
diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx
index ad1957bfb6..020e34c36c 100644
--- a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx
+++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx
@@ -7,9 +7,9 @@ import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
import { useGitStatus } from "../../../state/use-git-status";
-import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
-import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
import { useThreadSelection } from "../../../state/use-thread-selection";
+import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions";
+import { useSelectedThreadGitState } from "../use-selected-thread-git-state";
import { SheetActionButton } from "./gitSheetComponents";
export function GitBranchesSheet() {
diff --git a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx
index 7f2d3584a4..fc9195b5af 100644
--- a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx
+++ b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx
@@ -6,9 +6,9 @@ import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
import { useGitStatus } from "../../../state/use-git-status";
-import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
-import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
import { useThreadSelection } from "../../../state/use-thread-selection";
+import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions";
+import { useSelectedThreadGitState } from "../use-selected-thread-git-state";
import { SheetActionButton } from "./gitSheetComponents";
export function GitCommitSheet() {
diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx
index 6e792f6091..f73dc11d66 100644
--- a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx
+++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx
@@ -6,8 +6,8 @@ import { View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../../components/AppText";
-import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
-import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
+import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions";
+import { useSelectedThreadGitState } from "../use-selected-thread-git-state";
import { SheetActionButton } from "./gitSheetComponents";
export function GitConfirmSheet() {
diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx
index 9077a3eae3..dee4fe5e44 100644
--- a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx
+++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx
@@ -1,4 +1,3 @@
-import type { GitRunStackedActionResult } from "@t3tools/contracts";
import {
type GitActionRequestInput,
buildMenuItems,
@@ -15,9 +14,9 @@ import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text } from "../../../components/AppText";
import { StatusPill } from "../../../components/StatusPill";
import { useGitStatus } from "../../../state/use-git-status";
-import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
-import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
import { useThreadSelection } from "../../../state/use-thread-selection";
+import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions";
+import { useSelectedThreadGitState } from "../use-selected-thread-git-state";
import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents";
export function GitOverviewSheet() {
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 c44108ef34..0ddc8a6ef3 100644
--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx
+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
@@ -2,28 +2,33 @@ import React, { useCallback, useEffect, useMemo, useState } from "react";
import type {
ClaudeCodeEffort,
+ EnvironmentId,
GitBranch,
ModelSelection,
ProviderInteractionMode,
RuntimeMode,
} from "@t3tools/contracts";
import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE } from "@t3tools/contracts";
+import * as Arr from "effect/Array";
+import { pipe } from "effect/Function";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
-import type { ScopedMobileProject } from "../../lib/scopedEntities";
import { scopedProjectKey } from "../../lib/scopedEntities";
-import { useRemoteEnvironmentStore } from "../../state/remote-environment-store";
import { gitBranchManager, useGitBranches } from "../../state/use-git-branches";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
+import {
+ setPendingConnectionError,
+ useRemoteEnvironmentState,
+} from "../../state/use-remote-environment-registry";
+import { EnvironmentScopedProjectShell } from "@t3tools/client-runtime";
-export type { ModelOption, ProviderGroup };
-export type WorkspaceMode = "local" | "worktree";
+type WorkspaceMode = "local" | "worktree";
-export function normalizeSelectedWorktreePath(
- project: ScopedMobileProject,
+function normalizeSelectedWorktreePath(
+ project: EnvironmentScopedProjectShell,
branch: GitBranch,
): string | null {
if (!branch.worktreePath) {
@@ -35,7 +40,7 @@ export function normalizeSelectedWorktreePath(
export function branchBadgeLabel(input: {
readonly branch: GitBranch;
- readonly project: ScopedMobileProject | null;
+ readonly project: EnvironmentScopedProjectShell | null;
}): string | null {
if (input.branch.current) {
return "current";
@@ -55,9 +60,9 @@ export function branchBadgeLabel(input: {
type NewTaskFlowContextValue = {
readonly logicalProjects: ReadonlyArray<{
readonly key: string;
- readonly project: ScopedMobileProject;
+ readonly project: EnvironmentScopedProjectShell;
}>;
- readonly selectedEnvironmentId: string;
+ readonly selectedEnvironmentId: EnvironmentId;
readonly selectedProjectKey: string | null;
readonly selectedModelKey: string | null;
readonly workspaceMode: WorkspaceMode;
@@ -76,18 +81,18 @@ type NewTaskFlowContextValue = {
readonly contextWindow: string;
readonly expandedProvider: string | null;
readonly environments: ReadonlyArray<{
- readonly environmentId: string;
+ readonly environmentId: EnvironmentId;
readonly environmentLabel: string;
}>;
- readonly selectedProject: ScopedMobileProject | null;
+ readonly selectedProject: EnvironmentScopedProjectShell | null;
readonly modelOptions: ReadonlyArray;
readonly selectedModel: ModelSelection | null;
readonly selectedModelOption: ModelOption | null;
readonly providerGroups: ReadonlyArray;
readonly filteredBranches: ReadonlyArray;
readonly reset: () => void;
- readonly setProject: (project: ScopedMobileProject) => void;
- readonly selectEnvironment: (environmentId: string) => void;
+ readonly setProject: (project: EnvironmentScopedProjectShell) => void;
+ readonly selectEnvironment: (environmentId: EnvironmentId) => void;
readonly setSelectedModelKey: (key: string | null) => void;
readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
readonly selectBranch: (branch: GitBranch) => void;
@@ -111,9 +116,7 @@ const NewTaskFlowContext = React.createContext(n
export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const { projects, serverConfigByEnvironmentId, threads } = useRemoteCatalog();
- const setPendingConnectionError = useRemoteEnvironmentStore(
- (state) => state.setPendingConnectionError,
- );
+ const { savedConnectionsById } = useRemoteEnvironmentState();
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
@@ -121,15 +124,24 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
);
const logicalProjects = useMemo(
() =>
- repositoryGroups
- .map((group) => {
+ pipe(
+ repositoryGroups,
+ Arr.map((group) => {
const primaryProject = group.projects[0]?.project;
if (!primaryProject) {
return null;
}
return { key: group.key, project: primaryProject };
- })
- .filter((entry) => entry !== null),
+ }),
+ Arr.filter(
+ (
+ entry,
+ ): entry is {
+ readonly key: string;
+ readonly project: EnvironmentScopedProjectShell;
+ } => entry !== null,
+ ),
+ ),
[repositoryGroups],
);
@@ -212,19 +224,44 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const environments = useMemo(
() =>
- [
- ...new Map(
- projects.map((project) => [project.environmentId, project.environmentLabel]),
- ).entries(),
- ].map(([environmentId, environmentLabel]) => ({
- environmentId,
- environmentLabel,
- })),
- [projects],
+ pipe(
+ [
+ ...new Set(
+ pipe(
+ projects,
+ Arr.map((project) => project.environmentId),
+ ),
+ ),
+ ],
+ Arr.map((environmentId) => {
+ const environment = savedConnectionsById[environmentId];
+ if (!environment) {
+ return null;
+ }
+
+ return {
+ environmentId,
+ environmentLabel: environment.environmentLabel,
+ };
+ }),
+ Arr.filter(
+ (
+ entry,
+ ): entry is {
+ readonly environmentId: EnvironmentId;
+ readonly environmentLabel: string;
+ } => entry !== null,
+ ),
+ ),
+ [projects, savedConnectionsById],
);
const projectsForEnvironment = useMemo(
- () => projects.filter((project) => project.environmentId === selectedEnvironmentId),
+ () =>
+ pipe(
+ projects,
+ Arr.filter((project) => project.environmentId === selectedEnvironmentId),
+ ),
[projects, selectedEnvironmentId],
);
@@ -272,7 +309,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const branchState = useGitBranches(branchTarget);
const branchesLoading = branchState.isPending;
const availableBranches = useMemo(
- () => (branchState.data?.branches ?? []).filter((branch) => !branch.isRemote),
+ () =>
+ pipe(
+ branchState.data?.branches ?? [],
+ Arr.filter((branch) => !branch.isRemote),
+ ),
[branchState.data?.branches],
);
@@ -282,15 +323,18 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
return availableBranches;
}
- return availableBranches.filter((branch) => branch.name.toLowerCase().includes(query));
+ return pipe(
+ availableBranches,
+ Arr.filter((branch) => branch.name.toLowerCase().includes(query)),
+ );
}, [availableBranches, branchQuery]);
- const setProject = useCallback((project: ScopedMobileProject) => {
+ const setProject = useCallback((project: EnvironmentScopedProjectShell) => {
setSelectedEnvironmentId(project.environmentId);
setSelectedProjectKey(scopedProjectKey(project.environmentId, project.id));
}, []);
- const selectEnvironment = useCallback((environmentId: string) => {
+ const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
setSelectedEnvironmentId(environmentId);
setSelectedProjectKey(null);
setSelectedBranchName(null);
@@ -319,7 +363,10 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
query: null,
});
setPendingConnectionError(null);
- const branches = (result?.branches ?? []).filter((branch) => !branch.isRemote);
+ const branches = pipe(
+ result?.branches ?? [],
+ Arr.filter((branch) => !branch.isRemote),
+ );
if (workspaceMode === "worktree" && !selectedBranchName) {
const preferredBranch =
@@ -333,7 +380,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
} catch {
setPendingConnectionError("Failed to load branches.");
}
- }, [selectedBranchName, selectedProject, setPendingConnectionError, workspaceMode]);
+ }, [selectedBranchName, selectedProject, workspaceMode]);
const value = useMemo(
() => ({
diff --git a/apps/mobile/src/features/threads/threadPresentation.ts b/apps/mobile/src/features/threads/threadPresentation.ts
index 35d0a1d362..24c4138c8a 100644
--- a/apps/mobile/src/features/threads/threadPresentation.ts
+++ b/apps/mobile/src/features/threads/threadPresentation.ts
@@ -1,15 +1,13 @@
import type { ServerConfig as T3ServerConfig } from "@t3tools/contracts";
-import * as Arr from "effect/Array";
import type { StatusTone } from "../../components/StatusPill";
+import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
-import type { ScopedMobileThread } from "../../lib/scopedEntities";
-
-export function threadSortValue(thread: ScopedMobileThread): number {
+export function threadSortValue(thread: EnvironmentScopedThreadShell): number {
const candidate = Date.parse(thread.updatedAt ?? thread.createdAt);
return Number.isNaN(candidate) ? 0 : candidate;
}
-export function threadStatusTone(thread: ScopedMobileThread): StatusTone {
+export function threadStatusTone(thread: EnvironmentScopedThreadShell): StatusTone {
const status = thread.session?.status;
if (status === "running") {
return {
@@ -55,21 +53,13 @@ export function messageImageUrl(httpBaseUrl: string | null, attachmentId: string
return url.toString();
}
-export function lastConversationLine(thread: ScopedMobileThread): string {
- const candidate = Arr.findLast(
- thread.messages,
- (message) => message.role === "user" || message.role === "assistant",
- );
-
- if (candidate._tag === "None") {
+export function lastConversationLine(thread: EnvironmentScopedThreadShell): string {
+ if (!thread.latestUserMessageAt) {
return "No messages yet.";
}
-
- const trimmed = candidate.value.text.trim();
- if (trimmed.length === 0) {
- return candidate.value.role === "assistant" ? "(empty assistant response)" : "(empty message)";
- }
- return trimmed;
+ return thread.session?.status === "running" || thread.session?.status === "starting"
+ ? "Working on latest request..."
+ : "Open thread to view latest message.";
}
export function screenTitle(config: T3ServerConfig | null, serverUrl: string | null): string {
diff --git a/apps/mobile/src/state/use-project-actions.ts b/apps/mobile/src/features/threads/use-project-actions.ts
similarity index 81%
rename from apps/mobile/src/state/use-project-actions.ts
rename to apps/mobile/src/features/threads/use-project-actions.ts
index 2bfeda1da4..8be7826d08 100644
--- a/apps/mobile/src/state/use-project-actions.ts
+++ b/apps/mobile/src/features/threads/use-project-actions.ts
@@ -1,5 +1,6 @@
import { useCallback } from "react";
+import { EnvironmentScopedProjectShell } from "@t3tools/client-runtime";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -11,24 +12,21 @@ import {
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
-import { sanitizeFeatureBranchName } from "@t3tools/shared/git";
+import { buildTemporaryWorktreeBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
-import type { DraftComposerImageAttachment } from "../lib/composerImages";
-import { uuidv4 } from "../lib/uuid";
-import type { ScopedMobileProject } from "../lib/scopedEntities";
-import { buildTemporaryWorktreeBranchName } from "../lib/worktrees";
-import { deriveThreadTitleFromPrompt } from "./remote-runtime-types";
-import { useRemoteEnvironmentStore } from "./remote-environment-store";
-import { gitBranchManager } from "./use-git-branches";
-import { useRemoteCatalog } from "./use-remote-catalog";
-import { getEnvironmentClient, useRemoteEnvironmentState } from "./use-remote-environment-registry";
-import { useThreadSelectionStore } from "./thread-selection-store";
+import type { DraftComposerImageAttachment } from "../../lib/composerImages";
+import { uuidv4 } from "../../lib/uuid";
+import { environmentRuntimeManager } from "../../state/use-environment-runtime";
+import { gitBranchManager } from "../../state/use-git-branches";
+import { useRemoteCatalog } from "../../state/use-remote-catalog";
+import {
+ getEnvironmentClient,
+ setPendingConnectionError,
+ useRemoteEnvironmentState,
+} from "../../state/use-remote-environment-registry";
function useRefreshRemoteData() {
const { savedConnectionsById } = useRemoteEnvironmentState();
- const patchEnvironmentRuntimeState = useRemoteEnvironmentStore(
- (state) => state.patchEnvironmentRuntimeState,
- );
return useCallback(
async (environmentIds?: ReadonlyArray) => {
@@ -43,13 +41,13 @@ function useRefreshRemoteData() {
try {
const serverConfig = await client.server.getConfig();
- patchEnvironmentRuntimeState(environmentId, (current) => ({
+ environmentRuntimeManager.patch({ environmentId }, (current) => ({
...current,
serverConfig,
connectionError: null,
}));
} catch (error) {
- patchEnvironmentRuntimeState(environmentId, (current) => ({
+ environmentRuntimeManager.patch({ environmentId }, (current) => ({
...current,
connectionError:
error instanceof Error ? error.message : "Failed to refresh remote data.",
@@ -58,21 +56,27 @@ function useRefreshRemoteData() {
}),
);
},
- [patchEnvironmentRuntimeState, savedConnectionsById],
+ [savedConnectionsById],
);
}
+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 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 project: EnvironmentScopedProjectShell;
readonly modelSelection: ModelSelection;
readonly envMode: "local" | "worktree";
readonly branch: string | null;
@@ -164,21 +168,17 @@ export function useProjectActions() {
}
}
- selectThreadRef({
- environmentId: input.project.environmentId,
- threadId,
- });
await refreshRemoteData([input.project.environmentId]);
return {
environmentId: input.project.environmentId,
threadId,
};
},
- [refreshRemoteData, selectThreadRef],
+ [refreshRemoteData],
);
const onCreateThread = useCallback(
- async (project: ScopedMobileProject) => {
+ async (project: EnvironmentScopedProjectShell) => {
const latestProjectThread =
threads.find(
(thread) =>
@@ -203,11 +203,11 @@ export function useProjectActions() {
initialAttachments: [],
});
},
- [onCreateThreadWithOptions, setPendingConnectionError, threads],
+ [onCreateThreadWithOptions, threads],
);
const onListProjectBranches = useCallback(
- async (project: ScopedMobileProject): Promise> => {
+ async (project: EnvironmentScopedProjectShell): Promise> => {
const client = getEnvironmentClient(project.environmentId);
if (!client) {
return [];
@@ -227,12 +227,12 @@ export function useProjectActions() {
return [];
}
},
- [setPendingConnectionError],
+ [],
);
const onCreateProjectWorktree = useCallback(
async (
- project: ScopedMobileProject,
+ project: EnvironmentScopedProjectShell,
nextWorktree: {
readonly baseBranch: string;
readonly newBranch: string;
@@ -269,7 +269,7 @@ export function useProjectActions() {
return null;
}
},
- [setPendingConnectionError],
+ [],
);
return {
diff --git a/apps/mobile/src/state/use-selected-thread-commands.ts b/apps/mobile/src/features/threads/use-selected-thread-commands.ts
similarity index 76%
rename from apps/mobile/src/state/use-selected-thread-commands.ts
rename to apps/mobile/src/features/threads/use-selected-thread-commands.ts
index 60f17a282f..fc3e2711b5 100644
--- a/apps/mobile/src/state/use-selected-thread-commands.ts
+++ b/apps/mobile/src/features/threads/use-selected-thread-commands.ts
@@ -1,4 +1,4 @@
-import { useCallback } from "react";
+import { useCallback, useState } from "react";
import {
ApprovalRequestId,
@@ -9,12 +9,13 @@ import {
type RuntimeMode,
} from "@t3tools/contracts";
-import { uuidv4 } from "../lib/uuid";
-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";
+import { uuidv4 } from "../../lib/uuid";
+import { environmentRuntimeManager } from "../../state/use-environment-runtime";
+import {
+ getEnvironmentClient,
+ useRemoteEnvironmentState,
+} from "../../state/use-remote-environment-registry";
+import { useThreadSelection } from "../../state/use-thread-selection";
export function useSelectedThreadCommands(input: {
readonly activePendingUserInput: {
@@ -30,21 +31,10 @@ export function useSelectedThreadCommands(input: {
input;
const { selectedThread } = useThreadSelection();
const { savedConnectionsById } = useRemoteEnvironmentState();
- const patchEnvironmentRuntimeState = useRemoteEnvironmentStore(
- (state) => state.patchEnvironmentRuntimeState,
+ const [respondingApprovalId, setRespondingApprovalId] = useState(null);
+ const [respondingUserInputId, setRespondingUserInputId] = useState(
+ null,
);
- 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
@@ -60,13 +50,13 @@ export function useSelectedThreadCommands(input: {
try {
const serverConfig = await client.server.getConfig();
- patchEnvironmentRuntimeState(environmentId, (current) => ({
+ environmentRuntimeManager.patch({ environmentId }, (current) => ({
...current,
serverConfig,
connectionError: null,
}));
} catch (error) {
- patchEnvironmentRuntimeState(environmentId, (current) => ({
+ environmentRuntimeManager.patch({ environmentId }, (current) => ({
...current,
connectionError:
error instanceof Error ? error.message : "Failed to refresh remote data.",
@@ -78,12 +68,7 @@ export function useSelectedThreadCommands(input: {
if (selectedThread) {
await refreshSelectedThreadGitStatus({ quiet: true });
}
- }, [
- patchEnvironmentRuntimeState,
- refreshSelectedThreadGitStatus,
- savedConnectionsById,
- selectedThread,
- ]);
+ }, [refreshSelectedThreadGitStatus, savedConnectionsById, selectedThread]);
const onUpdateThreadModelSelection = useCallback(
async (modelSelection: ModelSelection) => {
@@ -215,7 +200,7 @@ export function useSelectedThreadCommands(input: {
return;
}
- beginRespondingApproval(requestId);
+ setRespondingApprovalId(requestId);
try {
await client.orchestration.dispatchCommand({
type: "thread.approval.respond",
@@ -226,10 +211,10 @@ export function useSelectedThreadCommands(input: {
createdAt: new Date().toISOString(),
});
} finally {
- finishRespondingApproval(requestId);
+ setRespondingApprovalId((current) => (current === requestId ? null : current));
}
},
- [beginRespondingApproval, finishRespondingApproval, selectedThread],
+ [selectedThread],
);
const onSubmitUserInput = useCallback(async () => {
@@ -242,7 +227,7 @@ export function useSelectedThreadCommands(input: {
return;
}
- beginRespondingUserInput(activePendingUserInput.requestId);
+ setRespondingUserInputId(activePendingUserInput.requestId);
try {
await client.orchestration.dispatchCommand({
type: "thread.user-input.respond",
@@ -253,15 +238,11 @@ export function useSelectedThreadCommands(input: {
createdAt: new Date().toISOString(),
});
} finally {
- finishRespondingUserInput(activePendingUserInput.requestId);
+ setRespondingUserInputId((current) =>
+ current === activePendingUserInput.requestId ? null : current,
+ );
}
- }, [
- activePendingUserInput,
- activePendingUserInputAnswers,
- beginRespondingUserInput,
- finishRespondingUserInput,
- selectedThread,
- ]);
+ }, [activePendingUserInput, activePendingUserInputAnswers, selectedThread]);
return {
respondingApprovalId,
diff --git a/apps/mobile/src/state/use-selected-thread-git-actions.ts b/apps/mobile/src/features/threads/use-selected-thread-git-actions.ts
similarity index 90%
rename from apps/mobile/src/state/use-selected-thread-git-actions.ts
rename to apps/mobile/src/features/threads/use-selected-thread-git-actions.ts
index bfe680e1fe..6892f381aa 100644
--- a/apps/mobile/src/state/use-selected-thread-git-actions.ts
+++ b/apps/mobile/src/features/threads/use-selected-thread-git-actions.ts
@@ -1,6 +1,10 @@
import { useCallback, useEffect } from "react";
-import { type GitActionRequestInput } from "@t3tools/client-runtime";
+import {
+ EnvironmentScopedProjectShell,
+ EnvironmentScopedThreadShell,
+ type GitActionRequestInput,
+} from "@t3tools/client-runtime";
import {
CommandId,
type GitBranch,
@@ -12,20 +16,18 @@ import {
sanitizeFeatureBranchName,
} from "@t3tools/shared/git";
-import { uuidv4 } from "../lib/uuid";
-import { type ScopedMobileProject, type ScopedMobileThread } from "../lib/scopedEntities";
-import { useRemoteEnvironmentStore } from "./remote-environment-store";
-import { getEnvironmentClient } from "./use-remote-environment-registry";
-import { gitActionManager } from "./use-git-action-state";
-import { gitBranchManager } from "./use-git-branches";
-import { gitStatusManager } from "./use-git-status";
-import { useThreadSelection } from "./use-thread-selection";
+import { uuidv4 } from "../../lib/uuid";
+import {
+ getEnvironmentClient,
+ setPendingConnectionError,
+} from "../../state/use-remote-environment-registry";
+import { gitActionManager } from "../../state/use-git-action-state";
+import { gitBranchManager } from "../../state/use-git-branches";
+import { gitStatusManager } from "../../state/use-git-status";
+import { useThreadSelection } from "../../state/use-thread-selection";
export function useSelectedThreadGitActions() {
const { selectedThread, selectedThreadProject } = useThreadSelection();
- const setPendingConnectionError = useRemoteEnvironmentStore(
- (state) => state.setPendingConnectionError,
- );
const selectedThreadGitRootCwd = selectedThreadProject?.workspaceRoot ?? null;
@@ -84,7 +86,7 @@ export function useSelectedThreadGitActions() {
return null;
}
},
- [selectedThread, selectedThreadProject, setPendingConnectionError],
+ [selectedThread, selectedThreadProject],
);
useEffect(() => {
@@ -98,8 +100,8 @@ export function useSelectedThreadGitActions() {
const runSelectedThreadGitMutation = useCallback(
async (
operation: (input: {
- readonly thread: ScopedMobileThread;
- readonly project: ScopedMobileProject;
+ readonly thread: EnvironmentScopedThreadShell;
+ readonly project: EnvironmentScopedProjectShell;
readonly cwd: string;
}) => Promise,
): Promise => {
@@ -124,7 +126,7 @@ export function useSelectedThreadGitActions() {
return null;
}
},
- [selectedThread, selectedThreadProject, setPendingConnectionError],
+ [selectedThread, selectedThreadProject],
);
const refreshSelectedThreadBranches = useCallback(async (): Promise> => {
@@ -152,11 +154,11 @@ export function useSelectedThreadGitActions() {
);
return [];
}
- }, [selectedThread, selectedThreadGitRootCwd, selectedThreadProject, setPendingConnectionError]);
+ }, [selectedThread, selectedThreadGitRootCwd, selectedThreadProject]);
const syncSelectedThreadBranchState = useCallback(
async (input: {
- readonly thread: ScopedMobileThread;
+ readonly thread: EnvironmentScopedThreadShell;
readonly cwd: string;
readonly branchRootCwd?: string | null;
readonly nextThreadState?: {
diff --git a/apps/mobile/src/state/use-selected-thread-git-state.ts b/apps/mobile/src/features/threads/use-selected-thread-git-state.ts
similarity index 87%
rename from apps/mobile/src/state/use-selected-thread-git-state.ts
rename to apps/mobile/src/features/threads/use-selected-thread-git-state.ts
index 099021dbcf..efcc6e2556 100644
--- a/apps/mobile/src/state/use-selected-thread-git-state.ts
+++ b/apps/mobile/src/features/threads/use-selected-thread-git-state.ts
@@ -2,9 +2,9 @@ import { useMemo } from "react";
import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
-import { useGitActionState } from "./use-git-action-state";
-import { useGitBranches } from "./use-git-branches";
-import { useThreadSelection } from "./use-thread-selection";
+import { useGitActionState } from "../../state/use-git-action-state";
+import { useGitBranches } from "../../state/use-git-branches";
+import { useThreadSelection } from "../../state/use-thread-selection";
export function useSelectedThreadGitState() {
const { selectedThread, selectedThreadProject } = useThreadSelection();
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/features/threads/use-thread-composer-state.ts
similarity index 54%
rename from apps/mobile/src/state/use-thread-composer-state.ts
rename to apps/mobile/src/features/threads/use-thread-composer-state.ts
index e39cb34be5..58e241f69b 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/features/threads/use-thread-composer-state.ts
@@ -1,30 +1,195 @@
+import { useAtomValue } from "@effect/atom-react";
import { useCallback, useEffect, useMemo } from "react";
-import { ApprovalRequestId, CommandId, MessageId, ThreadId } from "@t3tools/contracts";
+import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
+import {
+ ApprovalRequestId,
+ CommandId,
+ EnvironmentId,
+ MessageId,
+ ThreadId,
+} from "@t3tools/contracts";
import { deriveActiveWorkStartedAt, formatElapsed } from "@t3tools/shared/orchestrationTiming";
+import { Atom } from "effect/unstable/reactivity";
import {
convertPastedImagesToAttachments,
pasteComposerClipboard,
pickComposerImages,
-} from "../lib/composerImages";
-import type { ScopedMobileThread } from "../lib/scopedEntities";
-import { scopedRequestKey, scopedThreadKey } from "../lib/scopedEntities";
+} from "../../lib/composerImages";
+import type { DraftComposerImageAttachment } from "../../lib/composerImages";
+import { scopedRequestKey, scopedThreadKey } from "../../lib/scopedEntities";
import {
buildPendingUserInputAnswers,
buildThreadFeed,
derivePendingApprovals,
derivePendingUserInputs,
+ setPendingUserInputCustomAnswer,
+ type PendingUserInputDraftAnswer,
type QueuedThreadMessage,
-} from "../lib/threadActivity";
-import { uuidv4 } from "../lib/uuid";
-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";
+} from "../../lib/threadActivity";
+import { uuidv4 } from "../../lib/uuid";
+import { appAtomRegistry } from "../../state/atom-registry";
+import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
+import {
+ getEnvironmentClient,
+ setPendingConnectionError,
+ useRemoteConnectionStatus,
+} from "../../state/use-remote-environment-registry";
+import { useRemoteCatalog } from "../../state/use-remote-catalog";
+import { useSelectedThreadDetail } from "../../state/use-thread-detail";
+import { useThreadSelection } from "../../state/use-thread-selection";
+
+const threadComposerNowTickAtom = Atom.make(Date.now()).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("mobile:thread-composer:now-tick"),
+);
+
+const draftMessageByThreadKeyAtom = Atom.make>({}).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("mobile:thread-composer:draft-message"),
+);
+
+const draftAttachmentsByThreadKeyAtom = Atom.make<
+ Record>
+>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:thread-composer:draft-attachments"));
+
+const dispatchingQueuedMessageIdAtom = Atom.make(null).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("mobile:thread-composer:dispatching-message-id"),
+);
+
+const queuedMessagesByThreadKeyAtom = Atom.make>>(
+ {},
+).pipe(Atom.keepAlive, Atom.withLabel("mobile:thread-composer:queued-messages"));
+
+const userInputDraftsByRequestKeyAtom = Atom.make<
+ Record>
+>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
+
+function setNowTick(tick: number): void {
+ appAtomRegistry.set(threadComposerNowTickAtom, tick);
+}
+
+function setDraftMessage(threadKey: string, value: string): void {
+ const current = appAtomRegistry.get(draftMessageByThreadKeyAtom);
+ appAtomRegistry.set(draftMessageByThreadKeyAtom, {
+ ...current,
+ [threadKey]: value,
+ });
+}
+
+function appendDraftAttachments(
+ threadKey: string,
+ attachments: ReadonlyArray,
+): void {
+ const current = appAtomRegistry.get(draftAttachmentsByThreadKeyAtom);
+ appAtomRegistry.set(draftAttachmentsByThreadKeyAtom, {
+ ...current,
+ [threadKey]: [...(current[threadKey] ?? []), ...attachments],
+ });
+}
+
+function appendDraftMessage(threadKey: string, value: string): void {
+ const current = appAtomRegistry.get(draftMessageByThreadKeyAtom);
+ appAtomRegistry.set(draftMessageByThreadKeyAtom, {
+ ...current,
+ [threadKey]: `${current[threadKey] ?? ""}${value}`,
+ });
+}
+
+function clearDraft(threadKey: string): void {
+ const draftMessages = appAtomRegistry.get(draftMessageByThreadKeyAtom);
+ const draftAttachments = appAtomRegistry.get(draftAttachmentsByThreadKeyAtom);
+ appAtomRegistry.set(draftMessageByThreadKeyAtom, {
+ ...draftMessages,
+ [threadKey]: "",
+ });
+ appAtomRegistry.set(draftAttachmentsByThreadKeyAtom, {
+ ...draftAttachments,
+ [threadKey]: [],
+ });
+}
+
+function removeDraftImage(threadKey: string, imageId: string): void {
+ const current = appAtomRegistry.get(draftAttachmentsByThreadKeyAtom);
+ appAtomRegistry.set(draftAttachmentsByThreadKeyAtom, {
+ ...current,
+ [threadKey]: (current[threadKey] ?? []).filter((image) => image.id !== imageId),
+ });
+}
+
+function beginDispatchingQueuedMessage(queuedMessageId: MessageId): void {
+ appAtomRegistry.set(dispatchingQueuedMessageIdAtom, queuedMessageId);
+}
+
+function finishDispatchingQueuedMessage(queuedMessageId: MessageId): void {
+ const current = appAtomRegistry.get(dispatchingQueuedMessageIdAtom);
+ appAtomRegistry.set(dispatchingQueuedMessageIdAtom, current === queuedMessageId ? null : current);
+}
+
+function enqueueQueuedMessage(message: QueuedThreadMessage): void {
+ const current = appAtomRegistry.get(queuedMessagesByThreadKeyAtom);
+ const threadKey = scopedThreadKey(message.environmentId, message.threadId);
+ appAtomRegistry.set(queuedMessagesByThreadKeyAtom, {
+ ...current,
+ [threadKey]: [...(current[threadKey] ?? []), message],
+ });
+}
+
+function removeQueuedMessage(
+ environmentId: EnvironmentId,
+ threadId: ThreadId,
+ queuedMessageId: MessageId,
+): void {
+ const current = appAtomRegistry.get(queuedMessagesByThreadKeyAtom);
+ const threadKey = scopedThreadKey(environmentId, threadId);
+ const existing = current[threadKey];
+ if (!existing) {
+ return;
+ }
+
+ const nextQueue = existing.filter((entry) => entry.messageId !== queuedMessageId);
+ const next = { ...current };
+ if (nextQueue.length === 0) {
+ delete next[threadKey];
+ } else {
+ next[threadKey] = nextQueue;
+ }
+
+ appAtomRegistry.set(queuedMessagesByThreadKeyAtom, next);
+}
+
+function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void {
+ const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
+ appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
+ ...current,
+ [requestKey]: {
+ ...current[requestKey],
+ [questionId]: {
+ selectedOptionLabel: label,
+ },
+ },
+ });
+}
+
+function setUserInputDraftCustomAnswer(
+ requestKey: string,
+ questionId: string,
+ customAnswer: string,
+): void {
+ const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
+ appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
+ ...current,
+ [requestKey]: {
+ ...current[requestKey],
+ [questionId]: setPendingUserInputCustomAnswer(
+ current[requestKey]?.[questionId],
+ customAnswer,
+ ),
+ },
+ });
+}
function useWorkDurationTicker(
activeWorkStartedAt: string | null,
@@ -47,7 +212,7 @@ function useWorkDurationTicker(
function useQueueDrain(input: {
readonly dispatchingQueuedMessageId: string | null;
readonly queuedMessagesByThreadKey: Record>;
- readonly threads: ReadonlyArray;
+ readonly threads: ReadonlyArray;
readonly environments: ReadonlyArray;
readonly sendQueuedMessage: (message: QueuedThreadMessage) => Promise;
}) {
@@ -104,49 +269,21 @@ function useQueueDrain(input: {
export function useThreadComposerState() {
const { connectedEnvironments } = useRemoteConnectionStatus();
const { threads } = useRemoteCatalog();
- const { selectedThread } = useThreadSelection();
+ const { selectedThread: selectedThreadShell } = useThreadSelection();
+ const selectedThread = useSelectedThreadDetail();
+ const nowTick = useAtomValue(threadComposerNowTickAtom);
+ const draftMessageByThreadKey = useAtomValue(draftMessageByThreadKeyAtom);
+ const draftAttachmentsByThreadKey = useAtomValue(draftAttachmentsByThreadKeyAtom);
+ const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
+ const queuedMessagesByThreadKey = useAtomValue(queuedMessagesByThreadKeyAtom);
+ const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
- 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)
+ const selectedThreadKey = selectedThreadShell
+ ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
: null;
- const selectedRequestKey = selectedThread
- ? (requestId: ApprovalRequestId) => scopedRequestKey(selectedThread.environmentId, requestId)
+ const selectedRequestKey = selectedThreadShell
+ ? (requestId: ApprovalRequestId) =>
+ scopedRequestKey(selectedThreadShell.environmentId, requestId)
: null;
const selectedThreadQueuedMessages = useMemo(
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
@@ -270,13 +407,7 @@ export function useThreadComposerState() {
finishDispatchingQueuedMessage(queuedMessage.messageId);
}
},
- [
- beginDispatchingQueuedMessage,
- finishDispatchingQueuedMessage,
- removeQueuedMessage,
- setPendingConnectionError,
- threads,
- ],
+ [threads],
);
useQueueDrain({
@@ -288,11 +419,11 @@ export function useThreadComposerState() {
});
const onSendMessage = useCallback(() => {
- if (!selectedThread) {
+ if (!selectedThreadShell) {
return;
}
- const threadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const text = (draftMessageByThreadKey[threadKey] ?? "").trim();
const attachments = draftAttachmentsByThreadKey[threadKey] ?? [];
if (text.length === 0 && attachments.length === 0) {
@@ -301,8 +432,8 @@ export function useThreadComposerState() {
const createdAt = new Date().toISOString();
enqueueQueuedMessage({
- environmentId: selectedThread.environmentId,
- threadId: selectedThread.id,
+ environmentId: selectedThreadShell.environmentId,
+ threadId: selectedThreadShell.id,
messageId: MessageId.make(uuidv4()),
commandId: CommandId.make(uuidv4()),
text,
@@ -310,62 +441,56 @@ export function useThreadComposerState() {
createdAt,
});
clearDraft(threadKey);
- }, [
- clearDraft,
- draftAttachmentsByThreadKey,
- draftMessageByThreadKey,
- enqueueQueuedMessage,
- selectedThread,
- ]);
+ }, [draftAttachmentsByThreadKey, draftMessageByThreadKey, selectedThreadShell]);
const onSelectUserInputOption = useCallback(
(requestId: string, questionId: string, label: string) => {
- if (!selectedThread) {
+ if (!selectedThreadShell) {
return;
}
const requestKey = scopedRequestKey(
- selectedThread.environmentId,
+ selectedThreadShell.environmentId,
requestId as ApprovalRequestId,
);
setUserInputDraftOption(requestKey, questionId, label);
},
- [selectedThread, setUserInputDraftOption],
+ [selectedThreadShell],
);
const onChangeUserInputCustomAnswer = useCallback(
(requestId: string, questionId: string, customAnswer: string) => {
- if (!selectedThread) {
+ if (!selectedThreadShell) {
return;
}
const requestKey = scopedRequestKey(
- selectedThread.environmentId,
+ selectedThreadShell.environmentId,
requestId as ApprovalRequestId,
);
setUserInputDraftCustomAnswer(requestKey, questionId, customAnswer);
},
- [selectedThread, setUserInputDraftCustomAnswer],
+ [selectedThreadShell],
);
const onChangeDraftMessage = useCallback(
(value: string) => {
- if (!selectedThread) {
+ if (!selectedThreadShell) {
return;
}
- const threadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
setDraftMessage(threadKey, value);
},
- [selectedThread, setDraftMessage],
+ [selectedThreadShell],
);
const onPickDraftImages = useCallback(async () => {
- if (!selectedThread) {
+ if (!selectedThreadShell) {
return;
}
- const threadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const result = await pickComposerImages({
existingCount: draftAttachmentsByThreadKey[threadKey]?.length ?? 0,
});
@@ -375,19 +500,14 @@ export function useThreadComposerState() {
if (result.error) {
setPendingConnectionError(result.error);
}
- }, [
- appendDraftAttachments,
- draftAttachmentsByThreadKey,
- selectedThread,
- setPendingConnectionError,
- ]);
+ }, [draftAttachmentsByThreadKey, selectedThreadShell]);
const onPasteIntoDraft = useCallback(async () => {
- if (!selectedThread) {
+ if (!selectedThreadShell) {
return;
}
- const threadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const result = await pasteComposerClipboard({
existingCount: draftAttachmentsByThreadKey[threadKey]?.length ?? 0,
});
@@ -400,21 +520,15 @@ export function useThreadComposerState() {
if (result.error) {
setPendingConnectionError(result.error);
}
- }, [
- appendDraftAttachments,
- appendDraftMessage,
- draftAttachmentsByThreadKey,
- selectedThread,
- setPendingConnectionError,
- ]);
+ }, [draftAttachmentsByThreadKey, selectedThreadShell]);
const onNativePasteImages = useCallback(
async (uris: ReadonlyArray) => {
- if (!selectedThread || uris.length === 0) {
+ if (!selectedThreadShell || uris.length === 0) {
return;
}
- const threadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
try {
const images = await convertPastedImagesToAttachments({
uris,
@@ -427,19 +541,19 @@ export function useThreadComposerState() {
console.error("[native paste] error converting images", error);
}
},
- [appendDraftAttachments, draftAttachmentsByThreadKey, selectedThread],
+ [draftAttachmentsByThreadKey, selectedThreadShell],
);
const onRemoveDraftImage = useCallback(
(imageId: string) => {
- if (!selectedThread) {
+ if (!selectedThreadShell) {
return;
}
- const threadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
removeDraftImage(threadKey, imageId);
},
- [removeDraftImage, selectedThread],
+ [selectedThreadShell],
);
return {
diff --git a/apps/mobile/src/lib/connection.ts b/apps/mobile/src/lib/connection.ts
index fac0ac7a10..3127c64aac 100644
--- a/apps/mobile/src/lib/connection.ts
+++ b/apps/mobile/src/lib/connection.ts
@@ -1,3 +1,4 @@
+import { EnvironmentId } from "@t3tools/contracts";
import {
bootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor,
@@ -9,7 +10,7 @@ export interface RemoteConnectionInput {
}
export interface SavedRemoteConnection {
- readonly environmentId: string;
+ readonly environmentId: EnvironmentId;
readonly environmentLabel: string;
readonly pairingUrl: string;
readonly displayUrl: string;
@@ -18,6 +19,13 @@ export interface SavedRemoteConnection {
readonly bearerToken: string;
}
+export type RemoteClientConnectionState =
+ | "idle"
+ | "connecting"
+ | "ready"
+ | "reconnecting"
+ | "disconnected";
+
export async function bootstrapRemoteConnection(
input: RemoteConnectionInput,
): Promise {
diff --git a/apps/mobile/src/lib/remoteClient.ts b/apps/mobile/src/lib/remoteClient.ts
deleted file mode 100644
index 89cc11a3c7..0000000000
--- a/apps/mobile/src/lib/remoteClient.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export type RemoteClientConnectionState =
- | "idle"
- | "connecting"
- | "ready"
- | "reconnecting"
- | "disconnected";
diff --git a/apps/mobile/src/lib/repositoryGroups.test.ts b/apps/mobile/src/lib/repositoryGroups.test.ts
index 6a9714f28f..f557860ae0 100644
--- a/apps/mobile/src/lib/repositoryGroups.test.ts
+++ b/apps/mobile/src/lib/repositoryGroups.test.ts
@@ -1,14 +1,17 @@
import { describe, expect, it } from "vitest";
-import { ProjectId, ThreadId } from "@t3tools/contracts";
+import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
-import type { ScopedMobileProject, ScopedMobileThread } from "./scopedEntities";
import { groupProjectsByRepository } from "./repositoryGroups";
+import {
+ EnvironmentScopedProjectShell,
+ EnvironmentScopedThreadShell,
+} from "@t3tools/client-runtime";
function makeProject(
- input: Partial &
- Pick,
-): ScopedMobileProject {
+ input: Partial &
+ Pick,
+): EnvironmentScopedProjectShell {
return {
workspaceRoot: `/workspaces/${input.id}`,
repositoryIdentity: null,
@@ -21,12 +24,12 @@ function makeProject(
}
function makeThread(
- input: Partial &
+ input: Partial &
Pick<
- ScopedMobileThread,
- "environmentId" | "environmentLabel" | "id" | "projectId" | "title" | "modelSelection"
+ EnvironmentScopedThreadShell,
+ "environmentId" | "id" | "projectId" | "title" | "modelSelection"
>,
-): ScopedMobileThread {
+): EnvironmentScopedThreadShell {
return {
runtimeMode: "full-access",
interactionMode: "default",
@@ -36,11 +39,6 @@ function makeThread(
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
archivedAt: null,
- deletedAt: null,
- messages: [],
- proposedPlans: [],
- activities: [],
- checkpoints: [],
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
@@ -67,15 +65,13 @@ describe("groupProjectsByRepository", () => {
const projects = [
makeProject({
- environmentId: "env-local",
- environmentLabel: "Local",
+ environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("project-local"),
title: "T3 Code",
repositoryIdentity: repoIdentity,
}),
makeProject({
- environmentId: "env-staging",
- environmentLabel: "Staging",
+ environmentId: EnvironmentId.make("env-staging"),
id: ProjectId.make("project-staging"),
title: "T3 Code",
repositoryIdentity: repoIdentity,
@@ -84,8 +80,7 @@ describe("groupProjectsByRepository", () => {
const threads = [
makeThread({
- environmentId: "env-staging",
- environmentLabel: "Staging",
+ environmentId: EnvironmentId.make("env-staging"),
id: ThreadId.make("thread-2"),
projectId: ProjectId.make("project-staging"),
title: "Fix reconnect flow",
@@ -93,8 +88,7 @@ describe("groupProjectsByRepository", () => {
updatedAt: "2026-04-02T12:00:00.000Z",
}),
makeThread({
- environmentId: "env-local",
- environmentLabel: "Local",
+ environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-local"),
title: "Polish mobile shell",
@@ -113,17 +107,17 @@ describe("groupProjectsByRepository", () => {
projectCount: 2,
threadCount: 2,
});
- expect(groups[0]?.projects.map((entry) => entry.project.environmentLabel)).toEqual([
- "Local",
- "Staging",
- ]);
+ expect(
+ groups[0]?.projects
+ .map((entry) => entry.project.environmentId)
+ .toSorted((left, right) => left.localeCompare(right)),
+ ).toEqual(["env-local", "env-staging"]);
});
it("falls back to a scoped project key when repository identity is unavailable", () => {
const projects = [
makeProject({
- environmentId: "env-local",
- environmentLabel: "Local",
+ environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("project-local"),
title: "Scratchpad",
}),
diff --git a/apps/mobile/src/lib/repositoryGroups.ts b/apps/mobile/src/lib/repositoryGroups.ts
index f26098eca8..1468676a06 100644
--- a/apps/mobile/src/lib/repositoryGroups.ts
+++ b/apps/mobile/src/lib/repositoryGroups.ts
@@ -2,13 +2,16 @@ import * as Order from "effect/Order";
import * as Arr from "effect/Array";
import type { RepositoryIdentity } from "@t3tools/contracts";
-import type { ScopedMobileProject, ScopedMobileThread } from "./scopedEntities";
import { scopedProjectKey } from "./scopedEntities";
+import {
+ EnvironmentScopedProjectShell,
+ EnvironmentScopedThreadShell,
+} from "@t3tools/client-runtime";
export interface MobileRepositoryProjectGroup {
readonly key: string;
- readonly project: ScopedMobileProject;
- readonly threads: ReadonlyArray;
+ readonly project: EnvironmentScopedProjectShell;
+ readonly threads: ReadonlyArray;
readonly latestActivityAt: string;
}
@@ -27,13 +30,13 @@ function compareIsoDateDescending(left: string, right: string): number {
return new Date(right).getTime() - new Date(left).getTime();
}
-function deriveRepositoryGroupKey(project: ScopedMobileProject): string {
+function deriveRepositoryGroupKey(project: EnvironmentScopedProjectShell): string {
return (
project.repositoryIdentity?.canonicalKey ?? scopedProjectKey(project.environmentId, project.id)
);
}
-function deriveRepositoryTitle(project: ScopedMobileProject): string {
+function deriveRepositoryTitle(project: EnvironmentScopedProjectShell): string {
const identity = project.repositoryIdentity;
return identity?.displayName ?? identity?.name ?? project.title;
}
@@ -49,18 +52,18 @@ function deriveRepositorySubtitle(identity: RepositoryIdentity | null | undefine
}
function deriveProjectLatestActivity(
- project: ScopedMobileProject,
- threads: ReadonlyArray,
+ project: EnvironmentScopedProjectShell,
+ threads: ReadonlyArray,
): string {
const latestThread = threads[0];
return latestThread?.updatedAt ?? latestThread?.createdAt ?? project.updatedAt;
}
export function groupProjectsByRepository(input: {
- readonly projects: ReadonlyArray;
- readonly threads: ReadonlyArray;
+ readonly projects: ReadonlyArray;
+ readonly threads: ReadonlyArray;
}): ReadonlyArray {
- const threadsByProjectKey = new Map();
+ const threadsByProjectKey = new Map();
for (const thread of input.threads) {
const key = scopedProjectKey(thread.environmentId, thread.projectId);
diff --git a/apps/mobile/src/lib/routes.ts b/apps/mobile/src/lib/routes.ts
index 2f271a279b..293b3f4da4 100644
--- a/apps/mobile/src/lib/routes.ts
+++ b/apps/mobile/src/lib/routes.ts
@@ -1,11 +1,11 @@
import type { Router } from "expo-router";
import type { SelectedThreadRef } from "../state/remote-runtime-types";
-import type { ScopedMobileThread } from "./scopedEntities";
+import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
type ThreadRouteInput =
| Pick
- | Pick;
+ | Pick;
export function buildThreadRoutePath(input: ThreadRouteInput): string {
const environmentId = input.environmentId;
diff --git a/apps/mobile/src/lib/scopedEntities.ts b/apps/mobile/src/lib/scopedEntities.ts
index 28728dc513..34709957fd 100644
--- a/apps/mobile/src/lib/scopedEntities.ts
+++ b/apps/mobile/src/lib/scopedEntities.ts
@@ -1,42 +1,16 @@
-import type {
- ApprovalRequestId,
- OrchestrationProjectShell,
- OrchestrationThread,
- OrchestrationThreadShell,
- ProjectId,
- ThreadId,
-} from "@t3tools/contracts";
+import { ApprovalRequestId, EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
-export interface ScopedMobileProject extends OrchestrationProjectShell {
- readonly environmentId: string;
- readonly environmentLabel: string;
-}
-
-/**
- * Thread shape used throughout the mobile UI. Extends the lightweight shell
- * type with the full-detail fields the composer and detail screen expect.
- * The shell snapshot stubs these as empty arrays; `useThreadSelection`
- * overlays real data from the per-thread `subscribeThread` subscription
- * when a thread is selected.
- */
-export interface ScopedMobileThread extends OrchestrationThreadShell {
- readonly environmentId: string;
- readonly environmentLabel: string;
- readonly deletedAt: OrchestrationThread["deletedAt"];
- readonly messages: OrchestrationThread["messages"];
- readonly proposedPlans: OrchestrationThread["proposedPlans"];
- readonly activities: OrchestrationThread["activities"];
- readonly checkpoints: OrchestrationThread["checkpoints"];
-}
-
-export function scopedProjectKey(environmentId: string, projectId: ProjectId): string {
+export function scopedProjectKey(environmentId: EnvironmentId, projectId: ProjectId): string {
return `${environmentId}:${projectId}`;
}
-export function scopedThreadKey(environmentId: string, threadId: ThreadId): string {
+export function scopedThreadKey(environmentId: EnvironmentId, threadId: ThreadId): string {
return `${environmentId}:${threadId}`;
}
-export function scopedRequestKey(environmentId: string, requestId: ApprovalRequestId): string {
+export function scopedRequestKey(
+ environmentId: EnvironmentId,
+ requestId: ApprovalRequestId,
+): string {
return `${environmentId}:${requestId}`;
}
diff --git a/apps/mobile/src/lib/storage.ts b/apps/mobile/src/lib/storage.ts
index a737ea69bc..e40fdc3179 100644
--- a/apps/mobile/src/lib/storage.ts
+++ b/apps/mobile/src/lib/storage.ts
@@ -1,3 +1,5 @@
+import * as Arr from "effect/Array";
+import { pipe } from "effect/Function";
import * as SecureStore from "expo-secure-store";
import type { SavedRemoteConnection } from "./connection";
@@ -22,7 +24,10 @@ export async function loadSavedConnections(): Promise;
};
- return (parsed.connections ?? []).filter((c) => c.environmentId && c.bearerToken?.trim());
+ return pipe(
+ parsed.connections ?? [],
+ Arr.filter((c) => !!c.environmentId && !!c.bearerToken?.trim()),
+ );
} catch {
return [];
}
@@ -31,16 +36,20 @@ export async function loadSavedConnections(): Promise {
const current = await loadSavedConnections();
const next = current.some((entry) => entry.environmentId === connection.environmentId)
- ? current.map((entry) =>
- entry.environmentId === connection.environmentId ? connection : entry,
+ ? pipe(
+ current,
+ Arr.map((entry) => (entry.environmentId === connection.environmentId ? connection : entry)),
)
- : [...current, connection];
+ : pipe(current, Arr.append(connection));
await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
}
export async function clearSavedConnection(environmentId: string): Promise {
const current = await loadSavedConnections();
- const next = current.filter((entry) => entry.environmentId !== environmentId);
+ const next = pipe(
+ current,
+ Arr.filter((entry) => entry.environmentId !== environmentId),
+ );
await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
}
diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts
index d64baa774b..b74e1f7fe1 100644
--- a/apps/mobile/src/lib/threadActivity.ts
+++ b/apps/mobile/src/lib/threadActivity.ts
@@ -1,6 +1,7 @@
import type {
ApprovalRequestId,
CommandId,
+ EnvironmentId,
MessageId,
OrchestrationThread,
OrchestrationThreadActivity,
@@ -31,7 +32,7 @@ export interface PendingUserInputDraftAnswer {
}
export interface QueuedThreadMessage {
- readonly environmentId: string;
+ readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
readonly messageId: MessageId;
readonly commandId: CommandId;
diff --git a/apps/mobile/src/lib/worktrees.ts b/apps/mobile/src/lib/worktrees.ts
deleted file mode 100644
index bb5633b42c..0000000000
--- a/apps/mobile/src/lib/worktrees.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-const WORKTREE_BRANCH_PREFIX = "t3code";
-
-function randomHexToken(): string {
- const uuid = globalThis.crypto?.randomUUID?.();
- if (uuid) {
- return uuid.replace(/-/g, "").slice(0, 8).toLowerCase();
- }
-
- return Math.random().toString(16).slice(2, 10).padEnd(8, "0");
-}
-
-export function buildTemporaryWorktreeBranchName(): string {
- return `${WORKTREE_BRANCH_PREFIX}/${randomHexToken()}`;
-}
diff --git a/apps/mobile/src/state/atom-registry.ts b/apps/mobile/src/state/atom-registry.ts
new file mode 100644
index 0000000000..b30e7c3729
--- /dev/null
+++ b/apps/mobile/src/state/atom-registry.ts
@@ -0,0 +1,3 @@
+import { AtomRegistry } from "effect/unstable/reactivity";
+
+export const appAtomRegistry = AtomRegistry.make();
diff --git a/apps/mobile/src/state/atomRegistry.tsx b/apps/mobile/src/state/atomRegistry.tsx
deleted file mode 100644
index e36da5f3b2..0000000000
--- a/apps/mobile/src/state/atomRegistry.tsx
+++ /dev/null
@@ -1,9 +0,0 @@
-import { RegistryContext } from "@effect/atom-react";
-import { AtomRegistry } from "effect/unstable/reactivity";
-import type { ReactNode } from "react";
-
-export const appAtomRegistry = AtomRegistry.make();
-
-export function AppAtomRegistryProvider({ children }: { readonly children: ReactNode }) {
- return {children};
-}
diff --git a/apps/mobile/src/state/remote-environment-store.ts b/apps/mobile/src/state/remote-environment-store.ts
deleted file mode 100644
index 7592f62939..0000000000
--- a/apps/mobile/src/state/remote-environment-store.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { useStore } from "zustand";
-import { createStore } from "zustand/vanilla";
-
-import type { OrchestrationThread } from "@t3tools/contracts";
-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;
- /** Full thread detail keyed by `${environmentId}:${threadId}`. */
- readonly threadDetailByKey: 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;
- readonly setThreadDetail: (key: string, thread: OrchestrationThread) => void;
- readonly removeThreadDetail: (key: string) => void;
-}
-
-export const remoteEnvironmentStore = createStore()((set) => ({
- isLoadingSavedConnection: true,
- connectionPairingUrl: "",
- pendingConnectionError: null,
- savedConnectionsById: {},
- environmentStateById: {},
- threadDetailByKey: {},
-
- 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 };
- }),
- setThreadDetail: (key, thread) =>
- set((state) => ({
- threadDetailByKey: { ...state.threadDetailByKey, [key]: thread },
- })),
- removeThreadDetail: (key) =>
- set((state) => {
- const next = { ...state.threadDetailByKey };
- delete next[key];
- return { threadDetailByKey: next };
- }),
-}));
-
-export function useRemoteEnvironmentStore(
- 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
index 528c3c5778..74d2cc8d99 100644
--- a/apps/mobile/src/state/remote-runtime-types.ts
+++ b/apps/mobile/src/state/remote-runtime-types.ts
@@ -1,85 +1,26 @@
import type {
- OrchestrationShellSnapshot,
- ServerConfig as T3ServerConfig,
-} from "@t3tools/contracts";
-import type { EnvironmentConnection, WsRpcClient } from "@t3tools/client-runtime";
+ EnvironmentConnection,
+ EnvironmentConnectionState,
+ WsRpcClient,
+} from "@t3tools/client-runtime";
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
-export type RemoteClientConnectionState =
- | "idle"
- | "connecting"
- | "ready"
- | "reconnecting"
- | "disconnected";
+export type { EnvironmentRuntimeState } from "@t3tools/client-runtime";
export interface ConnectedEnvironmentSummary {
- readonly environmentId: string;
+ readonly environmentId: EnvironmentId;
readonly environmentLabel: string;
readonly displayUrl: string;
- readonly connectionState: RemoteClientConnectionState;
+ readonly connectionState: EnvironmentConnectionState;
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: OrchestrationShellSnapshot | null;
- readonly serverConfig: T3ServerConfig | null;
+ readonly environmentId: EnvironmentId;
+ readonly threadId: ThreadId;
}
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
deleted file mode 100644
index 07a03bfccc..0000000000
--- a/apps/mobile/src/state/thread-approval-store.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-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
deleted file mode 100644
index 848ecc3a8d..0000000000
--- a/apps/mobile/src/state/thread-composer-store.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-import type { MessageId, 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: MessageId | 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: MessageId) => void;
- readonly finishDispatchingQueuedMessage: (queuedMessageId: MessageId) => void;
- readonly enqueueQueuedMessage: (message: QueuedThreadMessage) => void;
- readonly removeQueuedMessage: (
- environmentId: string,
- threadId: ThreadId,
- queuedMessageId: MessageId,
- ) => 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.messageId !== 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-selection-store.ts b/apps/mobile/src/state/thread-selection-store.ts
deleted file mode 100644
index 7ef4e0eead..0000000000
--- a/apps/mobile/src/state/thread-selection-store.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-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
deleted file mode 100644
index d2b793da06..0000000000
--- a/apps/mobile/src/state/thread-user-input-store.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-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-environment-runtime.ts b/apps/mobile/src/state/use-environment-runtime.ts
new file mode 100644
index 0000000000..cd24c8dcdf
--- /dev/null
+++ b/apps/mobile/src/state/use-environment-runtime.ts
@@ -0,0 +1,73 @@
+import { useAtomValue } from "@effect/atom-react";
+import {
+ EMPTY_ENVIRONMENT_RUNTIME_ATOM,
+ EMPTY_ENVIRONMENT_RUNTIME_STATE,
+ createEnvironmentRuntimeManager,
+ environmentRuntimeStateAtom,
+ getEnvironmentRuntimeTargetKey,
+ type EnvironmentRuntimeState,
+} from "@t3tools/client-runtime";
+import { useCallback, useMemo, useRef, useSyncExternalStore } from "react";
+
+import { appAtomRegistry } from "./atom-registry";
+import * as Arr from "effect/Array";
+import * as Order from "effect/Order";
+
+export const environmentRuntimeManager = createEnvironmentRuntimeManager({
+ getRegistry: () => appAtomRegistry,
+});
+
+export function useEnvironmentRuntime(environmentId: string | null): EnvironmentRuntimeState {
+ const targetKey = getEnvironmentRuntimeTargetKey({ environmentId });
+ const state = useAtomValue(
+ targetKey !== null ? environmentRuntimeStateAtom(targetKey) : EMPTY_ENVIRONMENT_RUNTIME_ATOM,
+ );
+ return targetKey === null ? EMPTY_ENVIRONMENT_RUNTIME_STATE : state;
+}
+
+export function useEnvironmentRuntimeStates(
+ environmentIds: ReadonlyArray,
+): Readonly> {
+ const stableEnvironmentIds = useMemo(
+ () => Arr.sort(new Set(environmentIds), Order.String),
+ [environmentIds],
+ );
+ const snapshotCacheRef = useRef>>({});
+
+ const subscribe = useCallback(
+ (onStoreChange: () => void) => {
+ const unsubs = stableEnvironmentIds.map((environmentId) =>
+ appAtomRegistry.subscribe(environmentRuntimeStateAtom(environmentId), onStoreChange),
+ );
+ return () => {
+ for (const unsub of unsubs) {
+ unsub();
+ }
+ };
+ },
+ [stableEnvironmentIds],
+ );
+
+ const getSnapshot = useCallback(() => {
+ const previous = snapshotCacheRef.current;
+ let hasChanged = Object.keys(previous).length !== stableEnvironmentIds.length;
+ const next: Record = {};
+
+ for (const environmentId of stableEnvironmentIds) {
+ const snapshot = environmentRuntimeManager.getSnapshot({ environmentId });
+ next[environmentId] = snapshot;
+ if (!hasChanged && previous[environmentId] !== snapshot) {
+ hasChanged = true;
+ }
+ }
+
+ if (!hasChanged) {
+ return previous;
+ }
+
+ snapshotCacheRef.current = next;
+ return next;
+ }, [stableEnvironmentIds]);
+
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+}
diff --git a/apps/mobile/src/state/use-git-action-state.ts b/apps/mobile/src/state/use-git-action-state.ts
index d8e54015f3..8eb2d8ea66 100644
--- a/apps/mobile/src/state/use-git-action-state.ts
+++ b/apps/mobile/src/state/use-git-action-state.ts
@@ -10,7 +10,7 @@ import {
} from "@t3tools/client-runtime";
import { uuidv4 } from "../lib/uuid";
-import { appAtomRegistry } from "./atomRegistry";
+import { appAtomRegistry } from "./atom-registry";
import { getEnvironmentClient } from "./use-remote-environment-registry";
export const gitActionManager = createGitActionManager({
diff --git a/apps/mobile/src/state/use-git-branches.ts b/apps/mobile/src/state/use-git-branches.ts
index 49595309bf..20ac081221 100644
--- a/apps/mobile/src/state/use-git-branches.ts
+++ b/apps/mobile/src/state/use-git-branches.ts
@@ -9,7 +9,7 @@ import {
gitBranchStateAtom,
} from "@t3tools/client-runtime";
-import { appAtomRegistry } from "./atomRegistry";
+import { appAtomRegistry } from "./atom-registry";
import { getEnvironmentClient } from "./use-remote-environment-registry";
export const gitBranchManager = createGitBranchManager({
diff --git a/apps/mobile/src/state/use-git-status.ts b/apps/mobile/src/state/use-git-status.ts
index 54686ed69c..41ecdd47b7 100644
--- a/apps/mobile/src/state/use-git-status.ts
+++ b/apps/mobile/src/state/use-git-status.ts
@@ -10,7 +10,7 @@ import {
} from "@t3tools/client-runtime";
import { useEffect } from "react";
-import { appAtomRegistry } from "./atomRegistry";
+import { appAtomRegistry } from "./atom-registry";
import {
getEnvironmentClient,
subscribeEnvironmentConnections,
diff --git a/apps/mobile/src/state/use-remote-catalog.ts b/apps/mobile/src/state/use-remote-catalog.ts
index ac9aa2039d..01330b9843 100644
--- a/apps/mobile/src/state/use-remote-catalog.ts
+++ b/apps/mobile/src/state/use-remote-catalog.ts
@@ -1,74 +1,85 @@
import { useMemo } from "react";
-
-import type { ServerConfig as T3ServerConfig } from "@t3tools/contracts";
import * as Order from "effect/Order";
import * as Arr from "effect/Array";
-import type { ScopedMobileProject, ScopedMobileThread } from "../lib/scopedEntities";
+
import {
- deriveOverallConnectionState,
- type RemoteClientConnectionState,
-} from "./remote-runtime-types";
+ EnvironmentConnectionState,
+ EnvironmentScopedProjectShell,
+ EnvironmentScopedThreadShell,
+ scopeProjectShell,
+ scopeThreadShell,
+} from "@t3tools/client-runtime";
+
+import { ConnectedEnvironmentSummary } from "./remote-runtime-types";
+import { useShellSnapshotStates } from "./use-shell-snapshot";
import {
useRemoteConnectionStatus,
useRemoteEnvironmentState,
} from "./use-remote-environment-registry";
-const projectsSortOrder = Order.make(
+const projectsSortOrder = Order.make(
(left, right) =>
(left.title.localeCompare(right.title) as -1 | 0 | 1) ||
- (left.environmentLabel.localeCompare(right.environmentLabel) as -1 | 0 | 1),
+ (left.environmentId.localeCompare(right.environmentId) as -1 | 0 | 1),
);
-const threadsSortOrder = Order.make(
+const threadsSortOrder = Order.make(
(left, right) =>
((new Date(right.updatedAt ?? right.createdAt).getTime() -
new Date(left.updatedAt ?? left.createdAt).getTime()) as -1 | 0 | 1) ||
- (left.environmentLabel.localeCompare(right.environmentLabel) as -1 | 0 | 1),
+ (left.environmentId.localeCompare(right.environmentId) as -1 | 0 | 1),
);
+function deriveOverallConnectionState(
+ environments: ReadonlyArray,
+): EnvironmentConnectionState {
+ 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";
+}
+
export function useRemoteCatalog() {
const { connectedEnvironments, connectionState } = useRemoteConnectionStatus();
const { environmentStateById, savedConnectionsById } = useRemoteEnvironmentState();
+ const shellSnapshotStates = useShellSnapshotStates(Object.keys(savedConnectionsById));
- const projects = useMemo>(
+ const projects = useMemo(
() =>
Arr.sort(
Object.values(savedConnectionsById).flatMap((connection) =>
- (environmentStateById[connection.environmentId]?.snapshot?.projects ?? []).map(
- (project) =>
- Object.assign({}, project, {
- environmentId: connection.environmentId,
- environmentLabel: connection.environmentLabel,
- }),
+ (shellSnapshotStates[connection.environmentId]?.data?.projects ?? []).map((project) =>
+ scopeProjectShell(connection.environmentId, project),
),
),
projectsSortOrder,
),
- [environmentStateById, savedConnectionsById],
+ [savedConnectionsById, shellSnapshotStates],
);
- const threads = useMemo>(
+ const threads = useMemo(
() =>
Arr.sort(
Object.values(savedConnectionsById).flatMap((connection) =>
- (environmentStateById[connection.environmentId]?.snapshot?.threads ?? []).map((thread) =>
- Object.assign({}, thread, {
- environmentId: connection.environmentId,
- environmentLabel: connection.environmentLabel,
- deletedAt: null,
- messages: [],
- proposedPlans: [],
- activities: [],
- checkpoints: [],
- }),
+ (shellSnapshotStates[connection.environmentId]?.data?.threads ?? []).map((thread) =>
+ scopeThreadShell(connection.environmentId, thread),
),
),
threadsSortOrder,
),
- [environmentStateById, savedConnectionsById],
+ [savedConnectionsById, shellSnapshotStates],
);
- const serverConfigByEnvironmentId = useMemo>>(
+ const serverConfigByEnvironmentId = useMemo(
() =>
Object.fromEntries(
Object.entries(environmentStateById).map(([environmentId, runtime]) => [
@@ -79,7 +90,7 @@ export function useRemoteCatalog() {
[environmentStateById],
);
- const overallConnectionState = useMemo(
+ const overallConnectionState = useMemo(
() => deriveOverallConnectionState(connectedEnvironments),
[connectedEnvironments],
);
diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts
index 0f41857548..5f697259ef 100644
--- a/apps/mobile/src/state/use-remote-environment-registry.ts
+++ b/apps/mobile/src/state/use-remote-environment-registry.ts
@@ -1,36 +1,123 @@
+import { useAtomValue } from "@effect/atom-react";
import { useCallback, useEffect, useMemo } from "react";
import { Alert } from "react-native";
import {
- applyShellStreamEvent,
+ type EnvironmentRuntimeState,
createEnvironmentConnection,
createKnownEnvironment,
createWsRpcClient,
+ EnvironmentConnectionState,
WsTransport,
} from "@t3tools/client-runtime";
import { EnvironmentId } from "@t3tools/contracts";
import { resolveRemoteWebSocketConnectionUrl } from "@t3tools/shared/remote";
-import { useShallow } from "zustand/react/shallow";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
+import * as Option from "effect/Option";
+import { pipe } from "effect/Function";
+import { Atom } from "effect/unstable/reactivity";
import { type SavedRemoteConnection, bootstrapRemoteConnection } from "../lib/connection";
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";
+import { appAtomRegistry } from "./atom-registry";
+import { type ConnectedEnvironmentSummary, type EnvironmentSession } from "./remote-runtime-types";
+import { environmentRuntimeManager, useEnvironmentRuntimeStates } from "./use-environment-runtime";
+import { shellSnapshotManager } from "./use-shell-snapshot";
const environmentSessions = new Map();
const environmentConnectionListeners = new Set<() => void>();
+interface RemoteEnvironmentLocalState {
+ readonly isLoadingSavedConnection: boolean;
+ readonly connectionPairingUrl: string;
+ readonly pendingConnectionError: string | null;
+ readonly savedConnectionsById: Record;
+}
+
+const isLoadingSavedConnectionAtom = Atom.make(true).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("mobile:is-loading-saved-connection"),
+);
+
+const connectionPairingUrlAtom = Atom.make("").pipe(
+ Atom.keepAlive,
+ Atom.withLabel("mobile:connection-pairing-url"),
+);
+
+const pendingConnectionErrorAtom = Atom.make(null).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("mobile:pending-connection-error"),
+);
+
+const savedConnectionsByIdAtom = Atom.make>({}).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("mobile:saved-connections"),
+);
+
function notifyEnvironmentConnectionListeners() {
for (const listener of environmentConnectionListeners) listener();
}
+function getSavedConnectionsById(): Record {
+ return appAtomRegistry.get(savedConnectionsByIdAtom);
+}
+
+function setIsLoadingSavedConnection(value: boolean): void {
+ appAtomRegistry.set(isLoadingSavedConnectionAtom, value);
+}
+
+function setConnectionPairingUrl(pairingUrl: string): void {
+ appAtomRegistry.set(connectionPairingUrlAtom, pairingUrl);
+}
+
+function clearConnectionPairingUrl(): void {
+ appAtomRegistry.set(connectionPairingUrlAtom, "");
+}
+
+export function setPendingConnectionError(message: string | null): void {
+ appAtomRegistry.set(pendingConnectionErrorAtom, message);
+}
+
+function clearPendingConnectionError(): void {
+ appAtomRegistry.set(pendingConnectionErrorAtom, null);
+}
+
+function replaceSavedConnections(connections: Record): void {
+ appAtomRegistry.set(savedConnectionsByIdAtom, connections);
+}
+
+function upsertSavedConnection(connection: SavedRemoteConnection): void {
+ const current = appAtomRegistry.get(savedConnectionsByIdAtom);
+ appAtomRegistry.set(savedConnectionsByIdAtom, {
+ ...current,
+ [connection.environmentId]: connection,
+ });
+}
+
+function removeSavedConnection(environmentId: string): void {
+ const current = appAtomRegistry.get(savedConnectionsByIdAtom);
+ const next = { ...current };
+ delete next[environmentId];
+ appAtomRegistry.set(savedConnectionsByIdAtom, next);
+}
+
+function useRemoteEnvironmentLocalState(): RemoteEnvironmentLocalState {
+ const isLoadingSavedConnection = useAtomValue(isLoadingSavedConnectionAtom);
+ const connectionPairingUrl = useAtomValue(connectionPairingUrlAtom);
+ const pendingConnectionError = useAtomValue(pendingConnectionErrorAtom);
+ const savedConnectionsById = useAtomValue(savedConnectionsByIdAtom);
+
+ return useMemo(
+ () => ({
+ isLoadingSavedConnection,
+ connectionPairingUrl,
+ pendingConnectionError,
+ savedConnectionsById,
+ }),
+ [connectionPairingUrl, isLoadingSavedConnection, pendingConnectionError, savedConnectionsById],
+ );
+}
+
/**
* Subscribe to environment-connection changes (connect / disconnect / reconnect).
* Returns an unsubscribe function.
@@ -47,7 +134,7 @@ function setEnvironmentConnectionStatus(
state: ConnectedEnvironmentSummary["connectionState"],
error?: string | null,
) {
- remoteEnvironmentStore.getState().patchEnvironmentRuntimeState(environmentId, (current) => ({
+ environmentRuntimeManager.patch({ environmentId }, (current) => ({
...current,
connectionState: state,
connectionError: error === undefined ? current.connectionError : error,
@@ -66,11 +153,12 @@ export async function disconnectEnvironment(
environmentSessions.delete(environmentId);
notifyEnvironmentConnectionListeners();
await session?.connection.dispose();
- remoteEnvironmentStore.getState().removeEnvironmentRuntimeState(environmentId);
+ shellSnapshotManager.invalidate({ environmentId });
+ environmentRuntimeManager.invalidate({ environmentId });
if (options?.removeSaved) {
await clearSavedConnection(environmentId);
- remoteEnvironmentStore.getState().removeSavedConnection(environmentId);
+ removeSavedConnection(environmentId);
}
}
@@ -84,9 +172,9 @@ export async function connectSavedEnvironment(
await saveConnection(connection);
}
- const store = remoteEnvironmentStore.getState();
- store.upsertSavedConnection(connection);
+ upsertSavedConnection(connection);
setEnvironmentConnectionStatus(connection.environmentId, "connecting", null);
+ shellSnapshotManager.markPending({ environmentId: connection.environmentId });
const transport = new WsTransport(
() =>
@@ -97,21 +185,19 @@ export async function connectSavedEnvironment(
}),
{
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,
- };
- });
+ environmentRuntimeManager.patch({ environmentId: 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);
@@ -145,33 +231,25 @@ export async function connectSavedEnvironment(
},
client,
applyShellEvent: (event, environmentId) => {
- remoteEnvironmentStore.getState().patchEnvironmentRuntimeState(environmentId, (runtime) => {
- if (!runtime.snapshot) {
- return runtime;
- }
-
- return {
- ...runtime,
- snapshot: applyShellStreamEvent(runtime.snapshot, event),
- };
- });
+ shellSnapshotManager.applyEvent({ environmentId }, event);
},
syncShellSnapshot: (snapshot, environmentId) => {
- remoteEnvironmentStore.getState().patchEnvironmentRuntimeState(environmentId, (runtime) => ({
+ shellSnapshotManager.syncSnapshot({ environmentId }, snapshot);
+ environmentRuntimeManager.patch({ environmentId }, (runtime) => ({
...runtime,
- snapshot,
connectionState: "ready",
connectionError: null,
}));
},
+ onShellResubscribe: (environmentId) => {
+ shellSnapshotManager.markPending({ environmentId });
+ },
applyTerminalEvent: () => undefined,
onConfigSnapshot: (serverConfig) => {
- remoteEnvironmentStore
- .getState()
- .patchEnvironmentRuntimeState(connection.environmentId, (runtime) => ({
- ...runtime,
- serverConfig,
- }));
+ environmentRuntimeManager.patch({ environmentId: connection.environmentId }, (runtime) => ({
+ ...runtime,
+ serverConfig,
+ }));
},
});
@@ -198,7 +276,7 @@ const environmentsSortOrder = Order.make(
function deriveConnectedEnvironments(
savedConnectionsById: Record,
- environmentStateById: ReturnType["environmentStateById"],
+ environmentStateById: Record,
): ReadonlyArray {
return Arr.sort(
Object.values(savedConnectionsById).map((connection) => {
@@ -216,13 +294,6 @@ function deriveConnectedEnvironments(
}
export function useRemoteEnvironmentBootstrap() {
- const setIsLoadingSavedConnection = useRemoteEnvironmentStore(
- (state) => state.setIsLoadingSavedConnection,
- );
- const replaceSavedConnections = useRemoteEnvironmentStore(
- (state) => state.replaceSavedConnections,
- );
-
useEffect(() => {
let cancelled = false;
@@ -260,34 +331,36 @@ export function useRemoteEnvironmentBootstrap() {
void session.connection.dispose();
}
environmentSessions.clear();
+ environmentRuntimeManager.invalidate();
+ shellSnapshotManager.invalidate();
notifyEnvironmentConnectionListeners();
};
- }, [replaceSavedConnections, setIsLoadingSavedConnection]);
+ }, []);
}
export function useRemoteEnvironmentState() {
- return useRemoteEnvironmentStore(
- useShallow((state) => ({
- isLoadingSavedConnection: state.isLoadingSavedConnection,
- connectionPairingUrl: state.connectionPairingUrl,
- pendingConnectionError: state.pendingConnectionError,
- savedConnectionsById: state.savedConnectionsById,
- environmentStateById: state.environmentStateById,
- })),
+ const state = useRemoteEnvironmentLocalState();
+ const environmentStateById = useEnvironmentRuntimeStates(Object.keys(state.savedConnectionsById));
+
+ return useMemo(
+ () => ({
+ ...state,
+ environmentStateById,
+ }),
+ [environmentStateById, state],
);
}
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(() => {
+ const connectionState = useMemo(() => {
if (connectedEnvironments.length === 0) {
return "idle";
}
@@ -307,14 +380,15 @@ export function useRemoteConnectionStatus() {
const connectionError = useMemo(
() =>
- firstNonNull([
- pendingConnectionError,
- selectedThreadRef
- ? environmentStateById[selectedThreadRef.environmentId]?.connectionError
- : null,
- ...connectedEnvironments.map((environment) => environment.connectionError),
- ]),
- [connectedEnvironments, environmentStateById, pendingConnectionError, selectedThreadRef],
+ pipe(
+ Arr.appendAll(
+ [pendingConnectionError],
+ Arr.map(connectedEnvironments, (environment) => environment.connectionError),
+ ),
+ Arr.findFirst((value) => value !== null),
+ Option.getOrNull,
+ ),
+ [connectedEnvironments, pendingConnectionError],
);
return {
@@ -327,31 +401,23 @@ export function useRemoteConnectionStatus() {
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();
+ clearPendingConnectionError();
await connectSavedEnvironment(connection);
clearConnectionPairingUrl();
} catch (error) {
- remoteEnvironmentStore
- .getState()
- .setPendingConnectionError(
- error instanceof Error ? error.message : "Failed to pair with the environment.",
- );
+ setPendingConnectionError(
+ error instanceof Error ? error.message : "Failed to pair with the environment.",
+ );
throw error;
}
},
- [clearConnectionPairingUrl, connectionPairingUrl],
+ [connectionPairingUrl],
);
const onUpdateEnvironment = useCallback(
@@ -359,7 +425,7 @@ export function useRemoteConnections() {
environmentId: string,
updates: { readonly label: string; readonly displayUrl: string },
) => {
- const connection = remoteEnvironmentStore.getState().savedConnectionsById[environmentId];
+ const connection = getSavedConnectionsById()[environmentId];
if (!connection) {
return;
}
@@ -371,13 +437,13 @@ export function useRemoteConnections() {
};
await saveConnection(updated);
- remoteEnvironmentStore.getState().upsertSavedConnection(updated);
+ upsertSavedConnection(updated);
},
[],
);
const onReconnectEnvironment = useCallback((environmentId: string) => {
- const connection = remoteEnvironmentStore.getState().savedConnectionsById[environmentId];
+ const connection = getSavedConnectionsById()[environmentId];
if (!connection) {
return;
}
@@ -385,7 +451,7 @@ export function useRemoteConnections() {
}, []);
const onRemoveEnvironmentPress = useCallback((environmentId: string) => {
- const connection = remoteEnvironmentStore.getState().savedConnectionsById[environmentId];
+ const connection = getSavedConnectionsById()[environmentId];
if (!connection) {
return;
}
diff --git a/apps/mobile/src/state/use-shell-snapshot.ts b/apps/mobile/src/state/use-shell-snapshot.ts
new file mode 100644
index 0000000000..a5f5c213c7
--- /dev/null
+++ b/apps/mobile/src/state/use-shell-snapshot.ts
@@ -0,0 +1,73 @@
+import * as Arr from "effect/Array";
+import * as Order from "effect/Order";
+import { useAtomValue } from "@effect/atom-react";
+import {
+ EMPTY_SHELL_SNAPSHOT_ATOM,
+ EMPTY_SHELL_SNAPSHOT_STATE,
+ createShellSnapshotManager,
+ getShellSnapshotTargetKey,
+ shellSnapshotStateAtom,
+ type ShellSnapshotState,
+} from "@t3tools/client-runtime";
+import { useCallback, useMemo, useRef, useSyncExternalStore } from "react";
+
+import { appAtomRegistry } from "./atom-registry";
+
+export const shellSnapshotManager = createShellSnapshotManager({
+ getRegistry: () => appAtomRegistry,
+});
+
+export function useShellSnapshot(environmentId: string | null): ShellSnapshotState {
+ const targetKey = getShellSnapshotTargetKey({ environmentId });
+ const state = useAtomValue(
+ targetKey !== null ? shellSnapshotStateAtom(targetKey) : EMPTY_SHELL_SNAPSHOT_ATOM,
+ );
+ return targetKey === null ? EMPTY_SHELL_SNAPSHOT_STATE : state;
+}
+
+export function useShellSnapshotStates(
+ environmentIds: ReadonlyArray,
+): Readonly> {
+ const stableEnvironmentIds = useMemo(
+ () => Arr.sort(new Set(environmentIds), Order.String),
+ [environmentIds],
+ );
+ const snapshotCacheRef = useRef>>({});
+
+ const subscribe = useCallback(
+ (onStoreChange: () => void) => {
+ const unsubs = stableEnvironmentIds.map((environmentId) =>
+ appAtomRegistry.subscribe(shellSnapshotStateAtom(environmentId), onStoreChange),
+ );
+ return () => {
+ for (const unsub of unsubs) {
+ unsub();
+ }
+ };
+ },
+ [stableEnvironmentIds],
+ );
+
+ const getSnapshot = useCallback(() => {
+ const previous = snapshotCacheRef.current;
+ let hasChanged = Object.keys(previous).length !== stableEnvironmentIds.length;
+ const next: Record = {};
+
+ for (const environmentId of stableEnvironmentIds) {
+ const snapshot = shellSnapshotManager.getSnapshot({ environmentId });
+ next[environmentId] = snapshot;
+ if (!hasChanged && previous[environmentId] !== snapshot) {
+ hasChanged = true;
+ }
+ }
+
+ if (!hasChanged) {
+ return previous;
+ }
+
+ snapshotCacheRef.current = next;
+ return next;
+ }, [stableEnvironmentIds]);
+
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+}
diff --git a/apps/mobile/src/state/use-thread-detail-subscription.ts b/apps/mobile/src/state/use-thread-detail-subscription.ts
deleted file mode 100644
index 3b126d8b41..0000000000
--- a/apps/mobile/src/state/use-thread-detail-subscription.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { useEffect } from "react";
-
-import { applyThreadDetailEvent } from "@t3tools/client-runtime";
-import { ThreadId } from "@t3tools/contracts";
-
-import { scopedThreadKey } from "../lib/scopedEntities";
-import { remoteEnvironmentStore } from "./remote-environment-store";
-import { getEnvironmentClient } from "./use-remote-environment-registry";
-
-/**
- * Subscribe to full thread detail (messages, activities, checkpoints, etc.)
- * for the given environment + thread. The subscription is torn down when the
- * component unmounts or the identifiers change.
- *
- * Received snapshots and incremental events are written into
- * `remoteEnvironmentStore.threadDetailByKey` so that `useThreadSelection` can
- * merge them over the shell stubs.
- */
-export function useThreadDetailSubscription(
- environmentId: string | null,
- threadId: string | null,
-): void {
- useEffect(() => {
- if (!environmentId || !threadId) {
- return;
- }
-
- const brandedThreadId = ThreadId.make(threadId);
- const key = scopedThreadKey(environmentId, brandedThreadId);
- let unsubscribe: (() => void) | null = null;
- let disposed = false;
-
- function attach() {
- if (disposed) {
- return;
- }
-
- const client = getEnvironmentClient(environmentId!);
- if (!client) {
- return;
- }
-
- unsubscribe = client.orchestration.subscribeThread({ threadId: brandedThreadId }, (item) => {
- if (disposed) {
- return;
- }
-
- const store = remoteEnvironmentStore.getState();
-
- if (item.kind === "snapshot") {
- store.setThreadDetail(key, item.snapshot.thread);
- return;
- }
-
- const current = store.threadDetailByKey[key];
- if (!current) {
- return;
- }
-
- const result = applyThreadDetailEvent(current, item.event);
- if (result.kind === "updated") {
- store.setThreadDetail(key, result.thread);
- } else if (result.kind === "deleted") {
- store.removeThreadDetail(key);
- }
- });
- }
-
- attach();
-
- // If the client isn't available yet (still connecting), retry when the
- // connection state changes via a simple polling interval that clears once
- // attached. This avoids coupling to the connection listener API.
- let retryTimer: ReturnType | null = null;
- if (!unsubscribe) {
- retryTimer = setInterval(() => {
- if (disposed) {
- if (retryTimer) clearInterval(retryTimer);
- return;
- }
- if (unsubscribe) {
- if (retryTimer) clearInterval(retryTimer);
- return;
- }
- attach();
- if (unsubscribe && retryTimer) {
- clearInterval(retryTimer);
- retryTimer = null;
- }
- }, 500);
- }
-
- return () => {
- disposed = true;
- if (retryTimer) clearInterval(retryTimer);
- unsubscribe?.();
- remoteEnvironmentStore.getState().removeThreadDetail(key);
- };
- }, [environmentId, threadId]);
-}
diff --git a/apps/mobile/src/state/use-thread-detail.ts b/apps/mobile/src/state/use-thread-detail.ts
new file mode 100644
index 0000000000..82b29d9da7
--- /dev/null
+++ b/apps/mobile/src/state/use-thread-detail.ts
@@ -0,0 +1,82 @@
+import { useAtomValue } from "@effect/atom-react";
+import {
+ EMPTY_THREAD_DETAIL_ATOM,
+ EMPTY_THREAD_DETAIL_STATE,
+ createThreadDetailManager,
+ getThreadDetailTargetKey,
+ threadDetailStateAtom,
+ type ThreadDetailState,
+ type ThreadDetailTarget,
+} from "@t3tools/client-runtime";
+import { useEffect, useMemo } from "react";
+
+import { derivePendingApprovals, derivePendingUserInputs } from "../lib/threadActivity";
+import { appAtomRegistry } from "./atom-registry";
+import {
+ getEnvironmentClient,
+ subscribeEnvironmentConnections,
+} from "./use-remote-environment-registry";
+import { useThreadSelection } from "./use-thread-selection";
+
+function shouldKeepThreadDetailWarm(state: ThreadDetailState): boolean {
+ const thread = state.data;
+ if (!thread || state.isDeleted) {
+ return false;
+ }
+
+ if (thread.latestTurn?.sourceProposedPlan) {
+ return true;
+ }
+
+ const sessionStatus = thread.session?.status;
+ if (sessionStatus && sessionStatus !== "idle" && sessionStatus !== "stopped") {
+ return true;
+ }
+
+ return (
+ derivePendingApprovals(thread.activities).length > 0 ||
+ derivePendingUserInputs(thread.activities).length > 0
+ );
+}
+
+export const threadDetailManager = createThreadDetailManager({
+ getRegistry: () => appAtomRegistry,
+ getClient: (environmentId) => {
+ const client = getEnvironmentClient(environmentId);
+ return client ? client.orchestration : null;
+ },
+ getClientIdentity: (environmentId) => {
+ return getEnvironmentClient(environmentId) ? environmentId : null;
+ },
+ subscribeClientChanges: subscribeEnvironmentConnections,
+ retention: {
+ idleTtlMs: 5 * 60 * 1_000,
+ maxRetainedEntries: 24,
+ shouldKeepWarm: (_target, state) => shouldKeepThreadDetailWarm(state),
+ },
+});
+
+export function useThreadDetail(target: ThreadDetailTarget): ThreadDetailState {
+ const { environmentId, threadId } = target;
+ const targetKey = getThreadDetailTargetKey(target);
+
+ useEffect(
+ () => threadDetailManager.watch({ environmentId, threadId }),
+ [environmentId, threadId],
+ );
+
+ const state = useAtomValue(
+ targetKey !== null ? threadDetailStateAtom(targetKey) : EMPTY_THREAD_DETAIL_ATOM,
+ );
+ return targetKey === null ? EMPTY_THREAD_DETAIL_STATE : state;
+}
+
+export function useSelectedThreadDetail() {
+ const { selectedThread } = useThreadSelection();
+ const state = useThreadDetail({
+ environmentId: selectedThread?.environmentId ?? null,
+ threadId: selectedThread?.id ?? null,
+ });
+
+ return useMemo(() => state.data, [state.data]);
+}
diff --git a/apps/mobile/src/state/use-thread-selection.ts b/apps/mobile/src/state/use-thread-selection.ts
index dba488701e..cee31eb29e 100644
--- a/apps/mobile/src/state/use-thread-selection.ts
+++ b/apps/mobile/src/state/use-thread-selection.ts
@@ -1,18 +1,23 @@
-import { useCallback, useEffect, useMemo } from "react";
+import { useLocalSearchParams } from "expo-router";
+import { useMemo } from "react";
-import type { SavedRemoteConnection } from "../lib/connection";
-import type { ScopedMobileProject, ScopedMobileThread } from "../lib/scopedEntities";
-import { scopedThreadKey } from "../lib/scopedEntities";
+import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
+import { EnvironmentScopedProjectShell } from "@t3tools/client-runtime";
import { useRemoteCatalog } from "./use-remote-catalog";
-import { type EnvironmentRuntimeState } from "./remote-runtime-types";
-import { useRemoteEnvironmentStore } from "./remote-environment-store";
import { useRemoteEnvironmentState } from "./use-remote-environment-registry";
-import { useThreadSelectionStore } from "./thread-selection-store";
+
+function firstRouteParam(value: string | string[] | undefined): string | null {
+ if (Array.isArray(value)) {
+ return value[0] ?? null;
+ }
+
+ return value ?? null;
+}
function deriveSelectedThread(
selectedThreadRef: { readonly environmentId: string; readonly threadId: string } | null,
- threads: ReadonlyArray,
-): ScopedMobileThread | null {
+ threads: ReadonlyArray,
+): EnvironmentScopedThreadShell | null {
if (!selectedThreadRef) {
return null;
}
@@ -27,9 +32,9 @@ function deriveSelectedThread(
}
function deriveSelectedThreadProject(
- selectedThread: ScopedMobileThread | null,
- projects: ReadonlyArray,
-): ScopedMobileProject | null {
+ selectedThread: EnvironmentScopedThreadShell | null,
+ projects: ReadonlyArray,
+): EnvironmentScopedProjectShell | null {
if (!selectedThread) {
return null;
}
@@ -46,43 +51,23 @@ function deriveSelectedThreadProject(
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 threadDetailByKey = useRemoteEnvironmentStore((state) => state.threadDetailByKey);
-
- const selectedThread = useMemo(() => {
- const shell = deriveSelectedThread(selectedThreadRef, threads);
- if (!shell) {
+ const params = useLocalSearchParams<{
+ environmentId?: string | string[];
+ threadId?: string | string[];
+ }>();
+ const selectedThreadRef = useMemo(() => {
+ const environmentId = firstRouteParam(params.environmentId);
+ const threadId = firstRouteParam(params.threadId);
+ if (!environmentId || !threadId) {
return null;
}
- const key = scopedThreadKey(shell.environmentId, shell.id);
- const detail = threadDetailByKey[key];
- if (!detail) {
- return shell;
- }
-
- return {
- ...shell,
- messages: detail.messages,
- proposedPlans: detail.proposedPlans,
- activities: detail.activities,
- checkpoints: detail.checkpoints,
- latestTurn: detail.latestTurn,
- session: detail.session,
- deletedAt: detail.deletedAt,
- };
- }, [selectedThreadRef, threadDetailByKey, threads]);
-
- useEffect(() => {
- if (!selectedThreadRef || selectedThread) {
- return;
- }
-
- clearSelectedThreadRef();
- }, [clearSelectedThreadRef, selectedThread, selectedThreadRef]);
+ return { environmentId, threadId };
+ }, [params.environmentId, params.threadId]);
+ const selectedThread = useMemo(
+ () => deriveSelectedThread(selectedThreadRef, threads),
+ [selectedThreadRef, threads],
+ );
const selectedThreadProject = useMemo(
() => deriveSelectedThreadProject(selectedThread, projects),
@@ -96,34 +81,11 @@ export function useThreadSelection() {
? (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/bun.lock b/bun.lock
index 6566fa3968..3ede93f36d 100644
--- a/bun.lock
+++ b/bun.lock
@@ -90,7 +90,6 @@
"react-native-worklets": "0.7.2",
"tailwind-merge": "^3.5.0",
"uniwind": "^1.6.2",
- "zustand": "^5.0.12",
},
"devDependencies": {
"@types/react": "~19.2.10",
diff --git a/packages/client-runtime/src/environmentConnection.ts b/packages/client-runtime/src/environmentConnection.ts
index 385a816c63..4c267479df 100644
--- a/packages/client-runtime/src/environmentConnection.ts
+++ b/packages/client-runtime/src/environmentConnection.ts
@@ -39,6 +39,7 @@ interface EnvironmentConnectionInput extends OrchestrationHandlers {
readonly refreshMetadata?: () => Promise;
readonly onConfigSnapshot?: (config: ServerConfig) => void;
readonly onWelcome?: (payload: ServerLifecycleWelcomePayload) => void;
+ readonly onShellResubscribe?: (environmentId: EnvironmentId) => void;
}
export function createEnvironmentConnection(
@@ -118,6 +119,7 @@ export function createEnvironmentConnection(
// The server will re-emit a snapshot on resubscribe, so reset the
// bootstrap gate so reconnect callers can await the fresh snapshot.
resetBootstrapGate();
+ input.onShellResubscribe?.(environmentId);
},
},
);
diff --git a/packages/client-runtime/src/environmentRuntimeState.test.ts b/packages/client-runtime/src/environmentRuntimeState.test.ts
new file mode 100644
index 0000000000..dc44e256d8
--- /dev/null
+++ b/packages/client-runtime/src/environmentRuntimeState.test.ts
@@ -0,0 +1,74 @@
+import { AtomRegistry } from "effect/unstable/reactivity";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createEnvironmentRuntimeManager } from "./environmentRuntimeState";
+
+let atomRegistry = AtomRegistry.make();
+
+function resetAtomRegistry() {
+ atomRegistry.dispose();
+ atomRegistry = AtomRegistry.make();
+}
+
+const TARGET = { environmentId: "env-local" } as const;
+
+describe("createEnvironmentRuntimeManager", () => {
+ afterEach(() => {
+ resetAtomRegistry();
+ });
+
+ it("stores state per environment", () => {
+ const manager = createEnvironmentRuntimeManager({
+ getRegistry: () => atomRegistry,
+ });
+
+ manager.setState(TARGET, {
+ connectionState: "ready",
+ connectionError: null,
+ serverConfig: null,
+ });
+
+ expect(manager.getSnapshot(TARGET)).toEqual({
+ connectionState: "ready",
+ connectionError: null,
+ serverConfig: null,
+ });
+ });
+
+ it("patches the current state", () => {
+ const manager = createEnvironmentRuntimeManager({
+ getRegistry: () => atomRegistry,
+ });
+
+ manager.patch(TARGET, (current) => ({
+ ...current,
+ connectionState: "disconnected",
+ connectionError: "Socket closed.",
+ }));
+
+ expect(manager.getSnapshot(TARGET)).toEqual({
+ connectionState: "disconnected",
+ connectionError: "Socket closed.",
+ serverConfig: null,
+ });
+ });
+
+ it("invalidates a single environment", () => {
+ const manager = createEnvironmentRuntimeManager({
+ getRegistry: () => atomRegistry,
+ });
+
+ manager.setState(TARGET, {
+ connectionState: "ready",
+ connectionError: null,
+ serverConfig: null,
+ });
+ manager.invalidate(TARGET);
+
+ expect(manager.getSnapshot(TARGET)).toEqual({
+ connectionState: "idle",
+ connectionError: null,
+ serverConfig: null,
+ });
+ });
+});
diff --git a/packages/client-runtime/src/environmentRuntimeState.ts b/packages/client-runtime/src/environmentRuntimeState.ts
new file mode 100644
index 0000000000..1a5e3b95e0
--- /dev/null
+++ b/packages/client-runtime/src/environmentRuntimeState.ts
@@ -0,0 +1,104 @@
+import type { ServerConfig as T3ServerConfig } from "@t3tools/contracts";
+import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
+
+export type EnvironmentConnectionState =
+ | "idle"
+ | "connecting"
+ | "ready"
+ | "reconnecting"
+ | "disconnected";
+
+export interface EnvironmentRuntimeState {
+ readonly connectionState: EnvironmentConnectionState;
+ readonly connectionError: string | null;
+ readonly serverConfig: T3ServerConfig | null;
+}
+
+export interface EnvironmentRuntimeTarget {
+ readonly environmentId: string | null;
+}
+
+export const EMPTY_ENVIRONMENT_RUNTIME_STATE = Object.freeze({
+ connectionState: "idle",
+ connectionError: null,
+ serverConfig: null,
+});
+
+const knownEnvironmentRuntimeKeys = new Set();
+
+export const environmentRuntimeStateAtom = Atom.family((key: string) => {
+ knownEnvironmentRuntimeKeys.add(key);
+ return Atom.make(EMPTY_ENVIRONMENT_RUNTIME_STATE).pipe(
+ Atom.keepAlive,
+ Atom.withLabel(`environment-runtime:${key}`),
+ );
+});
+
+export const EMPTY_ENVIRONMENT_RUNTIME_ATOM = Atom.make(EMPTY_ENVIRONMENT_RUNTIME_STATE).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("environment-runtime:null"),
+);
+
+export function getEnvironmentRuntimeTargetKey(target: EnvironmentRuntimeTarget): string | null {
+ return target.environmentId;
+}
+
+export interface EnvironmentRuntimeManagerConfig {
+ readonly getRegistry: () => AtomRegistry.AtomRegistry;
+}
+
+export function createEnvironmentRuntimeManager(config: EnvironmentRuntimeManagerConfig) {
+ function getSnapshot(target: EnvironmentRuntimeTarget): EnvironmentRuntimeState {
+ const targetKey = getEnvironmentRuntimeTargetKey(target);
+ if (targetKey === null) {
+ return EMPTY_ENVIRONMENT_RUNTIME_STATE;
+ }
+
+ return config.getRegistry().get(environmentRuntimeStateAtom(targetKey));
+ }
+
+ function setState(target: EnvironmentRuntimeTarget, nextState: EnvironmentRuntimeState): void {
+ const targetKey = getEnvironmentRuntimeTargetKey(target);
+ if (targetKey === null) {
+ return;
+ }
+
+ config.getRegistry().set(environmentRuntimeStateAtom(targetKey), nextState);
+ }
+
+ function patch(
+ target: EnvironmentRuntimeTarget,
+ updater: (current: EnvironmentRuntimeState) => EnvironmentRuntimeState,
+ ): void {
+ const targetKey = getEnvironmentRuntimeTargetKey(target);
+ if (targetKey === null) {
+ return;
+ }
+
+ const current = config.getRegistry().get(environmentRuntimeStateAtom(targetKey));
+ config.getRegistry().set(environmentRuntimeStateAtom(targetKey), updater(current));
+ }
+
+ function invalidate(target?: EnvironmentRuntimeTarget): void {
+ if (target) {
+ setState(target, EMPTY_ENVIRONMENT_RUNTIME_STATE);
+ return;
+ }
+
+ for (const key of knownEnvironmentRuntimeKeys) {
+ config.getRegistry().set(environmentRuntimeStateAtom(key), EMPTY_ENVIRONMENT_RUNTIME_STATE);
+ }
+ }
+
+ function reset(): void {
+ invalidate();
+ }
+
+ return {
+ getSnapshot,
+ setState,
+ patch,
+ invalidate,
+ reset,
+ };
+}
diff --git a/packages/client-runtime/src/index.ts b/packages/client-runtime/src/index.ts
index d9519f0741..905cc0e607 100644
--- a/packages/client-runtime/src/index.ts
+++ b/packages/client-runtime/src/index.ts
@@ -1,8 +1,12 @@
export * from "./knownEnvironment";
export * from "./reconnectBackoff";
export * from "./scoped";
+export * from "./environmentRuntimeState";
+export * from "./shellTypes";
export * from "./shellSnapshotReducer";
+export * from "./shellSnapshotState";
export * from "./threadDetailReducer";
+export * from "./threadDetailState";
export * from "./gitActions";
export * from "./gitActionState";
export * from "./gitBranchState";
diff --git a/packages/client-runtime/src/shellSnapshotReducer.ts b/packages/client-runtime/src/shellSnapshotReducer.ts
index abca5b3d40..a30eedb769 100644
--- a/packages/client-runtime/src/shellSnapshotReducer.ts
+++ b/packages/client-runtime/src/shellSnapshotReducer.ts
@@ -1,3 +1,4 @@
+import * as Arr from "effect/Array";
import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts";
/**
@@ -15,26 +16,26 @@ export function applyShellStreamEvent(
switch (event.kind) {
case "project-upserted": {
const projects = snapshot.projects.some((p) => p.id === event.project.id)
- ? snapshot.projects.map((p) => (p.id === event.project.id ? event.project : p))
- : [...snapshot.projects, event.project];
+ ? Arr.map(snapshot.projects, (p) => (p.id === event.project.id ? event.project : p))
+ : Arr.append(snapshot.projects, event.project);
return { ...snapshot, projects, snapshotSequence: event.sequence };
}
case "project-removed":
return {
...snapshot,
- projects: snapshot.projects.filter((p) => p.id !== event.projectId),
+ projects: Arr.filter(snapshot.projects, (p) => p.id !== event.projectId),
snapshotSequence: event.sequence,
};
case "thread-upserted": {
const threads = snapshot.threads.some((t) => t.id === event.thread.id)
- ? snapshot.threads.map((t) => (t.id === event.thread.id ? event.thread : t))
- : [...snapshot.threads, event.thread];
+ ? Arr.map(snapshot.threads, (t) => (t.id === event.thread.id ? event.thread : t))
+ : Arr.append(snapshot.threads, event.thread);
return { ...snapshot, threads, snapshotSequence: event.sequence };
}
case "thread-removed":
return {
...snapshot,
- threads: snapshot.threads.filter((t) => t.id !== event.threadId),
+ threads: Arr.filter(snapshot.threads, (t) => t.id !== event.threadId),
snapshotSequence: event.sequence,
};
default:
diff --git a/packages/client-runtime/src/shellSnapshotState.test.ts b/packages/client-runtime/src/shellSnapshotState.test.ts
new file mode 100644
index 0000000000..63137c74bd
--- /dev/null
+++ b/packages/client-runtime/src/shellSnapshotState.test.ts
@@ -0,0 +1,122 @@
+import { AtomRegistry } from "effect/unstable/reactivity";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { ProjectId, ThreadId, type OrchestrationShellSnapshot } from "@t3tools/contracts";
+
+import { createShellSnapshotManager } from "./shellSnapshotState";
+
+let atomRegistry = AtomRegistry.make();
+
+function resetAtomRegistry() {
+ atomRegistry.dispose();
+ atomRegistry = AtomRegistry.make();
+}
+
+const BASE_SNAPSHOT: OrchestrationShellSnapshot = {
+ snapshotSequence: 1,
+ updatedAt: "2026-04-01T00:00:00.000Z",
+ projects: [
+ {
+ id: ProjectId.make("project-1"),
+ title: "Project",
+ workspaceRoot: "/repo",
+ repositoryIdentity: null,
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-01T00:00:00.000Z",
+ },
+ ],
+ threads: [
+ {
+ id: ThreadId.make("thread-1"),
+ projectId: ProjectId.make("project-1"),
+ title: "Thread",
+ modelSelection: { provider: "codex", model: "gpt-5.4" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ latestTurn: null,
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-01T00:00:00.000Z",
+ archivedAt: null,
+ session: null,
+ latestUserMessageAt: null,
+ hasPendingApprovals: false,
+ hasPendingUserInput: false,
+ hasActionableProposedPlan: false,
+ },
+ ],
+};
+
+const TARGET = { environmentId: "env-local" } as const;
+
+describe("createShellSnapshotManager", () => {
+ afterEach(() => {
+ resetAtomRegistry();
+ });
+
+ it("starts pending when marked pending", () => {
+ const manager = createShellSnapshotManager({
+ getRegistry: () => atomRegistry,
+ });
+
+ manager.markPending(TARGET);
+
+ expect(manager.getSnapshot(TARGET)).toEqual({
+ data: null,
+ error: null,
+ isPending: true,
+ });
+ });
+
+ it("stores snapshots", () => {
+ const manager = createShellSnapshotManager({
+ getRegistry: () => atomRegistry,
+ });
+
+ manager.syncSnapshot(TARGET, BASE_SNAPSHOT);
+
+ expect(manager.getSnapshot(TARGET)).toEqual({
+ data: BASE_SNAPSHOT,
+ error: null,
+ isPending: false,
+ });
+ });
+
+ it("applies incremental shell events", () => {
+ const manager = createShellSnapshotManager({
+ getRegistry: () => atomRegistry,
+ });
+ const existingThread = BASE_SNAPSHOT.threads[0]!;
+
+ manager.syncSnapshot(TARGET, BASE_SNAPSHOT);
+ manager.applyEvent(TARGET, {
+ kind: "thread-upserted",
+ sequence: 2,
+ thread: {
+ ...existingThread,
+ title: "Renamed thread",
+ },
+ });
+
+ expect(manager.getSnapshot(TARGET).data?.threads[0]?.title).toBe("Renamed thread");
+ expect(manager.getSnapshot(TARGET).data?.snapshotSequence).toBe(2);
+ });
+
+ it("invalidates per environment", () => {
+ const manager = createShellSnapshotManager({
+ getRegistry: () => atomRegistry,
+ });
+
+ manager.syncSnapshot(TARGET, BASE_SNAPSHOT);
+ manager.invalidate(TARGET);
+
+ expect(manager.getSnapshot(TARGET)).toEqual({
+ data: null,
+ error: null,
+ isPending: false,
+ });
+ });
+});
diff --git a/packages/client-runtime/src/shellSnapshotState.ts b/packages/client-runtime/src/shellSnapshotState.ts
new file mode 100644
index 0000000000..166e838ab7
--- /dev/null
+++ b/packages/client-runtime/src/shellSnapshotState.ts
@@ -0,0 +1,136 @@
+import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts";
+import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
+
+import { applyShellStreamEvent } from "./shellSnapshotReducer";
+
+export interface ShellSnapshotState {
+ readonly data: OrchestrationShellSnapshot | null;
+ readonly error: string | null;
+ readonly isPending: boolean;
+}
+
+export interface ShellSnapshotTarget {
+ readonly environmentId: string | null;
+}
+
+export const EMPTY_SHELL_SNAPSHOT_STATE = Object.freeze({
+ data: null,
+ error: null,
+ isPending: false,
+});
+
+const INITIAL_SHELL_SNAPSHOT_STATE = Object.freeze({
+ data: null,
+ error: null,
+ isPending: true,
+});
+
+const knownShellSnapshotKeys = new Set();
+
+export const shellSnapshotStateAtom = Atom.family((key: string) => {
+ knownShellSnapshotKeys.add(key);
+ return Atom.make(INITIAL_SHELL_SNAPSHOT_STATE).pipe(
+ Atom.keepAlive,
+ Atom.withLabel(`shell-snapshot:${key}`),
+ );
+});
+
+export const EMPTY_SHELL_SNAPSHOT_ATOM = Atom.make(EMPTY_SHELL_SNAPSHOT_STATE).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("shell-snapshot:null"),
+);
+
+export function getShellSnapshotTargetKey(target: ShellSnapshotTarget): string | null {
+ return target.environmentId;
+}
+
+export interface ShellSnapshotManagerConfig {
+ readonly getRegistry: () => AtomRegistry.AtomRegistry;
+}
+
+export function createShellSnapshotManager(config: ShellSnapshotManagerConfig) {
+ function getSnapshot(target: ShellSnapshotTarget): ShellSnapshotState {
+ const targetKey = getShellSnapshotTargetKey(target);
+ if (targetKey === null) {
+ return EMPTY_SHELL_SNAPSHOT_STATE;
+ }
+
+ return config.getRegistry().get(shellSnapshotStateAtom(targetKey));
+ }
+
+ function setState(targetKey: string, nextState: ShellSnapshotState): void {
+ config.getRegistry().set(shellSnapshotStateAtom(targetKey), nextState);
+ }
+
+ function markPending(target: ShellSnapshotTarget): void {
+ const targetKey = getShellSnapshotTargetKey(target);
+ if (targetKey === null) {
+ return;
+ }
+
+ const current = config.getRegistry().get(shellSnapshotStateAtom(targetKey));
+ setState(targetKey, {
+ data: current.data,
+ error: null,
+ isPending: true,
+ });
+ }
+
+ function syncSnapshot(target: ShellSnapshotTarget, snapshot: OrchestrationShellSnapshot): void {
+ const targetKey = getShellSnapshotTargetKey(target);
+ if (targetKey === null) {
+ return;
+ }
+
+ setState(targetKey, {
+ data: snapshot,
+ error: null,
+ isPending: false,
+ });
+ }
+
+ function applyEvent(target: ShellSnapshotTarget, event: OrchestrationShellStreamEvent): void {
+ const targetKey = getShellSnapshotTargetKey(target);
+ if (targetKey === null) {
+ return;
+ }
+
+ const current = config.getRegistry().get(shellSnapshotStateAtom(targetKey));
+ if (current.data === null) {
+ return;
+ }
+
+ setState(targetKey, {
+ data: applyShellStreamEvent(current.data, event),
+ error: null,
+ isPending: false,
+ });
+ }
+
+ function invalidate(target?: ShellSnapshotTarget): void {
+ if (target) {
+ const targetKey = getShellSnapshotTargetKey(target);
+ if (targetKey !== null) {
+ setState(targetKey, EMPTY_SHELL_SNAPSHOT_STATE);
+ }
+ return;
+ }
+
+ for (const key of knownShellSnapshotKeys) {
+ setState(key, EMPTY_SHELL_SNAPSHOT_STATE);
+ }
+ }
+
+ function reset(): void {
+ invalidate();
+ }
+
+ return {
+ markPending,
+ syncSnapshot,
+ applyEvent,
+ getSnapshot,
+ invalidate,
+ reset,
+ };
+}
diff --git a/packages/client-runtime/src/shellTypes.ts b/packages/client-runtime/src/shellTypes.ts
new file mode 100644
index 0000000000..1d3a6e35de
--- /dev/null
+++ b/packages/client-runtime/src/shellTypes.ts
@@ -0,0 +1,38 @@
+import type {
+ EnvironmentId,
+ OrchestrationProjectShell,
+ OrchestrationShellSnapshot,
+ OrchestrationThreadShell,
+ ThreadId,
+} from "@t3tools/contracts";
+
+export interface EnvironmentScopedProjectShell extends OrchestrationProjectShell {
+ readonly environmentId: EnvironmentId;
+}
+
+export interface EnvironmentScopedThreadShell extends OrchestrationThreadShell {
+ readonly environmentId: EnvironmentId;
+}
+
+export function scopeProjectShell(
+ environmentId: EnvironmentId,
+ project: OrchestrationProjectShell,
+): EnvironmentScopedProjectShell {
+ return { ...project, environmentId };
+}
+
+export function scopeThreadShell(
+ environmentId: EnvironmentId,
+ thread: OrchestrationThreadShell,
+): EnvironmentScopedThreadShell {
+ return { ...thread, environmentId };
+}
+
+export function selectScopedThreadShell(
+ snapshot: OrchestrationShellSnapshot | null,
+ environmentId: EnvironmentId,
+ threadId: ThreadId,
+): EnvironmentScopedThreadShell | null {
+ const thread = snapshot?.threads.find((candidate) => candidate.id === threadId) ?? null;
+ return thread ? scopeThreadShell(environmentId, thread) : null;
+}
diff --git a/packages/client-runtime/src/threadDetailReducer.ts b/packages/client-runtime/src/threadDetailReducer.ts
index 260194dafa..125f39428a 100644
--- a/packages/client-runtime/src/threadDetailReducer.ts
+++ b/packages/client-runtime/src/threadDetailReducer.ts
@@ -1,3 +1,6 @@
+import { pipe } from "effect/Function";
+import * as Arr from "effect/Array";
+import * as O from "effect/Order";
import type {
MessageId,
OrchestrationCheckpointSummary,
@@ -32,6 +35,23 @@ export type ThreadDetailReducerResult =
| { readonly kind: "deleted" }
| { readonly kind: "unchanged" };
+const proposedPlanOrder = O.combine(
+ O.mapInput(O.String, (p) => p.createdAt),
+ O.mapInput(O.String, (p) => p.id),
+);
+
+const checkpointOrder = O.mapInput(
+ O.Number,
+ (cp: OrchestrationThread["checkpoints"][number]) =>
+ cp.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER,
+);
+
+const activityOrder = O.combineAll([
+ O.mapInput(O.Number, (a) => a.sequence ?? Number.MAX_SAFE_INTEGER),
+ O.mapInput(O.String, (a) => a.createdAt),
+ O.mapInput(O.String, (a) => a.id),
+]);
+
/**
* Apply a single orchestration event to an `OrchestrationThread`, returning
* the updated thread, a deletion signal, or an "unchanged" marker when the
@@ -191,7 +211,7 @@ export function applyThreadDetailEvent(
const existingMessage = thread.messages.find((entry) => entry.id === message.id);
const messages = existingMessage
- ? thread.messages.map((entry) =>
+ ? Arr.map(thread.messages, (entry) =>
entry.id !== message.id
? entry
: {
@@ -209,8 +229,8 @@ export function applyThreadDetailEvent(
: {}),
},
)
- : [...thread.messages, message];
- const cappedMessages = messages.slice(-limits.maxMessages);
+ : Arr.append(thread.messages, message);
+ const cappedMessages = Arr.takeRight(messages, limits.maxMessages);
// Update latestTurn for assistant messages bound to a turn.
const latestTurn: OrchestrationThread["latestTurn"] =
@@ -319,15 +339,14 @@ export function applyThreadDetailEvent(
// ── Proposed plans ──────────────────────────────────────────────
case "thread.proposed-plan-upserted": {
const proposedPlan = event.payload.proposedPlan;
- const proposedPlans = [
- ...thread.proposedPlans.filter((entry) => entry.id !== proposedPlan.id),
- proposedPlan,
- ]
- .toSorted(
- (left, right) =>
- left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
- )
- .slice(-limits.maxProposedPlans);
+
+ const proposedPlans = pipe(
+ thread.proposedPlans,
+ Arr.filter((entry) => entry.id !== proposedPlan.id),
+ Arr.append(proposedPlan),
+ Arr.sort(proposedPlanOrder),
+ Arr.takeRight(limits.maxProposedPlans),
+ );
return {
kind: "updated",
@@ -353,16 +372,13 @@ export function applyThreadDetailEvent(
return { kind: "unchanged" };
}
- const checkpoints = [
- ...thread.checkpoints.filter((entry) => entry.turnId !== checkpoint.turnId),
- checkpoint,
- ]
- .toSorted(
- (left, right) =>
- (left.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER) -
- (right.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER),
- )
- .slice(-limits.maxCheckpoints);
+ const checkpoints = pipe(
+ thread.checkpoints,
+ Arr.filter((entry) => entry.turnId !== checkpoint.turnId),
+ Arr.append(checkpoint),
+ Arr.sort(checkpointOrder),
+ Arr.takeRight(limits.maxCheckpoints),
+ );
const latestTurn =
thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId
@@ -384,30 +400,30 @@ export function applyThreadDetailEvent(
// ── Revert ──────────────────────────────────────────────────────
case "thread.reverted": {
- const checkpoints = thread.checkpoints
- .filter(
+ const checkpoints = pipe(
+ thread.checkpoints,
+ Arr.filter(
(entry) =>
entry.checkpointTurnCount !== undefined &&
entry.checkpointTurnCount <= event.payload.turnCount,
- )
- .toSorted(
- (left, right) =>
- (left.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER) -
- (right.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER),
- )
- .slice(-limits.maxCheckpoints);
+ ),
+ Arr.sort(checkpointOrder),
+ Arr.takeRight(limits.maxCheckpoints),
+ );
- const retainedTurnIds = new Set(checkpoints.map((entry) => entry.turnId));
- const messages = retainMessagesAfterRevert(
- thread.messages,
- retainedTurnIds,
- event.payload.turnCount,
- ).slice(-limits.maxMessages);
- const proposedPlans = thread.proposedPlans
- .filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId))
- .slice(-limits.maxProposedPlans);
- const activities = thread.activities.filter(
- (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId),
+ const retainedTurnIds = new Set(Arr.map(checkpoints, (entry) => entry.turnId));
+ const messages = pipe(
+ retainMessagesAfterRevert(thread.messages, retainedTurnIds),
+ Arr.takeRight(limits.maxMessages),
+ );
+ const proposedPlans = pipe(
+ thread.proposedPlans,
+ Arr.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)),
+ Arr.takeRight(limits.maxProposedPlans),
+ );
+ const activities = pipe(
+ thread.activities,
+ Arr.filter((activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId)),
);
const latestCheckpoint = checkpoints.at(-1) ?? null;
@@ -439,12 +455,13 @@ export function applyThreadDetailEvent(
// ── Activities ──────────────────────────────────────────────────
case "thread.activity-appended": {
- const activities = [
- ...thread.activities.filter((activity) => activity.id !== event.payload.activity.id),
- event.payload.activity,
- ]
- .toSorted(compareActivities)
- .slice(-limits.maxActivities);
+ const activities = pipe(
+ thread.activities,
+ Arr.filter((activity) => activity.id !== event.payload.activity.id),
+ Arr.append(event.payload.activity),
+ Arr.sort(activityOrder),
+ Arr.takeRight(limits.maxActivities),
+ );
return {
kind: "updated",
@@ -478,24 +495,12 @@ function checkpointStatusToTurnState(
}
}
-function compareActivities(
- left: OrchestrationThreadActivity,
- right: OrchestrationThreadActivity,
-): number {
- const sequenceLeft = left.sequence ?? Number.MAX_SAFE_INTEGER;
- const sequenceRight = right.sequence ?? Number.MAX_SAFE_INTEGER;
- if (sequenceLeft !== sequenceRight) {
- return sequenceLeft - sequenceRight;
- }
- return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
-}
-
function rebindCheckpointAssistantMessage(
checkpoints: ReadonlyArray,
turnId: TurnId,
messageId: MessageId,
): OrchestrationCheckpointSummary[] {
- return checkpoints.map((entry) =>
+ return Arr.map(checkpoints, (entry) =>
entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry,
);
}
@@ -503,11 +508,10 @@ function rebindCheckpointAssistantMessage(
function retainMessagesAfterRevert(
messages: ReadonlyArray,
retainedTurnIds: ReadonlySet,
- turnCount: number,
): OrchestrationMessage[] {
// Keep messages that belong to a retained turn, plus system messages and
// messages without a turn binding (pre-turn-0 user messages).
- return messages.filter((message) => {
+ return Arr.filter(messages, (message) => {
if (message.role === "system") {
return true;
}
diff --git a/packages/client-runtime/src/threadDetailState.test.ts b/packages/client-runtime/src/threadDetailState.test.ts
new file mode 100644
index 0000000000..a4f393b5f3
--- /dev/null
+++ b/packages/client-runtime/src/threadDetailState.test.ts
@@ -0,0 +1,317 @@
+import { AtomRegistry } from "effect/unstable/reactivity";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import {
+ EventId,
+ MessageId,
+ ProjectId,
+ ThreadId,
+ TurnId,
+ type OrchestrationThread,
+ type OrchestrationThreadStreamItem,
+} from "@t3tools/contracts";
+
+import { createThreadDetailManager, type ThreadDetailClient } from "./threadDetailState";
+
+let atomRegistry = AtomRegistry.make();
+
+function resetAtomRegistry() {
+ atomRegistry.dispose();
+ atomRegistry = AtomRegistry.make();
+}
+
+function registerListener(listeners: Set<(event: T) => void>, listener: (event: T) => void) {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+const baseEventFields = {
+ eventId: EventId.make("event-1"),
+ commandId: null,
+ causationEventId: null,
+ correlationId: null,
+ metadata: {},
+} as const;
+
+const BASE_THREAD: OrchestrationThread = {
+ id: ThreadId.make("thread-1"),
+ projectId: ProjectId.make("project-1"),
+ title: "Test Thread",
+ modelSelection: { provider: "codex", model: "gpt-5.4" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ latestTurn: null,
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-01T00:00:00.000Z",
+ archivedAt: null,
+ deletedAt: null,
+ messages: [],
+ proposedPlans: [],
+ activities: [],
+ checkpoints: [],
+ session: null,
+};
+
+const TARGET = { environmentId: "env-local", threadId: "thread-1" } as const;
+
+function createMockClient(): {
+ client: ThreadDetailClient;
+ listeners: Set<(event: OrchestrationThreadStreamItem) => void>;
+ emit: (event: OrchestrationThreadStreamItem) => void;
+} {
+ const listeners = new Set<(event: OrchestrationThreadStreamItem) => void>();
+ const client: ThreadDetailClient = {
+ subscribeThread: vi.fn((_input, listener: (event: OrchestrationThreadStreamItem) => void) =>
+ registerListener(listeners, listener),
+ ),
+ };
+
+ return {
+ client,
+ listeners,
+ emit: (event) => {
+ for (const listener of listeners) {
+ listener(event);
+ }
+ },
+ };
+}
+
+describe("createThreadDetailManager", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ resetAtomRegistry();
+ });
+
+ it("starts in a pending state when watching", () => {
+ const { client } = createMockClient();
+ const manager = createThreadDetailManager({
+ getRegistry: () => atomRegistry,
+ getClient: () => null,
+ });
+
+ manager.watch(TARGET, client);
+
+ expect(manager.getSnapshot(TARGET)).toEqual({
+ data: null,
+ error: null,
+ isPending: true,
+ isDeleted: false,
+ });
+ });
+
+ it("applies snapshots and incremental events", () => {
+ const { client, emit } = createMockClient();
+ const manager = createThreadDetailManager({
+ getRegistry: () => atomRegistry,
+ getClient: () => null,
+ });
+
+ const release = manager.watch(TARGET, client);
+
+ emit({
+ kind: "snapshot",
+ snapshot: {
+ snapshotSequence: 1,
+ thread: BASE_THREAD,
+ },
+ });
+
+ emit({
+ kind: "event",
+ event: {
+ ...baseEventFields,
+ sequence: 2,
+ occurredAt: "2026-04-01T01:00:00.000Z",
+ aggregateKind: "thread",
+ aggregateId: ThreadId.make("thread-1"),
+ type: "thread.message-sent",
+ payload: {
+ threadId: ThreadId.make("thread-1"),
+ turnId: TurnId.make("turn-1"),
+ messageId: MessageId.make("message-1"),
+ role: "assistant",
+ text: "hello",
+ streaming: false,
+ createdAt: "2026-04-01T01:00:00.000Z",
+ updatedAt: "2026-04-01T01:00:00.000Z",
+ },
+ } as any,
+ });
+
+ expect(manager.getSnapshot(TARGET)).toEqual({
+ data: {
+ ...BASE_THREAD,
+ updatedAt: "2026-04-01T01:00:00.000Z",
+ latestTurn: {
+ turnId: TurnId.make("turn-1"),
+ state: "completed",
+ requestedAt: "2026-04-01T01:00:00.000Z",
+ startedAt: "2026-04-01T01:00:00.000Z",
+ completedAt: "2026-04-01T01:00:00.000Z",
+ assistantMessageId: MessageId.make("message-1"),
+ },
+ messages: [
+ {
+ id: MessageId.make("message-1"),
+ role: "assistant",
+ text: "hello",
+ turnId: TurnId.make("turn-1"),
+ streaming: false,
+ createdAt: "2026-04-01T01:00:00.000Z",
+ updatedAt: "2026-04-01T01:00:00.000Z",
+ },
+ ],
+ },
+ error: null,
+ isPending: false,
+ isDeleted: false,
+ });
+
+ release();
+ });
+
+ it("marks threads as deleted when the stream deletes them", () => {
+ const { client, emit } = createMockClient();
+ const manager = createThreadDetailManager({
+ getRegistry: () => atomRegistry,
+ getClient: () => null,
+ });
+
+ const release = manager.watch(TARGET, client);
+
+ emit({
+ kind: "snapshot",
+ snapshot: {
+ snapshotSequence: 1,
+ thread: BASE_THREAD,
+ },
+ });
+ emit({
+ kind: "event",
+ event: {
+ ...baseEventFields,
+ sequence: 3,
+ occurredAt: "2026-04-01T01:10:00.000Z",
+ aggregateKind: "thread",
+ aggregateId: ThreadId.make("thread-1"),
+ type: "thread.deleted",
+ payload: {
+ threadId: ThreadId.make("thread-1"),
+ deletedAt: "2026-04-01T01:10:00.000Z",
+ },
+ } as any,
+ });
+
+ expect(manager.getSnapshot(TARGET)).toEqual({
+ data: null,
+ error: null,
+ isPending: false,
+ isDeleted: true,
+ });
+
+ release();
+ });
+
+ it("waits for delayed client registration when subscribeClientChanges is configured", () => {
+ const connectionListeners = new Set<() => void>();
+ const clients = new Map>();
+ const manager = createThreadDetailManager({
+ getRegistry: () => atomRegistry,
+ getClient: (environmentId) => clients.get(environmentId)?.client ?? null,
+ getClientIdentity: (environmentId) => (clients.has(environmentId) ? environmentId : null),
+ subscribeClientChanges: (listener) => {
+ connectionListeners.add(listener);
+ return () => connectionListeners.delete(listener);
+ },
+ });
+
+ const release = manager.watch(TARGET);
+ expect(manager.getSnapshot(TARGET).isPending).toBe(true);
+
+ const mock = createMockClient();
+ clients.set("env-local", mock);
+ for (const listener of connectionListeners) {
+ listener();
+ }
+
+ mock.emit({
+ kind: "snapshot",
+ snapshot: {
+ snapshotSequence: 1,
+ thread: BASE_THREAD,
+ },
+ });
+
+ expect(manager.getSnapshot(TARGET).data?.id).toBe(ThreadId.make("thread-1"));
+
+ release();
+ });
+
+ it("evicts idle subscriptions after the configured ttl", () => {
+ vi.useFakeTimers();
+ const mock = createMockClient();
+ const manager = createThreadDetailManager({
+ getRegistry: () => atomRegistry,
+ getClient: () => mock.client,
+ retention: {
+ idleTtlMs: 60_000,
+ maxRetainedEntries: 10,
+ },
+ });
+
+ const release = manager.watch(TARGET);
+ expect(mock.listeners.size).toBe(1);
+
+ release();
+ expect(mock.listeners.size).toBe(1);
+
+ vi.advanceTimersByTime(60_000);
+ expect(mock.listeners.size).toBe(0);
+ });
+
+ it("keeps non-idle threads warm when the retention policy says to", () => {
+ vi.useFakeTimers();
+ const mock = createMockClient();
+ const manager = createThreadDetailManager({
+ getRegistry: () => atomRegistry,
+ getClient: () => mock.client,
+ retention: {
+ idleTtlMs: 60_000,
+ maxRetainedEntries: 10,
+ shouldKeepWarm: (_target, state) => state.data?.session?.status === "running",
+ },
+ });
+
+ const release = manager.watch(TARGET);
+ mock.emit({
+ kind: "snapshot",
+ snapshot: {
+ snapshotSequence: 1,
+ thread: {
+ ...BASE_THREAD,
+ session: {
+ threadId: ThreadId.make("thread-1"),
+ status: "running",
+ providerName: "codex",
+ runtimeMode: "full-access",
+ activeTurnId: TurnId.make("turn-1"),
+ lastError: null,
+ updatedAt: "2026-04-01T00:10:00.000Z",
+ },
+ },
+ },
+ });
+
+ release();
+ vi.advanceTimersByTime(60_000);
+
+ expect(mock.listeners.size).toBe(1);
+ manager.reset();
+ expect(mock.listeners.size).toBe(0);
+ });
+});
diff --git a/packages/client-runtime/src/threadDetailState.ts b/packages/client-runtime/src/threadDetailState.ts
new file mode 100644
index 0000000000..606e72cf43
--- /dev/null
+++ b/packages/client-runtime/src/threadDetailState.ts
@@ -0,0 +1,433 @@
+import { pipe } from "effect/Function";
+import * as Order from "effect/Order";
+import * as Arr from "effect/Array";
+import type {
+ OrchestrationThread,
+ OrchestrationThreadStreamItem,
+ ThreadId as ThreadIdType,
+} from "@t3tools/contracts";
+import { ThreadId } from "@t3tools/contracts";
+import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
+
+import {
+ DEFAULT_THREAD_DETAIL_LIMITS,
+ applyThreadDetailEvent,
+ type ThreadDetailRetentionLimits,
+} from "./threadDetailReducer";
+import type { WsRpcClient } from "./wsRpcClient";
+
+export interface ThreadDetailState {
+ readonly data: OrchestrationThread | null;
+ readonly error: string | null;
+ readonly isPending: boolean;
+ readonly isDeleted: boolean;
+}
+
+export interface ThreadDetailTarget {
+ readonly environmentId: string | null;
+ readonly threadId: string | null;
+}
+
+export type ThreadDetailClient = Pick;
+
+export interface ThreadDetailRetentionPolicy {
+ readonly idleTtlMs: number;
+ readonly maxRetainedEntries: number;
+ readonly shouldKeepWarm?: (
+ target: { readonly environmentId: string; readonly threadId: string },
+ state: ThreadDetailState,
+ ) => boolean;
+}
+
+interface ThreadDetailEntry {
+ readonly target: {
+ readonly environmentId: string;
+ readonly threadId: string;
+ };
+ watcherCount: number;
+ retainCount: number;
+ teardown: () => void;
+ lastAccessedAt: number;
+ evictionTimeoutId: ReturnType | null;
+}
+
+const NOOP: () => void = () => undefined;
+
+function clearEntryEviction(entry: ThreadDetailEntry): void {
+ if (entry.evictionTimeoutId !== null) {
+ clearTimeout(entry.evictionTimeoutId);
+ entry.evictionTimeoutId = null;
+ }
+}
+
+export const EMPTY_THREAD_DETAIL_STATE = Object.freeze({
+ data: null,
+ error: null,
+ isPending: false,
+ isDeleted: false,
+});
+
+const INITIAL_THREAD_DETAIL_STATE = Object.freeze({
+ data: null,
+ error: null,
+ isPending: true,
+ isDeleted: false,
+});
+
+const knownThreadDetailKeys = new Set();
+
+export const threadDetailStateAtom = Atom.family((key: string) => {
+ knownThreadDetailKeys.add(key);
+ return Atom.make(INITIAL_THREAD_DETAIL_STATE).pipe(
+ Atom.keepAlive,
+ Atom.withLabel(`thread-detail:${key}`),
+ );
+});
+
+export const EMPTY_THREAD_DETAIL_ATOM = Atom.make(EMPTY_THREAD_DETAIL_STATE).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("thread-detail:null"),
+);
+
+export function getThreadDetailTargetKey(target: ThreadDetailTarget): string | null {
+ if (target.environmentId === null || target.threadId === null) {
+ return null;
+ }
+
+ return `${target.environmentId}:${target.threadId}`;
+}
+
+export interface ThreadDetailManagerConfig {
+ readonly getRegistry: () => AtomRegistry.AtomRegistry;
+ readonly getClient: (environmentId: string) => ThreadDetailClient | null;
+ readonly getClientIdentity?: (environmentId: string) => string | null;
+ readonly subscribeClientChanges?: (listener: () => void) => () => void;
+ readonly limits?: ThreadDetailRetentionLimits;
+ readonly retention?: ThreadDetailRetentionPolicy;
+}
+
+export function createThreadDetailManager(config: ThreadDetailManagerConfig) {
+ const entries = new Map();
+
+ function getSnapshot(target: ThreadDetailTarget): ThreadDetailState {
+ const targetKey = getThreadDetailTargetKey(target);
+ if (targetKey === null) {
+ return EMPTY_THREAD_DETAIL_STATE;
+ }
+
+ return config.getRegistry().get(threadDetailStateAtom(targetKey));
+ }
+
+ function setState(targetKey: string, nextState: ThreadDetailState): void {
+ config.getRegistry().set(threadDetailStateAtom(targetKey), nextState);
+ reconcileRetention(targetKey);
+ }
+
+ function markPending(targetKey: string): void {
+ const current = config.getRegistry().get(threadDetailStateAtom(targetKey));
+ setState(targetKey, {
+ ...current,
+ error: null,
+ isPending: true,
+ });
+ }
+
+ function setData(targetKey: string, thread: OrchestrationThread): void {
+ setState(targetKey, {
+ data: thread,
+ error: null,
+ isPending: false,
+ isDeleted: false,
+ });
+ }
+
+ function setDeleted(targetKey: string): void {
+ setState(targetKey, {
+ data: null,
+ error: null,
+ isPending: false,
+ isDeleted: true,
+ });
+ }
+
+ function shouldKeepWarm(entry: ThreadDetailEntry): boolean {
+ return config.retention?.shouldKeepWarm?.(entry.target, getSnapshot(entry.target)) ?? false;
+ }
+
+ function disposeEntry(targetKey: string): void {
+ const entry = entries.get(targetKey);
+ if (!entry) {
+ return;
+ }
+
+ clearEntryEviction(entry);
+ entry.teardown();
+ entries.delete(targetKey);
+ }
+
+ function evictIdleEntriesToCapacity(): void {
+ const retention = config.retention;
+ if (!retention || entries.size <= retention.maxRetainedEntries) {
+ return;
+ }
+
+ const idleEntries = pipe(
+ Arr.fromIterable(entries),
+ Arr.filter(
+ ([, entry]) =>
+ entry.watcherCount === 0 && entry.retainCount === 0 && !shouldKeepWarm(entry),
+ ),
+ Arr.sortWith(([, e]) => e.lastAccessedAt, Order.Number),
+ );
+
+ for (const [targetKey] of idleEntries) {
+ if (entries.size <= retention.maxRetainedEntries) {
+ return;
+ }
+ disposeEntry(targetKey);
+ }
+ }
+
+ function scheduleEviction(targetKey: string, entry: ThreadDetailEntry): void {
+ const retention = config.retention;
+ clearEntryEviction(entry);
+
+ if (!retention) {
+ disposeEntry(targetKey);
+ return;
+ }
+
+ if (retention.idleTtlMs <= 0) {
+ disposeEntry(targetKey);
+ return;
+ }
+
+ entry.evictionTimeoutId = setTimeout(() => {
+ const current = entries.get(targetKey);
+ if (!current) {
+ return;
+ }
+
+ current.evictionTimeoutId = null;
+ if (current.watcherCount > 0 || current.retainCount > 0 || shouldKeepWarm(current)) {
+ return;
+ }
+
+ disposeEntry(targetKey);
+ }, retention.idleTtlMs);
+ }
+
+ function reconcileRetention(targetKey: string): void {
+ const entry = entries.get(targetKey);
+ if (!entry) {
+ return;
+ }
+
+ clearEntryEviction(entry);
+ if (entry.watcherCount > 0 || entry.retainCount > 0 || shouldKeepWarm(entry)) {
+ return;
+ }
+
+ scheduleEviction(targetKey, entry);
+ evictIdleEntriesToCapacity();
+ }
+
+ function applyStreamItem(
+ targetKey: string,
+ item: OrchestrationThreadStreamItem,
+ threadId: ThreadIdType,
+ ): void {
+ if (item.kind === "snapshot") {
+ setData(targetKey, item.snapshot.thread);
+ return;
+ }
+
+ const current = getSnapshot({
+ environmentId: entries.get(targetKey)?.target.environmentId ?? null,
+ threadId,
+ }).data;
+
+ if (current === null) {
+ if (item.event.type === "thread.deleted") {
+ setDeleted(targetKey);
+ }
+ return;
+ }
+
+ const result = applyThreadDetailEvent(
+ current,
+ item.event,
+ config.limits ?? DEFAULT_THREAD_DETAIL_LIMITS,
+ );
+
+ if (result.kind === "updated") {
+ setData(targetKey, result.thread);
+ return;
+ }
+
+ if (result.kind === "deleted") {
+ setDeleted(targetKey);
+ }
+ }
+
+ function subscribeStream(
+ targetKey: string,
+ target: { readonly environmentId: string; readonly threadId: string },
+ client: ThreadDetailClient,
+ ): () => void {
+ markPending(targetKey);
+ return client.subscribeThread(
+ { threadId: ThreadId.make(target.threadId) },
+ (item) => applyStreamItem(targetKey, item, ThreadId.make(target.threadId)),
+ {
+ onResubscribe: () => markPending(targetKey),
+ },
+ );
+ }
+
+ function createDynamicSubscription(
+ targetKey: string,
+ target: { readonly environmentId: string; readonly threadId: string },
+ ): () => void {
+ let currentIdentity: string | null = null;
+ let currentUnsub = NOOP;
+
+ const sync = () => {
+ const client = config.getClient(target.environmentId);
+ const identity = client
+ ? (config.getClientIdentity?.(target.environmentId) ?? target.environmentId)
+ : null;
+
+ if (!client || identity === null) {
+ if (currentIdentity !== null) {
+ currentUnsub();
+ currentUnsub = NOOP;
+ currentIdentity = null;
+ }
+ markPending(targetKey);
+ return;
+ }
+
+ if (currentIdentity === identity) {
+ return;
+ }
+
+ currentUnsub();
+ currentIdentity = identity;
+ currentUnsub = subscribeStream(targetKey, target, client);
+ };
+
+ const unsubChanges = config.subscribeClientChanges!(sync);
+ sync();
+
+ return () => {
+ unsubChanges();
+ currentUnsub();
+ };
+ }
+
+ function acquire(
+ target: ThreadDetailTarget,
+ kind: "watcher" | "retain",
+ client?: ThreadDetailClient,
+ ): () => void {
+ const targetKey = getThreadDetailTargetKey(target);
+ if (targetKey === null || target.environmentId === null || target.threadId === null) {
+ return NOOP;
+ }
+
+ const existing = entries.get(targetKey);
+ if (existing) {
+ clearEntryEviction(existing);
+ existing.lastAccessedAt = Date.now();
+ if (kind === "watcher") {
+ existing.watcherCount += 1;
+ } else {
+ existing.retainCount += 1;
+ }
+ return () => release(targetKey, kind);
+ }
+
+ let teardown: () => void;
+ const resolvedTarget = {
+ environmentId: target.environmentId,
+ threadId: target.threadId,
+ };
+
+ if (client) {
+ teardown = subscribeStream(targetKey, resolvedTarget, client);
+ } else if (config.subscribeClientChanges) {
+ teardown = createDynamicSubscription(targetKey, resolvedTarget);
+ } else {
+ const resolved = config.getClient(target.environmentId);
+ if (!resolved) {
+ return NOOP;
+ }
+ teardown = subscribeStream(targetKey, resolvedTarget, resolved);
+ }
+
+ entries.set(targetKey, {
+ target: resolvedTarget,
+ watcherCount: kind === "watcher" ? 1 : 0,
+ retainCount: kind === "retain" ? 1 : 0,
+ teardown,
+ lastAccessedAt: Date.now(),
+ evictionTimeoutId: null,
+ });
+ evictIdleEntriesToCapacity();
+ return () => release(targetKey, kind);
+ }
+
+ function release(targetKey: string, kind: "watcher" | "retain"): void {
+ const entry = entries.get(targetKey);
+ if (!entry) {
+ return;
+ }
+
+ if (kind === "watcher") {
+ entry.watcherCount = Math.max(0, entry.watcherCount - 1);
+ } else {
+ entry.retainCount = Math.max(0, entry.retainCount - 1);
+ }
+ entry.lastAccessedAt = Date.now();
+ reconcileRetention(targetKey);
+ }
+
+ function watch(target: ThreadDetailTarget, client?: ThreadDetailClient): () => void {
+ return acquire(target, "watcher", client);
+ }
+
+ function retain(target: ThreadDetailTarget, client?: ThreadDetailClient): () => void {
+ return acquire(target, "retain", client);
+ }
+
+ function invalidate(target?: ThreadDetailTarget): void {
+ if (target) {
+ const targetKey = getThreadDetailTargetKey(target);
+ if (targetKey !== null) {
+ disposeEntry(targetKey);
+ config.getRegistry().set(threadDetailStateAtom(targetKey), EMPTY_THREAD_DETAIL_STATE);
+ }
+ return;
+ }
+
+ for (const targetKey of entries.keys()) {
+ disposeEntry(targetKey);
+ }
+ for (const key of knownThreadDetailKeys) {
+ config.getRegistry().set(threadDetailStateAtom(key), EMPTY_THREAD_DETAIL_STATE);
+ }
+ }
+
+ function reset(): void {
+ invalidate();
+ }
+
+ return {
+ watch,
+ retain,
+ getSnapshot,
+ invalidate,
+ reset,
+ };
+}