diff --git a/apps/mobile/src/app/connections/index.tsx b/apps/mobile/src/app/connections/index.tsx
index 8e1ec1a9bf..6b5717094b 100644
--- a/apps/mobile/src/app/connections/index.tsx
+++ b/apps/mobile/src/app/connections/index.tsx
@@ -33,7 +33,7 @@ export default function ConnectionsRouteScreen() {
(
@@ -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() {
/>
- No backends connected yet.{"\n"}Tap{" "}
+ No environments connected yet.{"\n"}Tap{" "}
+ to add one.
diff --git a/apps/mobile/src/app/connections/new.tsx b/apps/mobile/src/app/connections/new.tsx
index 1a05ea40c5..6601090059 100644
--- a/apps/mobile/src/app/connections/new.tsx
+++ b/apps/mobile/src/app/connections/new.tsx
@@ -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() {
(
@@ -231,13 +232,11 @@ export default function ConnectionsNewRouteScreen() {
/>
- {connectionError ? : null}
+ {pairingConnectionError ? : null}
{
diff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx
index bc70ed2622..626b248a4f 100644
--- a/apps/mobile/src/app/index.tsx
+++ b/apps/mobile/src/app/index.tsx
@@ -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["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() {
- router.push("/connections")}
- separateBackground
- />
+
+ router.push("/connections")}
+ >
+
+
+
{/* Bottom toolbar: search + compose, visually split like iMessage */}
@@ -99,8 +130,10 @@ export default function HomeRouteScreen() {
router.push("/connections/new")}
onSelectThread={(thread) => {
router.push(buildThreadRoutePath(thread));
}}
diff --git a/apps/mobile/src/app/new/index.tsx b/apps/mobile/src/app/new/index.tsx
index a7fd8f809a..18ae1c16e4 100644
--- a/apps/mobile/src/app/new/index.tsx
+++ b/apps/mobile/src/app/new/index.tsx
@@ -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 (
@@ -65,17 +118,31 @@ export default function NewTaskRoute() {
{items.length === 0 ? (
-
-
- Loading projects...
+
+ {projectEmptyState.loading ? : null}
+
+ {projectEmptyState.title}
+
+ {projectEmptyState.detail}
+
+ {!catalogState.hasReadyEnvironment ? (
+ router.push("/connections/new")}
+ >
+
+ Add environment
+
+
+ ) : null}
) : (
diff --git a/apps/mobile/src/components/EmptyState.tsx b/apps/mobile/src/components/EmptyState.tsx
index 30ded6045a..c36647c90a 100644
--- a/apps/mobile/src/components/EmptyState.tsx
+++ b/apps/mobile/src/components/EmptyState.tsx
@@ -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 (
{props.title}
{props.detail}
+ {props.actionLabel && props.onAction ? (
+
+
+ {props.actionLabel}
+
+
+ ) : null}
);
}
diff --git a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx
index a73356129f..1dc6db74cc 100644
--- a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx
+++ b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx
@@ -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}
>
-
+
{props.environment.displayUrl}
+ {statusLabel ? (
+
+ {statusLabel}
+
+ ) : null}
{props.environment.connectionError ? (
();
@@ -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() {
(
@@ -231,13 +232,11 @@ export function NewConnectionRouteScreen() {
/>
- {connectionError ? : null}
+ {pairingConnectionError ? : null}
{
diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx
index a52f6c6a6d..00e4582957 100644
--- a/apps/mobile/src/features/home/HomeScreen.tsx
+++ b/apps/mobile/src/features/home/HomeScreen.tsx
@@ -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;
readonly threads: ReadonlyArray;
+ readonly catalogState: RemoteCatalogState;
readonly savedConnectionsById: Readonly>;
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>(() => 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 (
{!hasAnyThreads ? (
-
+
+
+ {emptyState.loading ? (
+
+
+
+ ) : null}
+
) : !hasResults ? (
) : (
diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx
index 74238bfe4e..50bd91b0c6 100644
--- a/apps/mobile/src/features/review/ReviewSheet.tsx
+++ b/apps/mobile/src/features/review/ReviewSheet.tsx
@@ -385,9 +385,6 @@ export function ReviewSheet() {
}}
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
- contentContainerStyle={{
- paddingTop: REVIEW_HEADER_SPACING,
- }}
>
{listHeader}
{!selectedSection ? (
diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts
index 958e3cd168..4592657316 100644
--- a/apps/mobile/src/features/review/reviewModel.test.ts
+++ b/apps/mobile/src/features/review/reviewModel.test.ts
@@ -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", () => {
diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts
index 11e5fe7a07..2fda1b9bd0 100644
--- a/apps/mobile/src/features/review/reviewModel.ts
+++ b/apps/mobile/src/features/review/reviewModel.ts
@@ -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(
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;
readonly turnDiffById: Readonly>;
readonly loadingTurnIds: Readonly>;
+ readonly loadingGitSections: boolean;
}): ReadonlyArray {
const turnItems = getReadyReviewCheckpoints(input.checkpoints).map(
(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(
diff --git a/apps/mobile/src/features/review/useReviewSections.ts b/apps/mobile/src/features/review/useReviewSections.ts
index 8b6bc93e0d..4c5a1abffb 100644
--- a/apps/mobile/src/features/review/useReviewSections.ts
+++ b/apps/mobile/src/features/review/useReviewSections.ts
@@ -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(
() =>
diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
index 1b082d9983..4b08a9fe4b 100644
--- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
@@ -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>(
() =>
@@ -1031,7 +1023,7 @@ export function ThreadTerminalRouteScreen() {
-
+
-
+
({
- 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 (
-
+
@@ -443,72 +437,74 @@ export function NewTaskDraftScreen(props: {
-
+
- {flow.attachments.length > 0 ? (
-
-
+ {flow.attachments.length > 0 ? (
+
+
+
+ ) : null}
+
+ void handlePickImages()} />
+ handleModelMenuAction(nativeEvent.event)}
+ themeVariant={isDarkMode ? "dark" : "light"}
+ >
+
+ }
+ />
+
+ handleOptionsMenuAction(nativeEvent.event)}
+ themeVariant={isDarkMode ? "dark" : "light"}
+ >
+
+
+ handleEnvironmentMenuAction(nativeEvent.event)}
+ themeVariant={isDarkMode ? "dark" : "light"}
+ >
+
+
+ handleWorkspaceMenuAction(nativeEvent.event)}
+ themeVariant={isDarkMode ? "dark" : "light"}
+ >
+
+
+ void handleStart()}
+ variant="primary"
+ disabled={
+ !flow.selectedProject ||
+ !flow.selectedModel ||
+ flow.prompt.trim().length === 0 ||
+ flow.submitting ||
+ (flow.workspaceMode === "worktree" && !flow.selectedBranchName)
+ }
/>
- ) : null}
-
- void handlePickImages()} />
- handleModelMenuAction(nativeEvent.event)}
- themeVariant={isDarkMode ? "dark" : "light"}
- >
- }
- />
-
- handleOptionsMenuAction(nativeEvent.event)}
- themeVariant={isDarkMode ? "dark" : "light"}
- >
-
-
- handleEnvironmentMenuAction(nativeEvent.event)}
- themeVariant={isDarkMode ? "dark" : "light"}
- >
-
-
- handleWorkspaceMenuAction(nativeEvent.event)}
- themeVariant={isDarkMode ? "dark" : "light"}
- >
-
-
- void handleStart()}
- variant="primary"
- disabled={
- !flow.selectedProject ||
- !flow.selectedModel ||
- flow.prompt.trim().length === 0 ||
- flow.submitting ||
- (flow.workspaceMode === "worktree" && !flow.selectedBranchName)
- }
- />
-
-
+
+
);
}
diff --git a/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx b/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx
index ab175cb84f..84ae71dce5 100644
--- a/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx
+++ b/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx
@@ -188,10 +188,10 @@ export function ThreadNavigationDrawer(props: {
{groupedThreads.map((group) => (
diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx
index fac10fde20..40eda92d0f 100644
--- a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx
+++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx
@@ -55,10 +55,10 @@ export function GitBranchesSheet() {
return (
diff --git a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx
index 4f944e9ce4..df163d3a7d 100644
--- a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx
+++ b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx
@@ -65,10 +65,10 @@ export function GitCommitSheet() {
diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx
index d664299895..5aad049057 100644
--- a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx
+++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx
@@ -184,10 +184,10 @@ export function GitOverviewSheet() {
diff --git a/apps/mobile/src/lib/storage.ts b/apps/mobile/src/lib/storage.ts
index c13caa9a36..7b7b63c433 100644
--- a/apps/mobile/src/lib/storage.ts
+++ b/apps/mobile/src/lib/storage.ts
@@ -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(key: string): Promise {
}
}
+function isRecord(value: unknown): value is Record {
+ 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 {
+ 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 {
+ 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 {
+ 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> {
const parsed = await readJsonStorageItem<{
readonly connections?: ReadonlyArray;
diff --git a/apps/mobile/src/state/use-remote-catalog.ts b/apps/mobile/src/state/use-remote-catalog.ts
index 65037384d6..cafecc8381 100644
--- a/apps/mobile/src/state/use-remote-catalog.ts
+++ b/apps/mobile/src/state/use-remote-catalog.ts
@@ -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(() => {
+ 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,
};
}
diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts
index fcbb46a0ec..d2657ad55e 100644
--- a/apps/mobile/src/state/use-remote-environment-registry.ts
+++ b/apps/mobile/src/state/use-remote-environment-registry.ts
@@ -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 void>();
+const SAVED_CONNECTION_BOOTSTRAP_TIMEOUT_MS = 8_000;
interface RemoteEnvironmentLocalState {
readonly isLoadingSavedConnection: boolean;
@@ -137,22 +150,49 @@ function setEnvironmentConnectionStatus(
}));
}
+function withTimeout(
+ promise: Promise,
+ timeoutMs: number,
+ timeoutMessage: string,
+): Promise {
+ return new Promise((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,
diff --git a/apps/mobile/src/state/use-shell-snapshot.ts b/apps/mobile/src/state/use-shell-snapshot.ts
index ed7c75eeee..56d69db7bf 100644
--- a/apps/mobile/src/state/use-shell-snapshot.ts
+++ b/apps/mobile/src/state/use-shell-snapshot.ts
@@ -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>
+>({}).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
+> {
+ return useAtomValue(cachedShellSnapshotMetadataAtom);
+}
+
export function useShellSnapshot(environmentId: EnvironmentId | null): ShellSnapshotState {
const targetKey = getShellSnapshotTargetKey({ environmentId });
const state = useAtomValue(
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 86ca3e422a..7185a082ab 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -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);
}
}
diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx
index 6b5f2dacc2..cc023d34cf 100644
--- a/apps/web/src/components/chat/OpenInPicker.tsx
+++ b/apps/web/src/components/chat/OpenInPicker.tsx
@@ -146,7 +146,8 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray availableEditors.includes(option.value));
+ const availableEditorSet = new Set(availableEditors);
+ return baseOptions.filter((option) => availableEditorSet.has(option.value));
};
export const OpenInPicker = memo(function OpenInPicker({
diff --git a/apps/web/src/terminalUiStateStore.ts b/apps/web/src/terminalUiStateStore.ts
index 3039201ac3..cc577b5f9e 100644
--- a/apps/web/src/terminalUiStateStore.ts
+++ b/apps/web/src/terminalUiStateStore.ts
@@ -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);
diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts
index b76f5f6859..f16495bed7 100644
--- a/apps/web/src/uiStateStore.ts
+++ b/apps/web/src/uiStateStore.ts
@@ -63,6 +63,7 @@ const initialState: UiState = {
const persistedCollapsedProjectCwds = new Set();
const persistedExpandedProjectCwds = new Set();
const persistedProjectOrderCwds: string[] = [];
+const persistedProjectOrderCwdSet = new Set();
// 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>();
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
diff --git a/packages/client-runtime/src/archivedThreadsState.ts b/packages/client-runtime/src/archivedThreadsState.ts
index 1abbad0988..b1d6ec59e4 100644
--- a/packages/client-runtime/src/archivedThreadsState.ts
+++ b/packages/client-runtime/src/archivedThreadsState.ts
@@ -70,11 +70,16 @@ export function createArchivedThreadsManager(config: {
readonly idleTtlMs?: number;
}) {
const knownEnvironmentKeys = new Set();
+ const knownEnvironmentIdsByKey = new Map>();
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> => {
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));
}
}