Update ESLint configuration, remove unused dependencies, and refactor connection handling
- Added "apps/mobile/uniwind-types.d.ts" to .oxlintrc.json ignore list. - Disabled the "unicorn/no-array-sort" rule in ESLint. - Removed "zustand" from bun.lock and package.json. - Refactored connection handling in various components, including the introduction of ConnectionSheetButton and updates to connection-related functions. - Updated type imports to use EnvironmentScoped types across multiple files. - Cleaned up unused imports and improved code structure in several components.
This commit is contained in:
1 parent
6d1ef7603d
commit
131f25ce8f
73 files changed
+2426
-1859
No files matched your search
+3
-1
@@ -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"
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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 (
|
||||
<AppAtomRegistryProvider>
|
||||
<RegistryContext value={appAtomRegistry}>
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<KeyboardProvider statusBarTranslucent>
|
||||
<SafeAreaProvider>
|
||||
@@ -99,6 +99,6 @@ export default function RootLayout() {
|
||||
</SafeAreaProvider>
|
||||
</KeyboardProvider>
|
||||
</GestureHandlerRootView>
|
||||
</AppAtomRegistryProvider>
|
||||
</RegistryContext>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<Pressable
|
||||
onPress={props.onPress}
|
||||
disabled={props.disabled}
|
||||
className={
|
||||
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"
|
||||
}
|
||||
style={{ backgroundColor }}
|
||||
>
|
||||
<Pressable onPress={props.onPress} disabled={props.disabled} className={containerClassName}>
|
||||
{props.iconNode ? (
|
||||
<View className="h-4 w-4 items-center justify-center">{props.iconNode}</View>
|
||||
) : props.icon ? (
|
||||
<SymbolView name={props.icon} size={16} tintColor={iconTintColor} type="monochrome" />
|
||||
) : null}
|
||||
{props.label ? (
|
||||
<Text className="text-center text-[12px] font-t3-bold" style={{ color: labelColor }}>
|
||||
{props.label}
|
||||
</Text>
|
||||
) : null}
|
||||
{props.label ? <Text className={labelClassName}>{props.label}</Text> : null}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
-35
@@ -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)",
|
||||
@@ -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;
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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() {
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
Camera permission is required to scan a QR code.
|
||||
</Text>
|
||||
<SheetButton
|
||||
<ConnectionSheetButton
|
||||
compact
|
||||
icon="camera"
|
||||
label="Allow camera"
|
||||
@@ -236,7 +233,7 @@ export function NewConnectionRouteScreen() {
|
||||
|
||||
{connectionError ? <ErrorBanner message={connectionError} /> : null}
|
||||
|
||||
<SheetButton
|
||||
<ConnectionSheetButton
|
||||
icon="plus"
|
||||
label={
|
||||
isSubmitting || connectionState === "connecting" ? "Pairing..." : "Add backend"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { RemoteClientConnectionState } from "../../lib/remoteClient";
|
||||
import type { RemoteClientConnectionState } from "../../lib/connection";
|
||||
|
||||
export function connectionTone(state: RemoteClientConnectionState): StatusTone {
|
||||
switch (state) {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { extractPairingUrlFromQrPayload } from "./pairingQr";
|
||||
import { extractPairingUrlFromQrPayload } from "./pairing";
|
||||
|
||||
describe("extractPairingUrlFromQrPayload", () => {
|
||||
it("trims raw pairing urls from qr payloads", () => {
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<string, string> = {
|
||||
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 (
|
||||
<>
|
||||
<Stack.Screen
|
||||
@@ -138,7 +130,6 @@ export function HomeRouteScreen() {
|
||||
savedConnectionsById={savedConnectionsById}
|
||||
searchQuery={searchQuery}
|
||||
onSelectThread={(thread) => {
|
||||
onSelectThread(thread);
|
||||
router.push(buildThreadRoutePath(thread));
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -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<ScopedMobileProject>;
|
||||
readonly threads: ReadonlyArray<ScopedMobileThread>;
|
||||
readonly projects: ReadonlyArray<EnvironmentScopedProjectShell>;
|
||||
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
|
||||
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
|
||||
readonly searchQuery: string;
|
||||
readonly onSelectThread: (thread: ScopedMobileThread) => void;
|
||||
readonly onSelectThread: (thread: EnvironmentScopedThreadShell) => void;
|
||||
}
|
||||
|
||||
interface ProjectGroup {
|
||||
readonly key: string;
|
||||
readonly project: ScopedMobileProject;
|
||||
readonly threads: ReadonlyArray<ScopedMobileThread>;
|
||||
readonly project: EnvironmentScopedProjectShell;
|
||||
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
|
||||
}
|
||||
|
||||
/* ─── 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<string> {
|
||||
/* ─── 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<ReadonlyArray<ProjectGroup>>(() => {
|
||||
const byProject = new Map<string, ScopedMobileThread[]>();
|
||||
const byProject = new Map<string, EnvironmentScopedThreadShell[]>();
|
||||
for (const thread of filteredThreads) {
|
||||
const key = scopedProjectKey(thread.environmentId, thread.projectId);
|
||||
const existing = byProject.get(key);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<void>;
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
@@ -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),
|
||||
}}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
maxWidth: isSplitLayout ? 960 : undefined,
|
||||
alignSelf: isSplitLayout ? "center" : undefined,
|
||||
width: "100%",
|
||||
}}
|
||||
>
|
||||
<View className="w-full">
|
||||
{/* Input surface — the pill/card IS the glass element */}
|
||||
<ComposerSurface
|
||||
isDarkMode={isDarkMode}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
ModelSelection,
|
||||
OrchestrationThread,
|
||||
ProviderApprovalDecision,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
@@ -17,7 +18,6 @@ import { runOnJS } from "react-native-reanimated";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import type { MobileLayoutVariant } from "../../lib/mobileLayout";
|
||||
import type { ScopedMobileThread } from "../../lib/scopedEntities";
|
||||
import type {
|
||||
PendingApproval,
|
||||
PendingUserInput,
|
||||
@@ -34,7 +34,7 @@ import {
|
||||
import { ThreadFeed } from "./ThreadFeed";
|
||||
|
||||
export interface ThreadDetailScreenProps {
|
||||
readonly selectedThread: ScopedMobileThread;
|
||||
readonly selectedThread: OrchestrationThread;
|
||||
readonly screenTone: StatusTone;
|
||||
readonly connectionError: string | null;
|
||||
readonly httpBaseUrl: string | null;
|
||||
@@ -264,7 +264,6 @@ export function ThreadDetailScreen(props: ThreadDetailScreenProps) {
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
layoutVariant={layoutVariant}
|
||||
bottomInset={composerBottomInset}
|
||||
onChangeDraftMessage={props.onChangeDraftMessage}
|
||||
onPickDraftImages={props.onPickDraftImages}
|
||||
|
||||
@@ -100,9 +100,7 @@ function buildActivityRows(
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
|
||||
|
||||
interface MarkdownStyleSets {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
readonly user: Record<string, any>;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
readonly assistant: Record<string, any>;
|
||||
}
|
||||
|
||||
|
||||
@@ -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<ScopedMobileProject>;
|
||||
readonly threads: ReadonlyArray<ScopedMobileThread>;
|
||||
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<void>;
|
||||
readonly onCreateThread: (project: ScopedMobileProject) => Promise<void>;
|
||||
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<typeof SymbolView>["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 (
|
||||
<Pressable
|
||||
className={cn(
|
||||
"min-h-[50px] flex-1 flex-row items-center justify-center gap-2 rounded-[16px] px-3 py-3",
|
||||
props.primary ? "bg-primary" : "border border-secondary-border bg-secondary",
|
||||
)}
|
||||
onPress={props.onPress}
|
||||
>
|
||||
<SymbolView
|
||||
name={props.icon}
|
||||
size={18}
|
||||
tintColor={tintColor}
|
||||
type="monochrome"
|
||||
weight="medium"
|
||||
/>
|
||||
<Text
|
||||
className={cn(
|
||||
"text-[13px] font-t3-bold uppercase",
|
||||
props.primary ? "text-primary-foreground" : "text-secondary-foreground",
|
||||
)}
|
||||
style={{ letterSpacing: 0.9 }}
|
||||
>
|
||||
{props.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function StatCard(props: {
|
||||
readonly label: string;
|
||||
readonly value: string;
|
||||
readonly icon: React.ComponentProps<typeof SymbolView>["name"];
|
||||
}) {
|
||||
const foregroundSecondary = useThemeColor("--color-foreground-secondary");
|
||||
|
||||
return (
|
||||
<View className="flex-1 gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<SymbolView name={props.icon} size={15} tintColor={foregroundSecondary} type="monochrome" />
|
||||
<Text
|
||||
className="text-[11px] font-t3-bold uppercase text-foreground-secondary"
|
||||
style={{ letterSpacing: 1 }}
|
||||
>
|
||||
{props.label}
|
||||
</Text>
|
||||
</View>
|
||||
<Text className="text-[28px] font-t3-bold text-foreground">{props.value}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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<RNView>(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 (
|
||||
<Pressable
|
||||
ref={containerRef}
|
||||
className="gap-3 rounded-[18px] border px-4 py-4"
|
||||
style={{
|
||||
backgroundColor,
|
||||
borderColor: resolvedBorderColor,
|
||||
opacity: props.hidden ? 0 : 1,
|
||||
}}
|
||||
onPress={() => {
|
||||
containerRef.current?.measureInWindow((x, y, width, height) => {
|
||||
if (width > 0 && height > 0) {
|
||||
props.onPress({ x, y, width, height });
|
||||
return;
|
||||
}
|
||||
props.onPress(null);
|
||||
});
|
||||
}}
|
||||
>
|
||||
<View className="flex-row items-start justify-between gap-3">
|
||||
<View className="flex-1 gap-2">
|
||||
<Text className="text-[17px] font-t3-bold text-foreground">{props.thread.title}</Text>
|
||||
<Text className="text-[13px] font-medium leading-[19px] text-foreground-secondary">
|
||||
{lastConversationLine(props.thread)}
|
||||
</Text>
|
||||
</View>
|
||||
<StatusPill {...tone} />
|
||||
</View>
|
||||
|
||||
<Text
|
||||
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
|
||||
style={{ letterSpacing: 0.9 }}
|
||||
>
|
||||
{props.thread.environmentLabel} · {props.thread.modelSelection.provider} ·{" "}
|
||||
{relativeTime(props.thread.updatedAt ?? props.thread.createdAt)}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function ProjectSection(props: {
|
||||
readonly project: ScopedMobileProject;
|
||||
readonly threads: ReadonlyArray<ScopedMobileThread>;
|
||||
readonly hiddenThreadKey?: string | null;
|
||||
readonly selectedThreadKey?: string | null;
|
||||
readonly onCreateThread: (project: ScopedMobileProject) => Promise<void>;
|
||||
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 (
|
||||
<View className="gap-3 rounded-[22px] border border-border px-4 py-4">
|
||||
<View className="flex-row items-start justify-between gap-3">
|
||||
<View className="flex-1 gap-1">
|
||||
<Text className="text-[15px] font-t3-bold text-foreground">
|
||||
{props.project.environmentLabel}
|
||||
</Text>
|
||||
<Text className="text-[12px] font-medium leading-[18px] text-foreground-secondary">
|
||||
{props.project.workspaceRoot}
|
||||
</Text>
|
||||
</View>
|
||||
<Pressable
|
||||
className="rounded-full bg-subtle px-3 py-2"
|
||||
onPress={() => void props.onCreateThread(props.project)}
|
||||
>
|
||||
<Text
|
||||
className="text-[11px] font-t3-bold uppercase text-foreground"
|
||||
style={{ letterSpacing: 0.9 }}
|
||||
>
|
||||
New thread
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
{props.threads.length === 0 ? (
|
||||
<EmptyState
|
||||
title="No threads yet"
|
||||
detail="Start a thread in this environment to bring it onto the mobile board."
|
||||
/>
|
||||
) : (
|
||||
<View className="gap-3">
|
||||
{visibleThreads.map((thread) => (
|
||||
<ThreadRow
|
||||
key={scopedThreadKey(thread.environmentId, thread.id)}
|
||||
thread={thread}
|
||||
hidden={props.hiddenThreadKey === scopedThreadKey(thread.environmentId, thread.id)}
|
||||
selected={
|
||||
props.selectedThreadKey === scopedThreadKey(thread.environmentId, thread.id)
|
||||
}
|
||||
onPress={(sourceFrame) => props.onSelectThread(thread, sourceFrame)}
|
||||
/>
|
||||
))}
|
||||
|
||||
{hiddenCount > 0 ? (
|
||||
<Pressable
|
||||
className="items-center rounded-[16px] bg-separator px-3 py-3"
|
||||
onPress={() => setExpanded((current) => !current)}
|
||||
>
|
||||
<Text
|
||||
className="text-[11px] font-t3-bold uppercase text-foreground-secondary"
|
||||
style={{ letterSpacing: 1 }}
|
||||
>
|
||||
{expanded ? "Show less" : `Show ${hiddenCount} more`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateThreadModal(props: {
|
||||
readonly group: MobileRepositoryGroup | null;
|
||||
readonly visible: boolean;
|
||||
readonly onClose: () => void;
|
||||
readonly onSelectProject: (project: ScopedMobileProject) => Promise<void>;
|
||||
}) {
|
||||
if (!props.group) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal transparent animationType="slide" visible={props.visible} onRequestClose={props.onClose}>
|
||||
<View className="flex-1 justify-end bg-backdrop">
|
||||
<View className="gap-4 rounded-t-[28px] bg-screen px-5 pb-8 pt-5">
|
||||
<View className="gap-1">
|
||||
<Text className="text-[22px] font-t3-bold text-foreground">
|
||||
New thread in {props.group.title}
|
||||
</Text>
|
||||
<Text className="text-[13px] font-medium leading-[19px] text-foreground-secondary">
|
||||
Choose which environment should own the new thread.
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{ gap: 12 }}>
|
||||
{props.group.projects.map(({ project, threads }) => (
|
||||
<Pressable
|
||||
key={project.environmentId + project.id}
|
||||
className="gap-2 rounded-[20px] border border-border bg-card px-4 py-4"
|
||||
onPress={() => {
|
||||
void props.onSelectProject(project).then(props.onClose);
|
||||
}}
|
||||
>
|
||||
<View className="flex-row items-start justify-between gap-3">
|
||||
<View className="flex-1 gap-1">
|
||||
<Text className="text-[16px] font-t3-bold text-foreground">
|
||||
{project.environmentLabel}
|
||||
</Text>
|
||||
<Text className="text-[12px] font-medium leading-[18px] text-foreground-secondary">
|
||||
{project.workspaceRoot}
|
||||
</Text>
|
||||
</View>
|
||||
<View className="rounded-full bg-subtle px-3 py-2">
|
||||
<Text
|
||||
className="text-[11px] font-t3-bold uppercase text-foreground"
|
||||
style={{ letterSpacing: 0.9 }}
|
||||
>
|
||||
{threads.length} thread{threads.length === 1 ? "" : "s"}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</Pressable>
|
||||
))}
|
||||
</ScrollView>
|
||||
|
||||
<ActionButton icon="xmark" label="Close" onPress={props.onClose} />
|
||||
</View>
|
||||
</View>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
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<MobileRepositoryGroup | null>(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<void> => {
|
||||
if (refreshing) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRefreshing(true);
|
||||
try {
|
||||
await refreshThreads();
|
||||
} finally {
|
||||
setRefreshing(false);
|
||||
}
|
||||
}, [refreshThreads, refreshing]);
|
||||
|
||||
return (
|
||||
<View
|
||||
className="flex-1 bg-screen"
|
||||
style={{
|
||||
borderRadius: isSplitLayout ? 32 : 0,
|
||||
borderWidth: isSplitLayout ? 1 : 0,
|
||||
borderColor: panelBorderColor,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<View className="absolute inset-x-0 top-0 z-20">
|
||||
<GlassSafeAreaView leftSlot={props.showBrandWordmark ? <BrandMark compact /> : null} />
|
||||
</View>
|
||||
|
||||
<ScrollView
|
||||
className="flex-1"
|
||||
showsVerticalScrollIndicator={false}
|
||||
refreshControl={
|
||||
<RefreshControl refreshing={refreshing} onRefresh={() => void handleRefresh()} />
|
||||
}
|
||||
contentContainerStyle={{
|
||||
gap: 16,
|
||||
paddingHorizontal: contentHorizontalPadding,
|
||||
paddingBottom: isSplitLayout ? 32 : 48,
|
||||
paddingTop: isSplitLayout ? 112 : 124,
|
||||
}}
|
||||
>
|
||||
<Animated.View
|
||||
entering={FadeInDown.duration(260)}
|
||||
layout={LinearTransition.springify().damping(18).stiffness(180)}
|
||||
className="gap-4 rounded-[26px] border border-border bg-card-translucent px-4 py-4"
|
||||
>
|
||||
<View className="flex-row items-start justify-between gap-4">
|
||||
<View className="flex-1 gap-2">
|
||||
<Text
|
||||
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
|
||||
style={{ letterSpacing: 1.1 }}
|
||||
>
|
||||
{props.heroTitle}
|
||||
</Text>
|
||||
<Text className="text-[26px] font-t3-bold text-foreground">
|
||||
{isSplitLayout ? "Native workspace" : "Repo board"}
|
||||
</Text>
|
||||
<Text className="text-[13px] font-medium leading-[19px] text-foreground-secondary">
|
||||
{isSplitLayout
|
||||
? "Keep your repositories visible while you move between active threads."
|
||||
: "Your connected repositories, grouped by identity across environments."}
|
||||
</Text>
|
||||
</View>
|
||||
<ConnectionStatusDot state={props.connectionState} pulse={props.connectionPulse} />
|
||||
</View>
|
||||
|
||||
<View className="flex-row gap-3">
|
||||
<StatCard label="Repos" value={String(repositoryGroups.length)} icon="shippingbox" />
|
||||
<StatCard
|
||||
label="Threads"
|
||||
value={String(props.threads.length)}
|
||||
icon="square.stack.3d.up"
|
||||
/>
|
||||
<StatCard label="Envs" value={String(props.connectedEnvironmentCount)} icon="link" />
|
||||
</View>
|
||||
|
||||
<View className="flex-row gap-3">
|
||||
<ActionButton
|
||||
icon={props.hasClient ? "link" : "iphone"}
|
||||
label={props.hasClient ? "Edit link" : "Connect"}
|
||||
primary
|
||||
onPress={props.onOpenConnectionEditor}
|
||||
/>
|
||||
<ActionButton
|
||||
icon="arrow.clockwise"
|
||||
label="Refresh"
|
||||
onPress={() => void handleRefresh()}
|
||||
/>
|
||||
</View>
|
||||
</Animated.View>
|
||||
|
||||
{repositoryGroups.length === 0 ? (
|
||||
<EmptyState
|
||||
title={props.hasClient ? "No repositories yet" : "No connection yet"}
|
||||
detail={
|
||||
props.hasClient
|
||||
? "Connect an environment with indexed projects, then refresh this screen."
|
||||
: "Connect this phone to a T3 environment to load repositories and threads."
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{repositoryGroups.map((group, index) => (
|
||||
<Animated.View
|
||||
key={group.key}
|
||||
entering={FadeInDown.duration(260).delay(40 * Math.min(index, 6))}
|
||||
layout={LinearTransition.springify().damping(18).stiffness(180)}
|
||||
className="gap-4 rounded-[26px] border border-border bg-card-translucent px-4 py-4"
|
||||
>
|
||||
<View className="flex-row items-start justify-between gap-4">
|
||||
<View className="flex-1 gap-1">
|
||||
<Text className="text-[22px] font-t3-bold text-foreground">{group.title}</Text>
|
||||
{group.subtitle ? (
|
||||
<Text className="text-[13px] font-medium leading-[19px] text-foreground-secondary">
|
||||
{group.subtitle}
|
||||
</Text>
|
||||
) : null}
|
||||
<Text
|
||||
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
|
||||
style={{ letterSpacing: 0.9 }}
|
||||
>
|
||||
{group.projectCount} environment{group.projectCount === 1 ? "" : "s"} ·{" "}
|
||||
{group.threadCount} active thread{group.threadCount === 1 ? "" : "s"}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<Pressable
|
||||
className="rounded-full bg-primary px-3 py-2"
|
||||
onPress={() => {
|
||||
if (group.projects.length === 1) {
|
||||
void props.onCreateThread(group.projects[0]!.project);
|
||||
return;
|
||||
}
|
||||
setCreateTarget(group);
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
className="text-[11px] font-t3-bold uppercase text-primary-foreground"
|
||||
style={{ letterSpacing: 0.9 }}
|
||||
>
|
||||
New thread
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<View className="gap-3">
|
||||
{group.projects.map(({ project, threads }) => (
|
||||
<ProjectSection
|
||||
key={project.environmentId + project.id}
|
||||
project={project}
|
||||
threads={threads}
|
||||
hiddenThreadKey={props.hiddenThreadKey}
|
||||
selectedThreadKey={props.selectedThreadKey}
|
||||
onCreateThread={props.onCreateThread}
|
||||
onSelectThread={props.onSelectThread}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</Animated.View>
|
||||
))}
|
||||
</ScrollView>
|
||||
|
||||
<CreateThreadModal
|
||||
group={createTarget}
|
||||
visible={createTarget !== null}
|
||||
onClose={() => setCreateTarget(null)}
|
||||
onSelectProject={props.onCreateThread}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -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<ScopedMobileProject>;
|
||||
readonly threads: ReadonlyArray<ScopedMobileThread>;
|
||||
readonly projects: ReadonlyArray<EnvironmentScopedProjectShell>;
|
||||
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
|
||||
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],
|
||||
);
|
||||
|
||||
@@ -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 <LoadingScreen message="Opening thread…" />;
|
||||
}
|
||||
|
||||
if (!routeThread) {
|
||||
if (!selectedThread) {
|
||||
const stillHydrating =
|
||||
isLoadingSavedConnection ||
|
||||
connectionState === "connecting" ||
|
||||
connectionState === "reconnecting";
|
||||
routeConnectionState === "connecting" ||
|
||||
routeConnectionState === "reconnecting";
|
||||
|
||||
if (stillHydrating) {
|
||||
return <LoadingScreen message="Opening thread…" />;
|
||||
@@ -149,16 +128,24 @@ export function ThreadRouteScreen() {
|
||||
);
|
||||
}
|
||||
|
||||
if (!selectedMatchesRoute || !selectedThread) {
|
||||
if (!selectedThreadDetail) {
|
||||
return <LoadingScreen message="Opening thread…" />;
|
||||
}
|
||||
|
||||
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}
|
||||
</RNText>
|
||||
<RNText
|
||||
numberOfLines={1}
|
||||
@@ -209,7 +196,7 @@ export function ThreadRouteScreen() {
|
||||
/>
|
||||
|
||||
<ThreadGitControls
|
||||
currentBranch={selectedThread.branch}
|
||||
currentBranch={selectedThreadDetail.branch}
|
||||
gitStatus={gitStatus.data}
|
||||
gitOperationLabel={gitState.gitOperationLabel}
|
||||
onPull={gitActions.onPullSelectedThreadBranch}
|
||||
@@ -218,9 +205,9 @@ export function ThreadRouteScreen() {
|
||||
|
||||
<View className="flex-1 bg-screen">
|
||||
<ThreadDetailScreen
|
||||
selectedThread={selectedThread}
|
||||
screenTone={connectionTone(connectionState)}
|
||||
connectionError={connectionError}
|
||||
selectedThread={selectedThreadDetail}
|
||||
screenTone={connectionTone(routeConnectionState)}
|
||||
connectionError={routeConnectionError}
|
||||
httpBaseUrl={selectedEnvironmentConnection?.httpBaseUrl ?? null}
|
||||
bearerToken={selectedEnvironmentConnection?.bearerToken ?? null}
|
||||
selectedThreadFeed={composer.selectedThreadFeed}
|
||||
@@ -233,7 +220,7 @@ export function ThreadRouteScreen() {
|
||||
respondingUserInputId={commands.respondingUserInputId}
|
||||
draftMessage={composer.draftMessage}
|
||||
draftAttachments={composer.draftAttachments}
|
||||
connectionStateLabel={connectionState}
|
||||
connectionStateLabel={routeConnectionState}
|
||||
activeThreadBusy={composer.activeThreadBusy}
|
||||
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
|
||||
selectedThreadQueueCount={composer.selectedThreadQueueCount}
|
||||
@@ -263,7 +250,6 @@ export function ThreadRouteScreen() {
|
||||
selectedThreadKey={selectedThreadKey}
|
||||
onClose={() => setDrawerVisible(false)}
|
||||
onSelectThread={(thread) => {
|
||||
onSelectThread(thread);
|
||||
router.replace(buildThreadRoutePath(thread));
|
||||
}}
|
||||
onStartNewTask={() => router.push("/new")}
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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<ModelOption>;
|
||||
readonly selectedModel: ModelSelection | null;
|
||||
readonly selectedModelOption: ModelOption | null;
|
||||
readonly providerGroups: ReadonlyArray<ProviderGroup>;
|
||||
readonly filteredBranches: ReadonlyArray<GitBranch>;
|
||||
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<NewTaskFlowContextValue | null>(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<NewTaskFlowContextValue>(
|
||||
() => ({
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+33
-33
@@ -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<string>) => {
|
||||
@@ -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<ReadonlyArray<GitBranch>> => {
|
||||
async (project: EnvironmentScopedProjectShell): Promise<ReadonlyArray<GitBranch>> => {
|
||||
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 {
|
||||
+22
-41
@@ -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<ApprovalRequestId | null>(null);
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<ApprovalRequestId | null>(
|
||||
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,
|
||||
+20
-18
@@ -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 <T>(
|
||||
operation: (input: {
|
||||
readonly thread: ScopedMobileThread;
|
||||
readonly project: ScopedMobileProject;
|
||||
readonly thread: EnvironmentScopedThreadShell;
|
||||
readonly project: EnvironmentScopedProjectShell;
|
||||
readonly cwd: string;
|
||||
}) => Promise<T>,
|
||||
): Promise<T | null> => {
|
||||
@@ -124,7 +126,7 @@ export function useSelectedThreadGitActions() {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[selectedThread, selectedThreadProject, setPendingConnectionError],
|
||||
[selectedThread, selectedThreadProject],
|
||||
);
|
||||
|
||||
const refreshSelectedThreadBranches = useCallback(async (): Promise<ReadonlyArray<GitBranch>> => {
|
||||
@@ -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?: {
|
||||
+3
-3
@@ -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();
|
||||
+219
-105
@@ -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<Record<string, string>>({}).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("mobile:thread-composer:draft-message"),
|
||||
);
|
||||
|
||||
const draftAttachmentsByThreadKeyAtom = Atom.make<
|
||||
Record<string, ReadonlyArray<DraftComposerImageAttachment>>
|
||||
>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:thread-composer:draft-attachments"));
|
||||
|
||||
const dispatchingQueuedMessageIdAtom = Atom.make<MessageId | null>(null).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("mobile:thread-composer:dispatching-message-id"),
|
||||
);
|
||||
|
||||
const queuedMessagesByThreadKeyAtom = Atom.make<Record<string, ReadonlyArray<QueuedThreadMessage>>>(
|
||||
{},
|
||||
).pipe(Atom.keepAlive, Atom.withLabel("mobile:thread-composer:queued-messages"));
|
||||
|
||||
const userInputDraftsByRequestKeyAtom = Atom.make<
|
||||
Record<string, Record<string, PendingUserInputDraftAnswer>>
|
||||
>({}).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<DraftComposerImageAttachment>,
|
||||
): 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<string, ReadonlyArray<QueuedThreadMessage>>;
|
||||
readonly threads: ReadonlyArray<ScopedMobileThread>;
|
||||
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
|
||||
readonly environments: ReadonlyArray<ConnectedEnvironmentSummary>;
|
||||
readonly sendQueuedMessage: (message: QueuedThreadMessage) => Promise<void>;
|
||||
}) {
|
||||
@@ -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<string>) => {
|
||||
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 {
|
||||
@@ -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<SavedRemoteConnection> {
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
export type RemoteClientConnectionState =
|
||||
| "idle"
|
||||
| "connecting"
|
||||
| "ready"
|
||||
| "reconnecting"
|
||||
| "disconnected";
|
||||
@@ -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<ScopedMobileProject> &
|
||||
Pick<ScopedMobileProject, "environmentId" | "environmentLabel" | "id" | "title">,
|
||||
): ScopedMobileProject {
|
||||
input: Partial<EnvironmentScopedProjectShell> &
|
||||
Pick<EnvironmentScopedProjectShell, "environmentId" | "id" | "title">,
|
||||
): EnvironmentScopedProjectShell {
|
||||
return {
|
||||
workspaceRoot: `/workspaces/${input.id}`,
|
||||
repositoryIdentity: null,
|
||||
@@ -21,12 +24,12 @@ function makeProject(
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<ScopedMobileThread> &
|
||||
input: Partial<EnvironmentScopedThreadShell> &
|
||||
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",
|
||||
}),
|
||||
|
||||
@@ -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<ScopedMobileThread>;
|
||||
readonly project: EnvironmentScopedProjectShell;
|
||||
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
|
||||
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<ScopedMobileThread>,
|
||||
project: EnvironmentScopedProjectShell,
|
||||
threads: ReadonlyArray<EnvironmentScopedThreadShell>,
|
||||
): string {
|
||||
const latestThread = threads[0];
|
||||
return latestThread?.updatedAt ?? latestThread?.createdAt ?? project.updatedAt;
|
||||
}
|
||||
|
||||
export function groupProjectsByRepository(input: {
|
||||
readonly projects: ReadonlyArray<ScopedMobileProject>;
|
||||
readonly threads: ReadonlyArray<ScopedMobileThread>;
|
||||
readonly projects: ReadonlyArray<EnvironmentScopedProjectShell>;
|
||||
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
|
||||
}): ReadonlyArray<MobileRepositoryGroup> {
|
||||
const threadsByProjectKey = new Map<string, ScopedMobileThread[]>();
|
||||
const threadsByProjectKey = new Map<string, EnvironmentScopedThreadShell[]>();
|
||||
|
||||
for (const thread of input.threads) {
|
||||
const key = scopedProjectKey(thread.environmentId, thread.projectId);
|
||||
|
||||
@@ -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<SelectedThreadRef, "environmentId" | "threadId">
|
||||
| Pick<ScopedMobileThread, "environmentId" | "id">;
|
||||
| Pick<EnvironmentScopedThreadShell, "environmentId" | "id">;
|
||||
|
||||
export function buildThreadRoutePath(input: ThreadRouteInput): string {
|
||||
const environmentId = input.environmentId;
|
||||
|
||||
@@ -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}`;
|
||||
}
|
||||
@@ -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<ReadonlyArray<SavedRemoteC
|
||||
const parsed = JSON.parse(raw) as {
|
||||
readonly connections?: ReadonlyArray<SavedRemoteConnection>;
|
||||
};
|
||||
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<ReadonlyArray<SavedRemoteC
|
||||
export async function saveConnection(connection: SavedRemoteConnection): Promise<void> {
|
||||
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<void> {
|
||||
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 }));
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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()}`;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
export const appAtomRegistry = AtomRegistry.make();
|
||||
@@ -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 <RegistryContext.Provider value={appAtomRegistry}>{children}</RegistryContext.Provider>;
|
||||
}
|
||||
@@ -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<string, SavedRemoteConnection>;
|
||||
readonly environmentStateById: Record<string, EnvironmentRuntimeState>;
|
||||
/** Full thread detail keyed by `${environmentId}:${threadId}`. */
|
||||
readonly threadDetailByKey: Record<string, OrchestrationThread>;
|
||||
|
||||
readonly setIsLoadingSavedConnection: (value: boolean) => void;
|
||||
readonly setConnectionPairingUrl: (pairingUrl: string) => void;
|
||||
readonly clearConnectionPairingUrl: () => void;
|
||||
readonly setPendingConnectionError: (message: string | null) => void;
|
||||
readonly clearPendingConnectionError: () => void;
|
||||
readonly replaceSavedConnections: (connections: Record<string, SavedRemoteConnection>) => void;
|
||||
readonly upsertSavedConnection: (connection: SavedRemoteConnection) => void;
|
||||
readonly removeSavedConnection: (environmentId: string) => void;
|
||||
readonly patchEnvironmentRuntimeState: (
|
||||
environmentId: string,
|
||||
updater: (current: EnvironmentRuntimeState) => EnvironmentRuntimeState,
|
||||
) => void;
|
||||
readonly removeEnvironmentRuntimeState: (environmentId: string) => void;
|
||||
readonly setThreadDetail: (key: string, thread: OrchestrationThread) => void;
|
||||
readonly removeThreadDetail: (key: string) => void;
|
||||
}
|
||||
|
||||
export const remoteEnvironmentStore = createStore<RemoteEnvironmentStoreState>()((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<T>(
|
||||
selector: (state: RemoteEnvironmentStoreState) => T,
|
||||
): T {
|
||||
return useStore(remoteEnvironmentStore, selector);
|
||||
}
|
||||
@@ -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<T>(values: ReadonlyArray<T | null | undefined>): T | null {
|
||||
for (const value of values) {
|
||||
if (value !== null && value !== undefined) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function deriveThreadTitleFromPrompt(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return "New thread";
|
||||
}
|
||||
|
||||
const compact = trimmed.replace(/\s+/g, " ");
|
||||
return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
|
||||
}
|
||||
|
||||
export function deriveOverallConnectionState(
|
||||
environments: ReadonlyArray<ConnectedEnvironmentSummary>,
|
||||
): RemoteClientConnectionState {
|
||||
if (environments.length === 0) {
|
||||
return "idle";
|
||||
}
|
||||
if (environments.some((environment) => environment.connectionState === "ready")) {
|
||||
return "ready";
|
||||
}
|
||||
if (environments.some((environment) => environment.connectionState === "reconnecting")) {
|
||||
return "reconnecting";
|
||||
}
|
||||
if (environments.some((environment) => environment.connectionState === "connecting")) {
|
||||
return "connecting";
|
||||
}
|
||||
return "disconnected";
|
||||
}
|
||||
@@ -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<ThreadApprovalStoreState>()((set) => ({
|
||||
respondingApprovalId: null,
|
||||
beginRespondingApproval: (requestId) => set({ respondingApprovalId: requestId }),
|
||||
finishRespondingApproval: (requestId) =>
|
||||
set((state) => ({
|
||||
respondingApprovalId:
|
||||
state.respondingApprovalId === requestId ? null : state.respondingApprovalId,
|
||||
})),
|
||||
}));
|
||||
|
||||
export function useThreadApprovalStore<T>(selector: (state: ThreadApprovalStoreState) => T): T {
|
||||
return useStore(threadApprovalStore, selector);
|
||||
}
|
||||
@@ -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<string, string>;
|
||||
readonly draftAttachmentsByThreadKey: Record<string, ReadonlyArray<DraftComposerImageAttachment>>;
|
||||
readonly dispatchingQueuedMessageId: MessageId | null;
|
||||
readonly queuedMessagesByThreadKey: Record<string, ReadonlyArray<QueuedThreadMessage>>;
|
||||
|
||||
readonly setNowTick: (tick: number) => void;
|
||||
readonly setDraftMessage: (threadKey: string, value: string) => void;
|
||||
readonly appendDraftAttachments: (
|
||||
threadKey: string,
|
||||
attachments: ReadonlyArray<DraftComposerImageAttachment>,
|
||||
) => void;
|
||||
readonly appendDraftMessage: (threadKey: string, value: string) => void;
|
||||
readonly clearDraft: (threadKey: string) => void;
|
||||
readonly removeDraftImage: (threadKey: string, imageId: string) => void;
|
||||
readonly beginDispatchingQueuedMessage: (queuedMessageId: 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<ThreadComposerStoreState>()((set) => ({
|
||||
nowTick: Date.now(),
|
||||
draftMessageByThreadKey: {},
|
||||
draftAttachmentsByThreadKey: {},
|
||||
dispatchingQueuedMessageId: null,
|
||||
queuedMessagesByThreadKey: {},
|
||||
|
||||
setNowTick: (tick) => set({ nowTick: tick }),
|
||||
setDraftMessage: (threadKey, value) =>
|
||||
set((state) => ({
|
||||
draftMessageByThreadKey: {
|
||||
...state.draftMessageByThreadKey,
|
||||
[threadKey]: value,
|
||||
},
|
||||
})),
|
||||
appendDraftAttachments: (threadKey, attachments) =>
|
||||
set((state) => ({
|
||||
draftAttachmentsByThreadKey: {
|
||||
...state.draftAttachmentsByThreadKey,
|
||||
[threadKey]: [...(state.draftAttachmentsByThreadKey[threadKey] ?? []), ...attachments],
|
||||
},
|
||||
})),
|
||||
appendDraftMessage: (threadKey, value) =>
|
||||
set((state) => ({
|
||||
draftMessageByThreadKey: {
|
||||
...state.draftMessageByThreadKey,
|
||||
[threadKey]: `${state.draftMessageByThreadKey[threadKey] ?? ""}${value}`,
|
||||
},
|
||||
})),
|
||||
clearDraft: (threadKey) =>
|
||||
set((state) => ({
|
||||
draftMessageByThreadKey: {
|
||||
...state.draftMessageByThreadKey,
|
||||
[threadKey]: "",
|
||||
},
|
||||
draftAttachmentsByThreadKey: {
|
||||
...state.draftAttachmentsByThreadKey,
|
||||
[threadKey]: [],
|
||||
},
|
||||
})),
|
||||
removeDraftImage: (threadKey, imageId) =>
|
||||
set((state) => ({
|
||||
draftAttachmentsByThreadKey: {
|
||||
...state.draftAttachmentsByThreadKey,
|
||||
[threadKey]: (state.draftAttachmentsByThreadKey[threadKey] ?? []).filter(
|
||||
(image) => image.id !== imageId,
|
||||
),
|
||||
},
|
||||
})),
|
||||
beginDispatchingQueuedMessage: (queuedMessageId) =>
|
||||
set({ dispatchingQueuedMessageId: queuedMessageId }),
|
||||
finishDispatchingQueuedMessage: (queuedMessageId) =>
|
||||
set((state) => ({
|
||||
dispatchingQueuedMessageId:
|
||||
state.dispatchingQueuedMessageId === queuedMessageId
|
||||
? null
|
||||
: state.dispatchingQueuedMessageId,
|
||||
})),
|
||||
enqueueQueuedMessage: (message) =>
|
||||
set((state) => {
|
||||
const threadKey = scopedThreadKey(message.environmentId, message.threadId);
|
||||
return {
|
||||
queuedMessagesByThreadKey: {
|
||||
...state.queuedMessagesByThreadKey,
|
||||
[threadKey]: [...(state.queuedMessagesByThreadKey[threadKey] ?? []), message],
|
||||
},
|
||||
};
|
||||
}),
|
||||
removeQueuedMessage: (environmentId, threadId, queuedMessageId) =>
|
||||
set((state) => {
|
||||
const threadKey = scopedThreadKey(environmentId, threadId);
|
||||
const existing = state.queuedMessagesByThreadKey[threadKey];
|
||||
if (!existing) {
|
||||
return state;
|
||||
}
|
||||
const nextQueue = existing.filter((entry) => entry.messageId !== queuedMessageId);
|
||||
const next = { ...state.queuedMessagesByThreadKey };
|
||||
if (nextQueue.length === 0) {
|
||||
delete next[threadKey];
|
||||
} else {
|
||||
next[threadKey] = nextQueue;
|
||||
}
|
||||
return { queuedMessagesByThreadKey: next };
|
||||
}),
|
||||
}));
|
||||
|
||||
export function useThreadComposerStore<T>(selector: (state: ThreadComposerStoreState) => T): T {
|
||||
return useStore(threadComposerStore, selector);
|
||||
}
|
||||
@@ -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<ThreadSelectionStoreState>()((set) => ({
|
||||
selectedThreadRef: null,
|
||||
selectThreadRef: (threadRef) => set({ selectedThreadRef: threadRef }),
|
||||
clearSelectedThreadRef: () => set({ selectedThreadRef: null }),
|
||||
}));
|
||||
|
||||
export function useThreadSelectionStore<T>(selector: (state: ThreadSelectionStoreState) => T): T {
|
||||
return useStore(threadSelectionStore, selector);
|
||||
}
|
||||
@@ -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<string, Record<string, PendingUserInputDraftAnswer>>;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
|
||||
readonly setUserInputDraftOption: (requestKey: string, questionId: string, label: string) => void;
|
||||
readonly setUserInputDraftCustomAnswer: (
|
||||
requestKey: string,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
readonly beginRespondingUserInput: (requestId: ApprovalRequestId) => void;
|
||||
readonly finishRespondingUserInput: (requestId: ApprovalRequestId) => void;
|
||||
}
|
||||
|
||||
export const threadUserInputStore = createStore<ThreadUserInputStoreState>()((set) => ({
|
||||
userInputDraftsByRequestKey: {},
|
||||
respondingUserInputId: null,
|
||||
|
||||
setUserInputDraftOption: (requestKey, questionId, label) =>
|
||||
set((state) => ({
|
||||
userInputDraftsByRequestKey: {
|
||||
...state.userInputDraftsByRequestKey,
|
||||
[requestKey]: {
|
||||
...state.userInputDraftsByRequestKey[requestKey],
|
||||
[questionId]: {
|
||||
selectedOptionLabel: label,
|
||||
},
|
||||
},
|
||||
},
|
||||
})),
|
||||
setUserInputDraftCustomAnswer: (requestKey, questionId, customAnswer) =>
|
||||
set((state) => ({
|
||||
userInputDraftsByRequestKey: {
|
||||
...state.userInputDraftsByRequestKey,
|
||||
[requestKey]: {
|
||||
...state.userInputDraftsByRequestKey[requestKey],
|
||||
[questionId]: setPendingUserInputCustomAnswer(
|
||||
state.userInputDraftsByRequestKey[requestKey]?.[questionId],
|
||||
customAnswer,
|
||||
),
|
||||
},
|
||||
},
|
||||
})),
|
||||
beginRespondingUserInput: (requestId) => set({ respondingUserInputId: requestId }),
|
||||
finishRespondingUserInput: (requestId) =>
|
||||
set((state) => ({
|
||||
respondingUserInputId:
|
||||
state.respondingUserInputId === requestId ? null : state.respondingUserInputId,
|
||||
})),
|
||||
}));
|
||||
|
||||
export function useThreadUserInputStore<T>(selector: (state: ThreadUserInputStoreState) => T): T {
|
||||
return useStore(threadUserInputStore, selector);
|
||||
}
|
||||
@@ -0,0 +1,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<string>,
|
||||
): Readonly<Record<string, EnvironmentRuntimeState>> {
|
||||
const stableEnvironmentIds = useMemo(
|
||||
() => Arr.sort(new Set(environmentIds), Order.String),
|
||||
[environmentIds],
|
||||
);
|
||||
const snapshotCacheRef = useRef<Readonly<Record<string, EnvironmentRuntimeState>>>({});
|
||||
|
||||
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<string, EnvironmentRuntimeState> = {};
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -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({
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<ScopedMobileProject>(
|
||||
const projectsSortOrder = Order.make<EnvironmentScopedProjectShell>(
|
||||
(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<ScopedMobileThread>(
|
||||
const threadsSortOrder = Order.make<EnvironmentScopedThreadShell>(
|
||||
(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<ConnectedEnvironmentSummary>,
|
||||
): 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<ReadonlyArray<ScopedMobileProject>>(
|
||||
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<ReadonlyArray<ScopedMobileThread>>(
|
||||
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<Readonly<Record<string, T3ServerConfig | null>>>(
|
||||
const serverConfigByEnvironmentId = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
Object.entries(environmentStateById).map(([environmentId, runtime]) => [
|
||||
@@ -79,7 +90,7 @@ export function useRemoteCatalog() {
|
||||
[environmentStateById],
|
||||
);
|
||||
|
||||
const overallConnectionState = useMemo<RemoteClientConnectionState>(
|
||||
const overallConnectionState = useMemo(
|
||||
() => deriveOverallConnectionState(connectedEnvironments),
|
||||
[connectedEnvironments],
|
||||
);
|
||||
|
||||
@@ -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<string, EnvironmentSession>();
|
||||
const environmentConnectionListeners = new Set<() => void>();
|
||||
|
||||
interface RemoteEnvironmentLocalState {
|
||||
readonly isLoadingSavedConnection: boolean;
|
||||
readonly connectionPairingUrl: string;
|
||||
readonly pendingConnectionError: string | null;
|
||||
readonly savedConnectionsById: Record<string, SavedRemoteConnection>;
|
||||
}
|
||||
|
||||
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<string | null>(null).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("mobile:pending-connection-error"),
|
||||
);
|
||||
|
||||
const savedConnectionsByIdAtom = Atom.make<Record<string, SavedRemoteConnection>>({}).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("mobile:saved-connections"),
|
||||
);
|
||||
|
||||
function notifyEnvironmentConnectionListeners() {
|
||||
for (const listener of environmentConnectionListeners) listener();
|
||||
}
|
||||
|
||||
function getSavedConnectionsById(): Record<string, SavedRemoteConnection> {
|
||||
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<string, SavedRemoteConnection>): 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<ConnectedEnvironmentSummary>(
|
||||
|
||||
function deriveConnectedEnvironments(
|
||||
savedConnectionsById: Record<string, SavedRemoteConnection>,
|
||||
environmentStateById: ReturnType<typeof remoteEnvironmentStore.getState>["environmentStateById"],
|
||||
environmentStateById: Record<EnvironmentId, EnvironmentRuntimeState>,
|
||||
): ReadonlyArray<ConnectedEnvironmentSummary> {
|
||||
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<RemoteClientConnectionState>(() => {
|
||||
const connectionState = useMemo<EnvironmentConnectionState>(() => {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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<string>,
|
||||
): Readonly<Record<string, ShellSnapshotState>> {
|
||||
const stableEnvironmentIds = useMemo(
|
||||
() => Arr.sort(new Set(environmentIds), Order.String),
|
||||
[environmentIds],
|
||||
);
|
||||
const snapshotCacheRef = useRef<Readonly<Record<string, ShellSnapshotState>>>({});
|
||||
|
||||
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<string, ShellSnapshotState> = {};
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -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<typeof setInterval> | null = null;
|
||||
if (!unsubscribe) {
|
||||
retryTimer = setInterval(() => {
|
||||
if (disposed) {
|
||||
if (retryTimer) clearInterval(retryTimer);
|
||||
return;
|
||||
}
|
||||
if (unsubscribe) {
|
||||
if (retryTimer) clearInterval(retryTimer);
|
||||
return;
|
||||
}
|
||||
attach();
|
||||
if (unsubscribe && retryTimer) {
|
||||
clearInterval(retryTimer);
|
||||
retryTimer = null;
|
||||
}
|
||||
}, 500);
|
||||
}
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
if (retryTimer) clearInterval(retryTimer);
|
||||
unsubscribe?.();
|
||||
remoteEnvironmentStore.getState().removeThreadDetail(key);
|
||||
};
|
||||
}, [environmentId, threadId]);
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -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>,
|
||||
): ScopedMobileThread | null {
|
||||
threads: ReadonlyArray<EnvironmentScopedThreadShell>,
|
||||
): EnvironmentScopedThreadShell | null {
|
||||
if (!selectedThreadRef) {
|
||||
return null;
|
||||
}
|
||||
@@ -27,9 +32,9 @@ function deriveSelectedThread(
|
||||
}
|
||||
|
||||
function deriveSelectedThreadProject(
|
||||
selectedThread: ScopedMobileThread | null,
|
||||
projects: ReadonlyArray<ScopedMobileProject>,
|
||||
): ScopedMobileProject | null {
|
||||
selectedThread: EnvironmentScopedThreadShell | null,
|
||||
projects: ReadonlyArray<EnvironmentScopedProjectShell>,
|
||||
): 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<string, SavedRemoteConnection>;
|
||||
readonly environmentStateById: Record<string, EnvironmentRuntimeState>;
|
||||
};
|
||||
@@ -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",
|
||||
|
||||
@@ -39,6 +39,7 @@ interface EnvironmentConnectionInput extends OrchestrationHandlers {
|
||||
readonly refreshMetadata?: () => Promise<void>;
|
||||
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);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<EnvironmentRuntimeState>({
|
||||
connectionState: "idle",
|
||||
connectionError: null,
|
||||
serverConfig: null,
|
||||
});
|
||||
|
||||
const knownEnvironmentRuntimeKeys = new Set<string>();
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -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";
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<ShellSnapshotState>({
|
||||
data: null,
|
||||
error: null,
|
||||
isPending: false,
|
||||
});
|
||||
|
||||
const INITIAL_SHELL_SNAPSHOT_STATE = Object.freeze<ShellSnapshotState>({
|
||||
data: null,
|
||||
error: null,
|
||||
isPending: true,
|
||||
});
|
||||
|
||||
const knownShellSnapshotKeys = new Set<string>();
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<OrchestrationThread["proposedPlans"][number]>(
|
||||
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<OrchestrationThreadActivity>([
|
||||
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<OrchestrationCheckpointSummary>,
|
||||
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<OrchestrationMessage>,
|
||||
retainedTurnIds: ReadonlySet<string>,
|
||||
turnCount: number,
|
||||
): OrchestrationMessage[] {
|
||||
// Keep messages that belong to a retained turn, plus system messages and
|
||||
// messages without a turn binding (pre-turn-0 user messages).
|
||||
return messages.filter((message) => {
|
||||
return Arr.filter(messages, (message) => {
|
||||
if (message.role === "system") {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -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<T>(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<string, ReturnType<typeof createMockClient>>();
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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<WsRpcClient["orchestration"], "subscribeThread">;
|
||||
|
||||
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<typeof setTimeout> | 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<ThreadDetailState>({
|
||||
data: null,
|
||||
error: null,
|
||||
isPending: false,
|
||||
isDeleted: false,
|
||||
});
|
||||
|
||||
const INITIAL_THREAD_DETAIL_STATE = Object.freeze<ThreadDetailState>({
|
||||
data: null,
|
||||
error: null,
|
||||
isPending: true,
|
||||
isDeleted: false,
|
||||
});
|
||||
|
||||
const knownThreadDetailKeys = new Set<string>();
|
||||
|
||||
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<string, ThreadDetailEntry>();
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user