Refine mobile environment connection flows
- Rename backends to environments across mobile UI - Add richer loading and empty states for connections, home, and new task flows - Improve review section loading handling and terminal keyboard layout
This commit is contained in:
1 parent
89672b3d89
commit
2632c9251e
27 files changed
+723
-176
No files matched your search
@@ -33,7 +33,7 @@ export default function ConnectionsRouteScreen() {
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "Backends",
|
||||
title: "Environments",
|
||||
headerRight: () => (
|
||||
<Link href="/connections/new" asChild>
|
||||
<Pressable className="h-10 w-10 items-center justify-center rounded-full bg-primary active:opacity-70">
|
||||
@@ -53,10 +53,10 @@ export default function ConnectionsRouteScreen() {
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 16,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
}}
|
||||
>
|
||||
{hasEnvironments ? (
|
||||
@@ -92,7 +92,7 @@ export default function ConnectionsRouteScreen() {
|
||||
/>
|
||||
</View>
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
No backends connected yet.{"\n"}Tap{" "}
|
||||
No environments connected yet.{"\n"}Tap{" "}
|
||||
<Text className="font-t3-bold text-foreground">+</Text> to add one.
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
@@ -16,11 +16,10 @@ import { buildPairingUrl, parsePairingUrl } from "../../features/connection/pair
|
||||
|
||||
export default function ConnectionsNewRouteScreen() {
|
||||
const {
|
||||
connectionError,
|
||||
connectionPairingUrl,
|
||||
connectionState,
|
||||
onChangeConnectionPairingUrl,
|
||||
onConnectPress,
|
||||
pairingConnectionError,
|
||||
} = useRemoteConnections();
|
||||
const router = useRouter();
|
||||
const params = useLocalSearchParams<{ mode?: string }>();
|
||||
@@ -35,8 +34,7 @@ export default function ConnectionsNewRouteScreen() {
|
||||
const textColor = useThemeColor("--color-icon");
|
||||
const placeholderColor = useThemeColor("--color-placeholder");
|
||||
|
||||
const connectDisabled =
|
||||
isSubmitting || connectionState === "connecting" || hostInput.trim().length === 0;
|
||||
const connectDisabled = isSubmitting || hostInput.trim().length === 0;
|
||||
|
||||
useEffect(() => {
|
||||
const { host, code } = parsePairingUrl(connectionPairingUrl);
|
||||
@@ -45,10 +43,10 @@ export default function ConnectionsNewRouteScreen() {
|
||||
}, [connectionPairingUrl]);
|
||||
|
||||
useEffect(() => {
|
||||
if (connectionError) {
|
||||
if (pairingConnectionError) {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}, [connectionError]);
|
||||
}, [pairingConnectionError]);
|
||||
|
||||
const handleHostChange = useCallback((value: string) => {
|
||||
setHostInput(value);
|
||||
@@ -72,7 +70,10 @@ export default function ConnectionsNewRouteScreen() {
|
||||
return;
|
||||
}
|
||||
|
||||
Alert.alert("Camera access needed", "Allow camera access to scan a backend pairing QR code.");
|
||||
Alert.alert(
|
||||
"Camera access needed",
|
||||
"Allow camera access to scan an environment pairing QR code.",
|
||||
);
|
||||
}, [cameraPermission?.granted, requestCameraPermission]);
|
||||
|
||||
const closeScanner = useCallback(() => {
|
||||
@@ -126,7 +127,7 @@ export default function ConnectionsNewRouteScreen() {
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: showScanner ? "Scan QR Code" : "Add Backend",
|
||||
title: showScanner ? "Scan QR Code" : "Add Environment",
|
||||
headerRight: () => (
|
||||
<Pressable
|
||||
className="h-10 w-10 items-center justify-center rounded-full border border-border bg-secondary"
|
||||
@@ -154,10 +155,10 @@ export default function ConnectionsNewRouteScreen() {
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 16,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
}}
|
||||
>
|
||||
<View collapsable={false} className="gap-5">
|
||||
@@ -231,13 +232,11 @@ export default function ConnectionsNewRouteScreen() {
|
||||
/>
|
||||
</View>
|
||||
|
||||
{connectionError ? <ErrorBanner message={connectionError} /> : null}
|
||||
{pairingConnectionError ? <ErrorBanner message={pairingConnectionError} /> : null}
|
||||
|
||||
<ConnectionSheetButton
|
||||
icon="plus"
|
||||
label={
|
||||
isSubmitting || connectionState === "connecting" ? "Pairing..." : "Add backend"
|
||||
}
|
||||
label={isSubmitting ? "Pairing..." : "Add environment"}
|
||||
disabled={connectDisabled}
|
||||
tone="primary"
|
||||
onPress={() => {
|
||||
|
||||
@@ -1,23 +1,50 @@
|
||||
import { Stack, useRouter } from "expo-router";
|
||||
import { useState } from "react";
|
||||
import { Text as RNText, View, useColorScheme } from "react-native";
|
||||
import { type ComponentProps, useState } from "react";
|
||||
import { Pressable, Text as RNText, View, useColorScheme } from "react-native";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
import { buildThreadRoutePath } from "../lib/routes";
|
||||
import { useRemoteCatalog } from "../state/use-remote-catalog";
|
||||
import { useRemoteEnvironmentState } from "../state/use-remote-environment-registry";
|
||||
import { HomeScreen } from "../features/home/HomeScreen";
|
||||
import type { RemoteCatalogState } from "../state/use-remote-catalog";
|
||||
|
||||
function resolveHeaderStatus(state: RemoteCatalogState): {
|
||||
readonly icon: ComponentProps<typeof SymbolView>["name"];
|
||||
readonly color: string;
|
||||
readonly label: string;
|
||||
} {
|
||||
if (state.isLoadingSavedConnections) {
|
||||
return { icon: "hourglass", color: "#737373", label: "Loading environments" };
|
||||
}
|
||||
if (state.connectionError) {
|
||||
return { icon: "exclamationmark.triangle.fill", color: "#ef4444", label: "Environment error" };
|
||||
}
|
||||
if (state.connectionState === "ready") {
|
||||
return { icon: "checkmark.circle.fill", color: "#22c55e", label: "Environment online" };
|
||||
}
|
||||
if (state.connectionState === "connecting" || state.connectionState === "reconnecting") {
|
||||
return {
|
||||
icon: "arrow.triangle.2.circlepath",
|
||||
color: "#f59e0b",
|
||||
label: "Environment connecting",
|
||||
};
|
||||
}
|
||||
return { icon: "wifi.slash", color: "#ef4444", label: "Environment offline" };
|
||||
}
|
||||
|
||||
/* ─── Route screen ───────────────────────────────────────────────────── */
|
||||
|
||||
export default function HomeRouteScreen() {
|
||||
const { projects, threads } = useRemoteCatalog();
|
||||
const { projects, state: catalogState, threads } = useRemoteCatalog();
|
||||
const { savedConnectionsById } = useRemoteEnvironmentState();
|
||||
const router = useRouter();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
|
||||
const isDark = useColorScheme() === "dark";
|
||||
const iconColor = String(useThemeColor("--color-icon"));
|
||||
const status = resolveHeaderStatus(catalogState);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -78,11 +105,15 @@ export default function HomeRouteScreen() {
|
||||
</Stack.Toolbar>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Button
|
||||
icon="network"
|
||||
onPress={() => router.push("/connections")}
|
||||
separateBackground
|
||||
/>
|
||||
<Stack.Toolbar.View hidesSharedBackground>
|
||||
<Pressable
|
||||
accessibilityLabel={status.label}
|
||||
className="h-11 w-11 items-center justify-center rounded-full bg-card active:opacity-70"
|
||||
onPress={() => router.push("/connections")}
|
||||
>
|
||||
<SymbolView name={status.icon} size={21} tintColor={status.color} type="monochrome" />
|
||||
</Pressable>
|
||||
</Stack.Toolbar.View>
|
||||
</Stack.Toolbar>
|
||||
|
||||
{/* Bottom toolbar: search + compose, visually split like iMessage */}
|
||||
@@ -99,8 +130,10 @@ export default function HomeRouteScreen() {
|
||||
<HomeScreen
|
||||
projects={projects}
|
||||
threads={threads}
|
||||
catalogState={catalogState}
|
||||
savedConnectionsById={savedConnectionsById}
|
||||
searchQuery={searchQuery}
|
||||
onAddConnection={() => router.push("/connections/new")}
|
||||
onSelectThread={(thread) => {
|
||||
router.push(buildThreadRoutePath(thread));
|
||||
}}
|
||||
|
||||
@@ -1,22 +1,74 @@
|
||||
import { Link, Stack } from "expo-router";
|
||||
import { Link, Stack, useRouter } from "expo-router";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { useMemo } from "react";
|
||||
import { Pressable, ScrollView, View } from "react-native";
|
||||
import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
|
||||
import { useRemoteCatalog } from "../../state/use-remote-catalog";
|
||||
import { type RemoteCatalogState, useRemoteCatalog } from "../../state/use-remote-catalog";
|
||||
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
|
||||
|
||||
function deriveProjectEmptyState(catalogState: RemoteCatalogState): {
|
||||
readonly title: string;
|
||||
readonly detail: string;
|
||||
readonly loading: boolean;
|
||||
} {
|
||||
if (catalogState.isLoadingSavedConnections) {
|
||||
return {
|
||||
title: "Loading environments",
|
||||
detail: "Checking saved environments on this device.",
|
||||
loading: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (!catalogState.hasSavedConnections) {
|
||||
return {
|
||||
title: "No environments connected",
|
||||
detail: "Add an environment before creating a task.",
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (catalogState.connectionState === "disconnected" && !catalogState.hasLoadedShellSnapshot) {
|
||||
return {
|
||||
title: "Environment unavailable",
|
||||
detail:
|
||||
catalogState.connectionError ??
|
||||
"The saved environment is offline. Check the URL or start the environment, then retry.",
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
catalogState.hasConnectingEnvironment &&
|
||||
!catalogState.hasLoadedShellSnapshot &&
|
||||
catalogState.connectionError === null
|
||||
) {
|
||||
return {
|
||||
title: "Connecting to environment",
|
||||
detail: "Loading projects from the saved environment.",
|
||||
loading: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
title: "No projects found",
|
||||
detail: "The connected environment did not report any projects.",
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
|
||||
export default function NewTaskRoute() {
|
||||
const { projects, threads } = useRemoteCatalog();
|
||||
const { projects, state: catalogState, threads } = useRemoteCatalog();
|
||||
const { savedConnectionsById } = useRemoteEnvironmentState();
|
||||
const router = useRouter();
|
||||
const insets = useSafeAreaInsets();
|
||||
const chevronColor = useThemeColor("--color-chevron");
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
const borderSubtleColor = useThemeColor("--color-border-subtle");
|
||||
const repositoryGroups = useMemo(
|
||||
() => groupProjectsByRepository({ projects, threads }),
|
||||
@@ -45,6 +97,7 @@ export default function NewTaskRoute() {
|
||||
}
|
||||
return nextItems;
|
||||
}, [repositoryGroups]);
|
||||
const projectEmptyState = deriveProjectEmptyState(catalogState);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
@@ -65,17 +118,31 @@ export default function NewTaskRoute() {
|
||||
<ScrollView
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 8,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
}}
|
||||
>
|
||||
{items.length === 0 ? (
|
||||
<View collapsable={false} className="items-center rounded-[24px] bg-card px-6 py-8">
|
||||
<Text className="text-[16px] font-medium text-foreground-muted">
|
||||
Loading projects...
|
||||
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
|
||||
{projectEmptyState.loading ? <ActivityIndicator color={accentColor} /> : null}
|
||||
<Text className="text-center text-[17px] font-t3-bold text-foreground">
|
||||
{projectEmptyState.title}
|
||||
</Text>
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
{projectEmptyState.detail}
|
||||
</Text>
|
||||
{!catalogState.hasReadyEnvironment ? (
|
||||
<Pressable
|
||||
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
|
||||
onPress={() => router.push("/connections/new")}
|
||||
>
|
||||
<Text className="text-[13px] font-t3-bold text-primary-foreground">
|
||||
Add environment
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
) : (
|
||||
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
|
||||
|
||||
@@ -1,14 +1,29 @@
|
||||
import { View } from "react-native";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "./AppText";
|
||||
|
||||
export function EmptyState(props: { readonly title: string; readonly detail: string }) {
|
||||
export function EmptyState(props: {
|
||||
readonly title: string;
|
||||
readonly detail: string;
|
||||
readonly actionLabel?: string;
|
||||
readonly onAction?: () => void;
|
||||
}) {
|
||||
return (
|
||||
<View className="rounded-[22px] border border-border bg-card p-5">
|
||||
<Text className="font-t3-bold text-lg text-foreground">{props.title}</Text>
|
||||
<Text className="mt-2 font-sans text-sm leading-[21px] text-foreground-muted">
|
||||
{props.detail}
|
||||
</Text>
|
||||
{props.actionLabel && props.onAction ? (
|
||||
<Pressable
|
||||
className="mt-4 self-start rounded-full bg-primary px-4 py-2.5 active:opacity-70"
|
||||
onPress={props.onAction}
|
||||
>
|
||||
<Text className="text-[13px] font-t3-bold text-primary-foreground">
|
||||
{props.actionLabel}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,25 @@ import { AppText as Text, AppTextInput as TextInput } from "../../components/App
|
||||
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
|
||||
import { ConnectionStatusDot } from "./ConnectionStatusDot";
|
||||
|
||||
function connectionStatusLabel(environment: ConnectedEnvironmentSummary): string | null {
|
||||
if (environment.connectionError) {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (environment.connectionState) {
|
||||
case "ready":
|
||||
return "Connected";
|
||||
case "connecting":
|
||||
return "Connecting";
|
||||
case "reconnecting":
|
||||
return "Reconnecting";
|
||||
case "disconnected":
|
||||
return null;
|
||||
case "idle":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function ConnectionEnvironmentRow(props: {
|
||||
readonly environment: ConnectedEnvironmentSummary;
|
||||
readonly expanded: boolean;
|
||||
@@ -27,6 +46,7 @@ export function ConnectionEnvironmentRow(props: {
|
||||
const placeholderColor = useThemeColor("--color-placeholder");
|
||||
const primaryFg = useThemeColor("--color-primary-foreground");
|
||||
const dangerFg = useThemeColor("--color-danger-foreground");
|
||||
const statusLabel = connectionStatusLabel(props.environment);
|
||||
|
||||
const handleSave = useCallback(() => {
|
||||
props.onUpdate(props.environment.environmentId, {
|
||||
@@ -42,7 +62,14 @@ export function ConnectionEnvironmentRow(props: {
|
||||
className="flex-row items-center gap-3 px-4 py-3.5 active:opacity-70"
|
||||
onPress={props.onToggle}
|
||||
>
|
||||
<ConnectionStatusDot state={props.environment.connectionState} pulse={false} size={8} />
|
||||
<ConnectionStatusDot
|
||||
state={props.environment.connectionState}
|
||||
pulse={
|
||||
props.environment.connectionState === "connecting" ||
|
||||
props.environment.connectionState === "reconnecting"
|
||||
}
|
||||
size={8}
|
||||
/>
|
||||
|
||||
<View className="flex-1 gap-0.5">
|
||||
<Text
|
||||
@@ -54,6 +81,11 @@ export function ConnectionEnvironmentRow(props: {
|
||||
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
|
||||
{props.environment.displayUrl}
|
||||
</Text>
|
||||
{statusLabel ? (
|
||||
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
|
||||
{statusLabel}
|
||||
</Text>
|
||||
) : null}
|
||||
{props.environment.connectionError ? (
|
||||
<Text
|
||||
className="text-[12px] leading-[16px] text-rose-500 dark:text-rose-400"
|
||||
|
||||
@@ -16,11 +16,10 @@ import { buildPairingUrl, parsePairingUrl } from "./pairing";
|
||||
|
||||
export function NewConnectionRouteScreen() {
|
||||
const {
|
||||
connectionError,
|
||||
connectionPairingUrl,
|
||||
connectionState,
|
||||
onChangeConnectionPairingUrl,
|
||||
onConnectPress,
|
||||
pairingConnectionError,
|
||||
} = useRemoteConnections();
|
||||
const router = useRouter();
|
||||
const params = useLocalSearchParams<{ mode?: string }>();
|
||||
@@ -35,8 +34,7 @@ export function NewConnectionRouteScreen() {
|
||||
const textColor = useThemeColor("--color-icon");
|
||||
const placeholderColor = useThemeColor("--color-placeholder");
|
||||
|
||||
const connectDisabled =
|
||||
isSubmitting || connectionState === "connecting" || hostInput.trim().length === 0;
|
||||
const connectDisabled = isSubmitting || hostInput.trim().length === 0;
|
||||
|
||||
useEffect(() => {
|
||||
const { host, code } = parsePairingUrl(connectionPairingUrl);
|
||||
@@ -45,10 +43,10 @@ export function NewConnectionRouteScreen() {
|
||||
}, [connectionPairingUrl]);
|
||||
|
||||
useEffect(() => {
|
||||
if (connectionError) {
|
||||
if (pairingConnectionError) {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}, [connectionError]);
|
||||
}, [pairingConnectionError]);
|
||||
|
||||
const handleHostChange = useCallback((value: string) => {
|
||||
setHostInput(value);
|
||||
@@ -72,7 +70,10 @@ export function NewConnectionRouteScreen() {
|
||||
return;
|
||||
}
|
||||
|
||||
Alert.alert("Camera access needed", "Allow camera access to scan a backend pairing QR code.");
|
||||
Alert.alert(
|
||||
"Camera access needed",
|
||||
"Allow camera access to scan an environment pairing QR code.",
|
||||
);
|
||||
}, [cameraPermission?.granted, requestCameraPermission]);
|
||||
|
||||
const closeScanner = useCallback(() => {
|
||||
@@ -126,7 +127,7 @@ export function NewConnectionRouteScreen() {
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: showScanner ? "Scan QR Code" : "Add Backend",
|
||||
title: showScanner ? "Scan QR Code" : "Add Environment",
|
||||
headerRight: () => (
|
||||
<Pressable
|
||||
className="h-10 w-10 items-center justify-center rounded-full border border-border bg-secondary"
|
||||
@@ -154,10 +155,10 @@ export function NewConnectionRouteScreen() {
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 16,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
}}
|
||||
>
|
||||
<View collapsable={false} className="gap-5">
|
||||
@@ -231,13 +232,11 @@ export function NewConnectionRouteScreen() {
|
||||
/>
|
||||
</View>
|
||||
|
||||
{connectionError ? <ErrorBanner message={connectionError} /> : null}
|
||||
{pairingConnectionError ? <ErrorBanner message={pairingConnectionError} /> : null}
|
||||
|
||||
<ConnectionSheetButton
|
||||
icon="plus"
|
||||
label={
|
||||
isSubmitting || connectionState === "connecting" ? "Pairing..." : "Add backend"
|
||||
}
|
||||
label={isSubmitting ? "Pairing..." : "Add environment"}
|
||||
disabled={connectDisabled}
|
||||
tone="primary"
|
||||
onPress={() => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import type {
|
||||
} from "@t3tools/client-runtime";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { Pressable, ScrollView, View } from "react-native";
|
||||
import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
@@ -16,6 +16,7 @@ import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import type { RemoteCatalogState } from "../../state/use-remote-catalog";
|
||||
import { useVcsStatus } from "../../state/use-vcs-status";
|
||||
import { threadStatusTone } from "../threads/threadPresentation";
|
||||
|
||||
@@ -24,8 +25,10 @@ import { threadStatusTone } from "../threads/threadPresentation";
|
||||
interface HomeScreenProps {
|
||||
readonly projects: ReadonlyArray<EnvironmentScopedProjectShell>;
|
||||
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
|
||||
readonly catalogState: RemoteCatalogState;
|
||||
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
|
||||
readonly searchQuery: string;
|
||||
readonly onAddConnection: () => void;
|
||||
readonly onSelectThread: (thread: EnvironmentScopedThreadShell) => void;
|
||||
}
|
||||
|
||||
@@ -63,6 +66,64 @@ function statusColors(thread: EnvironmentScopedThreadShell): { bg: string; fg: s
|
||||
|
||||
const COLLAPSED_THREAD_LIMIT = 6;
|
||||
|
||||
function deriveEmptyState(props: {
|
||||
readonly catalogState: RemoteCatalogState;
|
||||
readonly projectCount: number;
|
||||
}): { readonly title: string; readonly detail: string; readonly loading: boolean } {
|
||||
const { catalogState } = props;
|
||||
if (catalogState.isLoadingSavedConnections) {
|
||||
return {
|
||||
title: "Loading environments",
|
||||
detail: "Checking saved environments on this device.",
|
||||
loading: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (!catalogState.hasSavedConnections) {
|
||||
return {
|
||||
title: "No environments connected",
|
||||
detail: "Add an environment to load projects and start coding sessions.",
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (catalogState.connectionState === "disconnected" && !catalogState.hasLoadedShellSnapshot) {
|
||||
return {
|
||||
title: "Environment unavailable",
|
||||
detail:
|
||||
catalogState.connectionError ??
|
||||
"The saved environment is offline. Check the URL or start the environment, then retry.",
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
catalogState.hasConnectingEnvironment &&
|
||||
!catalogState.hasLoadedShellSnapshot &&
|
||||
catalogState.connectionError === null
|
||||
) {
|
||||
return {
|
||||
title: "Connecting to environment",
|
||||
detail: "Loading projects and threads from the saved environment.",
|
||||
loading: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (props.projectCount === 0 && catalogState.hasLoadedShellSnapshot) {
|
||||
return {
|
||||
title: "No projects found",
|
||||
detail: "The connected environment did not report any projects.",
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
title: "No threads yet",
|
||||
detail: "Create a task to start a new coding session in one of your connected projects.",
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
|
||||
/* ─── Project group header ───────────────────────────────────────────── */
|
||||
|
||||
function ProjectGroupLabel(props: {
|
||||
@@ -233,6 +294,7 @@ function ThreadRow(props: {
|
||||
|
||||
export function HomeScreen(props: HomeScreenProps) {
|
||||
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set());
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
|
||||
const toggleExpanded = useCallback((key: string) => {
|
||||
setExpandedProjects((prev) => {
|
||||
@@ -288,6 +350,10 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
/* Empty states */
|
||||
const hasAnyThreads = props.threads.length > 0;
|
||||
const hasResults = filteredThreads.length > 0;
|
||||
const emptyState = deriveEmptyState({
|
||||
catalogState: props.catalogState,
|
||||
projectCount: props.projects.length,
|
||||
});
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
@@ -304,10 +370,19 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}}
|
||||
>
|
||||
{!hasAnyThreads ? (
|
||||
<EmptyState
|
||||
title="No threads yet"
|
||||
detail="Create a task to start a new coding session in one of your connected projects."
|
||||
/>
|
||||
<View>
|
||||
<EmptyState
|
||||
title={emptyState.title}
|
||||
detail={emptyState.detail}
|
||||
actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
|
||||
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
|
||||
/>
|
||||
{emptyState.loading ? (
|
||||
<View className="absolute right-5 top-5">
|
||||
<ActivityIndicator color={accentColor} />
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
) : !hasResults ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : (
|
||||
|
||||
@@ -385,9 +385,6 @@ export function ReviewSheet() {
|
||||
}}
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
contentContainerStyle={{
|
||||
paddingTop: REVIEW_HEADER_SPACING,
|
||||
}}
|
||||
>
|
||||
{listHeader}
|
||||
{!selectedSection ? (
|
||||
|
||||
@@ -95,6 +95,7 @@ describe("buildReviewSectionItems", () => {
|
||||
loadingTurnIds: {
|
||||
[getReviewSectionIdForCheckpoint(checkpoints[1])]: true,
|
||||
},
|
||||
loadingGitSections: false,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.id)).toEqual([
|
||||
@@ -110,6 +111,28 @@ describe("buildReviewSectionItems", () => {
|
||||
});
|
||||
expect(getDefaultReviewSectionId(items)).toBe("turn:2");
|
||||
});
|
||||
|
||||
it("shows dirty worktree while git preview is loading", () => {
|
||||
const items = buildReviewSectionItems({
|
||||
checkpoints: [],
|
||||
gitSections: [],
|
||||
turnDiffById: {},
|
||||
loadingTurnIds: {},
|
||||
loadingGitSections: true,
|
||||
});
|
||||
|
||||
expect(items).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "git:working-tree",
|
||||
kind: "working-tree",
|
||||
title: "Dirty worktree",
|
||||
subtitle: "Tracked, staged, and untracked worktree changes",
|
||||
diff: null,
|
||||
isLoading: true,
|
||||
}),
|
||||
]);
|
||||
expect(getDefaultReviewSectionId(items)).toBe("git:working-tree");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildReviewParsedDiff", () => {
|
||||
|
||||
@@ -7,6 +7,10 @@ import * as Order from "effect/Order";
|
||||
|
||||
export type ReviewSectionKind = "turn" | "working-tree" | "branch-range";
|
||||
|
||||
const DIRTY_WORKTREE_SECTION_ID = "git:working-tree";
|
||||
const DIRTY_WORKTREE_TITLE = "Dirty worktree";
|
||||
const DIRTY_WORKTREE_SUBTITLE = "Tracked, staged, and untracked worktree changes";
|
||||
|
||||
export interface ReviewSectionItem {
|
||||
readonly id: string;
|
||||
readonly kind: ReviewSectionKind;
|
||||
@@ -153,7 +157,7 @@ const readyCheckpointOrder = Order.make<OrchestrationCheckpointSummary>(
|
||||
|
||||
function gitSubtitle(section: ReviewDiffPreviewSource): string | null {
|
||||
if (section.kind === "working-tree") {
|
||||
return "Tracked, staged, and untracked worktree changes";
|
||||
return DIRTY_WORKTREE_SUBTITLE;
|
||||
}
|
||||
if (section.baseRef) {
|
||||
return `${section.baseRef} ... ${section.headRef ?? "HEAD"}`;
|
||||
@@ -526,6 +530,7 @@ export function buildReviewSectionItems(input: {
|
||||
readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
|
||||
readonly turnDiffById: Readonly<Record<string, string | undefined>>;
|
||||
readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
|
||||
readonly loadingGitSections: boolean;
|
||||
}): ReadonlyArray<ReviewSectionItem> {
|
||||
const turnItems = getReadyReviewCheckpoints(input.checkpoints).map<ReviewSectionItem>(
|
||||
(checkpoint) => {
|
||||
@@ -549,8 +554,23 @@ export function buildReviewSectionItems(input: {
|
||||
diff: section.diff,
|
||||
isLoading: false,
|
||||
}));
|
||||
const hasDirtyWorktreeItem = gitItems.some((item) => item.id === DIRTY_WORKTREE_SECTION_ID);
|
||||
const visibleGitItems =
|
||||
input.loadingGitSections && !hasDirtyWorktreeItem
|
||||
? [
|
||||
{
|
||||
id: DIRTY_WORKTREE_SECTION_ID,
|
||||
kind: "working-tree",
|
||||
title: DIRTY_WORKTREE_TITLE,
|
||||
subtitle: DIRTY_WORKTREE_SUBTITLE,
|
||||
diff: null,
|
||||
isLoading: true,
|
||||
} satisfies ReviewSectionItem,
|
||||
...gitItems,
|
||||
]
|
||||
: gitItems;
|
||||
|
||||
return [...turnItems, ...gitItems];
|
||||
return [...turnItems, ...visibleGitItems];
|
||||
}
|
||||
|
||||
export function getDefaultReviewSectionId(
|
||||
|
||||
@@ -66,8 +66,15 @@ export function useReviewSections(input: {
|
||||
gitSections: reviewCache.gitSections,
|
||||
turnDiffById: reviewCache.turnDiffById,
|
||||
loadingTurnIds,
|
||||
loadingGitSections: diffPreview.isPending,
|
||||
}),
|
||||
[loadingTurnIds, readyCheckpoints, reviewCache.gitSections, reviewCache.turnDiffById],
|
||||
[
|
||||
diffPreview.isPending,
|
||||
loadingTurnIds,
|
||||
readyCheckpoints,
|
||||
reviewCache.gitSections,
|
||||
reviewCache.turnDiffById,
|
||||
],
|
||||
);
|
||||
const selectedSection = useMemo(
|
||||
() =>
|
||||
|
||||
@@ -9,7 +9,6 @@ import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
|
||||
import { KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-reanimated";
|
||||
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { LoadingScreen } from "../../components/LoadingScreen";
|
||||
@@ -191,7 +190,6 @@ function pickRunningTerminalSessionForBootstrap(
|
||||
|
||||
export function ThreadTerminalRouteScreen() {
|
||||
const router = useRouter();
|
||||
const keyboard = useAnimatedKeyboard();
|
||||
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
|
||||
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
|
||||
const params = useLocalSearchParams<{
|
||||
@@ -397,12 +395,6 @@ export function ThreadTerminalRouteScreen() {
|
||||
];
|
||||
}, [hostPlatform]);
|
||||
const terminalBottomInset = TERMINAL_ACCESSORY_HEIGHT;
|
||||
const terminalContainerAnimatedStyle = useAnimatedStyle(() => ({
|
||||
paddingBottom:
|
||||
keyboard.height.value > 0
|
||||
? keyboard.height.value + TERMINAL_ACCESSORY_HEIGHT
|
||||
: terminalBottomInset,
|
||||
}));
|
||||
|
||||
const terminalMenuSessions = useMemo<ReadonlyArray<TerminalMenuSession>>(
|
||||
() =>
|
||||
@@ -1031,7 +1023,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
</Stack.Toolbar>
|
||||
|
||||
<View style={{ flex: 1, backgroundColor: terminalTheme.background }}>
|
||||
<Animated.View style={[{ flex: 1 }, terminalContainerAnimatedStyle]}>
|
||||
<View style={{ flex: 1, paddingBottom: terminalBottomInset }}>
|
||||
<TerminalSurface
|
||||
buffer={terminalSurfaceBuffer}
|
||||
fontSize={fontSize}
|
||||
@@ -1041,7 +1033,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
style={{ flex: 1 }}
|
||||
terminalKey={terminalKey}
|
||||
/>
|
||||
</Animated.View>
|
||||
</View>
|
||||
|
||||
<KeyboardStickyView style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}>
|
||||
<View
|
||||
|
||||
@@ -4,7 +4,7 @@ import { SymbolView } from "expo-symbols";
|
||||
import { TextInputWrapper } from "expo-paste-input";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
import { Pressable, View, useColorScheme } from "react-native";
|
||||
import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-reanimated";
|
||||
import { KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
@@ -35,13 +35,7 @@ export function NewTaskDraftScreen(props: {
|
||||
const router = useRouter();
|
||||
const insets = useSafeAreaInsets();
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const keyboard = useAnimatedKeyboard();
|
||||
const containerAnimatedStyle = useAnimatedStyle(() => ({
|
||||
paddingBottom: keyboard.height.value,
|
||||
}));
|
||||
const controlsBottomPadding = useAnimatedStyle(() => ({
|
||||
paddingBottom: keyboard.height.value > 0 ? 4 : Math.max(insets.bottom, 10),
|
||||
}));
|
||||
const controlsBottomPadding = Math.max(insets.bottom, 10);
|
||||
const { logicalProjects, selectedProject, setProject } = flow;
|
||||
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
@@ -402,7 +396,7 @@ export function NewTaskDraftScreen(props: {
|
||||
}
|
||||
|
||||
return (
|
||||
<Animated.View className="flex-1 bg-sheet" style={containerAnimatedStyle}>
|
||||
<View className="flex-1 bg-sheet">
|
||||
<View style={{ minHeight: 16, paddingTop: 8 }} />
|
||||
|
||||
<View className="items-center gap-1 px-5 pb-3 pt-4">
|
||||
@@ -443,72 +437,74 @@ export function NewTaskDraftScreen(props: {
|
||||
</TextInputWrapper>
|
||||
</View>
|
||||
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
<KeyboardStickyView>
|
||||
<View
|
||||
style={{
|
||||
borderTopWidth: 1,
|
||||
borderTopColor: borderColor,
|
||||
},
|
||||
controlsBottomPadding,
|
||||
]}
|
||||
>
|
||||
{flow.attachments.length > 0 ? (
|
||||
<View style={{ paddingHorizontal: 16, paddingTop: 12 }}>
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
onRemove={flow.removeAttachment}
|
||||
imageSize={88}
|
||||
imageBorderRadius={20}
|
||||
paddingBottom: controlsBottomPadding,
|
||||
}}
|
||||
>
|
||||
{flow.attachments.length > 0 ? (
|
||||
<View style={{ paddingHorizontal: 16, paddingTop: 12 }}>
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
onRemove={flow.removeAttachment}
|
||||
imageSize={88}
|
||||
imageBorderRadius={20}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<View className="flex-row items-center justify-between gap-2 px-4 pb-1 pt-4">
|
||||
<ControlPill icon="plus" onPress={() => void handlePickImages()} />
|
||||
<MenuView
|
||||
actions={modelMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
|
||||
themeVariant={isDarkMode ? "dark" : "light"}
|
||||
>
|
||||
<ControlPill
|
||||
iconNode={
|
||||
<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
/>
|
||||
</MenuView>
|
||||
<MenuView
|
||||
actions={optionsMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
|
||||
themeVariant={isDarkMode ? "dark" : "light"}
|
||||
>
|
||||
<ControlPill icon="slider.horizontal.3" />
|
||||
</MenuView>
|
||||
<MenuView
|
||||
actions={environmentMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
|
||||
themeVariant={isDarkMode ? "dark" : "light"}
|
||||
>
|
||||
<ControlPill icon="desktopcomputer" />
|
||||
</MenuView>
|
||||
<MenuView
|
||||
actions={workspaceMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
|
||||
themeVariant={isDarkMode ? "dark" : "light"}
|
||||
>
|
||||
<ControlPill icon="point.topleft.down.curvedto.point.bottomright.up" />
|
||||
</MenuView>
|
||||
<ControlPill
|
||||
icon="arrow.up"
|
||||
label={flow.submitting ? "Starting" : "Start"}
|
||||
onPress={() => void handleStart()}
|
||||
variant="primary"
|
||||
disabled={
|
||||
!flow.selectedProject ||
|
||||
!flow.selectedModel ||
|
||||
flow.prompt.trim().length === 0 ||
|
||||
flow.submitting ||
|
||||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
|
||||
}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<View className="flex-row items-center justify-between gap-2 px-4 pb-1 pt-4">
|
||||
<ControlPill icon="plus" onPress={() => void handlePickImages()} />
|
||||
<MenuView
|
||||
actions={modelMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
|
||||
themeVariant={isDarkMode ? "dark" : "light"}
|
||||
>
|
||||
<ControlPill
|
||||
iconNode={<ProviderIcon provider={flow.selectedModel?.provider} size={16} />}
|
||||
/>
|
||||
</MenuView>
|
||||
<MenuView
|
||||
actions={optionsMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
|
||||
themeVariant={isDarkMode ? "dark" : "light"}
|
||||
>
|
||||
<ControlPill icon="slider.horizontal.3" />
|
||||
</MenuView>
|
||||
<MenuView
|
||||
actions={environmentMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
|
||||
themeVariant={isDarkMode ? "dark" : "light"}
|
||||
>
|
||||
<ControlPill icon="desktopcomputer" />
|
||||
</MenuView>
|
||||
<MenuView
|
||||
actions={workspaceMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
|
||||
themeVariant={isDarkMode ? "dark" : "light"}
|
||||
>
|
||||
<ControlPill icon="point.topleft.down.curvedto.point.bottomright.up" />
|
||||
</MenuView>
|
||||
<ControlPill
|
||||
icon="arrow.up"
|
||||
label={flow.submitting ? "Starting" : "Start"}
|
||||
onPress={() => void handleStart()}
|
||||
variant="primary"
|
||||
disabled={
|
||||
!flow.selectedProject ||
|
||||
!flow.selectedModel ||
|
||||
flow.prompt.trim().length === 0 ||
|
||||
flow.submitting ||
|
||||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
|
||||
}
|
||||
/>
|
||||
</View>
|
||||
</Animated.View>
|
||||
</Animated.View>
|
||||
</KeyboardStickyView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -188,10 +188,10 @@ export function ThreadNavigationDrawer(props: {
|
||||
|
||||
<ScrollView
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 12 }}
|
||||
contentContainerStyle={{
|
||||
gap: 20,
|
||||
paddingHorizontal: 14,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 12,
|
||||
}}
|
||||
>
|
||||
{groupedThreads.map((group) => (
|
||||
|
||||
@@ -55,10 +55,10 @@ export function GitBranchesSheet() {
|
||||
return (
|
||||
<ScrollView
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 8,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
gap: 16,
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -65,10 +65,10 @@ export function GitCommitSheet() {
|
||||
<ScrollView
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 8,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
gap: 16,
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -184,10 +184,10 @@ export function GitOverviewSheet() {
|
||||
<ScrollView
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 8,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
gap: 14,
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
import * as Arr from "effect/Array";
|
||||
import { pipe } from "effect/Function";
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, OrchestrationShellSnapshot } from "@t3tools/contracts";
|
||||
|
||||
import type { SavedRemoteConnection } from "./connection";
|
||||
|
||||
const CONNECTIONS_KEY = "t3code.connections";
|
||||
const PREFERENCES_KEY = "t3code.preferences";
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
|
||||
|
||||
export interface CachedShellSnapshot {
|
||||
readonly schemaVersion: typeof SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly snapshotReceivedAt: string;
|
||||
readonly snapshot: OrchestrationShellSnapshot;
|
||||
}
|
||||
|
||||
export interface MobilePreferences {
|
||||
readonly terminalFontSize?: number;
|
||||
@@ -33,6 +42,104 @@ async function readJsonStorageItem<T>(key: string): Promise<T | null> {
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function isShellSnapshot(value: unknown): value is OrchestrationShellSnapshot {
|
||||
if (!isRecord(value)) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
typeof value.snapshotSequence === "number" &&
|
||||
Array.isArray(value.projects) &&
|
||||
Array.isArray(value.threads) &&
|
||||
typeof value.updatedAt === "string"
|
||||
);
|
||||
}
|
||||
|
||||
function isCachedShellSnapshot(value: unknown): value is CachedShellSnapshot {
|
||||
if (!isRecord(value)) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
value.schemaVersion === SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION &&
|
||||
typeof value.environmentId === "string" &&
|
||||
typeof value.snapshotReceivedAt === "string" &&
|
||||
isShellSnapshot(value.snapshot)
|
||||
);
|
||||
}
|
||||
|
||||
function cachedShellSnapshotFileName(environmentId: EnvironmentId): string {
|
||||
return `${encodeURIComponent(environmentId)}.json`;
|
||||
}
|
||||
|
||||
async function getShellSnapshotCacheDirectory() {
|
||||
const { Directory, Paths } = await import("expo-file-system");
|
||||
const directory = new Directory(Paths.document, SHELL_SNAPSHOT_CACHE_DIRECTORY);
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
return directory;
|
||||
}
|
||||
|
||||
export async function loadCachedShellSnapshot(
|
||||
environmentId: EnvironmentId,
|
||||
): Promise<CachedShellSnapshot | null> {
|
||||
try {
|
||||
const { File } = await import("expo-file-system");
|
||||
const directory = await getShellSnapshotCacheDirectory();
|
||||
const file = new File(directory, cachedShellSnapshotFileName(environmentId));
|
||||
if (!file.exists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(await file.text()) as unknown;
|
||||
if (!isCachedShellSnapshot(parsed) || parsed.environmentId !== environmentId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return parsed;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveCachedShellSnapshot(
|
||||
environmentId: EnvironmentId,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const { File } = await import("expo-file-system");
|
||||
const directory = await getShellSnapshotCacheDirectory();
|
||||
const file = new File(directory, cachedShellSnapshotFileName(environmentId));
|
||||
const document: CachedShellSnapshot = {
|
||||
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshotReceivedAt: new Date().toISOString(),
|
||||
snapshot,
|
||||
};
|
||||
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(document));
|
||||
} catch {
|
||||
// Cache persistence is best-effort and should never block live data.
|
||||
}
|
||||
}
|
||||
|
||||
export async function clearCachedShellSnapshot(environmentId: EnvironmentId): Promise<void> {
|
||||
try {
|
||||
const { File } = await import("expo-file-system");
|
||||
const directory = await getShellSnapshotCacheDirectory();
|
||||
const file = new File(directory, cachedShellSnapshotFileName(environmentId));
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
} catch {
|
||||
// Ignore cache cleanup failures.
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteConnection>> {
|
||||
const parsed = await readJsonStorageItem<{
|
||||
readonly connections?: ReadonlyArray<SavedRemoteConnection>;
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
|
||||
import { ConnectedEnvironmentSummary } from "./remote-runtime-types";
|
||||
import type { SavedRemoteConnection } from "../lib/connection";
|
||||
import { useShellSnapshotStates } from "./use-shell-snapshot";
|
||||
import { useCachedShellSnapshotMetadata, useShellSnapshotStates } from "./use-shell-snapshot";
|
||||
import {
|
||||
useRemoteConnectionStatus,
|
||||
useRemoteEnvironmentState,
|
||||
@@ -68,12 +68,30 @@ function listRemoteCatalogEnvironmentIds(
|
||||
return environmentIds;
|
||||
}
|
||||
|
||||
export interface RemoteCatalogState {
|
||||
readonly isLoadingSavedConnections: boolean;
|
||||
readonly hasSavedConnections: boolean;
|
||||
readonly hasLoadedShellSnapshot: boolean;
|
||||
readonly hasPendingShellSnapshot: boolean;
|
||||
readonly hasReadyEnvironment: boolean;
|
||||
readonly hasConnectingEnvironment: boolean;
|
||||
readonly connectionState: EnvironmentConnectionState;
|
||||
readonly connectionError: string | null;
|
||||
readonly shellSnapshotError: string | null;
|
||||
readonly isUsingCachedData: boolean;
|
||||
readonly latestCachedSnapshotReceivedAt: string | null;
|
||||
}
|
||||
|
||||
export function useRemoteCatalog() {
|
||||
const { connectedEnvironments, connectionState } = useRemoteConnectionStatus();
|
||||
const { environmentStateById, savedConnectionsById } = useRemoteEnvironmentState();
|
||||
const shellSnapshotStates = useShellSnapshotStates(
|
||||
listRemoteCatalogEnvironmentIds(savedConnectionsById),
|
||||
const { connectedEnvironments, connectionError, connectionState } = useRemoteConnectionStatus();
|
||||
const { environmentStateById, isLoadingSavedConnection, savedConnectionsById } =
|
||||
useRemoteEnvironmentState();
|
||||
const catalogEnvironmentIds = useMemo(
|
||||
() => listRemoteCatalogEnvironmentIds(savedConnectionsById),
|
||||
[savedConnectionsById],
|
||||
);
|
||||
const shellSnapshotStates = useShellSnapshotStates(catalogEnvironmentIds);
|
||||
const cachedShellSnapshotMetadata = useCachedShellSnapshotMetadata();
|
||||
|
||||
const projects = useMemo(() => {
|
||||
const scopedProjects: EnvironmentScopedProjectShell[] = [];
|
||||
@@ -121,11 +139,60 @@ export function useRemoteCatalog() {
|
||||
[threads],
|
||||
);
|
||||
|
||||
const state = useMemo<RemoteCatalogState>(() => {
|
||||
const shellSnapshots = Object.values(shellSnapshotStates);
|
||||
const cachedSnapshotReceivedAts: string[] = [];
|
||||
for (const environmentId of catalogEnvironmentIds) {
|
||||
const metadata = cachedShellSnapshotMetadata[environmentId];
|
||||
if (metadata) {
|
||||
cachedSnapshotReceivedAts.push(metadata.snapshotReceivedAt);
|
||||
}
|
||||
}
|
||||
let shellSnapshotError: string | null = null;
|
||||
for (const snapshot of shellSnapshots) {
|
||||
if (snapshot.error !== null) {
|
||||
shellSnapshotError = snapshot.error;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return {
|
||||
isLoadingSavedConnections: isLoadingSavedConnection,
|
||||
hasSavedConnections: catalogEnvironmentIds.length > 0,
|
||||
hasLoadedShellSnapshot: shellSnapshots.some((snapshot) => snapshot.data !== null),
|
||||
hasPendingShellSnapshot: shellSnapshots.some((snapshot) => snapshot.isPending),
|
||||
hasReadyEnvironment: connectedEnvironments.some(
|
||||
(environment) => environment.connectionState === "ready",
|
||||
),
|
||||
hasConnectingEnvironment: connectedEnvironments.some(
|
||||
(environment) =>
|
||||
environment.connectionState === "connecting" ||
|
||||
environment.connectionState === "reconnecting",
|
||||
),
|
||||
connectionState: connectionState ?? overallConnectionState,
|
||||
connectionError,
|
||||
shellSnapshotError,
|
||||
isUsingCachedData: cachedSnapshotReceivedAts.length > 0,
|
||||
latestCachedSnapshotReceivedAt:
|
||||
Arr.sort(cachedSnapshotReceivedAts, Order.flip(Order.String))[0] ?? null,
|
||||
};
|
||||
}, [
|
||||
cachedShellSnapshotMetadata,
|
||||
catalogEnvironmentIds,
|
||||
connectedEnvironments,
|
||||
connectionError,
|
||||
connectionState,
|
||||
isLoadingSavedConnection,
|
||||
overallConnectionState,
|
||||
shellSnapshotStates,
|
||||
]);
|
||||
|
||||
return {
|
||||
projects,
|
||||
threads,
|
||||
serverConfigByEnvironmentId,
|
||||
connectionState: connectionState ?? overallConnectionState,
|
||||
connectionState: state.connectionState,
|
||||
connectionError: state.connectionError,
|
||||
state,
|
||||
hasRemoteActivity,
|
||||
};
|
||||
}
|
||||
@@ -19,7 +19,14 @@ import { pipe } from "effect/Function";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { type SavedRemoteConnection, bootstrapRemoteConnection } from "../lib/connection";
|
||||
import { terminalDebugLog } from "../features/terminal/terminalDebugLog";
|
||||
import { clearSavedConnection, loadSavedConnections, saveConnection } from "../lib/storage";
|
||||
import {
|
||||
clearCachedShellSnapshot,
|
||||
clearSavedConnection,
|
||||
loadCachedShellSnapshot,
|
||||
loadSavedConnections,
|
||||
saveCachedShellSnapshot,
|
||||
saveConnection,
|
||||
} from "../lib/storage";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import {
|
||||
drainEnvironmentSessions,
|
||||
@@ -33,10 +40,16 @@ import {
|
||||
resetSourceControlDiscoveryState,
|
||||
} from "./use-source-control-discovery";
|
||||
import { environmentRuntimeManager, useEnvironmentRuntimeStates } from "./use-environment-runtime";
|
||||
import { shellSnapshotManager } from "./use-shell-snapshot";
|
||||
import {
|
||||
clearCachedShellSnapshotMetadata,
|
||||
hydrateCachedShellSnapshot,
|
||||
markShellSnapshotLive,
|
||||
shellSnapshotManager,
|
||||
} from "./use-shell-snapshot";
|
||||
import { subscribeTerminalMetadata, terminalSessionManager } from "./use-terminal-session";
|
||||
|
||||
const terminalMetadataUnsubscribers = new Map<EnvironmentId, () => void>();
|
||||
const SAVED_CONNECTION_BOOTSTRAP_TIMEOUT_MS = 8_000;
|
||||
|
||||
interface RemoteEnvironmentLocalState {
|
||||
readonly isLoadingSavedConnection: boolean;
|
||||
@@ -137,22 +150,49 @@ function setEnvironmentConnectionStatus(
|
||||
}));
|
||||
}
|
||||
|
||||
function withTimeout<T>(
|
||||
promise: Promise<T>,
|
||||
timeoutMs: number,
|
||||
timeoutMessage: string,
|
||||
): Promise<T> {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
reject(new Error(timeoutMessage));
|
||||
}, timeoutMs);
|
||||
|
||||
promise.then(
|
||||
(value) => {
|
||||
clearTimeout(timeoutId);
|
||||
resolve(value);
|
||||
},
|
||||
(error: unknown) => {
|
||||
clearTimeout(timeoutId);
|
||||
reject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export async function disconnectEnvironment(
|
||||
environmentId: EnvironmentId,
|
||||
options?: { readonly removeSaved?: boolean },
|
||||
options?: { readonly preserveShellSnapshot?: boolean; readonly removeSaved?: boolean },
|
||||
) {
|
||||
const session = removeEnvironmentSession(environmentId);
|
||||
notifyEnvironmentConnectionListeners();
|
||||
await session?.connection.dispose();
|
||||
terminalMetadataUnsubscribers.get(environmentId)?.();
|
||||
terminalMetadataUnsubscribers.delete(environmentId);
|
||||
shellSnapshotManager.invalidate({ environmentId });
|
||||
if (!options?.preserveShellSnapshot) {
|
||||
shellSnapshotManager.invalidate({ environmentId });
|
||||
}
|
||||
invalidateSourceControlDiscoveryForEnvironment(environmentId);
|
||||
terminalSessionManager.invalidateEnvironment(environmentId);
|
||||
environmentRuntimeManager.invalidate({ environmentId });
|
||||
|
||||
if (options?.removeSaved) {
|
||||
await clearSavedConnection(environmentId);
|
||||
await clearCachedShellSnapshot(environmentId);
|
||||
clearCachedShellSnapshotMetadata(environmentId);
|
||||
removeSavedConnection(environmentId);
|
||||
}
|
||||
}
|
||||
@@ -161,7 +201,7 @@ export async function connectSavedEnvironment(
|
||||
connection: SavedRemoteConnection,
|
||||
options?: { readonly persist?: boolean },
|
||||
) {
|
||||
await disconnectEnvironment(connection.environmentId);
|
||||
await disconnectEnvironment(connection.environmentId, { preserveShellSnapshot: true });
|
||||
|
||||
if (options?.persist !== false) {
|
||||
await saveConnection(connection);
|
||||
@@ -182,15 +222,15 @@ export async function connectSavedEnvironment(
|
||||
onAttempt: () => {
|
||||
environmentRuntimeManager.patch({ environmentId: connection.environmentId }, (previous) => {
|
||||
const nextState =
|
||||
previous.connectionState === "ready" ||
|
||||
previous.connectionState === "reconnecting" ||
|
||||
previous.connectionState === "disconnected"
|
||||
previous.connectionState === "ready" || previous.connectionState === "reconnecting"
|
||||
? "reconnecting"
|
||||
: "connecting";
|
||||
const keepSettledFailure =
|
||||
previous.connectionState === "disconnected" && previous.connectionError !== null;
|
||||
return {
|
||||
...previous,
|
||||
connectionState: nextState,
|
||||
connectionError: null,
|
||||
connectionState: keepSettledFailure ? "disconnected" : nextState,
|
||||
connectionError: keepSettledFailure ? previous.connectionError : null,
|
||||
};
|
||||
});
|
||||
},
|
||||
@@ -230,6 +270,8 @@ export async function connectSavedEnvironment(
|
||||
},
|
||||
syncShellSnapshot: (snapshot, environmentId) => {
|
||||
shellSnapshotManager.syncSnapshot({ environmentId }, snapshot);
|
||||
markShellSnapshotLive(environmentId);
|
||||
void saveCachedShellSnapshot(environmentId, snapshot);
|
||||
environmentRuntimeManager.patch({ environmentId }, (runtime) => ({
|
||||
...runtime,
|
||||
connectionState: "ready",
|
||||
@@ -264,7 +306,11 @@ export async function connectSavedEnvironment(
|
||||
notifyEnvironmentConnectionListeners();
|
||||
|
||||
try {
|
||||
await environmentConnection.ensureBootstrapped();
|
||||
await withTimeout(
|
||||
environmentConnection.ensureBootstrapped(),
|
||||
SAVED_CONNECTION_BOOTSTRAP_TIMEOUT_MS,
|
||||
"Environment did not respond before the connection timeout.",
|
||||
);
|
||||
} catch (error) {
|
||||
setEnvironmentConnectionStatus(
|
||||
connection.environmentId,
|
||||
@@ -320,13 +366,28 @@ export function useRemoteEnvironmentBootstrap() {
|
||||
|
||||
setIsLoadingSavedConnection(false);
|
||||
|
||||
void Promise.all(
|
||||
connections.map((connection) =>
|
||||
connectSavedEnvironment(connection, {
|
||||
persist: false,
|
||||
void (async () => {
|
||||
await Promise.all(
|
||||
connections.map(async (connection) => {
|
||||
const cached = await loadCachedShellSnapshot(connection.environmentId);
|
||||
if (!cancelled && cached) {
|
||||
hydrateCachedShellSnapshot(cached);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
);
|
||||
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
connections.map((connection) =>
|
||||
connectSavedEnvironment(connection, {
|
||||
persist: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
})();
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) {
|
||||
@@ -415,7 +476,7 @@ export function useRemoteConnectionStatus() {
|
||||
}
|
||||
|
||||
export function useRemoteConnections() {
|
||||
const { connectionPairingUrl } = useRemoteEnvironmentState();
|
||||
const { connectionPairingUrl, pendingConnectionError } = useRemoteEnvironmentState();
|
||||
const { connectedEnvironments, connectionError, connectionState } = useRemoteConnectionStatus();
|
||||
|
||||
const onConnectPress = useCallback(
|
||||
@@ -492,6 +553,7 @@ export function useRemoteConnections() {
|
||||
connectionPairingUrl,
|
||||
connectionState,
|
||||
connectionError,
|
||||
pairingConnectionError: pendingConnectionError,
|
||||
connectedEnvironments,
|
||||
connectedEnvironmentCount: connectedEnvironments.length,
|
||||
onChangeConnectionPairingUrl: setConnectionPairingUrl,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import {
|
||||
EMPTY_SHELL_SNAPSHOT_ATOM,
|
||||
EMPTY_SHELL_SNAPSHOT_STATE,
|
||||
@@ -13,11 +14,47 @@ import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useMemo, useRef, useSyncExternalStore } from "react";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import type { CachedShellSnapshot } from "../lib/storage";
|
||||
|
||||
const cachedShellSnapshotMetadataAtom = Atom.make<
|
||||
Readonly<Record<EnvironmentId, { readonly snapshotReceivedAt: string }>>
|
||||
>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:cached-shell-snapshot-metadata"));
|
||||
|
||||
export const shellSnapshotManager = createShellSnapshotManager({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
});
|
||||
|
||||
export function hydrateCachedShellSnapshot(cached: CachedShellSnapshot): void {
|
||||
shellSnapshotManager.syncSnapshot({ environmentId: cached.environmentId }, cached.snapshot);
|
||||
appAtomRegistry.set(cachedShellSnapshotMetadataAtom, {
|
||||
...appAtomRegistry.get(cachedShellSnapshotMetadataAtom),
|
||||
[cached.environmentId]: {
|
||||
snapshotReceivedAt: cached.snapshotReceivedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function markShellSnapshotLive(environmentId: EnvironmentId): void {
|
||||
const current = appAtomRegistry.get(cachedShellSnapshotMetadataAtom);
|
||||
if (current[environmentId] === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const next = { ...current };
|
||||
delete next[environmentId];
|
||||
appAtomRegistry.set(cachedShellSnapshotMetadataAtom, next);
|
||||
}
|
||||
|
||||
export function clearCachedShellSnapshotMetadata(environmentId: EnvironmentId): void {
|
||||
markShellSnapshotLive(environmentId);
|
||||
}
|
||||
|
||||
export function useCachedShellSnapshotMetadata(): Readonly<
|
||||
Record<EnvironmentId, { readonly snapshotReceivedAt: string }>
|
||||
> {
|
||||
return useAtomValue(cachedShellSnapshotMetadataAtom);
|
||||
}
|
||||
|
||||
export function useShellSnapshot(environmentId: EnvironmentId | null): ShellSnapshotState {
|
||||
const targetKey = getShellSnapshotTargetKey({ environmentId });
|
||||
const state = useAtomValue(
|
||||
|
||||
@@ -1612,8 +1612,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
if (previewUrls.length === 0) return;
|
||||
|
||||
const previousPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];
|
||||
const nextPreviewUrlSet = new Set(previewUrls);
|
||||
for (const previewUrl of previousPreviewUrls) {
|
||||
if (!previewUrls.includes(previewUrl)) {
|
||||
if (!nextPreviewUrlSet.has(previewUrl)) {
|
||||
revokeBlobPreviewUrl(previewUrl);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,7 +146,8 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
|
||||
value: "file-manager",
|
||||
},
|
||||
];
|
||||
return baseOptions.filter((option) => availableEditors.includes(option.value));
|
||||
const availableEditorSet = new Set(availableEditors);
|
||||
return baseOptions.filter((option) => availableEditorSet.has(option.value));
|
||||
};
|
||||
|
||||
export const OpenInPicker = memo(function OpenInPicker({
|
||||
|
||||
@@ -304,16 +304,17 @@ function upsertTerminalIntoGroups(
|
||||
if (!destinationGroup) {
|
||||
return normalized;
|
||||
}
|
||||
const destinationTerminalIdSet = new Set(destinationGroup.terminalIds);
|
||||
|
||||
if (
|
||||
isNewTerminal &&
|
||||
!destinationGroup.terminalIds.includes(terminalId) &&
|
||||
!destinationTerminalIdSet.has(terminalId) &&
|
||||
destinationGroup.terminalIds.length >= MAX_TERMINALS_PER_GROUP
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
if (!destinationGroup.terminalIds.includes(terminalId)) {
|
||||
if (!destinationTerminalIdSet.has(terminalId)) {
|
||||
const anchorIndex = destinationGroup.terminalIds.indexOf(normalized.activeTerminalId);
|
||||
if (anchorIndex >= 0) {
|
||||
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, terminalId);
|
||||
|
||||
@@ -63,6 +63,7 @@ const initialState: UiState = {
|
||||
const persistedCollapsedProjectCwds = new Set<string>();
|
||||
const persistedExpandedProjectCwds = new Set<string>();
|
||||
const persistedProjectOrderCwds: string[] = [];
|
||||
const persistedProjectOrderCwdSet = new Set<string>();
|
||||
// Pre-fix persisted shape only listed expanded cwds, so anything not listed
|
||||
// was treated as collapsed. Track whether the loaded blob carried the new
|
||||
// `collapsedProjectCwds` field so we can preserve that legacy semantic for
|
||||
@@ -140,6 +141,7 @@ export function hydratePersistedProjectState(parsed: PersistedUiState): void {
|
||||
persistedCollapsedProjectCwds.clear();
|
||||
persistedExpandedProjectCwds.clear();
|
||||
persistedProjectOrderCwds.length = 0;
|
||||
persistedProjectOrderCwdSet.clear();
|
||||
persistedProjectStateUsesLegacyShape = !Array.isArray(parsed.collapsedProjectCwds);
|
||||
for (const cwd of parsed.collapsedProjectCwds ?? []) {
|
||||
if (typeof cwd === "string" && cwd.length > 0) {
|
||||
@@ -152,7 +154,8 @@ export function hydratePersistedProjectState(parsed: PersistedUiState): void {
|
||||
}
|
||||
}
|
||||
for (const cwd of parsed.projectOrderCwds ?? []) {
|
||||
if (typeof cwd === "string" && cwd.length > 0 && !persistedProjectOrderCwds.includes(cwd)) {
|
||||
if (typeof cwd === "string" && cwd.length > 0 && !persistedProjectOrderCwdSet.has(cwd)) {
|
||||
persistedProjectOrderCwdSet.add(cwd);
|
||||
persistedProjectOrderCwds.push(cwd);
|
||||
}
|
||||
}
|
||||
@@ -254,14 +257,22 @@ export function syncProjects(state: UiState, projects: readonly SyncProjectInput
|
||||
currentLogicalKeyByPhysicalKey.set(project.key, project.logicalKey);
|
||||
}
|
||||
currentProjectCwdsByLogicalKey.clear();
|
||||
const currentProjectCwdSetsByLogicalKey = new Map<string, Set<string>>();
|
||||
for (const project of projects) {
|
||||
const cwds = currentProjectCwdsByLogicalKey.get(project.logicalKey);
|
||||
if (cwds) {
|
||||
if (!cwds.includes(project.cwd)) {
|
||||
let cwdSet = currentProjectCwdSetsByLogicalKey.get(project.logicalKey);
|
||||
if (!cwdSet) {
|
||||
cwdSet = new Set(cwds);
|
||||
currentProjectCwdSetsByLogicalKey.set(project.logicalKey, cwdSet);
|
||||
}
|
||||
if (!cwdSet.has(project.cwd)) {
|
||||
cwdSet.add(project.cwd);
|
||||
cwds.push(project.cwd);
|
||||
}
|
||||
} else {
|
||||
currentProjectCwdsByLogicalKey.set(project.logicalKey, [project.cwd]);
|
||||
currentProjectCwdSetsByLogicalKey.set(project.logicalKey, new Set([project.cwd]));
|
||||
}
|
||||
}
|
||||
// Build reverse map: for each new logical key, which previous logical keys
|
||||
|
||||
@@ -70,11 +70,16 @@ export function createArchivedThreadsManager(config: {
|
||||
readonly idleTtlMs?: number;
|
||||
}) {
|
||||
const knownEnvironmentKeys = new Set<string>();
|
||||
const knownEnvironmentIdsByKey = new Map<string, ReadonlySet<EnvironmentId>>();
|
||||
const staleTime = config.staleTimeMs ?? DEFAULT_ARCHIVED_THREADS_STALE_TIME_MS;
|
||||
const idleTtl = config.idleTtlMs ?? DEFAULT_ARCHIVED_THREADS_IDLE_TTL_MS;
|
||||
|
||||
const snapshotsAtom = Atom.family((environmentKey: string) => {
|
||||
knownEnvironmentKeys.add(environmentKey);
|
||||
knownEnvironmentIdsByKey.set(
|
||||
environmentKey,
|
||||
new Set(parseArchivedThreadsEnvironmentKey(environmentKey)),
|
||||
);
|
||||
return Atom.make(
|
||||
Effect.promise(async (): Promise<ReadonlyArray<ArchivedSnapshotEntry>> => {
|
||||
const snapshots = await Promise.all(
|
||||
@@ -119,7 +124,7 @@ export function createArchivedThreadsManager(config: {
|
||||
|
||||
function refreshForEnvironment(environmentId: EnvironmentId): void {
|
||||
for (const environmentKey of knownEnvironmentKeys) {
|
||||
if (parseArchivedThreadsEnvironmentKey(environmentKey).includes(environmentId)) {
|
||||
if (knownEnvironmentIdsByKey.get(environmentKey)?.has(environmentId)) {
|
||||
config.getRegistry().refresh(getAtom(environmentKey));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user