Migrate mobile UI to Uniwind and sheet-based thread routing

- Replace NativeWind styling with Uniwind tokens and helpers
- Split thread and git flows into nested sheet routes
- Add shared git state hooks and project favicon rendering
This commit is contained in:
Julius Marminge committed 2026-04-13 14:44:02 -07:00
1 parent 87d12d72a1
commit db30cdd26b
86 files changed
+4973 -4632

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
module.exports = function (api) {
api.cache(true);
return {
presets: [["babel-preset-expo", { unstable_transformImportMeta: true }], "nativewind/babel"],
presets: [["babel-preset-expo", { unstable_transformImportMeta: true }]],
};
};
+181 -6
View File
@@ -1,17 +1,192 @@
@import "tailwindcss/theme.css" layer(theme);
@import "tailwindcss/preflight.css" layer(base);
@import "tailwindcss/utilities.css" layer(utilities);
@import "tailwindcss";
@import "uniwind";
@import "nativewind/theme";
/* ─── Theme tokens ──────────────────────────────────────────────────── */
@layer theme {
:root {
@variant light {
/* Page backgrounds */
--color-screen: #f2f2f7;
--color-sheet: rgba(242, 242, 247, 0.98);
/* Card / surface */
--color-card: #ffffff;
--color-card-alt: #f5f5f5;
--color-card-translucent: rgba(255, 255, 255, 0.94);
/* Text */
--color-foreground: #262626;
--color-foreground-secondary: #525252;
--color-foreground-muted: #737373;
--color-foreground-tertiary: #a3a3a3;
/* Borders & separators */
--color-border: rgba(0, 0, 0, 0.08);
--color-border-subtle: rgba(0, 0, 0, 0.06);
--color-separator: rgba(0, 0, 0, 0.04);
/* Subtle backgrounds (badges, pills, overlays) */
--color-subtle: rgba(0, 0, 0, 0.04);
--color-subtle-strong: rgba(0, 0, 0, 0.08);
/* Primary action */
--color-primary: #262626;
--color-primary-foreground: #ffffff;
--color-primary-shadow: rgba(0, 0, 0, 0.18);
/* Secondary action */
--color-secondary: #ffffff;
--color-secondary-foreground: #262626;
--color-secondary-border: rgba(0, 0, 0, 0.08);
/* Danger */
--color-danger: #fef2f2;
--color-danger-border: rgba(239, 68, 68, 0.12);
--color-danger-foreground: #dc2626;
/* Inputs */
--color-input: #ffffff;
--color-input-border: rgba(0, 0, 0, 0.1);
--color-placeholder: #a3a3a3;
/* Icons */
--color-icon: #262626;
--color-icon-muted: #525252;
--color-icon-subtle: #a3a3a3;
/* Header / glass chrome */
--color-header: rgba(255, 255, 255, 0.97);
--color-header-border: rgba(0, 0, 0, 0.06);
/* StatusBar */
--color-status-bar: #f2f2f7;
/* Markdown */
--color-md-body: #262626;
--color-md-strong: #171717;
--color-md-link: #2563eb;
--color-md-blockquote-border: rgba(0, 0, 0, 0.08);
--color-md-blockquote-bg: rgba(0, 0, 0, 0.02);
--color-md-code-bg: rgba(0, 0, 0, 0.04);
--color-md-code-text: #262626;
--color-md-user-code-bg: rgba(255, 255, 255, 0.55);
--color-md-user-code-text: #262626;
--color-md-user-fence-bg: rgba(0, 0, 0, 0.04);
--color-md-user-fence-text: #1e3a5f;
--color-md-hr: rgba(0, 0, 0, 0.08);
/* Drawer / modal backdrop */
--color-backdrop: rgba(0, 0, 0, 0.22);
--color-drawer: rgba(255, 255, 255, 0.99);
--color-drawer-shadow: rgba(0, 0, 0, 0.12);
/* Misc */
--color-dot-separator: rgba(0, 0, 0, 0.2);
--color-wordmark: #262626;
--color-chevron: rgba(0, 0, 0, 0.2);
}
@variant dark {
/* Page backgrounds */
--color-screen: #0a0a0a;
--color-sheet: rgba(14, 14, 14, 0.98);
/* Card / surface */
--color-card: #171717;
--color-card-alt: #1c1c1c;
--color-card-translucent: rgba(17, 17, 17, 0.94);
/* Text */
--color-foreground: #f5f5f5;
--color-foreground-secondary: #a3a3a3;
--color-foreground-muted: #737373;
--color-foreground-tertiary: #525252;
/* Borders & separators */
--color-border: rgba(255, 255, 255, 0.06);
--color-border-subtle: rgba(255, 255, 255, 0.04);
--color-separator: rgba(255, 255, 255, 0.03);
/* Subtle backgrounds (badges, pills, overlays) */
--color-subtle: rgba(255, 255, 255, 0.04);
--color-subtle-strong: rgba(255, 255, 255, 0.08);
/* Primary action */
--color-primary: #f5f5f5;
--color-primary-foreground: #0a0a0a;
--color-primary-shadow: rgba(0, 0, 0, 0.22);
/* Secondary action */
--color-secondary: rgba(255, 255, 255, 0.04);
--color-secondary-foreground: #f5f5f5;
--color-secondary-border: rgba(255, 255, 255, 0.06);
/* Danger */
--color-danger: rgba(239, 68, 68, 0.14);
--color-danger-border: rgba(248, 113, 113, 0.18);
--color-danger-foreground: #fca5a5;
/* Inputs */
--color-input: #141414;
--color-input-border: rgba(255, 255, 255, 0.08);
--color-placeholder: #737373;
/* Icons */
--color-icon: #f5f5f5;
--color-icon-muted: #a3a3a3;
--color-icon-subtle: #737373;
/* Header / glass chrome */
--color-header: rgba(10, 10, 10, 0.97);
--color-header-border: rgba(255, 255, 255, 0.06);
/* StatusBar */
--color-status-bar: #0a0a0a;
/* Markdown */
--color-md-body: #e5e5e5;
--color-md-strong: #f5f5f5;
--color-md-link: #60a5fa;
--color-md-blockquote-border: rgba(255, 255, 255, 0.1);
--color-md-blockquote-bg: rgba(255, 255, 255, 0.03);
--color-md-code-bg: rgba(255, 255, 255, 0.06);
--color-md-code-text: #e5e5e5;
--color-md-user-code-bg: rgba(255, 255, 255, 0.1);
--color-md-user-code-text: #e5e5e5;
--color-md-user-fence-bg: rgba(255, 255, 255, 0.08);
--color-md-user-fence-text: #e5e5e5;
--color-md-hr: rgba(255, 255, 255, 0.08);
/* Drawer / modal backdrop */
--color-backdrop: rgba(0, 0, 0, 0.48);
--color-drawer: rgba(14, 14, 14, 0.99);
--color-drawer-shadow: rgba(0, 0, 0, 0.32);
/* Misc */
--color-dot-separator: rgba(255, 255, 255, 0.2);
--color-wordmark: #f5f5f5;
--color-chevron: rgba(255, 255, 255, 0.2);
}
}
}
/* ─── Font family ───────────────────────────────────────────────────── */
@theme {
--font-sans: "DMSans_400Regular";
--font-medium: "DMSans_500Medium";
--font-bold: "DMSans_700Bold";
}
/* ─── Custom utilities ──────────────────────────────────────────────── */
@utility font-t3-medium {
font-weight: 500;
font-family: "DMSans_500Medium";
}
@utility font-t3-bold {
font-weight: 700;
font-family: "DMSans_700Bold";
}
@utility font-t3-extrabold {
font-family: "DMSans_700Bold";
font-weight: 800;
}
+4 -4
View File
@@ -1,6 +1,6 @@
const path = require("node:path");
const { getDefaultConfig } = require("expo/metro-config");
const { withNativewind } = require("nativewind/metro");
const { withUniwindConfig } = require("uniwind/metro");
/** @type {import("expo/metro-config").MetroConfig} */
const config = getDefaultConfig(__dirname);
@@ -8,7 +8,7 @@ const workspaceRoot = path.resolve(__dirname, "../..");
config.watchFolders = [...new Set([...(config.watchFolders ?? []), workspaceRoot])];
module.exports = withNativewind(config, {
input: "./global.css",
globalClassNamePolyfill: true,
module.exports = withUniwindConfig(config, {
cssEntryFile: "./global.css",
polyfills: { rem: 14 },
});
-5
View File
@@ -1,5 +0,0 @@
/// <reference types="react-native-css/types" />
// NOTE: This file is generated by react-native-css / NativeWind integration.
declare module "*.css";
+4 -5
View File
@@ -13,6 +13,7 @@
},
"dependencies": {
"@callstack/liquid-glass": "^0.7.1",
"@effect/atom-react": "catalog:",
"@expo-google-fonts/dm-sans": "^0.4.2",
"@gorhom/bottom-sheet": "^5",
"@legendapp/list": "^3.0.0-beta.44",
@@ -22,6 +23,7 @@
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"clsx": "^2.1.1",
"effect": "catalog:",
"expo": "~55.0.14",
"expo-camera": "~55.0.15",
@@ -41,12 +43,10 @@
"expo-splash-screen": "~55.0.13",
"expo-symbols": "~55.0.5",
"expo-updates": "~55.0.16",
"nativewind": "5.0.0-preview.3",
"punycode": "^2.3.1",
"react": "19.2.0",
"react-dom": "19.2.0",
"react-native": "0.83.4",
"react-native-css": "3.0.7",
"react-native-gesture-handler": "~2.30.0",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.20.7",
@@ -56,14 +56,13 @@
"react-native-screens": "~4.23.0",
"react-native-svg": "15.15.3",
"react-native-worklets": "0.7.2",
"tailwind-merge": "^3.5.0",
"uniwind": "^1.6.2",
"zustand": "^5.0.12"
},
"devDependencies": {
"@tailwindcss/postcss": "4.1.12",
"@types/react": "~19.2.10",
"babel-preset-expo": "~55.0.8",
"lightningcss": "1.30.1",
"postcss": "^8.5.8",
"tailwindcss": "4.1.12",
"typescript": "~5.9.2"
}
-5
View File
@@ -1,5 +0,0 @@
export default {
plugins: {
"@tailwindcss/postcss": {},
},
};
+15 -15
View File
@@ -1,12 +1,12 @@
import { Link } from "expo-router";
import { Pressable, ScrollView, useColorScheme } from "react-native";
import { Pressable, ScrollView, StyleSheet, View } from "react-native";
import { useResolveClassNames } from "uniwind";
import { AppText as Text } from "../components/AppText";
import { makeAppPalette } from "../lib/theme";
export default function NotFoundRoute() {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen"));
const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary"));
return (
<ScrollView
@@ -19,23 +19,23 @@ export default function NotFoundRoute() {
paddingHorizontal: 24,
paddingVertical: 32,
}}
style={{ flex: 1, backgroundColor: palette.screenBackground }}
style={[{ flex: 1 }, screenBgStyle]}
>
<Text className="text-[28px] font-t3-bold" selectable style={{ color: palette.text }}>
<Text className="text-[28px] font-t3-bold text-foreground" selectable>
Route not found
</Text>
<Link href="/" asChild>
<Pressable
style={{
backgroundColor: palette.primaryButton,
borderRadius: 999,
paddingHorizontal: 20,
paddingVertical: 14,
}}
style={[
{
borderRadius: 999,
paddingHorizontal: 20,
paddingVertical: 14,
},
primaryBgStyle,
]}
>
<Text className="text-[16px] font-t3-bold" style={{ color: palette.primaryButtonText }}>
Return home
</Text>
<Text className="text-[16px] font-t3-bold text-primary-foreground">Return home</Text>
</Pressable>
</Link>
</ScrollView>
+31 -16
View File
@@ -6,15 +6,15 @@ import {
DMSans_700Bold,
useFonts,
} from "@expo-google-fonts/dm-sans";
import { BottomSheetModalProvider } from "@gorhom/bottom-sheet";
import Stack from "expo-router/stack";
import { StatusBar, useColorScheme } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { useCSSVariable, useResolveClassNames } from "uniwind";
import { LoadingScreen } from "../components/LoadingScreen";
import { makeAppPalette } from "../lib/theme";
import { AppAtomRegistryProvider } from "../state/atomRegistry";
import {
useRemoteEnvironmentBootstrap,
useRemoteEnvironmentState,
@@ -22,11 +22,13 @@ import {
function AppNavigator() {
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
const isDarkMode = useColorScheme() !== "light";
const palette = makeAppPalette(isDarkMode);
const colorScheme = useColorScheme();
const statusBarBg = useCSSVariable("--color-status-bar");
const sheetStyle = useResolveClassNames("bg-sheet");
const screenStyle = useResolveClassNames("bg-screen");
const newTaskScreenOptions = {
contentStyle: { backgroundColor: palette.sheetBackground },
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
@@ -35,7 +37,7 @@ function AppNavigator() {
};
const connectionSheetScreenOptions = {
contentStyle: { backgroundColor: palette.sheetBackground },
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
@@ -50,18 +52,27 @@ function AppNavigator() {
return (
<>
<StatusBar
barStyle={palette.statusBarStyle}
backgroundColor={palette.statusBarBackground}
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
backgroundColor={statusBarBg as string}
translucent
/>
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen
name="index"
options={{
contentStyle: { backgroundColor: "transparent" },
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
}}
/>
<Stack.Screen name="connections" options={connectionSheetScreenOptions} />
<Stack.Screen name="new" options={newTaskScreenOptions} />
<Stack.Screen
name="threads/[environmentId]/[threadId]"
options={{
animation: "slide_from_right",
contentStyle: { backgroundColor: palette.screenBackground },
contentStyle: { backgroundColor: "transparent" },
gestureEnabled: true,
headerShown: false,
}}
@@ -80,14 +91,18 @@ export default function RootLayout() {
useRemoteEnvironmentBootstrap();
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<BottomSheetModalProvider>
<AppAtomRegistryProvider>
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
{fontsLoaded ? <AppNavigator /> : <LoadingScreen message="Loading remote workspace…" />}
{fontsLoaded ? (
<AppNavigator />
) : (
<LoadingScreen message="Loading remote workspace…" />
)}
</SafeAreaProvider>
</BottomSheetModalProvider>
</KeyboardProvider>
</GestureHandlerRootView>
</KeyboardProvider>
</GestureHandlerRootView>
</AppAtomRegistryProvider>
);
}
+13 -1
View File
@@ -1,14 +1,26 @@
import Stack from "expo-router/stack";
import { useResolveClassNames } from "uniwind";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
anchor: "index",
};
export default function ConnectionsLayout() {
const contentStyle = useResolveClassNames("bg-sheet");
const connSheetBg = String(useThemeColor("--color-sheet"));
const headerTint = String(useThemeColor("--color-icon"));
return (
<Stack
screenOptions={{
contentStyle: { backgroundColor: "rgba(246,244,239,0.98)" },
contentStyle,
headerStyle: { backgroundColor: connSheetBg },
headerTintColor: headerTint,
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
headerShadowVisible: false,
headerBackButtonDisplayMode: "minimal",
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
+3 -5
View File
@@ -1,7 +1,6 @@
import Stack from "expo-router/stack";
import { useColorScheme } from "react-native";
import { useResolveClassNames } from "uniwind";
import { makeAppPalette } from "../../lib/theme";
import { NewTaskFlowProvider } from "../../features/threads/new-task-flow-provider";
export const unstable_settings = {
@@ -9,14 +8,13 @@ export const unstable_settings = {
};
export default function NewTaskLayout() {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const sheetStyle = useResolveClassNames("bg-sheet");
return (
<NewTaskFlowProvider>
<Stack
screenOptions={{
contentStyle: { backgroundColor: palette.sheetBackground },
contentStyle: sheetStyle,
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
+39 -26
View File
@@ -1,19 +1,22 @@
import { Link, Stack } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useMemo } from "react";
import { Pressable, ScrollView, useColorScheme, View } from "react-native";
import { 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 { makeAppPalette } from "../../lib/theme";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
export default function NewTaskRoute() {
const { projects, threads } = useRemoteCatalog();
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const { savedConnectionsById } = useRemoteEnvironmentState();
const insets = useSafeAreaInsets();
const chevronColor = useThemeColor("--color-chevron");
const borderSubtleColor = useThemeColor("--color-border-subtle");
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
@@ -32,6 +35,7 @@ export default function NewTaskRoute() {
id: project.id,
key: group.key,
title: project.title,
workspaceRoot: project.workspaceRoot,
};
})
.filter((entry) => entry !== null),
@@ -39,34 +43,38 @@ export default function NewTaskRoute() {
);
return (
<View collapsable={false} style={{ flex: 1, backgroundColor: palette.sheetBackground }}>
<Stack.Screen options={{ title: "Choose Project" }} />
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen options={{ headerShown: false }} />
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold">Choose project</Text>
</View>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 16,
paddingTop: 8,
paddingBottom: Math.max(insets.bottom, 18) + 18,
}}
>
{items.length === 0 ? (
<View
collapsable={false}
className="items-center rounded-[24px] px-6 py-8"
style={{ backgroundColor: palette.card }}
>
<Text className="text-[16px] font-medium" style={{ color: palette.textMuted }}>
Loading projects…
<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...
</Text>
</View>
) : (
<View
collapsable={false}
className="overflow-hidden rounded-[24px]"
style={{ backgroundColor: palette.card }}
>
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{items.map((item, index) => {
const isFirst = index === 0;
const isLast = index === items.length - 1;
@@ -85,12 +93,12 @@ export default function NewTaskRoute() {
asChild
>
<Pressable
className="bg-card"
style={{
paddingHorizontal: 16,
paddingVertical: 18,
borderTopWidth: isFirst ? 0 : 1,
borderTopColor: palette.borderSubtle,
backgroundColor: palette.card,
borderTopColor: borderSubtleColor,
borderTopLeftRadius: isFirst ? 24 : 0,
borderTopRightRadius: isFirst ? 24 : 0,
borderBottomLeftRadius: isLast ? 24 : 0,
@@ -98,15 +106,20 @@ export default function NewTaskRoute() {
}}
>
<View className="flex-row items-center justify-between gap-3">
<ProjectFavicon
size={22}
projectTitle={item.title}
httpBaseUrl={savedConnectionsById[item.environmentId]?.httpBaseUrl ?? null}
workspaceRoot={item.workspaceRoot}
bearerToken={savedConnectionsById[item.environmentId]?.bearerToken ?? null}
/>
<View className="flex-1">
<Text className="text-[18px] font-t3-bold" style={{ color: palette.text }}>
{item.title}
</Text>
<Text className="text-[18px] font-t3-bold">{item.title}</Text>
</View>
<SymbolView
name="chevron.right"
size={14}
tintColor={palette.chevronColor}
tintColor={chevronColor}
type="monochrome"
/>
</View>
@@ -1,5 +0,0 @@
import { ThreadRouteScreen } from "../../../features/threads/ThreadRouteScreen";
export default function ThreadRoute() {
return <ThreadRouteScreen />;
}
@@ -0,0 +1,43 @@
import Stack from "expo-router/stack";
import { StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
export default function ThreadLayout() {
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
return (
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen
name="index"
options={{
contentStyle: { backgroundColor: "transparent" },
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
}}
/>
<Stack.Screen
name="git"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.85],
sheetGrabberVisible: true,
}}
/>
<Stack.Screen
name="git-confirm"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.4],
sheetGrabberVisible: true,
}}
/>
</Stack>
);
}
@@ -0,0 +1,5 @@
import { GitConfirmSheet } from "../../../../features/threads/git/GitConfirmSheet";
export default function GitConfirmRoute() {
return <GitConfirmSheet />;
}
@@ -0,0 +1,45 @@
import Stack from "expo-router/stack";
import { StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
export const unstable_settings = {
anchor: "index",
};
export default function GitSheetLayout() {
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
const headerBg = { backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor };
return (
<Stack
screenOptions={{
contentStyle: sheetStyle,
headerShown: false,
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen
name="commit"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Commit changes",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="branches"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Branches & worktrees",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
</Stack>
);
}
@@ -0,0 +1,5 @@
import { GitBranchesSheet } from "../../../../../features/threads/git/GitBranchesSheet";
export default function GitBranchesRoute() {
return <GitBranchesSheet />;
}
@@ -0,0 +1,5 @@
import { GitCommitSheet } from "../../../../../features/threads/git/GitCommitSheet";
export default function GitCommitRoute() {
return <GitCommitSheet />;
}
@@ -0,0 +1,5 @@
import { GitOverviewSheet } from "../../../../../features/threads/git/GitOverviewSheet";
export default function GitRoute() {
return <GitOverviewSheet />;
}
@@ -0,0 +1,5 @@
import { ThreadRouteScreen } from "../../../../features/threads/ThreadRouteScreen";
export default function ThreadRoute() {
return <ThreadRouteScreen />;
}
+21 -299
View File
@@ -1,318 +1,40 @@
import {
Text as RNText,
type StyleProp,
TextInput as RNTextInput,
type TextInputProps as RNTextInputProps,
type TextProps as RNTextProps,
type TextStyle,
useColorScheme,
type ViewStyle,
} from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
type ClassNameProp = {
readonly className?: string;
};
import { cn } from "../lib/cn";
const colorMap = {
"text-white": "#ffffff",
"text-neutral-50": "#fafafa",
"text-neutral-300": "#d4d4d4",
"text-neutral-400": "#a3a3a3",
"text-neutral-500": "#737373",
"text-neutral-600": "#525252",
"text-neutral-700": "#404040",
"text-neutral-950": "#0a0a0a",
"text-orange-300": "#fdba74",
"text-orange-600": "#ea580c",
"text-orange-700": "#c2410c",
"text-emerald-300": "#6ee7b7",
"text-emerald-700": "#047857",
"text-rose-300": "#fda4af",
"text-rose-700": "#be123c",
"text-sky-300": "#7dd3fc",
"text-sky-700": "#0369a1",
} satisfies Record<string, string>;
export type AppTextProps = RNTextProps & { readonly className?: string };
const backgroundColorMap = {
"bg-white": "#ffffff",
"bg-neutral-900": "#171717",
"bg-neutral-950/70": "rgba(10, 10, 10, 0.7)",
} satisfies Record<string, string>;
const borderColorMap = {
"border-neutral-200": "#e5e5e5",
"border-white/8": "rgba(255, 255, 255, 0.08)",
} satisfies Record<string, string>;
function activeToken(token: string, isDarkMode: boolean) {
if (!token.startsWith("dark:")) {
return token;
}
return isDarkMode ? token.slice(5) : null;
/**
* Thin wrapper around RN Text with default font-family and foreground color.
* Uses Uniwind className — no manual style parsing.
*/
export function AppText({ className, ...props }: AppTextProps) {
return <RNText className={cn("font-sans text-foreground", className)} {...props} />;
}
function resolveTextStyle(className: string | undefined, isDarkMode: boolean): TextStyle {
const style: TextStyle = {
color: isDarkMode ? "#f5f5f5" : "#262626",
fontFamily: "DMSans_400Regular",
};
export type AppTextInputProps = RNTextInputProps & { readonly className?: string };
let hasLeadingNone = false;
for (const rawToken of className?.split(/\s+/) ?? []) {
const token = activeToken(rawToken, isDarkMode);
if (!token) {
continue;
}
if (token in colorMap) {
style.color = colorMap[token as keyof typeof colorMap];
continue;
}
if (token === "font-sans") {
style.fontFamily = "DMSans_400Regular";
continue;
}
if (token === "font-medium") {
style.fontFamily = "DMSans_500Medium";
continue;
}
if (token === "font-bold") {
style.fontFamily = "DMSans_700Bold";
continue;
}
if (token === "font-extrabold") {
style.fontFamily = "DMSans_700Bold";
continue;
}
if (token === "font-t3-medium") {
style.fontFamily = "DMSans_500Medium";
continue;
}
if (token === "font-t3-bold") {
style.fontFamily = "DMSans_700Bold";
continue;
}
if (token === "font-t3-extrabold") {
style.fontFamily = "DMSans_700Bold";
continue;
}
if (token === "text-xs") {
style.fontSize = 12;
continue;
}
if (token === "text-sm") {
style.fontSize = 14;
continue;
}
if (token === "text-lg") {
style.fontSize = 18;
continue;
}
if (token === "leading-none") {
hasLeadingNone = true;
continue;
}
if (token === "leading-5") {
style.lineHeight = 20;
continue;
}
if (token === "uppercase") {
style.textTransform = "uppercase";
continue;
}
if (token === "capitalize") {
style.textTransform = "capitalize";
continue;
}
if (token === "mt-2") {
style.marginTop = 8;
continue;
}
if (token === "pt-1.5") {
style.paddingTop = 6;
continue;
}
if (token === "pb-1") {
style.paddingBottom = 4;
continue;
}
if (token === "max-w-[640px]") {
style.maxWidth = 640;
continue;
}
const pxValue = token.match(/^text-\[(\d+)px\]$/);
if (pxValue) {
style.fontSize = Number(pxValue[1]);
continue;
}
const lineHeightValue = token.match(/^leading-\[(\d+)px\]$/);
if (lineHeightValue) {
style.lineHeight = Number(lineHeightValue[1]);
continue;
}
const trackingValue = token.match(/^tracking-\[([0-9.]+)px\]$/);
if (trackingValue) {
style.letterSpacing = Number(trackingValue[1]);
}
}
if (hasLeadingNone) {
style.lineHeight = style.fontSize ?? 16;
}
return style;
}
function resolveTextInputStyle(
className: string | undefined,
isDarkMode: boolean,
): ViewStyle & TextStyle {
const style: ViewStyle & TextStyle = {
color: isDarkMode ? "#f5f5f5" : "#262626",
backgroundColor: isDarkMode ? "#141414" : "#ffffff",
borderColor: isDarkMode ? "rgba(255, 255, 255, 0.08)" : "#e5e5e5",
borderWidth: 1,
borderRadius: 16,
paddingHorizontal: 14,
paddingVertical: 12,
fontSize: 15,
fontFamily: "DMSans_400Regular",
minHeight: 54,
};
for (const rawToken of className?.split(/\s+/) ?? []) {
const token = activeToken(rawToken, isDarkMode);
if (!token) {
continue;
}
if (token in colorMap) {
style.color = colorMap[token as keyof typeof colorMap];
continue;
}
if (token in backgroundColorMap) {
style.backgroundColor = backgroundColorMap[token as keyof typeof backgroundColorMap];
continue;
}
if (token in borderColorMap) {
style.borderColor = borderColorMap[token as keyof typeof borderColorMap];
continue;
}
if (token === "border") {
style.borderWidth = 1;
continue;
}
if (token === "rounded-2xl") {
style.borderRadius = 16;
continue;
}
if (token === "rounded-[18px]") {
style.borderRadius = 18;
continue;
}
if (token === "px-3.5") {
style.paddingHorizontal = 14;
continue;
}
if (token === "py-3") {
style.paddingVertical = 12;
continue;
}
if (token === "py-3.5") {
style.paddingVertical = 14;
continue;
}
if (token === "font-sans") {
style.fontFamily = "DMSans_400Regular";
continue;
}
if (token === "text-sm") {
style.fontSize = 14;
continue;
}
const minHeightValue = token.match(/^min-h-\[(\d+)px\]$/);
if (minHeightValue) {
style.minHeight = Number(minHeightValue[1]);
continue;
}
const maxHeightValue = token.match(/^max-h-\[(\d+)px\]$/);
if (maxHeightValue) {
style.maxHeight = Number(maxHeightValue[1]);
continue;
}
const textPxValue = token.match(/^text-\[(\d+)px\]$/);
if (textPxValue) {
style.fontSize = Number(textPxValue[1]);
continue;
}
const lineHeightValue = token.match(/^leading-\[(\d+)px\]$/);
if (lineHeightValue) {
style.lineHeight = Number(lineHeightValue[1]);
}
}
return style;
}
export type AppTextProps = RNTextProps & ClassNameProp;
export function AppText({ className, style, ...props }: AppTextProps) {
const isDarkMode = useColorScheme() === "dark";
return <RNText {...props} style={[resolveTextStyle(className, isDarkMode), style]} />;
}
export type AppTextInputProps = RNTextInputProps & ClassNameProp;
export function AppTextInput({
className,
placeholderTextColor,
style,
...props
}: AppTextInputProps) {
const isDarkMode = useColorScheme() === "dark";
const resolvedStyle = resolveTextInputStyle(className, isDarkMode);
/**
* Thin wrapper around RN TextInput with default input styling.
* Uses Uniwind className — no manual style parsing.
*/
export function AppTextInput({ className, placeholderTextColor, ...props }: AppTextInputProps) {
const placeholderColor = useThemeColor("--color-placeholder");
return (
<RNTextInput
className={cn(
"min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-[15px] text-foreground",
className,
)}
placeholderTextColor={placeholderTextColor ?? placeholderColor}
{...props}
placeholderTextColor={placeholderTextColor ?? (isDarkMode ? "#737373" : "#a3a3a3")}
style={[resolvedStyle as StyleProp<TextStyle>, style]}
/>
);
}
+7 -15
View File
@@ -1,13 +1,10 @@
import { Image, View, useColorScheme } from "react-native";
import { Image, View } from "react-native";
import { makeAppPalette } from "../lib/theme";
import { AppText as Text } from "./AppText";
const BRAND_MARK_SOURCE = require("../../../../assets/dev/blueprint-ios-1024.png");
export function BrandMark(props: { readonly compact?: boolean; readonly stageLabel?: string }) {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const compact = props.compact ?? false;
const iconSize = compact ? 32 : 44;
const stageLabel = props.stageLabel ?? "Alpha";
@@ -26,27 +23,22 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab
<View className="gap-1">
<View className="flex-row items-center gap-2">
<Text
className="text-[17px] font-t3-bold"
style={{ color: palette.text, letterSpacing: -0.4 }}
className="text-[17px] font-t3-bold text-foreground"
style={{ letterSpacing: -0.4 }}
>
T3 Code
</Text>
<View
className="rounded-full px-2 py-1"
style={{
backgroundColor: palette.subtleBg,
}}
>
<View className="rounded-full bg-subtle px-2 py-1">
<Text
className="text-[10px] font-t3-bold uppercase"
style={{ color: palette.textMuted, letterSpacing: 1.1 }}
className="text-[10px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1.1 }}
>
{stageLabel}
</Text>
</View>
</View>
{!compact ? (
<Text className="text-[12px] font-medium" style={{ color: palette.textMuted }}>
<Text className="text-[12px] font-medium text-foreground-muted">
Mobile control surface for your live coding environments
</Text>
) : null}
@@ -1,8 +1,8 @@
import { SymbolView } from "expo-symbols";
import { Image, Pressable, ScrollView, useColorScheme, View } from "react-native";
import { Image, Pressable, ScrollView, View } from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { makeAppPalette } from "../lib/theme";
export interface ComposerAttachmentStripProps {
/** Attachment images to display. */
@@ -22,8 +22,7 @@ export interface ComposerAttachmentStripProps {
* buttons. Used by both the thread composer and the new-task draft screen.
*/
export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const subtleBg = useThemeColor("--color-subtle");
const size = props.imageSize ?? 72;
const radius = props.imageBorderRadius ?? 16;
@@ -50,7 +49,7 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
width: size,
height: size,
borderRadius: radius,
backgroundColor: palette.subtleBg,
backgroundColor: subtleBg,
}}
resizeMode="cover"
/>
+24 -19
View File
@@ -1,9 +1,9 @@
import type { ComponentProps, ReactNode } from "react";
import { Pressable, useColorScheme, View } from "react-native";
import { Pressable, View } from "react-native";
import { SymbolView } from "expo-symbols";
import { useThemeColor } from "../lib/useThemeColor";
import { AppText as Text } from "./AppText";
import { makeAppPalette } from "../lib/theme";
export function ControlPill(props: {
readonly icon?: ComponentProps<typeof SymbolView>["name"];
@@ -13,31 +13,36 @@ export function ControlPill(props: {
readonly variant?: "circle" | "pill" | "primary" | "danger";
readonly disabled?: boolean;
}) {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const variant = props.variant ?? "circle";
const subtleBg = useThemeColor("--color-subtle");
const subtleBgStrong = useThemeColor("--color-subtle-strong");
const primaryBg = useThemeColor("--color-primary");
const dangerBg = useThemeColor("--color-danger");
const iconColor = useThemeColor("--color-icon");
const iconSubtle = useThemeColor("--color-icon-subtle");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerFg = useThemeColor("--color-danger-foreground");
const textColor = useThemeColor("--color-foreground");
const textMuted = useThemeColor("--color-foreground-muted");
const backgroundColor =
variant === "primary"
? props.disabled
? palette.subtleBgStrong
: palette.primaryButton
? subtleBgStrong
: primaryBg
: variant === "danger"
? palette.dangerButton
: palette.subtleBg;
? dangerBg
: subtleBg;
const iconTintColor =
variant === "primary"
? props.disabled
? palette.iconSubtle
: palette.primaryButtonText
? iconSubtle
: primaryFg
: variant === "danger"
? palette.dangerText
: palette.icon;
const textColor =
variant === "primary"
? props.disabled
? palette.textMuted
: palette.primaryButtonText
: palette.text;
? dangerFg
: iconColor;
const labelColor = variant === "primary" ? (props.disabled ? textMuted : primaryFg) : textColor;
const isCircle =
variant === "circle" || variant === "danger" || (variant === "primary" && !props.label);
@@ -61,7 +66,7 @@ export function ControlPill(props: {
<SymbolView name={props.icon} size={16} tintColor={iconTintColor} type="monochrome" />
) : null}
{props.label ? (
<Text className="text-center text-[12px] font-t3-bold" style={{ color: textColor }}>
<Text className="text-center text-[12px] font-t3-bold" style={{ color: labelColor }}>
{props.label}
</Text>
) : null}
+4 -5
View File
@@ -1,13 +1,12 @@
import { View } from "react-native";
import { AppText as Text } from "./AppText";
export function EmptyState(props: { readonly title: string; readonly detail: string }) {
return (
<View className="rounded-[22px] border border-neutral-200 bg-white p-5 dark:border-white/6 dark:bg-neutral-900">
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
{props.title}
</Text>
<Text className="mt-2 font-sans text-sm leading-[21px] text-neutral-600 dark:text-neutral-400">
<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>
</View>
+7 -9
View File
@@ -1,28 +1,26 @@
import { ActivityIndicator, StatusBar, View, useColorScheme } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../lib/useThemeColor";
import { makeAppPalette } from "../lib/theme";
import { AppText as Text } from "./AppText";
import { BrandMark } from "./BrandMark";
export function LoadingScreen(props: { readonly message: string }) {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const colorScheme = useColorScheme();
const screenBg = useThemeColor("--color-screen");
const insets = useSafeAreaInsets();
return (
<View style={{ flex: 1, backgroundColor: palette.screenBackground, paddingTop: insets.top }}>
<View className="flex-1 bg-screen" style={{ paddingTop: insets.top }}>
<StatusBar
barStyle={palette.statusBarStyle}
backgroundColor={palette.screenBackground}
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
backgroundColor={screenBg as string}
translucent
/>
<View className="flex-1 items-center justify-center gap-5 px-6">
<BrandMark compact />
<ActivityIndicator size="large" />
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
{props.message}
</Text>
<Text className="font-t3-bold text-lg text-foreground">{props.message}</Text>
</View>
</View>
);
@@ -0,0 +1,70 @@
import { SymbolView } from "expo-symbols";
import { useState } from "react";
import { Image, View } from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
/* ─── Favicon cache (matches web pattern) ────────────────────────────── */
const loadedFaviconUrls = new Set<string>();
/* ─── Component ──────────────────────────────────────────────────────── */
export function ProjectFavicon(props: {
readonly size?: number;
readonly projectTitle: string;
readonly httpBaseUrl?: string | null;
readonly workspaceRoot?: string | null;
readonly bearerToken?: string | null;
}) {
const size = props.size ?? 42;
const iconMuted = useThemeColor("--color-icon-subtle");
const faviconUrl =
props.httpBaseUrl && props.workspaceRoot
? `${props.httpBaseUrl}/api/project-favicon?cwd=${encodeURIComponent(props.workspaceRoot)}`
: null;
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
faviconUrl && loadedFaviconUrls.has(faviconUrl) ? "loaded" : "loading",
);
const showImage = faviconUrl && status === "loaded";
return (
<View
style={{
width: size,
height: size,
alignItems: "center",
justifyContent: "center",
}}
>
{/* Folder icon fallback (matches web's FolderIcon) */}
{!showImage ? (
<SymbolView name="folder.fill" size={size * 0.78} tintColor={iconMuted} type="monochrome" />
) : null}
{/* Favicon image (hidden until loaded) */}
{faviconUrl ? (
<Image
source={{
uri: faviconUrl,
...(props.bearerToken
? { headers: { Authorization: `Bearer ${props.bearerToken}` } }
: {}),
}}
style={{
width: size,
height: size,
borderRadius: size * 0.16,
...(showImage ? {} : { position: "absolute" as const, opacity: 0 }),
}}
resizeMode="contain"
onLoad={() => {
if (faviconUrl) loadedFaviconUrls.add(faviconUrl);
setStatus("loaded");
}}
onError={() => setStatus("error")}
/>
) : null}
</View>
);
}
+3 -3
View File
@@ -1,7 +1,7 @@
import { View } from "react-native";
import { AppText as Text } from "./AppText";
import { cx } from "../lib/classNames";
import { cn } from "../lib/cn";
export interface StatusTone {
readonly label: string;
@@ -17,14 +17,14 @@ export function StatusPill(
const size = props.size ?? "default";
return (
<View
className={cx(
className={cn(
"rounded-full",
size === "compact" ? "px-2.5 py-1" : "px-3 py-1.5",
props.pillClassName,
)}
>
<Text
className={cx(
className={cn(
"font-t3-bold",
size === "compact" ? "text-[11px]" : "text-xs",
props.textClassName,
@@ -1,415 +0,0 @@
import { BottomSheetBackdrop, BottomSheetModal, BottomSheetView } from "@gorhom/bottom-sheet";
import { useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useRef, useState } from "react";
import {
ActionSheetIOS,
Platform,
Pressable,
ScrollView,
View,
useColorScheme,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
import {
ConnectionSheetButton as SheetButton,
makeConnectionSheetPalette as makePalette,
type ConnectionSheetPalette,
} from "./connection-sheet-shared";
export interface ConnectionSheetProps {
readonly visible: boolean;
readonly connectedEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly onRequestClose: () => void;
readonly onUpdateEnvironment: (
environmentId: string,
updates: { readonly label: string; readonly displayUrl: string },
) => Promise<void>;
readonly onRemoveEnvironment: (environmentId: string) => void;
}
// ---------------------------------------------------------------------------
function EnvironmentCard(props: {
readonly environment: ConnectedEnvironmentSummary;
readonly palette: ConnectionSheetPalette;
readonly onPress: () => void;
readonly onRemove: (environmentId: string) => void;
}) {
return (
<Pressable
className="flex-row items-center gap-3 rounded-[18px] px-4 py-3.5"
style={[
{
backgroundColor: props.palette.card,
borderWidth: 1,
borderColor: props.palette.border,
},
props.palette.cardShadow,
]}
onPress={props.onPress}
>
<ConnectionStatusDot state={props.environment.connectionState} pulse={false} size={8} />
<View className="flex-1 gap-0.5">
<Text
className="text-[16px] font-t3-bold leading-[21px]"
style={{ color: props.palette.text }}
numberOfLines={1}
>
{props.environment.environmentLabel}
</Text>
<Text
className="text-[12px] leading-[16px]"
style={{ color: props.palette.muted }}
numberOfLines={1}
>
{props.environment.displayUrl}
</Text>
</View>
<Pressable
className="h-9 w-9 items-center justify-center rounded-[12px]"
style={{
backgroundColor: props.palette.dangerButton,
borderWidth: 1,
borderColor: props.palette.dangerBorder,
}}
onPress={(e) => {
e.stopPropagation();
props.onRemove(props.environment.environmentId);
}}
hitSlop={4}
>
<SymbolView name="trash" size={13} tintColor={props.palette.dangerText} type="monochrome" />
</Pressable>
</Pressable>
);
}
// ---------------------------------------------------------------------------
// Edit backend (nested sheet)
// ---------------------------------------------------------------------------
function EnvironmentDetailSheet(props: {
readonly environment: ConnectedEnvironmentSummary | null;
readonly palette: ConnectionSheetPalette;
readonly bottomInset: number;
readonly onDismiss: () => void;
readonly onSave: (
environmentId: string,
updates: { readonly label: string; readonly displayUrl: string },
) => void;
readonly onRemove: (environmentId: string) => void;
}) {
const sheetRef = useRef<BottomSheetModal>(null);
const [label, setLabel] = useState("");
const [displayUrl, setDisplayUrl] = useState("");
const env = props.environment;
useEffect(() => {
const sheet = sheetRef.current;
if (!sheet) return;
if (env) {
setLabel(env.environmentLabel);
setDisplayUrl(env.displayUrl);
sheet.present();
} else {
sheet.dismiss();
}
}, [env]);
const renderBackdrop = useCallback(
(backdropProps: React.ComponentProps<typeof BottomSheetBackdrop>) => (
<BottomSheetBackdrop
{...backdropProps}
appearsOnIndex={0}
disappearsOnIndex={-1}
opacity={0.24}
pressBehavior="close"
/>
),
[],
);
const hasChanges =
env !== null && (label.trim() !== env.environmentLabel || displayUrl.trim() !== env.displayUrl);
return (
<BottomSheetModal
ref={sheetRef}
stackBehavior="push"
index={0}
snapPoints={["52%"]}
enableDynamicSizing={false}
enablePanDownToClose
backdropComponent={renderBackdrop}
onDismiss={props.onDismiss}
backgroundStyle={{ backgroundColor: props.palette.sheet }}
handleIndicatorStyle={{ backgroundColor: "rgba(120,113,108,0.32)" }}
>
<BottomSheetView style={{ flex: 1 }}>
<View className="gap-5 px-5 pt-1">
<View className="flex-row items-center gap-3">
{env ? (
<ConnectionStatusDot state={env.connectionState} pulse={false} size={8} />
) : null}
<Text
className="text-[24px] font-t3-bold"
style={{ color: props.palette.text, letterSpacing: -0.2 }}
>
Edit backend
</Text>
</View>
<View className="gap-2">
<Text
className="text-[11px] font-t3-bold uppercase"
style={{ color: props.palette.muted, letterSpacing: 0.8 }}
>
Label
</Text>
<TextInput
autoCapitalize="words"
autoCorrect={false}
placeholder="My MacBook Pro"
placeholderTextColor={props.palette.placeholder}
value={label}
onChangeText={setLabel}
className="rounded-[14px] px-4 py-3.5 text-[15px]"
style={{
backgroundColor: props.palette.inputBackground,
borderWidth: 1,
borderColor: props.palette.inputBorder,
color: props.palette.text,
}}
/>
</View>
<View className="gap-2">
<Text
className="text-[11px] font-t3-bold uppercase"
style={{ color: props.palette.muted, letterSpacing: 0.8 }}
>
Host
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
placeholder="http://192.168.1.100:8080/"
placeholderTextColor={props.palette.placeholder}
value={displayUrl}
onChangeText={setDisplayUrl}
className="rounded-[14px] px-4 py-3.5 text-[15px]"
style={{
backgroundColor: props.palette.inputBackground,
borderWidth: 1,
borderColor: props.palette.inputBorder,
color: props.palette.text,
}}
/>
</View>
<View
className="flex-row gap-3"
style={{ paddingBottom: Math.max(props.bottomInset, 16) }}
>
<View className="flex-1">
<SheetButton
icon="checkmark"
label="Save"
disabled={!hasChanges}
palette={props.palette}
tone="primary"
onPress={() => {
if (env) {
props.onSave(env.environmentId, {
label: label.trim(),
displayUrl: displayUrl.trim(),
});
props.onDismiss();
}
}}
/>
</View>
<View className="flex-1">
<SheetButton
icon="xmark"
label="Cancel"
palette={props.palette}
tone="secondary"
onPress={props.onDismiss}
/>
</View>
</View>
</View>
</BottomSheetView>
</BottomSheetModal>
);
}
// ---------------------------------------------------------------------------
// Main connection sheet
// ---------------------------------------------------------------------------
export function ConnectionSheet(props: ConnectionSheetProps) {
const router = useRouter();
const insets = useSafeAreaInsets();
const isDarkMode = useColorScheme() === "dark";
const palette = makePalette(isDarkMode);
const [editingEnvironment, setEditingEnvironment] = useState<ConnectedEnvironmentSummary | null>(
null,
);
const hasEnvironments = props.connectedEnvironments.length > 0;
useEffect(() => {
if (!props.visible) {
setEditingEnvironment(null);
}
}, [props.visible]);
const handleAddPress = useCallback(() => {
if (Platform.OS === "ios") {
ActionSheetIOS.showActionSheetWithOptions(
{
cancelButtonIndex: 2,
options: ["Scan QR Code", "Enter Manually", "Cancel"],
title: "Add backend",
},
(buttonIndex) => {
console.log("[connections sheet] add action", buttonIndex);
if (buttonIndex === 0) {
router.push("/connections/new?mode=scan_qr");
return;
}
if (buttonIndex === 1) {
router.push("/connections/new");
}
},
);
return;
}
router.push("/connections/new");
}, [router]);
return (
<View style={{ flex: 1, backgroundColor: palette.sheet }}>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 4,
paddingBottom: Math.max(insets.bottom, 16) + 12,
gap: 10,
}}
>
{/* Header */}
<View className="flex-row items-center justify-between pb-4 pt-1">
<View className="flex-1 gap-1">
<Text
className="text-[28px] font-t3-bold"
style={{ color: palette.text, letterSpacing: -0.3 }}
>
Backends
</Text>
<Text className="text-[14px] leading-[20px]" style={{ color: palette.muted }}>
Manage your connected environments.
</Text>
</View>
<Pressable
className="h-11 w-11 items-center justify-center rounded-full"
style={{
backgroundColor: palette.primaryButton,
...Platform.select({
ios: {
shadowColor: "#000",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.12,
shadowRadius: 4,
},
android: { elevation: 3 },
}),
}}
onPress={handleAddPress}
>
<SymbolView
name="plus"
size={18}
tintColor={palette.primaryButtonText}
type="monochrome"
weight="semibold"
/>
</Pressable>
</View>
{/* Backend list */}
{hasEnvironments ? (
props.connectedEnvironments.map((environment) => (
<EnvironmentCard
key={environment.environmentId}
environment={environment}
palette={palette}
onPress={() => setEditingEnvironment(environment)}
onRemove={props.onRemoveEnvironment}
/>
))
) : (
<View
className="items-center gap-3 rounded-[20px] px-6 py-8"
style={{
backgroundColor: palette.card,
borderWidth: 1,
borderColor: palette.border,
}}
>
<View
className="h-12 w-12 items-center justify-center rounded-[16px]"
style={{ backgroundColor: palette.iconBg }}
>
<SymbolView
name="point.3.connected.trianglepath.dotted"
size={20}
tintColor={palette.accent}
type="monochrome"
/>
</View>
<Text
className="text-center text-[14px] leading-[20px]"
style={{ color: palette.muted }}
>
No backends connected yet.{"\n"}Tap{" "}
<Text className="font-t3-bold" style={{ color: palette.text }}>
+
</Text>{" "}
to add one.
</Text>
</View>
)}
</ScrollView>
{/* Nested: Edit backend */}
<EnvironmentDetailSheet
environment={editingEnvironment}
palette={palette}
bottomInset={insets.bottom}
onDismiss={() => setEditingEnvironment(null)}
onSave={(environmentId, updates) => {
void props.onUpdateEnvironment(environmentId, updates);
}}
onRemove={props.onRemoveEnvironment}
/>
</View>
);
}
@@ -1,15 +1,16 @@
import { Link, Stack } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useState } from "react";
import { Pressable, ScrollView, View, useColorScheme } from "react-native";
import { Pressable, ScrollView, View } from "react-native";
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { cn } from "../../lib/cn";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
import { makeConnectionSheetPalette as makePalette } from "./connection-sheet-shared";
function EnvironmentRow(props: {
readonly environment: ConnectedEnvironmentSummary;
@@ -20,11 +21,15 @@ function EnvironmentRow(props: {
environmentId: string,
updates: { readonly label: string; readonly displayUrl: string },
) => void;
readonly palette: ReturnType<typeof makePalette>;
}) {
const [label, setLabel] = useState(props.environment.environmentLabel);
const [url, setUrl] = useState(props.environment.displayUrl);
const mutedColor = useThemeColor("--color-icon-subtle");
const placeholderColor = useThemeColor("--color-placeholder");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerFg = useThemeColor("--color-danger-foreground");
const handleSave = useCallback(() => {
props.onUpdate(props.environment.environmentId, {
label: label.trim(),
@@ -34,26 +39,18 @@ function EnvironmentRow(props: {
}, [label, url, props]);
return (
<Animated.View
layout={LinearTransition.duration(250)}
style={{ backgroundColor: props.palette.card }}
>
<Animated.View layout={LinearTransition.duration(250)} className="bg-card">
<Pressable className="flex-row items-center gap-3 px-4 py-3.5" onPress={props.onToggle}>
<ConnectionStatusDot state={props.environment.connectionState} pulse={false} size={8} />
<View className="flex-1 gap-0.5">
<Text
className="text-[16px] font-t3-bold leading-[21px]"
style={{ color: props.palette.text }}
className="text-[16px] font-t3-bold leading-[21px] text-foreground"
numberOfLines={1}
>
{props.environment.environmentLabel}
</Text>
<Text
className="text-[12px] leading-[16px]"
style={{ color: props.palette.muted }}
numberOfLines={1}
>
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{props.environment.displayUrl}
</Text>
</View>
@@ -61,7 +58,7 @@ function EnvironmentRow(props: {
<SymbolView
name="chevron.down"
size={12}
tintColor={props.palette.muted}
tintColor={mutedColor}
type="monochrome"
style={{
transform: [{ rotate: props.expanded ? "180deg" : "0deg" }],
@@ -77,8 +74,8 @@ function EnvironmentRow(props: {
>
<View className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase"
style={{ color: props.palette.muted, letterSpacing: 0.8 }}
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Label
</Text>
@@ -86,23 +83,17 @@ function EnvironmentRow(props: {
autoCapitalize="words"
autoCorrect={false}
placeholder="My MacBook"
placeholderTextColor={props.palette.placeholder}
placeholderTextColor={placeholderColor}
value={label}
onChangeText={setLabel}
className="rounded-[14px] px-4 py-3 text-[15px]"
style={{
backgroundColor: props.palette.inputBackground,
borderWidth: 1,
borderColor: props.palette.inputBorder,
color: props.palette.text,
}}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-[15px] text-foreground"
/>
</View>
<View className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase"
style={{ color: props.palette.muted, letterSpacing: 0.8 }}
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
URL
</Text>
@@ -111,59 +102,32 @@ function EnvironmentRow(props: {
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={props.palette.placeholder}
placeholderTextColor={placeholderColor}
value={url}
onChangeText={setUrl}
className="rounded-[14px] px-4 py-3 text-[15px]"
style={{
backgroundColor: props.palette.inputBackground,
borderWidth: 1,
borderColor: props.palette.inputBorder,
color: props.palette.text,
}}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-[15px] text-foreground"
/>
</View>
<View className="flex-row gap-2">
<Pressable
className="min-h-[42px] flex-1 flex-row items-center justify-center gap-1.5 rounded-[14px] px-3.5 py-2.5"
className="min-h-[42px] flex-1 flex-row items-center justify-center gap-1.5 rounded-[14px] bg-primary px-3.5 py-2.5"
onPress={handleSave}
style={{
backgroundColor: props.palette.primaryButton,
}}
>
<SymbolView
name="checkmark"
size={13}
tintColor={props.palette.primaryButtonText}
type="monochrome"
/>
<SymbolView name="checkmark" size={13} tintColor={primaryFg} type="monochrome" />
<Text
className="text-[12px] font-t3-bold uppercase"
style={{
color: props.palette.primaryButtonText,
letterSpacing: 0.8,
}}
className="text-[12px] font-t3-bold uppercase text-primary-foreground"
style={{ letterSpacing: 0.8 }}
>
Save
</Text>
</Pressable>
<Pressable
className="h-[42px] w-[42px] items-center justify-center rounded-[14px]"
className="h-[42px] w-[42px] items-center justify-center rounded-[14px] border border-danger-border bg-danger"
onPress={() => props.onRemove(props.environment.environmentId)}
style={{
backgroundColor: props.palette.dangerButton,
borderWidth: 1,
borderColor: props.palette.dangerBorder,
}}
>
<SymbolView
name="trash"
size={14}
tintColor={props.palette.dangerText}
type="monochrome"
/>
<SymbolView name="trash" size={14} tintColor={dangerFg} type="monochrome" />
</Pressable>
</View>
</Animated.View>
@@ -176,30 +140,29 @@ export function ConnectionsRouteScreen() {
const { connectedEnvironments, onRemoveEnvironmentPress, onUpdateEnvironment } =
useRemoteConnections();
const insets = useSafeAreaInsets();
const isDarkMode = useColorScheme() === "dark";
const palette = makePalette(isDarkMode);
const hasEnvironments = connectedEnvironments.length > 0;
const [expandedId, setExpandedId] = useState<string | null>(null);
const primaryFg = useThemeColor("--color-primary-foreground");
const accentColor = useThemeColor("--color-icon-muted");
const mutedColor = useThemeColor("--color-icon-subtle");
const handleToggle = useCallback((environmentId: string) => {
setExpandedId((prev) => (prev === environmentId ? null : environmentId));
}, []);
return (
<View collapsable={false} style={{ flex: 1, backgroundColor: palette.sheet }}>
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: "Backends",
headerRight: () => (
<Link href="/connections/new" asChild>
<Pressable
className="h-10 w-10 items-center justify-center rounded-full"
style={{ backgroundColor: palette.primaryButton }}
>
<Pressable className="h-10 w-10 items-center justify-center rounded-full bg-primary">
<SymbolView
name="plus"
size={18}
tintColor={palette.primaryButtonText}
tintColor={primaryFg}
type="monochrome"
weight="semibold"
/>
@@ -219,19 +182,15 @@ export function ConnectionsRouteScreen() {
}}
>
{hasEnvironments ? (
<View
collapsable={false}
className="overflow-hidden rounded-[24px]"
style={{ backgroundColor: palette.card }}
>
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{connectedEnvironments.map((environment, index) => (
<View
key={environment.environmentId}
collapsable={false}
style={{
borderTopWidth: index === 0 ? 0 : 1,
borderTopColor: palette.border,
}}
className={cn(index !== 0 && "border-border")}
>
<EnvironmentRow
environment={environment}
@@ -239,37 +198,23 @@ export function ConnectionsRouteScreen() {
onToggle={() => handleToggle(environment.environmentId)}
onRemove={onRemoveEnvironmentPress}
onUpdate={onUpdateEnvironment}
palette={palette}
/>
</View>
))}
</View>
) : (
<View
collapsable={false}
className="items-center gap-3 rounded-[24px] px-6 py-8"
style={{ backgroundColor: palette.card }}
>
<View
className="h-12 w-12 items-center justify-center rounded-[16px]"
style={{ backgroundColor: palette.iconBg }}
>
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
<View className="h-12 w-12 items-center justify-center rounded-[16px] bg-subtle">
<SymbolView
name="point.3.connected.trianglepath.dotted"
size={20}
tintColor={palette.accent}
tintColor={accentColor}
type="monochrome"
/>
</View>
<Text
className="text-center text-[14px] leading-[20px]"
style={{ color: palette.muted }}
>
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
No backends connected yet.{"\n"}Tap{" "}
<Text className="font-t3-bold" style={{ color: palette.text }}>
+
</Text>{" "}
to add one.
<Text className="font-t3-bold text-foreground">+</Text> to add one.
</Text>
</View>
)}
@@ -2,18 +2,18 @@ import { CameraView, useCameraPermissions } from "expo-camera";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useState } from "react";
import { Alert, Pressable, ScrollView, View, useColorScheme } from "react-native";
import { Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ErrorBanner } from "../../components/ErrorBanner";
import { dismissRoute } from "../../lib/routes";
import { extractPairingUrlFromQrPayload } from "../../lib/pairingQr";
import { extractPairingUrlFromQrPayload } from "./pairingQr";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import {
buildPairingUrl,
ConnectionSheetButton as SheetButton,
makeConnectionSheetPalette as makePalette,
parsePairingUrl,
} from "./connection-sheet-shared";
@@ -28,8 +28,6 @@ export function NewConnectionRouteScreen() {
const router = useRouter();
const params = useLocalSearchParams<{ mode?: string }>();
const insets = useSafeAreaInsets();
const isDarkMode = useColorScheme() === "dark";
const palette = makePalette(isDarkMode);
const [hostInput, setHostInput] = useState("");
const [codeInput, setCodeInput] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
@@ -37,6 +35,9 @@ export function NewConnectionRouteScreen() {
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
const [scannerLocked, setScannerLocked] = useState(false);
const textColor = useThemeColor("--color-icon");
const placeholderColor = useThemeColor("--color-placeholder");
const connectDisabled =
isSubmitting || connectionState === "connecting" || hostInput.trim().length === 0;
@@ -125,13 +126,13 @@ export function NewConnectionRouteScreen() {
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
return (
<View collapsable={false} style={{ flex: 1, backgroundColor: palette.sheet }}>
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: showScanner ? "Scan QR Code" : "Add Backend",
headerRight: () => (
<Pressable
className="h-10 w-10 items-center justify-center rounded-full"
className="h-10 w-10 items-center justify-center rounded-full border border-border bg-secondary"
onPress={() => {
if (showScanner) {
closeScanner();
@@ -139,16 +140,11 @@ export function NewConnectionRouteScreen() {
void openScanner();
}
}}
style={{
backgroundColor: palette.secondaryButton,
borderWidth: 1,
borderColor: palette.border,
}}
>
<SymbolView
name={showScanner ? "xmark" : "qrcode.viewfinder"}
size={showScanner ? 14 : 18}
tintColor={palette.text}
tintColor={textColor}
type="monochrome"
weight="semibold"
/>
@@ -182,20 +178,16 @@ export function NewConnectionRouteScreen() {
</View>
) : (
<View
className="items-center gap-3 rounded-[24px] px-5 py-8"
style={{ backgroundColor: palette.card, borderCurve: "continuous" }}
className="items-center gap-3 rounded-[24px] bg-card px-5 py-8"
style={{ borderCurve: "continuous" }}
>
<Text
className="text-center text-[14px] leading-[20px]"
style={{ color: palette.muted }}
>
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
Camera permission is required to scan a QR code.
</Text>
<SheetButton
compact
icon="camera"
label="Allow camera"
palette={palette}
tone="secondary"
onPress={() => {
void openScanner();
@@ -204,15 +196,11 @@ export function NewConnectionRouteScreen() {
</View>
)
) : (
<View
collapsable={false}
className="gap-4 rounded-[24px] p-4"
style={{ backgroundColor: palette.card }}
>
<View collapsable={false} className="gap-4 rounded-[24px] bg-card p-4">
<View collapsable={false} className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase"
style={{ color: palette.muted, letterSpacing: 0.8 }}
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Host
</Text>
@@ -221,23 +209,17 @@ export function NewConnectionRouteScreen() {
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={palette.placeholder}
placeholderTextColor={placeholderColor}
value={hostInput}
onChangeText={handleHostChange}
className="rounded-[14px] px-4 py-3.5 text-[15px]"
style={{
backgroundColor: palette.inputBackground,
borderWidth: 1,
borderColor: palette.inputBorder,
color: palette.text,
}}
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-[15px] text-foreground"
/>
</View>
<View collapsable={false} className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase"
style={{ color: palette.muted, letterSpacing: 0.8 }}
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Pairing code
</Text>
@@ -245,16 +227,10 @@ export function NewConnectionRouteScreen() {
autoCapitalize="none"
autoCorrect={false}
placeholder="abc-123-xyz"
placeholderTextColor={palette.placeholder}
placeholderTextColor={placeholderColor}
value={codeInput}
onChangeText={handleCodeChange}
className="rounded-[14px] px-4 py-3.5 text-[15px]"
style={{
backgroundColor: palette.inputBackground,
borderWidth: 1,
borderColor: palette.inputBorder,
color: palette.text,
}}
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-[15px] text-foreground"
/>
</View>
@@ -263,10 +239,9 @@ export function NewConnectionRouteScreen() {
<SheetButton
icon="plus"
label={
isSubmitting || connectionState === "connecting" ? "Pairing…" : "Add backend"
isSubmitting || connectionState === "connecting" ? "Pairing..." : "Add backend"
}
disabled={connectDisabled}
palette={palette}
tone="primary"
onPress={() => {
void handleSubmit();
@@ -1,7 +1,9 @@
import { SymbolView } from "expo-symbols";
import { Platform, Pressable } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
export function parsePairingUrl(url: string): { host: string; code: string } {
const trimmed = url.trim();
@@ -38,73 +40,27 @@ export function buildPairingUrl(host: string, code: string): string {
}
}
export function makeConnectionSheetPalette(isDarkMode: boolean) {
if (isDarkMode) {
return {
sheet: "rgba(18,20,23,0.98)",
card: "#1f2329",
cardAlt: "#242a31",
border: "rgba(255,255,255,0.06)",
text: "#f8fafc",
muted: "#94a3b8",
subtle: "#cbd5e1",
accent: "#f59e0b",
accentSubtle: "rgba(245,158,11,0.12)",
iconBg: "rgba(245,158,11,0.10)",
inputBackground: "#171b20",
inputBorder: "rgba(255,255,255,0.06)",
primaryButton: "#f8fafc",
primaryButtonText: "#171717",
secondaryButton: "rgba(255,255,255,0.05)",
secondaryButtonText: "#f8fafc",
dangerButton: "rgba(190,24,93,0.14)",
dangerBorder: "rgba(244,114,182,0.18)",
dangerText: "#fda4af",
placeholder: "#64748b",
cardShadow: {
shadowColor: "#000",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.18,
shadowRadius: 8,
elevation: 4,
} as const,
separator: "rgba(255,255,255,0.04)",
};
}
const CARD_SHADOW = Platform.select({
ios: {
shadowColor: "rgba(23,23,23,0.08)",
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 1,
shadowRadius: 16,
},
android: { elevation: 3 },
});
return {
sheet: "rgba(246,244,239,0.98)",
card: "#fffdf9",
cardAlt: "#f8f4ec",
border: "rgba(23,23,23,0.06)",
text: "#171717",
muted: "#78716c",
subtle: "#57534e",
accent: "#a16207",
accentSubtle: "rgba(161,98,7,0.08)",
iconBg: "rgba(161,98,7,0.07)",
inputBackground: "#ffffff",
inputBorder: "rgba(23,23,23,0.06)",
primaryButton: "#171717",
primaryButtonText: "#fafaf9",
secondaryButton: "#f1ece3",
secondaryButtonText: "#171717",
dangerButton: "#fff1f2",
dangerBorder: "rgba(225,29,72,0.10)",
dangerText: "#be123c",
placeholder: "#94a3b8",
cardShadow: {
shadowColor: "rgba(23,23,23,0.08)",
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 1,
shadowRadius: 16,
elevation: 3,
} as const,
separator: "rgba(23,23,23,0.04)",
};
}
const CARD_SHADOW_DARK = Platform.select({
ios: {
shadowColor: "#000",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.18,
shadowRadius: 8,
},
android: { elevation: 4 },
});
export type ConnectionSheetPalette = ReturnType<typeof makeConnectionSheetPalette>;
export { CARD_SHADOW, CARD_SHADOW_DARK };
export function ConnectionSheetButton(props: {
readonly icon: React.ComponentProps<typeof SymbolView>["name"];
@@ -112,27 +68,36 @@ export function ConnectionSheetButton(props: {
readonly disabled?: boolean;
readonly tone?: "primary" | "secondary" | "danger";
readonly compact?: boolean;
readonly palette: ConnectionSheetPalette;
readonly onPress: () => void;
}) {
const tone = props.tone ?? "secondary";
const primaryBg = useThemeColor("--color-primary");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerBg = useThemeColor("--color-danger");
const dangerBorderColor = useThemeColor("--color-danger-border");
const dangerFg = useThemeColor("--color-danger-foreground");
const secondaryBg = useThemeColor("--color-secondary");
const secondaryFg = useThemeColor("--color-secondary-foreground");
const borderColor = useThemeColor("--color-border");
const colors =
tone === "primary"
? {
backgroundColor: props.palette.primaryButton,
backgroundColor: primaryBg,
borderColor: "transparent",
textColor: props.palette.primaryButtonText,
textColor: primaryFg,
}
: tone === "danger"
? {
backgroundColor: props.palette.dangerButton,
borderColor: props.palette.dangerBorder,
textColor: props.palette.dangerText,
backgroundColor: dangerBg,
borderColor: dangerBorderColor,
textColor: dangerFg,
}
: {
backgroundColor: props.palette.secondaryButton,
borderColor: props.palette.border,
textColor: props.palette.secondaryButtonText,
backgroundColor: secondaryBg,
borderColor: borderColor,
textColor: secondaryFg,
};
const primaryShadow =
@@ -150,11 +115,11 @@ export function ConnectionSheetButton(props: {
return (
<Pressable
className={
className={cn(
props.compact
? "min-h-[42px] flex-row items-center justify-center gap-1.5 rounded-[14px] px-3.5 py-2.5"
: "min-h-[48px] flex-row items-center justify-center gap-2 rounded-[16px] px-4 py-3"
}
: "min-h-[48px] flex-row items-center justify-center gap-2 rounded-[16px] px-4 py-3",
)}
disabled={props.disabled}
onPress={props.onPress}
style={[
+127 -16
View File
@@ -1,15 +1,37 @@
import { useFocusEffect, useRouter } from "expo-router";
import { useCallback } from "react";
import { Stack, useFocusEffect, useRouter } from "expo-router";
import { useCallback, useState } from "react";
import { Pressable, Text as RNText, View, useColorScheme } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
import { buildThreadRoutePath } from "../../lib/routes";
import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
import { useThreadSelection } from "../../state/use-thread-selection";
import { HomeScreen } from "./HomeScreen";
/* ─── Connection pill label ──────────────────────────────────────────── */
const CONNECTION_LABEL: Record<string, string> = {
ready: "Connected",
connecting: "Connecting",
reconnecting: "Reconnecting",
disconnected: "Offline",
idle: "No backends",
};
/* ─── Route screen ───────────────────────────────────────────────────── */
export function HomeRouteScreen() {
const { connectionState, hasRemoteActivity, projects, threads } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
const { onBackFromThread, onSelectThread } = useThreadSelection();
const router = useRouter();
const [searchQuery, setSearchQuery] = useState("");
const isDark = useColorScheme() === "dark";
const iconColor = String(useThemeColor("--color-icon"));
const secondaryFg = isDark ? "#a3a3a3" : "#525252";
useFocusEffect(
useCallback(() => {
@@ -18,19 +40,108 @@ export function HomeRouteScreen() {
);
return (
<HomeScreen
projects={projects}
threads={threads}
connectionState={connectionState}
connectionPulse={hasRemoteActivity}
onOpenConnectionEditor={() => router.push("/connections")}
onOpenNewTask={() => router.push("/new")}
onSelectThread={(thread) => {
onSelectThread(thread);
router.push(buildThreadRoutePath(thread));
}}
showFloatingConnectionButton
showFloatingNewTaskButton
/>
<>
<Stack.Screen
options={{
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTintColor: iconColor,
headerTitle: "",
headerRight: () => (
<Pressable
onPress={() => router.push("/connections")}
hitSlop={8}
style={{
flexDirection: "row",
alignItems: "center",
gap: 8,
paddingHorizontal: 4,
paddingVertical: 4,
}}
>
<ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 12,
color: secondaryFg,
}}
>
{CONNECTION_LABEL[connectionState] ?? "Unknown"}
</RNText>
</Pressable>
),
headerSearchBarOptions: {
placeholder: "Search threads",
onChangeText: (event) => {
setSearchQuery(event.nativeEvent.text);
},
allowToolbarIntegration: true,
},
}}
/>
{/* Header left: plain text, no Liquid Glass button chrome */}
<Stack.Toolbar placement="left">
<Stack.Toolbar.View hidesSharedBackground>
<View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 17,
color: iconColor,
letterSpacing: -0.4,
}}
>
T3 Code
</RNText>
<View
style={{
backgroundColor: isDark ? "rgba(255,255,255,0.04)" : "rgba(0,0,0,0.04)",
borderRadius: 99,
paddingHorizontal: 8,
paddingVertical: 3,
}}
>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 10,
color: "#737373",
letterSpacing: 1.1,
textTransform: "uppercase",
}}
>
Alpha
</RNText>
</View>
</View>
</Stack.Toolbar.View>
</Stack.Toolbar>
{/* Bottom toolbar: search + compose, visually split like iMessage */}
<Stack.Toolbar placement="bottom">
<Stack.Toolbar.SearchBarSlot />
<Stack.Toolbar.Spacer width={8} sharesBackground={false} />
<Stack.Toolbar.Button
icon="square.and.pencil"
onPress={() => router.push("/new")}
separateBackground
/>
</Stack.Toolbar>
<HomeScreen
projects={projects}
threads={threads}
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
onSelectThread={(thread) => {
onSelectThread(thread);
router.push(buildThreadRoutePath(thread));
}}
/>
</>
);
}
+329 -195
View File
@@ -1,215 +1,349 @@
import * as Haptics from "expo-haptics";
import type { GitStatusState } from "@t3tools/client-runtime";
import { SymbolView } from "expo-symbols";
import { useMemo, useState } from "react";
import { Pressable, ScrollView, useColorScheme, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useCallback, useMemo, useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import { StatusPill } from "../../components/StatusPill";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import type { SavedRemoteConnection } from "../../lib/connection";
import type { ScopedMobileProject, ScopedMobileThread } from "../../lib/scopedEntities";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import { makeAppPalette } from "../../lib/theme";
import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
import { threadStatusTone } from "../threads/threadPresentation";
import { useGitStatus } from "../../state/use-git-status";
import { lastConversationLine, threadStatusTone } from "../threads/threadPresentation";
export function HomeScreen(props: {
/* ─── Types ──────────────────────────────────────────────────────────── */
interface HomeScreenProps {
readonly projects: ReadonlyArray<ScopedMobileProject>;
readonly threads: ReadonlyArray<ScopedMobileThread>;
readonly connectionState: "ready" | "connecting" | "reconnecting" | "disconnected" | "idle";
readonly connectionPulse: boolean;
readonly onOpenConnectionEditor: () => void;
readonly onOpenNewTask: () => void;
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
readonly searchQuery: string;
readonly onSelectThread: (thread: ScopedMobileThread) => void;
readonly showFloatingConnectionButton: boolean;
readonly showFloatingNewTaskButton: boolean;
}
interface ProjectGroup {
readonly key: string;
readonly project: ScopedMobileProject;
readonly threads: ReadonlyArray<ScopedMobileThread>;
}
/* ─── Status indicator colors ────────────────────────────────────────── */
function statusColors(thread: ScopedMobileThread): { bg: string; fg: string } {
switch (thread.session?.status) {
case "running":
return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" };
case "ready":
return { bg: "rgba(34,197,94,0.14)", fg: "#22c55e" };
case "starting":
return { bg: "rgba(59,130,246,0.14)", fg: "#3b82f6" };
case "error":
return { bg: "rgba(239,68,68,0.14)", fg: "#ef4444" };
default:
return { bg: "rgba(163,163,163,0.10)", fg: "#a3a3a3" };
}
}
const COLLAPSED_THREAD_LIMIT = 6;
/* ─── Project group header ───────────────────────────────────────────── */
function ProjectGroupLabel(props: {
readonly project: ScopedMobileProject;
readonly totalThreadCount: number;
readonly httpBaseUrl: string | null;
readonly bearerToken: string | null;
readonly isExpanded: boolean;
readonly onToggleExpand: () => void;
}) {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const insets = useSafeAreaInsets();
const [newTaskPressed, setNewTaskPressed] = useState(false);
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects: props.projects, threads: props.threads }),
[props.projects, props.threads],
);
const projectLabelsByKey = useMemo(() => {
const map = new Map<
string,
{
readonly projectTitle: string;
readonly environmentLabel: string;
}
>();
for (const group of repositoryGroups) {
const primaryProjectTitle = group.projects[0]?.project.title ?? group.title;
for (const projectGroup of group.projects) {
map.set(scopedProjectKey(projectGroup.project.environmentId, projectGroup.project.id), {
projectTitle: primaryProjectTitle,
environmentLabel: projectGroup.project.environmentLabel,
});
}
}
return map;
}, [repositoryGroups]);
const hiddenCount = props.totalThreadCount - COLLAPSED_THREAD_LIMIT;
return (
<View style={{ flex: 1, backgroundColor: palette.screenBackground }}>
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={{
paddingBottom: Math.max(insets.bottom, 24) + (props.showFloatingNewTaskButton ? 92 : 24),
paddingHorizontal: 20,
paddingTop: insets.top + 6,
gap: 16,
}}
<View className="flex-row items-center gap-2.5 px-1 pb-2">
<ProjectFavicon
size={18}
projectTitle={props.project.title}
httpBaseUrl={props.httpBaseUrl}
workspaceRoot={props.project.workspaceRoot}
bearerToken={props.bearerToken}
/>
<Text
className="flex-1 text-[13px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.6 }}
numberOfLines={1}
>
<View className="flex-row items-center justify-between">
<Text className="text-[34px] font-t3-bold" style={{ color: palette.text }}>
Recents
{props.project.title}
</Text>
{hiddenCount > 0 ? (
<Pressable onPress={props.onToggleExpand} hitSlop={8}>
<Text
className="text-[13px] font-t3-bold text-foreground-muted"
style={{ letterSpacing: 0.6 }}
>
{props.isExpanded ? "Show less" : `${hiddenCount} more`}
</Text>
{props.showFloatingConnectionButton ? (
<Pressable
onPress={props.onOpenConnectionEditor}
className="h-14 min-w-[56px] items-center justify-center rounded-full px-4"
style={{
backgroundColor: isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(255,255,255,0.9)",
borderWidth: isDarkMode ? 1 : 0,
borderColor: isDarkMode ? palette.border : "transparent",
}}
>
<ConnectionStatusDot state={props.connectionState} pulse={props.connectionPulse} />
</Pressable>
) : null}
</View>
{props.threads.length === 0 ? (
<EmptyState
title="No threads yet"
detail="Create a task to start a new coding session in one of your connected projects."
/>
) : (
<View
className="overflow-hidden rounded-[24px]"
style={{ backgroundColor: palette.card }}
>
{props.threads.map((thread, index) => {
const projectKey = scopedProjectKey(thread.environmentId, thread.projectId);
const projectLabel = projectLabelsByKey.get(projectKey);
return (
<Pressable
key={`${thread.environmentId}:${thread.id}`}
onPress={() => props.onSelectThread(thread)}
style={{
paddingHorizontal: 16,
paddingVertical: 13,
borderTopWidth: index === 0 ? 0 : 1,
borderTopColor: palette.borderSubtle,
}}
>
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-1.5">
<Text
className="text-[17px] font-t3-bold leading-[24px]"
numberOfLines={2}
style={{ color: palette.text }}
>
{thread.title}
</Text>
</View>
<StatusPill {...threadStatusTone(thread)} size="compact" />
</View>
<View className="mt-2 flex-row items-center justify-between gap-3">
<View className="flex-1 flex-row items-center gap-2">
<Text
className="text-[13px] font-medium leading-[18px]"
numberOfLines={1}
style={{ color: palette.textSecondary, flexShrink: 1 }}
>
{projectLabel?.projectTitle ?? thread.title}
</Text>
<View
className="h-1 w-1 rounded-full"
style={{ backgroundColor: palette.dotSeparator }}
/>
<Text
className="text-[12px] font-t3-bold uppercase tracking-[0.4px]"
numberOfLines={1}
style={{ color: palette.textMuted, flexShrink: 1 }}
>
{projectLabel?.environmentLabel ?? "Local"}
</Text>
</View>
<Text
className="text-[12px] font-t3-bold"
style={{ color: palette.textMuted, fontVariant: ["tabular-nums"] }}
>
{relativeTime(thread.updatedAt ?? thread.createdAt)}
</Text>
</View>
</Pressable>
);
})}
</View>
)}
</ScrollView>
{props.showFloatingNewTaskButton ? (
<View
pointerEvents="box-none"
style={{
position: "absolute",
right: 20,
bottom: Math.max(insets.bottom, 18),
}}
>
<Pressable
accessibilityRole="button"
hitSlop={6}
onPressIn={() => {
setNewTaskPressed(true);
void Haptics.selectionAsync();
}}
onPressOut={() => {
setNewTaskPressed(false);
}}
onPress={props.onOpenNewTask}
>
<View
className="flex-row items-center gap-3 rounded-full px-6 py-4"
style={{
backgroundColor: palette.primaryButton,
borderWidth: isDarkMode ? 1 : 0,
borderColor: isDarkMode ? "rgba(255,255,255,0.08)" : "transparent",
boxShadow: newTaskPressed
? `0 12px 24px ${palette.primaryButtonShadow}`
: `0 20px 36px ${palette.primaryButtonShadow}`,
opacity: newTaskPressed ? 0.96 : 1,
transform: [{ scale: newTaskPressed ? 0.985 : 1 }],
}}
>
<SymbolView
name="square.and.pencil"
size={20}
tintColor={palette.primaryButtonText}
type="monochrome"
/>
<Text
className="text-[18px] font-t3-bold"
style={{ color: palette.primaryButtonText }}
>
New task
</Text>
</View>
</Pressable>
</View>
</Pressable>
) : null}
</View>
);
}
/* ─── Git summary line ──────────────────────────────────────────────── */
function gitSummaryParts(gitStatus: GitStatusState): ReadonlyArray<string> {
if (!gitStatus.data) return [];
const { data } = gitStatus;
const parts: string[] = [];
if (data.hasWorkingTreeChanges) {
parts.push(`${data.workingTree.files.length} changed`);
}
if (data.aheadCount > 0) parts.push(`${data.aheadCount} ahead`);
if (data.behindCount > 0) parts.push(`${data.behindCount} behind`);
if (data.pr?.state === "open") parts.push(`PR #${data.pr.number}`);
return parts;
}
/* ─── Thread row ─────────────────────────────────────────────────────── */
function ThreadRow(props: {
readonly thread: ScopedMobileThread;
readonly projectCwd: string | null;
readonly onPress: () => void;
readonly isLast: boolean;
}) {
const separatorColor = useThemeColor("--color-separator");
const { bg, fg } = statusColors(props.thread);
const tone = threadStatusTone(props.thread);
const preview = lastConversationLine(props.thread);
const timestamp = relativeTime(props.thread.updatedAt ?? props.thread.createdAt);
const branch = props.thread.branch;
// Subscribe to live git status — only when thread has a branch set.
// Threads sharing the same cwd share one WS subscription via ref-counting.
const cwd = branch ? (props.thread.worktreePath ?? props.projectCwd) : null;
const gitStatus = useGitStatus({
environmentId: cwd ? props.thread.environmentId : null,
cwd,
});
const gitParts = gitSummaryParts(gitStatus);
return (
<Pressable onPress={props.onPress} style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}>
<View
style={{
flexDirection: "row",
paddingLeft: 16,
paddingRight: 16,
paddingVertical: 10,
gap: 12,
borderBottomWidth: props.isLast ? 0 : 1,
borderBottomColor: separatorColor,
}}
>
{/* Git status indicator */}
<View
style={{
width: 30,
height: 30,
borderRadius: 9,
backgroundColor: bg,
alignItems: "center",
justifyContent: "center",
marginTop: 2,
}}
>
<SymbolView name="arrow.triangle.branch" size={13} tintColor={fg} type="monochrome" />
</View>
{/* Content */}
<View style={{ flex: 1, gap: 3 }}>
{/* Title + Status + Timestamp */}
<View className="flex-row items-center justify-between gap-2">
<Text
className="flex-1 text-[15px] font-t3-bold leading-[20px] text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<View className="flex-row items-center gap-2">
<View
className={tone.pillClassName}
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
>
<Text className={`text-[10px] font-t3-bold ${tone.textClassName}`}>
{tone.label}
</Text>
</View>
<Text
className="text-[12px] text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
</View>
</View>
{/* Message preview */}
<Text className="text-[13px] leading-[18px] text-foreground-muted" numberOfLines={2}>
{preview}
</Text>
{/* Branch + git info */}
{branch ? (
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor="#737373"
type="monochrome"
/>
<Text
className="text-[11px] text-foreground-tertiary"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{branch}
</Text>
{gitParts.length > 0 ? (
<Text className="text-[11px] text-foreground-tertiary">
{" · " + gitParts.join(" · ")}
</Text>
) : null}
</View>
) : null}
</View>
</View>
</Pressable>
);
}
/* ─── Main screen ────────────────────────────────────────────────────── */
export function HomeScreen(props: HomeScreenProps) {
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set());
const toggleExpanded = useCallback((key: string) => {
setExpandedProjects((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
}, []);
/* Build project title lookup for search */
const projectTitleByKey = useMemo(() => {
const map = new Map<string, string>();
for (const p of props.projects) {
map.set(scopedProjectKey(p.environmentId, p.id), p.title);
}
return map;
}, [props.projects]);
/* Filter threads by search query */
const filteredThreads = useMemo(() => {
const q = props.searchQuery.trim().toLowerCase();
if (!q) return props.threads;
return props.threads.filter((t) => {
if (t.title.toLowerCase().includes(q)) return true;
const key = scopedProjectKey(t.environmentId, t.projectId);
return projectTitleByKey.get(key)?.toLowerCase().includes(q) ?? false;
});
}, [props.threads, props.searchQuery, projectTitleByKey]);
/* Group filtered threads by project */
const projectGroups = useMemo<ReadonlyArray<ProjectGroup>>(() => {
const byProject = new Map<string, ScopedMobileThread[]>();
for (const thread of filteredThreads) {
const key = scopedProjectKey(thread.environmentId, thread.projectId);
const existing = byProject.get(key);
if (existing) existing.push(thread);
else byProject.set(key, [thread]);
}
const groups: ProjectGroup[] = [];
for (const project of props.projects) {
const key = scopedProjectKey(project.environmentId, project.id);
const threads = byProject.get(key);
if (threads && threads.length > 0) {
groups.push({ key, project, threads });
}
}
groups.sort((a, b) => {
const aTime = new Date(a.threads[0]!.updatedAt ?? a.threads[0]!.createdAt).getTime();
const bTime = new Date(b.threads[0]!.updatedAt ?? b.threads[0]!.createdAt).getTime();
return bTime - aTime;
});
return groups;
}, [props.projects, filteredThreads]);
/* Empty states */
const hasAnyThreads = props.threads.length > 0;
const hasResults = filteredThreads.length > 0;
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
className="flex-1 bg-screen"
contentContainerStyle={{
paddingHorizontal: 16,
paddingTop: 8,
paddingBottom: 24,
gap: 20,
}}
>
{!hasAnyThreads ? (
<EmptyState
title="No threads yet"
detail="Create a task to start a new coding session in one of your connected projects."
/>
) : !hasResults ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : (
projectGroups.map((group) => {
const connection = props.savedConnectionsById[group.project.environmentId];
const isExpanded = expandedProjects.has(group.key);
const visibleThreads = isExpanded
? group.threads
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
return (
<View key={group.key}>
<ProjectGroupLabel
project={group.project}
totalThreadCount={group.threads.length}
httpBaseUrl={connection?.httpBaseUrl ?? null}
bearerToken={connection?.bearerToken ?? null}
isExpanded={isExpanded}
onToggleExpand={() => toggleExpanded(group.key)}
/>
<View
className="overflow-hidden rounded-[20px] bg-card"
style={{ borderCurve: "continuous" }}
>
{visibleThreads.map((thread, i) => (
<ThreadRow
key={`${thread.environmentId}:${thread.id}`}
thread={thread}
projectCwd={group.project.workspaceRoot}
onPress={() => props.onSelectThread(thread)}
isLast={i === visibleThreads.length - 1}
/>
))}
</View>
</View>
);
})
)}
</ScrollView>
);
}
@@ -3,9 +3,10 @@ import { useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { TextInputWrapper } from "expo-paste-input";
import { useCallback, useEffect, useMemo } from "react";
import { Pressable, useColorScheme, View } from "react-native";
import { Pressable, View, useColorScheme } from "react-native";
import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import type { ModelSelection } from "@t3tools/contracts";
import { CLAUDE_CODE_EFFORT_OPTIONS } from "@t3tools/contracts";
@@ -17,7 +18,6 @@ import { ProviderIcon } from "../../components/ProviderIcon";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
import { buildThreadRoutePath } from "../../lib/routes";
import { makeAppPalette } from "../../lib/theme";
import { useProjectActions } from "../../state/use-project-actions";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useNativePaste } from "../../hooks/useNativePaste";
@@ -33,9 +33,8 @@ export function NewTaskDraftScreen(props: {
const { onCreateThreadWithOptions } = useProjectActions();
const flow = useNewTaskFlow();
const router = useRouter();
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const insets = useSafeAreaInsets();
const isDarkMode = useColorScheme() === "dark";
const keyboard = useAnimatedKeyboard();
const containerAnimatedStyle = useAnimatedStyle(() => ({
paddingBottom: keyboard.height.value,
@@ -45,6 +44,9 @@ export function NewTaskDraftScreen(props: {
}));
const { logicalProjects, selectedProject, setProject } = flow;
const iconColor = useThemeColor("--color-icon");
const borderColor = useThemeColor("--color-border");
useEffect(() => {
if (props.initialProjectRef?.environmentId && props.initialProjectRef?.projectId) {
const directProject =
@@ -384,54 +386,48 @@ export function NewTaskDraftScreen(props: {
if (!selectedProject) {
return (
<View style={{ flex: 1, backgroundColor: palette.sheetBackground }}>
<View className="flex-1 bg-sheet">
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
<Text
className="text-[12px] font-t3-bold uppercase"
style={{ color: palette.textMuted, letterSpacing: 1 }}
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold" style={{ color: palette.text }}>
Loading task
</Text>
<Text className="text-[28px] font-t3-bold">Loading task</Text>
</View>
</View>
);
}
return (
<Animated.View
style={[{ flex: 1, backgroundColor: palette.sheetBackground }, containerAnimatedStyle]}
>
<Animated.View className="flex-1 bg-sheet" style={containerAnimatedStyle}>
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
{flow.logicalProjects.length > 1 ? (
<Pressable
className="absolute left-3 top-4 h-9 w-9 items-center justify-center rounded-full"
style={{ backgroundColor: palette.subtleBg, zIndex: 1 }}
className="absolute left-3 top-4 h-9 w-9 items-center justify-center rounded-full bg-subtle"
style={{ zIndex: 1 }}
onPress={() => router.back()}
>
<SymbolView
name="chevron.left"
size={16}
tintColor={palette.icon}
tintColor={iconColor}
type="monochrome"
weight="medium"
/>
</Pressable>
) : null}
<Text
className="text-[12px] font-t3-bold uppercase"
style={{ color: palette.textMuted, letterSpacing: 1 }}
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold" style={{ color: palette.text }}>
{selectedProject.title}
</Text>
<Text className="text-[28px] font-t3-bold">{selectedProject.title}</Text>
</View>
<View style={{ flex: 1, paddingHorizontal: 20, paddingTop: 8 }}>
@@ -440,17 +436,9 @@ export function NewTaskDraftScreen(props: {
multiline
value={flow.prompt}
onChangeText={flow.setPrompt}
placeholderTextColor={palette.placeholder}
placeholder={`Describe a coding task in ${selectedProject.title}`}
textAlignVertical="top"
style={{
flex: 1,
borderWidth: 0,
backgroundColor: "transparent",
color: palette.text,
fontSize: 18,
lineHeight: 28,
}}
className="flex-1 border-0 bg-transparent text-[18px] leading-[28px]"
/>
</TextInputWrapper>
</View>
@@ -459,7 +447,7 @@ export function NewTaskDraftScreen(props: {
style={[
{
borderTopWidth: 1,
borderTopColor: palette.border,
borderTopColor: borderColor,
},
controlsBottomPadding,
]}
@@ -479,6 +467,7 @@ export function NewTaskDraftScreen(props: {
<MenuView
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill
iconNode={<ProviderIcon provider={flow.selectedModel?.provider} size={16} />}
@@ -487,18 +476,21 @@ export function NewTaskDraftScreen(props: {
<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>
@@ -2,7 +2,7 @@ import type { ApprovalRequestId } from "@t3tools/contracts";
import { Pressable, View } from "react-native";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { cx } from "../../lib/classNames";
import { cn } from "../../lib/cn";
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
export interface PendingUserInputCardProps {
@@ -45,7 +45,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
return (
<Pressable
key={option.label}
className={cx(
className={cn(
"rounded-full border px-3 py-2.5 ",
selected
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
@@ -60,7 +60,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
}
>
<Text
className={cx(
className={cn(
"font-t3-bold text-[13px]",
selected
? "text-sky-700 dark:text-sky-300"
@@ -85,7 +85,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
);
})}
<Pressable
className={cx(
className={cn(
"items-center justify-center rounded-2xl px-4 py-3.5",
props.answers ? "bg-blue-500" : "bg-neutral-200 dark:bg-neutral-700/60",
)}
@@ -1,135 +0,0 @@
import {
BottomSheetBackdrop,
BottomSheetModal,
BottomSheetScrollView,
BottomSheetView,
} from "@gorhom/bottom-sheet";
import { useCallback, useEffect, useMemo, useRef } from "react";
import { Pressable, useColorScheme, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { makeAppPalette } from "../../lib/theme";
import type { ScopedMobileProject, ScopedMobileThread } from "../../lib/scopedEntities";
export function ProjectPickerSheet(props: {
readonly visible: boolean;
readonly projects: ReadonlyArray<ScopedMobileProject>;
readonly threads: ReadonlyArray<ScopedMobileThread>;
readonly onClose: () => void;
readonly onSelectProject: (project: ScopedMobileProject) => void;
}) {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const insets = useSafeAreaInsets();
const sheetRef = useRef<BottomSheetModal>(null);
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects: props.projects, threads: props.threads }),
[props.projects, props.threads],
);
const logicalProjects = useMemo(
() =>
repositoryGroups
.map((group) => {
const primaryProject = group.projects[0]?.project;
if (!primaryProject) {
return null;
}
return {
key: group.key,
project: primaryProject,
};
})
.filter((entry) => entry !== null),
[repositoryGroups],
);
const renderBackdrop = useCallback(
(backdropProps: React.ComponentProps<typeof BottomSheetBackdrop>) => (
<BottomSheetBackdrop
{...backdropProps}
appearsOnIndex={0}
disappearsOnIndex={-1}
opacity={0.18}
pressBehavior="close"
/>
),
[],
);
useEffect(() => {
const sheet = sheetRef.current;
if (!sheet) {
return;
}
if (props.visible) {
sheet.present();
return;
}
sheet.dismiss();
}, [props.visible]);
return (
<BottomSheetModal
ref={sheetRef}
index={0}
snapPoints={["88%"]}
enableDynamicSizing={false}
enablePanDownToClose
backdropComponent={renderBackdrop}
onDismiss={props.onClose}
backgroundStyle={{ backgroundColor: palette.sheetBackground }}
handleIndicatorStyle={{ backgroundColor: palette.dotSeparator }}
>
<BottomSheetView className="px-4 pt-1">
<View className="mb-4 items-center gap-1">
<Text
className="text-[12px] font-t3-bold uppercase"
style={{ color: palette.textMuted, letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold" style={{ color: palette.text }}>
Choose project
</Text>
</View>
<BottomSheetScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={{
paddingBottom: Math.max(insets.bottom, 18) + 18,
}}
>
<View
className="overflow-hidden rounded-[24px]"
style={{ backgroundColor: palette.card }}
>
{logicalProjects.map((entry, index) => (
<Pressable
key={entry.key}
onPress={() => props.onSelectProject(entry.project)}
style={{
paddingHorizontal: 16,
paddingVertical: 18,
borderTopWidth: index === 0 ? 0 : 1,
borderTopColor: palette.borderSubtle,
}}
>
<View className="flex-row items-center justify-between gap-3">
<View className="flex-1">
<Text className="text-[18px] font-t3-bold" style={{ color: palette.text }}>
{entry.project.title}
</Text>
</View>
</View>
</Pressable>
))}
</View>
</BottomSheetScrollView>
</BottomSheetView>
</BottomSheetModal>
);
}
@@ -20,6 +20,7 @@ import {
type ViewStyle,
} from "react-native";
import ImageViewing from "react-native-image-viewing";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
@@ -29,7 +30,6 @@ import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import type { MobileLayoutVariant } from "../../lib/mobileLayout";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import type { RemoteClientConnectionState } from "../../lib/remoteClient";
import { makeAppPalette } from "../../lib/theme";
import { useNativePaste } from "../../hooks/useNativePaste";
/**
@@ -109,7 +109,8 @@ function ComposerSurface(props: {
export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const placeholderColor = useThemeColor("--color-placeholder");
const foregroundColor = useThemeColor("--color-foreground");
const inputRef = useRef<RNTextInput>(null);
const [isFocused, setIsFocused] = useState(false);
const wasExpandedBeforePreviewRef = useRef(false);
@@ -337,14 +338,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
return (
<View
className="bg-screen"
style={{
paddingHorizontal: 16,
paddingTop: isExpanded ? 12 : 10,
paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 4 : 10),
// Always opaque — the glass effect lives on the ComposerSurface (pill/card),
// not the container. This prevents chat feed text from bleeding through
// the padding areas around and below the pill.
backgroundColor: palette.screenBackground,
}}
>
<View
@@ -395,7 +393,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
value={props.draftMessage}
onChangeText={props.onChangeDraftMessage}
placeholder={props.placeholder}
placeholderTextColor={palette.placeholder}
placeholderTextColor={placeholderColor}
editable={props.connectionState === "ready"}
onFocus={() => setIsFocused(true)}
onBlur={() => setIsFocused(false)}
@@ -409,7 +407,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
paddingVertical: 4,
fontSize: 15,
lineHeight: 22,
color: palette.text,
color: foregroundColor,
fontFamily: "DMSans_400Regular",
}
: {
@@ -417,7 +415,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
paddingVertical: 6,
fontSize: 15,
lineHeight: 20,
color: palette.text,
color: foregroundColor,
fontFamily: "DMSans_400Regular",
}
}
@@ -430,11 +428,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
<Pressable key={image.id} onPress={() => onPressImage(image.previewUri)}>
<Image
source={{ uri: image.previewUri }}
className="bg-subtle"
style={{
width: 30,
height: 30,
borderRadius: 8,
backgroundColor: palette.subtleBg,
}}
resizeMode="cover"
/>
@@ -442,22 +440,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
))}
{props.draftAttachments.length > 3 ? (
<View
className="bg-subtle-strong"
style={{
width: 30,
height: 30,
borderRadius: 8,
backgroundColor: palette.subtleBgStrong,
alignItems: "center",
justifyContent: "center",
}}
>
<Text
style={{
fontSize: 11,
fontFamily: "DMSans_700Bold",
color: palette.textMuted,
}}
>
<Text className="text-foreground-muted text-[11px] font-t3-bold">
+{props.draftAttachments.length - 3}
</Text>
</View>
@@ -497,12 +489,14 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
<MenuView
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill iconNode={<ProviderIcon provider={modelProvider} size={16} />} />
</MenuView>
<MenuView
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="slider.horizontal.3" />
</MenuView>
@@ -527,8 +521,8 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
{/* Queue count */}
{props.queueCount > 0 ? (
<Text
className="text-foreground-muted"
style={{
color: palette.textMuted,
fontSize: 12,
lineHeight: 18,
paddingTop: 8,
@@ -1,31 +1,23 @@
import type {
ApprovalRequestId,
GitBranch,
GitRunStackedActionResult,
GitStatusResult,
ModelSelection,
ProviderApprovalDecision,
ProviderInteractionMode,
RuntimeMode,
ServerConfig as T3ServerConfig,
} from "@t3tools/contracts";
import type { GitActionRequestInput } from "@t3tools/client-runtime";
import * as Haptics from "expo-haptics";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Modal, Pressable, useColorScheme, View } from "react-native";
import { View } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { KeyboardAvoidingView, KeyboardStickyView } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, { runOnJS } from "react-native-reanimated";
import { runOnJS } from "react-native-reanimated";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { GlassSafeAreaView } from "../../components/GlassSafeAreaView";
import type { StatusTone } from "../../components/StatusPill";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import type { MobileLayoutVariant } from "../../lib/mobileLayout";
import type { ScopedMobileThread } from "../../lib/scopedEntities";
import { makeAppPalette } from "../../lib/theme";
import type {
PendingApproval,
PendingUserInput,
@@ -33,7 +25,6 @@ import type {
ThreadFeedEntry,
} from "../../lib/threadActivity";
import { PendingApprovalCard } from "./PendingApprovalCard";
import { ThreadGitControls } from "./ThreadGitControls";
import { PendingUserInputCard } from "./PendingUserInputCard";
import {
COMPOSER_COLLAPSED_CHROME,
@@ -41,7 +32,6 @@ import {
ThreadComposer,
} from "./ThreadComposer";
import { ThreadFeed } from "./ThreadFeed";
import { screenTitle } from "./threadPresentation";
export interface ThreadDetailScreenProps {
readonly selectedThread: ScopedMobileThread;
@@ -61,12 +51,10 @@ export interface ThreadDetailScreenProps {
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly connectionStateLabel: "ready" | "connecting" | "reconnecting" | "disconnected" | "idle";
readonly activeThreadBusy: boolean;
readonly selectedThreadGitStatus: GitStatusResult | null;
readonly gitOperationLabel: string | null;
readonly projectWorkspaceRoot: string | null;
readonly selectedThreadQueueCount: number;
readonly serverConfig: T3ServerConfig | null;
readonly layoutVariant?: MobileLayoutVariant;
readonly onBack: () => void;
readonly onOpenDrawer: () => void;
readonly onOpenConnectionEditor: () => void;
readonly onChangeDraftMessage: (value: string) => void;
@@ -74,21 +62,6 @@ export interface ThreadDetailScreenProps {
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onRefresh: () => Promise<void>;
readonly onRefreshSelectedThreadGitStatus: (options?: {
readonly quiet?: boolean;
}) => Promise<void>;
readonly onListSelectedThreadBranches: () => Promise<ReadonlyArray<GitBranch>>;
readonly onCheckoutSelectedThreadBranch: (branch: string) => Promise<void>;
readonly onCreateSelectedThreadBranch: (branch: string) => Promise<void>;
readonly onCreateSelectedThreadWorktree: (input: {
readonly baseBranch: string;
readonly newBranch: string;
}) => Promise<void>;
readonly onPullSelectedThreadBranch: () => Promise<void>;
readonly onRunSelectedThreadGitAction: (
input: GitActionRequestInput,
) => Promise<GitRunStackedActionResult | null>;
readonly onRenameThread: (title: string) => Promise<void>;
readonly onStopThread: () => Promise<void>;
readonly onSendMessage: () => void;
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => Promise<void>;
@@ -107,7 +80,6 @@ export interface ThreadDetailScreenProps {
customAnswer: string,
) => void;
readonly onSubmitUserInput: () => Promise<void>;
readonly showHeader?: boolean;
readonly showContent?: boolean;
}
@@ -182,20 +154,15 @@ function useStreamingHaptics(threadId: string, feed: ReadonlyArray<ThreadFeedEnt
}
export function ThreadDetailScreen(props: ThreadDetailScreenProps) {
const { onOpenDrawer, onRefresh, onRefreshSelectedThreadGitStatus } = props;
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const { onOpenDrawer, onRefresh } = props;
const insets = useSafeAreaInsets();
const agentLabel = `${props.selectedThread.modelSelection.provider} agent`;
const headerOverlayHeight = insets.top + 118;
const composerBottomInset = Math.max(insets.bottom, 12);
const [composerExpanded, setComposerExpanded] = useState(false);
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
const composerOverlapHeight = composerChrome + composerBottomInset;
const [renameVisible, setRenameVisible] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const [renameDraft, setRenameDraft] = useState(props.selectedThread.title);
const showHeader = props.showHeader ?? true;
const showContent = props.showContent ?? true;
const layoutVariant = props.layoutVariant ?? "compact";
const isSplitLayout = layoutVariant === "split";
@@ -214,12 +181,12 @@ export function ThreadDetailScreen(props: ThreadDetailScreenProps) {
setRefreshing(true);
try {
await onRefresh();
await onRefreshSelectedThreadGitStatus();
} finally {
setRefreshing(false);
}
}, [onRefresh, onRefreshSelectedThreadGitStatus, refreshing]);
}, [onRefresh, refreshing]);
const drawerGestureThreshold = 80;
const headerDrawerGesture = useMemo(
() =>
Gesture.Pan()
@@ -229,110 +196,16 @@ export function ThreadDetailScreen(props: ThreadDetailScreenProps) {
.failOffsetY([-24, 24])
.onEnd((event) => {
const translationX = Math.max(event.translationX, 0);
if (event.y < headerOverlayHeight && translationX > 56) {
if (event.y < drawerGestureThreshold && translationX > 56) {
runOnJS(completeDrawerGesture)();
}
}),
[completeDrawerGesture, headerOverlayHeight, isSplitLayout],
[completeDrawerGesture, isSplitLayout],
);
async function handleSubmitRename(): Promise<void> {
const trimmed = renameDraft.trim();
if (trimmed.length === 0) {
return;
}
await props.onRenameThread(trimmed);
setRenameVisible(false);
}
return (
<GestureDetector gesture={headerDrawerGesture}>
<View style={{ flex: 1, backgroundColor: palette.screenBackground }}>
{showHeader ? (
<View className="absolute inset-x-0 top-0 z-20">
<View
style={{
backgroundColor: palette.headerBackground,
borderBottomWidth: 1,
borderBottomColor: palette.headerBorder,
}}
>
<GlassSafeAreaView
leftSlot={
isSplitLayout ? null : (
<Pressable
className="h-11 w-11 items-center justify-center rounded-full"
style={{
backgroundColor: palette.subtleBg,
}}
onPress={props.onBack}
>
<SymbolView
name="chevron.left"
size={18}
tintColor={palette.icon}
type="monochrome"
/>
</Pressable>
)
}
centerSlot={
<View style={{ alignItems: "center", gap: 2, width: "100%" }}>
<Pressable
style={{ maxWidth: "100%" }}
onLongPress={() => {
setRenameDraft(props.selectedThread.title);
setRenameVisible(true);
}}
>
<Animated.Text
numberOfLines={1}
style={{
color: palette.text,
fontSize: 17,
fontWeight: "800",
lineHeight: 22,
textAlign: "center",
}}
>
{props.selectedThread.title}
</Animated.Text>
</Pressable>
<Text
className="text-[11px] font-t3-medium"
numberOfLines={1}
style={{ color: palette.textMuted, letterSpacing: 0.3, textAlign: "center" }}
>
{[
screenTitle(props.serverConfig, null),
props.selectedThread.environmentLabel,
]
.filter(Boolean)
.join(" · ")}
</Text>
</View>
}
rightSlot={
<ThreadGitControls
currentBranch={props.selectedThread.branch}
currentWorktreePath={props.selectedThread.worktreePath}
gitStatus={props.selectedThreadGitStatus}
gitOperationLabel={props.gitOperationLabel}
onRefreshStatus={props.onRefreshSelectedThreadGitStatus}
onListBranches={props.onListSelectedThreadBranches}
onCheckoutBranch={props.onCheckoutSelectedThreadBranch}
onCreateBranch={props.onCreateSelectedThreadBranch}
onCreateWorktree={props.onCreateSelectedThreadWorktree}
onPull={props.onPullSelectedThreadBranch}
onRunAction={props.onRunSelectedThreadGitAction}
/>
}
/>
</View>
</View>
) : null}
<View className="flex-1">
{/* Feed area — KAV shrinks this when keyboard opens */}
<KeyboardAvoidingView behavior="padding" style={{ flex: 1 }}>
{showContent ? (
@@ -343,7 +216,6 @@ export function ThreadDetailScreen(props: ThreadDetailScreenProps) {
httpBaseUrl={props.httpBaseUrl}
bearerToken={props.bearerToken}
agentLabel={agentLabel}
contentTopInset={headerOverlayHeight + 20}
contentBottomInset={composerOverlapHeight + 8}
layoutVariant={layoutVariant}
composerExpanded={composerExpanded}
@@ -410,95 +282,6 @@ export function ThreadDetailScreen(props: ThreadDetailScreenProps) {
/>
</KeyboardStickyView>
) : null}
<Modal
transparent
animationType="fade"
visible={renameVisible}
onRequestClose={() => setRenameVisible(false)}
>
<View
className="flex-1 items-center justify-center px-5"
style={{ backgroundColor: palette.backdrop }}
>
<View
className="w-full gap-4 px-4 py-4"
style={{
maxWidth: 420,
borderWidth: 1,
borderColor: palette.border,
backgroundColor: palette.card,
}}
>
<View className="gap-2">
<Text
className="text-[11px] font-bold uppercase"
style={{ color: palette.textMuted, letterSpacing: 1.2 }}
>
Thread name
</Text>
<Text
className="text-[20px] font-extrabold leading-[24px]"
style={{ color: palette.text }}
>
Rename thread
</Text>
</View>
<TextInput
value={renameDraft}
onChangeText={setRenameDraft}
placeholder="Thread title"
className="min-h-[56px] px-4 py-3 text-[15px]"
style={{
borderWidth: 1,
borderColor: palette.border,
backgroundColor: palette.inputBackground,
color: palette.text,
}}
onSubmitEditing={() => {
void handleSubmitRename();
}}
/>
<View className="flex-row gap-3">
<Pressable
className="min-h-[48px] flex-1 items-center justify-center px-4 py-3"
style={{
borderWidth: 1,
borderColor: palette.border,
backgroundColor: palette.secondaryButton,
}}
onPress={() => {
setRenameDraft(props.selectedThread.title);
setRenameVisible(false);
}}
>
<Text
className="text-sm font-extrabold uppercase"
style={{ color: palette.text, letterSpacing: 1 }}
>
Cancel
</Text>
</Pressable>
<Pressable
className="min-h-[48px] flex-1 items-center justify-center px-4 py-3"
style={{ backgroundColor: palette.primaryButton }}
onPress={() => {
void handleSubmitRename();
}}
>
<Text
className="text-sm font-extrabold uppercase"
style={{ color: palette.primaryButtonText, letterSpacing: 1 }}
>
Save
</Text>
</Pressable>
</View>
</View>
</View>
</Modal>
</View>
</GestureDetector>
);
+45 -38
View File
@@ -4,15 +4,15 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useState, useRef } from "react";
import Markdown from "react-native-markdown-display";
import { Image, Pressable, ScrollView, useColorScheme, View } from "react-native";
import { Image, Pressable, ScrollView, View } from "react-native";
import { TouchableOpacity } from "react-native-gesture-handler";
import ImageViewing from "react-native-image-viewing";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import { cx } from "../../lib/classNames";
import { cn } from "../../lib/cn";
import type { MobileLayoutVariant } from "../../lib/mobileLayout";
import { makeAppPalette } from "../../lib/theme";
import type { ThreadFeedEntry } from "../../lib/threadActivity";
import { relativeTime } from "../../lib/time";
import { messageImageUrl } from "./threadPresentation";
@@ -23,7 +23,6 @@ export interface ThreadFeedProps {
readonly httpBaseUrl: string | null;
readonly bearerToken: string | null;
readonly agentLabel: string;
readonly contentTopInset?: number;
readonly contentBottomInset?: number;
readonly refreshing?: boolean;
readonly onRefresh?: () => void;
@@ -99,18 +98,26 @@ function buildActivityRows(
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
function makeMarkdownStyles(isDarkMode: boolean) {
const bodyColor = isDarkMode ? "#e5e5e5" : "#262626";
const strongColor = isDarkMode ? "#f5f5f5" : "#171717";
const linkColor = isDarkMode ? "#60a5fa" : "#2563eb";
const blockquoteBg = isDarkMode ? "rgba(255,255,255,0.03)" : "rgba(0,0,0,0.02)";
const blockquoteBorder = isDarkMode ? "rgba(255,255,255,0.10)" : "rgba(0,0,0,0.10)";
const codeBg = isDarkMode ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.04)";
const codeText = isDarkMode ? "#e5e5e5" : "#262626";
const hrColor = isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.08)";
const userCodeBg = isDarkMode ? "rgba(255,255,255,0.10)" : "rgba(0,0,0,0.05)";
const userCodeText = isDarkMode ? "#e5e5e5" : "#1e3a5f";
const userFenceBg = isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.04)";
interface MarkdownStyleSets {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
readonly user: Record<string, any>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
readonly assistant: Record<string, any>;
}
function useMarkdownStyles(): MarkdownStyleSets {
const bodyColor = useThemeColor("--color-md-body");
const strongColor = useThemeColor("--color-md-strong");
const linkColor = useThemeColor("--color-md-link");
const blockquoteBg = useThemeColor("--color-md-blockquote-bg");
const blockquoteBorder = useThemeColor("--color-md-blockquote-border");
const codeBg = useThemeColor("--color-md-code-bg");
const codeText = useThemeColor("--color-md-code-text");
const hrColor = useThemeColor("--color-md-hr");
const userCodeBg = useThemeColor("--color-md-user-code-bg");
const userCodeText = useThemeColor("--color-md-user-code-text");
const userFenceBg = useThemeColor("--color-md-user-fence-bg");
const userFenceText = useThemeColor("--color-md-user-fence-text");
const base = {
body: {
@@ -193,7 +200,7 @@ function makeMarkdownStyles(isDarkMode: boolean) {
},
code_block: {
backgroundColor: userFenceBg,
color: userCodeText,
color: userFenceText,
borderRadius: 12,
padding: 12,
fontFamily: "ui-monospace",
@@ -202,7 +209,7 @@ function makeMarkdownStyles(isDarkMode: boolean) {
},
fence: {
backgroundColor: userFenceBg,
color: userCodeText,
color: userFenceText,
borderRadius: 12,
padding: 12,
fontFamily: "ui-monospace",
@@ -253,12 +260,12 @@ function renderFeedEntry(
readonly onCopyWorkRow: (rowId: string, value: string) => void;
readonly onToggleWorkGroup: (groupId: string) => void;
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
readonly isDarkMode: boolean;
readonly iconSubtleColor: string | import("react-native").ColorValue;
readonly markdownStyles: MarkdownStyleSets;
},
) {
const entry = info.item;
const markdownStyles = makeMarkdownStyles(props.isDarkMode);
const palette = makeAppPalette(props.isDarkMode);
const { markdownStyles, iconSubtleColor } = props;
if (entry.type === "message") {
const { message } = entry;
@@ -389,18 +396,13 @@ function renderFeedEntry(
{visibleRows.map((row, index) => (
<View
key={row.id}
className={cx(
className={cn(
"flex-row items-center gap-2 rounded-lg px-1 py-1",
index > 0 && "border-t border-neutral-200/80 dark:border-white/[0.06]",
)}
>
<View className="items-center justify-center pt-0.5">
<SymbolView
name="terminal"
size={13}
tintColor={palette.iconSubtle}
type="monochrome"
/>
<SymbolView name="terminal" size={13} tintColor={iconSubtleColor} type="monochrome" />
</View>
<ScrollView
horizontal
@@ -439,7 +441,6 @@ function renderFeedEntry(
}
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const isDarkMode = useColorScheme() === "dark";
const listRef = useRef<LegendListRef>(null);
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [copiedRowId, setCopiedRowId] = useState<string | null>(null);
@@ -450,6 +451,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
} | null>(null);
const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const markdownStyles = useMarkdownStyles();
useEffect(() => {
setCopiedRowId(null);
setExpandedWorkGroups({});
@@ -509,12 +513,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onCopyWorkRow,
onToggleWorkGroup,
onPressImage,
isDarkMode,
iconSubtleColor,
markdownStyles,
}),
[
copiedRowId,
expandedWorkGroups,
isDarkMode,
iconSubtleColor,
markdownStyles,
onCopyWorkRow,
onPressImage,
onToggleWorkGroup,
@@ -525,12 +531,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
if (props.feed.length === 0) {
return (
<View
className="flex-1"
style={{
minHeight: 0,
<ScrollView
style={{ flex: 1 }}
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
flexGrow: 1,
paddingHorizontal: horizontalPadding,
paddingTop: props.contentTopInset ?? 18,
paddingBottom: props.contentBottomInset ?? 18,
}}
>
@@ -538,7 +544,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
title="No conversation yet"
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
/>
</View>
</ScrollView>
);
}
@@ -548,6 +554,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
ref={listRef}
key={props.threadId}
style={{ flex: 1 }}
contentInsetAdjustmentBehavior="automatic"
data={props.feed as ThreadFeedEntry[]}
renderItem={renderItem}
keyExtractor={(entry) => `${entry.type}:${entry.id}`}
@@ -561,7 +568,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onRefresh={props.onRefresh}
contentContainerStyle={{
paddingHorizontal: horizontalPadding,
paddingTop: props.contentTopInset ?? 18,
paddingTop: 8,
paddingBottom: props.contentBottomInset ?? 18,
}}
/>
File diff suppressed because it is too large. Load diff
@@ -10,14 +10,15 @@ import {
type View as RNView,
} from "react-native";
import Animated, { FadeInDown, LinearTransition } from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { BrandMark } from "../../components/BrandMark";
import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import { GlassSafeAreaView } from "../../components/GlassSafeAreaView";
import { StatusPill } from "../../components/StatusPill";
import { cn } from "../../lib/cn";
import type { MobileLayout } from "../../lib/mobileLayout";
import { makeAppPalette } from "../../lib/theme";
import {
scopedThreadKey,
type ScopedMobileProject,
@@ -70,32 +71,31 @@ function ActionButton(props: {
readonly primary?: boolean;
readonly onPress: () => void;
}) {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const primaryForeground = useThemeColor("--color-primary-foreground");
const secondaryForeground = useThemeColor("--color-secondary-foreground");
const tintColor = props.primary ? primaryForeground : secondaryForeground;
return (
<Pressable
className="min-h-[50px] flex-1 flex-row items-center justify-center gap-2 rounded-[16px] px-3 py-3"
style={{
backgroundColor: props.primary ? palette.primaryButton : palette.secondaryButton,
borderWidth: props.primary ? 0 : 1,
borderColor: props.primary ? "transparent" : palette.secondaryButtonBorder,
}}
className={cn(
"min-h-[50px] flex-1 flex-row items-center justify-center gap-2 rounded-[16px] px-3 py-3",
props.primary ? "bg-primary" : "border border-secondary-border bg-secondary",
)}
onPress={props.onPress}
>
<SymbolView
name={props.icon}
size={18}
tintColor={props.primary ? palette.primaryButtonText : palette.secondaryButtonText}
tintColor={tintColor}
type="monochrome"
weight="medium"
/>
<Text
className="text-[13px] font-t3-bold uppercase"
style={{
color: props.primary ? palette.primaryButtonText : palette.secondaryButtonText,
letterSpacing: 0.9,
}}
className={cn(
"text-[13px] font-t3-bold uppercase",
props.primary ? "text-primary-foreground" : "text-secondary-foreground",
)}
style={{ letterSpacing: 0.9 }}
>
{props.label}
</Text>
@@ -108,35 +108,20 @@ function StatCard(props: {
readonly value: string;
readonly icon: React.ComponentProps<typeof SymbolView>["name"];
}) {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const foregroundSecondary = useThemeColor("--color-foreground-secondary");
return (
<View
className="flex-1 gap-2 rounded-[18px] px-4 py-4"
style={{
backgroundColor: palette.card,
borderWidth: 1,
borderColor: palette.border,
}}
>
<View className="flex-1 gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
<View className="flex-row items-center gap-2">
<SymbolView
name={props.icon}
size={15}
tintColor={palette.textSecondary}
type="monochrome"
/>
<SymbolView name={props.icon} size={15} tintColor={foregroundSecondary} type="monochrome" />
<Text
className="text-[11px] font-t3-bold uppercase"
style={{ color: palette.textSecondary, letterSpacing: 1 }}
className="text-[11px] font-t3-bold uppercase text-foreground-secondary"
style={{ letterSpacing: 1 }}
>
{props.label}
</Text>
</View>
<Text className="text-[28px] font-t3-bold" style={{ color: palette.text }}>
{props.value}
</Text>
<Text className="text-[28px] font-t3-bold text-foreground">{props.value}</Text>
</View>
);
}
@@ -148,19 +133,20 @@ function ThreadRow(props: {
readonly onPress: (sourceFrame: TransitionSourceFrame | null) => void;
}) {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const cardColor = useThemeColor("--color-card");
const borderColor = useThemeColor("--color-border");
const containerRef = useRef<RNView>(null);
const tone = threadStatusTone(props.thread);
const backgroundColor = props.selected
? isDarkMode
? "rgba(249,115,22,0.12)"
: "rgba(249,115,22,0.09)"
: palette.card;
const borderColor = props.selected
: cardColor;
const resolvedBorderColor = props.selected
? isDarkMode
? "rgba(249,115,22,0.32)"
: "rgba(249,115,22,0.28)"
: palette.border;
: borderColor;
return (
<Pressable
@@ -168,7 +154,7 @@ function ThreadRow(props: {
className="gap-3 rounded-[18px] border px-4 py-4"
style={{
backgroundColor,
borderColor,
borderColor: resolvedBorderColor,
opacity: props.hidden ? 0 : 1,
}}
onPress={() => {
@@ -183,13 +169,8 @@ function ThreadRow(props: {
>
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-2">
<Text className="text-[17px] font-t3-bold" style={{ color: palette.text }}>
{props.thread.title}
</Text>
<Text
className="text-[13px] font-medium leading-[19px]"
style={{ color: palette.textSecondary }}
>
<Text className="text-[17px] font-t3-bold text-foreground">{props.thread.title}</Text>
<Text className="text-[13px] font-medium leading-[19px] text-foreground-secondary">
{lastConversationLine(props.thread)}
</Text>
</View>
@@ -197,8 +178,8 @@ function ThreadRow(props: {
</View>
<Text
className="text-[11px] font-t3-bold uppercase"
style={{ color: palette.textMuted, letterSpacing: 0.9 }}
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.9 }}
>
{props.thread.environmentLabel} · {props.thread.modelSelection.provider} ·{" "}
{relativeTime(props.thread.updatedAt ?? props.thread.createdAt)}
@@ -218,34 +199,28 @@ function ProjectSection(props: {
sourceFrame: TransitionSourceFrame | null,
) => void;
}) {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const [expanded, setExpanded] = useState(false);
const visibleThreads = expanded ? props.threads : props.threads.slice(0, 2);
const hiddenCount = Math.max(props.threads.length - visibleThreads.length, 0);
return (
<View className="gap-3 rounded-[22px] border px-4 py-4" style={{ borderColor: palette.border }}>
<View className="gap-3 rounded-[22px] border border-border px-4 py-4">
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-1">
<Text className="text-[15px] font-t3-bold" style={{ color: palette.text }}>
<Text className="text-[15px] font-t3-bold text-foreground">
{props.project.environmentLabel}
</Text>
<Text
className="text-[12px] font-medium leading-[18px]"
style={{ color: palette.textSecondary }}
>
<Text className="text-[12px] font-medium leading-[18px] text-foreground-secondary">
{props.project.workspaceRoot}
</Text>
</View>
<Pressable
className="rounded-full px-3 py-2"
style={{ backgroundColor: palette.subtleBg }}
className="rounded-full bg-subtle px-3 py-2"
onPress={() => void props.onCreateThread(props.project)}
>
<Text
className="text-[11px] font-t3-bold uppercase"
style={{ color: palette.text, letterSpacing: 0.9 }}
className="text-[11px] font-t3-bold uppercase text-foreground"
style={{ letterSpacing: 0.9 }}
>
New thread
</Text>
@@ -273,13 +248,12 @@ function ProjectSection(props: {
{hiddenCount > 0 ? (
<Pressable
className="items-center rounded-[16px] px-3 py-3"
style={{ backgroundColor: palette.separator }}
className="items-center rounded-[16px] bg-separator px-3 py-3"
onPress={() => setExpanded((current) => !current)}
>
<Text
className="text-[11px] font-t3-bold uppercase"
style={{ color: palette.textSecondary, letterSpacing: 1 }}
className="text-[11px] font-t3-bold uppercase text-foreground-secondary"
style={{ letterSpacing: 1 }}
>
{expanded ? "Show less" : `Show ${hiddenCount} more`}
</Text>
@@ -297,28 +271,19 @@ function CreateThreadModal(props: {
readonly onClose: () => void;
readonly onSelectProject: (project: ScopedMobileProject) => Promise<void>;
}) {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
if (!props.group) {
return null;
}
return (
<Modal transparent animationType="slide" visible={props.visible} onRequestClose={props.onClose}>
<View className="flex-1 justify-end" style={{ backgroundColor: palette.backdrop }}>
<View
className="gap-4 rounded-t-[28px] px-5 pb-8 pt-5"
style={{ backgroundColor: palette.screenBackground }}
>
<View className="flex-1 justify-end bg-backdrop">
<View className="gap-4 rounded-t-[28px] bg-screen px-5 pb-8 pt-5">
<View className="gap-1">
<Text className="text-[22px] font-t3-bold" style={{ color: palette.text }}>
<Text className="text-[22px] font-t3-bold text-foreground">
New thread in {props.group.title}
</Text>
<Text
className="text-[13px] font-medium leading-[19px]"
style={{ color: palette.textSecondary }}
>
<Text className="text-[13px] font-medium leading-[19px] text-foreground-secondary">
Choose which environment should own the new thread.
</Text>
</View>
@@ -327,31 +292,24 @@ function CreateThreadModal(props: {
{props.group.projects.map(({ project, threads }) => (
<Pressable
key={project.environmentId + project.id}
className="gap-2 rounded-[20px] border px-4 py-4"
style={{ backgroundColor: palette.card, borderColor: palette.border }}
className="gap-2 rounded-[20px] border border-border bg-card px-4 py-4"
onPress={() => {
void props.onSelectProject(project).then(props.onClose);
}}
>
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-1">
<Text className="text-[16px] font-t3-bold" style={{ color: palette.text }}>
<Text className="text-[16px] font-t3-bold text-foreground">
{project.environmentLabel}
</Text>
<Text
className="text-[12px] font-medium leading-[18px]"
style={{ color: palette.textSecondary }}
>
<Text className="text-[12px] font-medium leading-[18px] text-foreground-secondary">
{project.workspaceRoot}
</Text>
</View>
<View
className="rounded-full px-3 py-2"
style={{ backgroundColor: palette.subtleBg }}
>
<View className="rounded-full bg-subtle px-3 py-2">
<Text
className="text-[11px] font-t3-bold uppercase"
style={{ color: palette.text, letterSpacing: 0.9 }}
className="text-[11px] font-t3-bold uppercase text-foreground"
style={{ letterSpacing: 0.9 }}
>
{threads.length} thread{threads.length === 1 ? "" : "s"}
</Text>
@@ -369,8 +327,7 @@ function CreateThreadModal(props: {
}
export function ThreadListScreen(props: ThreadListScreenProps) {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const borderColorValue = useThemeColor("--color-border");
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects: props.projects, threads: props.threads }),
[props.projects, props.threads],
@@ -379,7 +336,7 @@ export function ThreadListScreen(props: ThreadListScreenProps) {
const [refreshing, setRefreshing] = useState(false);
const isSplitLayout = props.layout.usesSplitView;
const contentHorizontalPadding = isSplitLayout ? 18 : 20;
const panelBorderColor = isSplitLayout ? palette.border : "transparent";
const panelBorderColor = isSplitLayout ? borderColorValue : "transparent";
const refreshThreads = props.onRefresh;
const handleRefresh = useCallback(async (): Promise<void> => {
@@ -397,9 +354,8 @@ export function ThreadListScreen(props: ThreadListScreenProps) {
return (
<View
className="flex-1"
className="flex-1 bg-screen"
style={{
backgroundColor: palette.screenBackground,
borderRadius: isSplitLayout ? 32 : 0,
borderWidth: isSplitLayout ? 1 : 0,
borderColor: panelBorderColor,
@@ -426,28 +382,20 @@ export function ThreadListScreen(props: ThreadListScreenProps) {
<Animated.View
entering={FadeInDown.duration(260)}
layout={LinearTransition.springify().damping(18).stiffness(180)}
className="gap-4 rounded-[26px] px-4 py-4"
style={{
backgroundColor: palette.cardTranslucent,
borderWidth: 1,
borderColor: palette.border,
}}
className="gap-4 rounded-[26px] border border-border bg-card-translucent px-4 py-4"
>
<View className="flex-row items-start justify-between gap-4">
<View className="flex-1 gap-2">
<Text
className="text-[11px] font-t3-bold uppercase"
style={{ color: palette.textMuted, letterSpacing: 1.1 }}
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1.1 }}
>
{props.heroTitle}
</Text>
<Text className="text-[26px] font-t3-bold" style={{ color: palette.text }}>
<Text className="text-[26px] font-t3-bold text-foreground">
{isSplitLayout ? "Native workspace" : "Repo board"}
</Text>
<Text
className="text-[13px] font-medium leading-[19px]"
style={{ color: palette.textSecondary }}
>
<Text className="text-[13px] font-medium leading-[19px] text-foreground-secondary">
{isSplitLayout
? "Keep your repositories visible while you move between active threads."
: "Your connected repositories, grouped by identity across environments."}
@@ -497,29 +445,19 @@ export function ThreadListScreen(props: ThreadListScreenProps) {
key={group.key}
entering={FadeInDown.duration(260).delay(40 * Math.min(index, 6))}
layout={LinearTransition.springify().damping(18).stiffness(180)}
className="gap-4 rounded-[26px] px-4 py-4"
style={{
backgroundColor: palette.cardTranslucent,
borderWidth: 1,
borderColor: palette.border,
}}
className="gap-4 rounded-[26px] border border-border bg-card-translucent px-4 py-4"
>
<View className="flex-row items-start justify-between gap-4">
<View className="flex-1 gap-1">
<Text className="text-[22px] font-t3-bold" style={{ color: palette.text }}>
{group.title}
</Text>
<Text className="text-[22px] font-t3-bold text-foreground">{group.title}</Text>
{group.subtitle ? (
<Text
className="text-[13px] font-medium leading-[19px]"
style={{ color: palette.textSecondary }}
>
<Text className="text-[13px] font-medium leading-[19px] text-foreground-secondary">
{group.subtitle}
</Text>
) : null}
<Text
className="text-[11px] font-t3-bold uppercase"
style={{ color: palette.textMuted, letterSpacing: 0.9 }}
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.9 }}
>
{group.projectCount} environment{group.projectCount === 1 ? "" : "s"} ·{" "}
{group.threadCount} active thread{group.threadCount === 1 ? "" : "s"}
@@ -527,8 +465,7 @@ export function ThreadListScreen(props: ThreadListScreenProps) {
</View>
<Pressable
className="rounded-full px-3 py-2"
style={{ backgroundColor: palette.primaryButton }}
className="rounded-full bg-primary px-3 py-2"
onPress={() => {
if (group.projects.length === 1) {
void props.onCreateThread(group.projects[0]!.project);
@@ -538,8 +475,8 @@ export function ThreadListScreen(props: ThreadListScreenProps) {
}}
>
<Text
className="text-[11px] font-t3-bold uppercase"
style={{ color: palette.primaryButtonText, letterSpacing: 0.9 }}
className="text-[11px] font-t3-bold uppercase text-primary-foreground"
style={{ letterSpacing: 0.9 }}
>
New thread
</Text>
@@ -1,13 +1,6 @@
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
Modal,
Pressable,
ScrollView,
useColorScheme,
useWindowDimensions,
View,
} from "react-native";
import { Modal, Pressable, ScrollView, useWindowDimensions, View } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, {
@@ -16,6 +9,7 @@ import Animated, {
useSharedValue,
withTiming,
} from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { StatusPill } from "../../components/StatusPill";
@@ -23,7 +17,6 @@ import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import type { ScopedMobileProject, ScopedMobileThread } from "../../lib/scopedEntities";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import { makeAppPalette } from "../../lib/theme";
import { threadStatusTone } from "./threadPresentation";
function compareThreadActivity(left: ScopedMobileThread, right: ScopedMobileThread): number {
@@ -42,14 +35,19 @@ export function ThreadNavigationDrawer(props: {
readonly onSelectThread: (thread: ScopedMobileThread) => void;
readonly onStartNewTask: () => void;
}) {
const isDarkMode = useColorScheme() === "dark";
const palette = makeAppPalette(isDarkMode);
const insets = useSafeAreaInsets();
const { width } = useWindowDimensions();
const drawerWidth = Math.min(width * 0.84, 360);
const [mounted, setMounted] = useState(props.visible);
const translateX = useSharedValue(-drawerWidth);
const overlayOpacity = useSharedValue(0);
const backdropColor = useThemeColor("--color-backdrop");
const drawerBg = useThemeColor("--color-drawer");
const drawerShadow = useThemeColor("--color-drawer-shadow");
const primaryForeground = useThemeColor("--color-primary-foreground");
const borderSubtleColor = useThemeColor("--color-border-subtle");
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects: props.projects, threads: props.threads }),
[props.projects, props.threads],
@@ -130,7 +128,7 @@ export function ThreadNavigationDrawer(props: {
right: 0,
top: 0,
bottom: 0,
backgroundColor: palette.backdrop,
backgroundColor: backdropColor,
},
backdropStyle,
]}
@@ -149,30 +147,27 @@ export function ThreadNavigationDrawer(props: {
top: 0,
bottom: 0,
width: drawerWidth,
backgroundColor: palette.drawerBackground,
backgroundColor: drawerBg,
paddingTop: insets.top + 10,
paddingBottom: Math.max(insets.bottom, 18),
boxShadow: `20px 0 36px ${palette.drawerShadow}`,
boxShadow: `20px 0 36px ${String(drawerShadow)}`,
},
drawerStyle,
]}
>
<View className="flex-row items-center justify-between px-4 pb-5">
<Text className="text-[26px] font-t3-bold" style={{ color: palette.text }}>
Threads
</Text>
<Text className="text-[26px] font-t3-bold">Threads</Text>
<Pressable
onPress={() => {
props.onClose();
props.onStartNewTask();
}}
className="h-11 w-11 items-center justify-center rounded-full"
style={{ backgroundColor: palette.primaryButton }}
className="h-11 w-11 items-center justify-center rounded-full bg-primary"
>
<SymbolView
name="square.and.pencil"
size={17}
tintColor={palette.primaryButtonText}
tintColor={primaryForeground}
type="monochrome"
/>
</Pressable>
@@ -189,22 +184,16 @@ export function ThreadNavigationDrawer(props: {
{groupedThreads.map((group) => (
<View key={group.key} className="gap-3">
<Text
className="px-1 text-[15px] font-t3-bold"
style={{ color: palette.textMuted, letterSpacing: -0.2 }}
className="px-1 text-[15px] font-t3-bold text-foreground-muted"
style={{ letterSpacing: -0.2 }}
>
{group.title}
</Text>
<View
className="overflow-hidden rounded-[22px]"
style={{ backgroundColor: palette.card }}
>
<View className="overflow-hidden rounded-[22px] bg-card">
{group.threads.length === 0 ? (
<View className="px-4 py-4">
<Text
className="text-[14px] font-medium"
style={{ color: palette.textTertiary }}
>
<Text className="text-[14px] font-medium text-foreground-tertiary">
No threads yet
</Text>
</View>
@@ -224,23 +213,19 @@ export function ThreadNavigationDrawer(props: {
paddingHorizontal: 16,
paddingVertical: 15,
borderTopWidth: index === 0 ? 0 : 1,
borderTopColor: palette.borderSubtle,
backgroundColor: selected ? palette.subtleBg : "transparent",
borderTopColor: borderSubtleColor,
backgroundColor: selected ? undefined : "transparent",
}}
className={selected ? "bg-subtle" : undefined}
>
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-1">
<Text
className="text-[16px] font-t3-bold"
numberOfLines={1}
style={{ color: palette.text }}
>
<Text className="text-[16px] font-t3-bold" numberOfLines={1}>
{thread.title}
</Text>
<Text
className="text-[13px] font-medium"
className="text-[13px] font-medium text-foreground-muted"
numberOfLines={1}
style={{ color: palette.textMuted }}
>
{relativeTime(thread.updatedAt ?? thread.createdAt)}
</Text>
@@ -1,12 +1,13 @@
import { useLocalSearchParams, useRouter } from "expo-router";
import { useEffect, useMemo, useState } from "react";
import { ScrollView, useColorScheme, View } from "react-native";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
import { useGitStatus, gitStatusManager } from "../../state/use-git-status";
import { EmptyState } from "../../components/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen";
import { buildThreadRoutePath, dismissRoute } from "../../lib/routes";
import { buildThreadRoutePath } from "../../lib/routes";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { makeAppPalette } from "../../lib/theme";
import { connectionTone } from "../connection/connectionTone";
import { firstNonNull } from "../../state/remote-runtime-types";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
@@ -14,12 +15,15 @@ import {
useRemoteConnectionStatus,
useRemoteEnvironmentState,
} from "../../state/use-remote-environment-registry";
import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
import { useSelectedThreadCommands } from "../../state/use-selected-thread-commands";
import { useSelectedThreadGit } from "../../state/use-selected-thread-git";
import { useThreadComposerState } from "../../state/use-thread-composer-state";
import { useThreadSelection } from "../../state/use-thread-selection";
import { ThreadDetailScreen } from "./ThreadDetailScreen";
import { ThreadGitControls } from "./ThreadGitControls";
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
import { screenTitle } from "./threadPresentation";
function firstRouteParam(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) {
@@ -36,19 +40,19 @@ export function ThreadRouteScreen() {
const {
onSelectThread,
selectedThread,
selectedThreadProject,
selectedEnvironmentConnection,
selectedEnvironmentRuntime,
} = useThreadSelection();
const composer = useThreadComposerState();
const git = useSelectedThreadGit();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const commands = useSelectedThreadCommands({
activePendingUserInput: composer.activePendingUserInput,
activePendingUserInputAnswers: composer.activePendingUserInputAnswers,
refreshSelectedThreadGitStatus: git.refreshSelectedThreadGitStatus,
refreshSelectedThreadGitStatus: gitActions.refreshSelectedThreadGitStatus,
});
const router = useRouter();
const colorScheme = useColorScheme();
const isDarkMode = colorScheme !== "light";
const params = useLocalSearchParams<{
environmentId?: string | string[];
threadId?: string | string[];
@@ -57,6 +61,32 @@ export function ThreadRouteScreen() {
const environmentId = firstRouteParam(params.environmentId);
const threadId = firstRouteParam(params.threadId);
/* ─── Native header theming ──────────────────────────────────────── */
const isDark = useColorScheme() === "dark";
const iconColor = String(useThemeColor("--color-icon"));
const foregroundColor = String(useThemeColor("--color-foreground"));
const secondaryFg = isDark ? "#a3a3a3" : "#525252";
/* ─── Git status for native header trigger ───────────────────────── */
const gitStatus = useGitStatus({
environmentId: selectedThread?.environmentId ?? "",
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
});
const handleRefreshGitStatus = useCallback(async () => {
if (!selectedThread) return;
await gitStatusManager.refresh({
environmentId: selectedThread.environmentId,
cwd: selectedThread.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
});
}, [selectedThread, selectedThreadProject?.workspaceRoot]);
/** Wraps thread refresh + git status refresh for pull-to-refresh */
const handleRefreshAll = useCallback(async () => {
await commands.onRefresh();
await handleRefreshGitStatus();
}, [commands, handleRefreshGitStatus]);
const routeThread = useMemo(() => {
if (!environmentId || !threadId) {
return null;
@@ -106,7 +136,7 @@ export function ThreadRouteScreen() {
paddingHorizontal: 24,
paddingVertical: 32,
}}
style={{ flex: 1, backgroundColor: makeAppPalette(isDarkMode).screenBackground }}
className="bg-screen flex-1"
>
<EmptyState
title="Thread unavailable"
@@ -125,71 +155,117 @@ export function ThreadRouteScreen() {
selectedEnvironmentRuntime?.serverConfig ??
firstNonNull(Object.values(environmentStateById).map((runtime) => runtime.serverConfig));
const headerSubtitle = [screenTitle(serverConfig, null), selectedThread.environmentLabel]
.filter(Boolean)
.join(" · ");
return (
<View style={{ flex: 1 }}>
<ThreadDetailScreen
selectedThread={selectedThread}
screenTone={connectionTone(connectionState)}
connectionError={connectionError}
httpBaseUrl={selectedEnvironmentConnection?.httpBaseUrl ?? null}
bearerToken={selectedEnvironmentConnection?.bearerToken ?? null}
selectedThreadFeed={composer.selectedThreadFeed}
activeWorkDurationLabel={composer.activeWorkDurationLabel}
activePendingApproval={composer.activePendingApproval}
respondingApprovalId={commands.respondingApprovalId}
activePendingUserInput={composer.activePendingUserInput}
activePendingUserInputDrafts={composer.activePendingUserInputDrafts}
activePendingUserInputAnswers={composer.activePendingUserInputAnswers}
respondingUserInputId={commands.respondingUserInputId}
draftMessage={composer.draftMessage}
draftAttachments={composer.draftAttachments}
connectionStateLabel={connectionState}
activeThreadBusy={composer.activeThreadBusy}
selectedThreadGitStatus={git.selectedThreadGitStatus}
gitOperationLabel={git.gitOperationLabel}
selectedThreadQueueCount={composer.selectedThreadQueueCount}
onBack={() => dismissRoute(router)}
onOpenDrawer={() => setDrawerVisible(true)}
onOpenConnectionEditor={() => router.push("/connections")}
onChangeDraftMessage={composer.onChangeDraftMessage}
onPickDraftImages={composer.onPickDraftImages}
onNativePasteImages={composer.onNativePasteImages}
onRemoveDraftImage={composer.onRemoveDraftImage}
onRefresh={commands.onRefresh}
onRefreshSelectedThreadGitStatus={async (options) => {
await git.refreshSelectedThreadGitStatus(options);
<>
<Stack.Screen
options={{
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTintColor: iconColor,
headerBackTitle: "",
headerTitle: () => (
<Pressable
style={{ alignItems: "center", maxWidth: 200 }}
onLongPress={() => {
// TODO: trigger rename modal
}}
>
<RNText
numberOfLines={1}
style={{
fontFamily: "DMSans_700Bold",
fontSize: 18,
fontWeight: "900",
color: foregroundColor,
letterSpacing: -0.4,
}}
>
{selectedThread.title}
</RNText>
<RNText
numberOfLines={1}
style={{
fontFamily: "DMSans_700Bold",
fontSize: 12,
fontWeight: "700",
color: secondaryFg,
letterSpacing: 0.3,
}}
>
{headerSubtitle}
</RNText>
</Pressable>
),
}}
onListSelectedThreadBranches={git.onListSelectedThreadBranches}
onCheckoutSelectedThreadBranch={git.onCheckoutSelectedThreadBranch}
onCreateSelectedThreadBranch={git.onCreateSelectedThreadBranch}
onCreateSelectedThreadWorktree={git.onCreateSelectedThreadWorktree}
onPullSelectedThreadBranch={git.onPullSelectedThreadBranch}
onRunSelectedThreadGitAction={git.onRunSelectedThreadGitAction}
serverConfig={serverConfig}
onRenameThread={commands.onRenameThread}
onStopThread={commands.onStopThread}
onSendMessage={composer.onSendMessage}
onUpdateThreadModelSelection={commands.onUpdateThreadModelSelection}
onUpdateThreadRuntimeMode={commands.onUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={commands.onUpdateThreadInteractionMode}
onRespondToApproval={commands.onRespondToApproval}
onSelectUserInputOption={composer.onSelectUserInputOption}
onChangeUserInputCustomAnswer={composer.onChangeUserInputCustomAnswer}
onSubmitUserInput={commands.onSubmitUserInput}
/>
<ThreadNavigationDrawer
visible={drawerVisible}
projects={projects}
threads={threads}
selectedThreadKey={selectedThreadKey}
onClose={() => setDrawerVisible(false)}
onSelectThread={(thread) => {
onSelectThread(thread);
router.replace(buildThreadRoutePath(thread));
}}
onStartNewTask={() => router.push("/new")}
<ThreadGitControls
currentBranch={selectedThread.branch}
gitStatus={gitStatus.data}
gitOperationLabel={gitState.gitOperationLabel}
onPull={gitActions.onPullSelectedThreadBranch}
onRunAction={gitActions.onRunSelectedThreadGitAction}
/>
</View>
<View className="flex-1 bg-screen">
<ThreadDetailScreen
selectedThread={selectedThread}
screenTone={connectionTone(connectionState)}
connectionError={connectionError}
httpBaseUrl={selectedEnvironmentConnection?.httpBaseUrl ?? null}
bearerToken={selectedEnvironmentConnection?.bearerToken ?? null}
selectedThreadFeed={composer.selectedThreadFeed}
activeWorkDurationLabel={composer.activeWorkDurationLabel}
activePendingApproval={composer.activePendingApproval}
respondingApprovalId={commands.respondingApprovalId}
activePendingUserInput={composer.activePendingUserInput}
activePendingUserInputDrafts={composer.activePendingUserInputDrafts}
activePendingUserInputAnswers={composer.activePendingUserInputAnswers}
respondingUserInputId={commands.respondingUserInputId}
draftMessage={composer.draftMessage}
draftAttachments={composer.draftAttachments}
connectionStateLabel={connectionState}
activeThreadBusy={composer.activeThreadBusy}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
selectedThreadQueueCount={composer.selectedThreadQueueCount}
onOpenDrawer={() => setDrawerVisible(true)}
onOpenConnectionEditor={() => router.push("/connections")}
onChangeDraftMessage={composer.onChangeDraftMessage}
onPickDraftImages={composer.onPickDraftImages}
onNativePasteImages={composer.onNativePasteImages}
onRemoveDraftImage={composer.onRemoveDraftImage}
onRefresh={handleRefreshAll}
serverConfig={serverConfig}
onStopThread={commands.onStopThread}
onSendMessage={composer.onSendMessage}
onUpdateThreadModelSelection={commands.onUpdateThreadModelSelection}
onUpdateThreadRuntimeMode={commands.onUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={commands.onUpdateThreadInteractionMode}
onRespondToApproval={commands.onRespondToApproval}
onSelectUserInputOption={composer.onSelectUserInputOption}
onChangeUserInputCustomAnswer={composer.onChangeUserInputCustomAnswer}
onSubmitUserInput={commands.onSubmitUserInput}
/>
<ThreadNavigationDrawer
visible={drawerVisible}
projects={projects}
threads={threads}
selectedThreadKey={selectedThreadKey}
onClose={() => setDrawerVisible(false)}
onSelectThread={(thread) => {
onSelectThread(thread);
router.replace(buildThreadRoutePath(thread));
}}
onStartNewTask={() => router.push("/new")}
/>
</View>
</>
);
}
@@ -0,0 +1,205 @@
import { sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { useRouter } from "expo-router";
import { useEffect, useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
import { useGitStatus } from "../../../state/use-git-status";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { SheetActionButton } from "./gitSheetComponents";
export function GitBranchesSheet() {
const router = useRouter();
const insets = useSafeAreaInsets();
const { selectedThread, selectedThreadProject } = useThreadSelection();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const borderColor = useThemeColor("--color-border");
const inputBorderColor = useThemeColor("--color-input-border");
const inputBg = useThemeColor("--color-input");
const foregroundColor = useThemeColor("--color-foreground");
const subtleStrongColor = useThemeColor("--color-subtle-strong");
const gitStatus = useGitStatus({
environmentId: selectedThread?.environmentId ?? "",
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
});
const currentBranchLabel = gitStatus.data?.branch ?? selectedThread?.branch ?? "Detached HEAD";
const currentWorktreePath = selectedThread?.worktreePath ?? null;
const availableBranches = gitState.selectedThreadBranches;
const branchesLoading = gitState.selectedThreadBranchesLoading;
const busy = gitState.gitOperationLabel !== null;
const [newBranchName, setNewBranchName] = useState("");
const [worktreeBaseBranch, setWorktreeBaseBranch] = useState(
currentBranchLabel === "Detached HEAD" ? "main" : currentBranchLabel,
);
const [worktreeBranchName, setWorktreeBranchName] = useState("");
const disabledExistingBranches = new Set(
availableBranches
.filter(
(branch) => branch.worktreePath !== null && branch.worktreePath !== currentWorktreePath,
)
.map((branch) => branch.name),
);
useEffect(() => {
void gitActions.refreshSelectedThreadBranches();
}, [gitActions]);
return (
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 8,
paddingBottom: Math.max(insets.bottom, 18) + 18,
gap: 16,
}}
>
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
<Text
className="text-foreground-secondary text-[11px] font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
New branch
</Text>
<TextInput
value={newBranchName}
onChangeText={setNewBranchName}
placeholder="feature/mobile-polish"
className="rounded-[18px] px-3.5 py-3 font-sans text-[15px]"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<SheetActionButton
icon="plus"
label="Create & checkout"
tone="primary"
disabled={busy || newBranchName.trim().length === 0}
onPress={() => {
const branch = sanitizeFeatureBranchName(newBranchName.trim());
if (branch.length === 0) return;
void gitActions.onCreateSelectedThreadBranch(branch).then(() => {
setNewBranchName("");
router.dismiss();
});
}}
/>
</View>
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
<Text
className="text-foreground-secondary text-[11px] font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
New worktree
</Text>
<TextInput
value={worktreeBaseBranch}
onChangeText={setWorktreeBaseBranch}
placeholder="main"
className="rounded-[18px] px-3.5 py-3 font-sans text-[15px]"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<TextInput
value={worktreeBranchName}
onChangeText={setWorktreeBranchName}
placeholder="feature/mobile-thread"
className="rounded-[18px] px-3.5 py-3 font-sans text-[15px]"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<SheetActionButton
icon="square.split.2x1"
label="Create worktree"
tone="primary"
disabled={
busy || worktreeBaseBranch.trim().length === 0 || worktreeBranchName.trim().length === 0
}
onPress={() => {
const baseBranch = worktreeBaseBranch.trim();
const newBranch = worktreeBranchName.trim();
if (baseBranch.length === 0 || newBranch.length === 0) return;
void gitActions
.onCreateSelectedThreadWorktree({ baseBranch, newBranch })
.then(() => {
setWorktreeBranchName("");
router.dismiss();
});
}}
/>
</View>
<View className="gap-2">
<Text
className="text-foreground-secondary text-[11px] font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
Existing branches
</Text>
{branchesLoading ? (
<Text className="text-foreground-secondary text-[13px] font-medium">
Loading branches...
</Text>
) : null}
{!branchesLoading && availableBranches.length === 0 ? (
<Text className="text-foreground-secondary text-[13px] font-medium">
No local branches found.
</Text>
) : null}
{availableBranches.map((branch) => {
const disabled = disabledExistingBranches.has(branch.name);
const subtitle = branch.worktreePath
? branch.worktreePath === currentWorktreePath
? "Checked out in this thread"
: "Checked out in another worktree"
: branch.isDefault
? "Default branch"
: "Local branch";
return (
<Pressable
key={branch.name}
className="gap-1 rounded-[18px] border px-4 py-3"
disabled={busy || disabled}
style={{
borderColor: branch.current ? subtleStrongColor : borderColor,
opacity: busy || disabled ? 0.45 : 1,
}}
onPress={() => {
void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => {
router.dismiss();
});
}}
>
<View className="absolute inset-0 rounded-[18px] bg-card" />
<Text className="text-foreground text-[15px] font-t3-bold">{branch.name}</Text>
<Text className="text-foreground-secondary text-[12px] font-medium">{subtitle}</Text>
</Pressable>
);
})}
</View>
</ScrollView>
);
}
@@ -0,0 +1,242 @@
import { useRouter } from "expo-router";
import { useCallback, useState } from "react";
import { Pressable, ScrollView, View, useColorScheme } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
import { useGitStatus } from "../../../state/use-git-status";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { SheetActionButton } from "./gitSheetComponents";
export function GitCommitSheet() {
const router = useRouter();
const insets = useSafeAreaInsets();
const isDarkMode = useColorScheme() === "dark";
const { selectedThread, selectedThreadProject } = useThreadSelection();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const borderColor = useThemeColor("--color-border");
const borderSubtleColor = useThemeColor("--color-border-subtle");
const inputBorderColor = useThemeColor("--color-input-border");
const inputBg = useThemeColor("--color-input");
const foregroundColor = useThemeColor("--color-foreground");
const gitStatus = useGitStatus({
environmentId: selectedThread?.environmentId ?? "",
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
});
const busy = gitState.gitOperationLabel !== null;
const isDefaultBranch = gitStatus.data?.isDefaultBranch ?? false;
const allFiles = gitStatus.data?.workingTree?.files ?? [];
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
const [excludedFiles, setExcludedFiles] = useState<ReadonlySet<string>>(new Set());
const [isEditingFiles, setIsEditingFiles] = useState(false);
const selectedFiles = allFiles.filter((file) => !excludedFiles.has(file.path));
const allSelected = excludedFiles.size === 0;
const noneSelected = selectedFiles.length === 0;
const selectedInsertions = selectedFiles.reduce((sum, file) => sum + file.insertions, 0);
const selectedDeletions = selectedFiles.reduce((sum, file) => sum + file.deletions, 0);
const selectedFilePreview = selectedFiles.slice(0, 3);
const runCommitAction = useCallback(
async (featureBranch: boolean) => {
const commitMessage = dialogCommitMessage.trim();
router.dismiss();
await gitActions.onRunSelectedThreadGitAction({
action: "commit",
featureBranch,
...(commitMessage ? { commitMessage } : {}),
...(!allSelected ? { filePaths: selectedFiles.map((file) => file.path) } : {}),
});
},
[allSelected, dialogCommitMessage, gitActions, router, selectedFiles],
);
return (
<ScrollView
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 8,
paddingBottom: Math.max(insets.bottom, 18) + 18,
gap: 16,
}}
>
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
<View className="flex-row items-center justify-between gap-3">
<Text className="text-foreground-muted text-[13px] font-medium">Branch</Text>
<Text className="text-foreground text-[15px] font-t3-bold">
{gitStatus.data?.branch ?? "(detached HEAD)"}
</Text>
</View>
{isDefaultBranch ? (
<Text
className="text-[12px] leading-[18px]"
style={{ color: isDarkMode ? "#fbbf24" : "#b45309" }}
>
Warning: this is the default branch.
</Text>
) : null}
</View>
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
<View className="flex-row items-center justify-between gap-3">
<View className="gap-1">
<Text className="text-foreground text-[16px] font-t3-bold">Files</Text>
<Text className="text-foreground-muted text-[12px] leading-[18px]">
{selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions}
</Text>
</View>
<View className="flex-row items-center gap-2">
{!allSelected && isEditingFiles ? (
<Pressable
className="bg-subtle rounded-full px-3 py-2"
onPress={() => setExcludedFiles(new Set())}
>
<Text className="text-foreground text-[11px] font-t3-bold uppercase">Reset</Text>
</Pressable>
) : null}
<Pressable
className="bg-subtle rounded-full px-3 py-2"
onPress={() => setIsEditingFiles((current) => !current)}
>
<Text className="text-foreground text-[11px] font-t3-bold uppercase">
{isEditingFiles ? "Done" : "Edit"}
</Text>
</Pressable>
</View>
</View>
{allFiles.length === 0 ? (
<Text className="text-foreground-secondary text-[13px] leading-[19px]">
No changed files are available to commit.
</Text>
) : !isEditingFiles ? (
<View className="gap-2">
{selectedFilePreview.map((file) => (
<View key={file.path} className="flex-row items-center justify-between gap-3">
<Text
className="text-foreground flex-1 text-[13px] font-medium"
numberOfLines={1}
>
{file.path}
</Text>
<Text className="text-[12px] font-t3-bold" style={{ color: "#10b981" }}>
+{file.insertions}
</Text>
<Text className="text-[12px] font-t3-bold" style={{ color: "#f43f5e" }}>
-{file.deletions}
</Text>
</View>
))}
{selectedFiles.length > selectedFilePreview.length ? (
<Text className="text-foreground-muted text-[12px] leading-[17px]">
+{selectedFiles.length - selectedFilePreview.length} more files
</Text>
) : null}
</View>
) : (
<View className="gap-2">
{allFiles.map((file) => {
const included = !excludedFiles.has(file.path);
return (
<Pressable
key={file.path}
className="rounded-[18px] border px-4 py-3"
style={{
borderColor: included ? borderColor : borderSubtleColor,
}}
onPress={() => {
setExcludedFiles((current) => {
const next = new Set(current);
if (next.has(file.path)) {
next.delete(file.path);
} else {
next.add(file.path);
}
return next;
});
}}
>
<View
className={`absolute inset-0 rounded-[18px] ${included ? "bg-card" : "bg-subtle"}`}
/>
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-1">
<Text
selectable
className={`text-[13px] font-t3-bold ${included ? "text-foreground" : "text-foreground-muted"}`}
>
{file.path}
</Text>
{!included ? (
<Text className="text-foreground-muted text-[11px] leading-[16px]">
Excluded from this commit
</Text>
) : null}
</View>
<View className="items-end gap-1">
<Text className="text-[12px] font-t3-bold" style={{ color: "#10b981" }}>
+{file.insertions}
</Text>
<Text className="text-[12px] font-t3-bold" style={{ color: "#f43f5e" }}>
-{file.deletions}
</Text>
</View>
</View>
</Pressable>
);
})}
</View>
)}
</View>
<View className="gap-2">
<Text className="text-foreground text-[13px] font-t3-bold">Commit message</Text>
<TextInput
multiline
value={dialogCommitMessage}
onChangeText={setDialogCommitMessage}
placeholder="Leave empty to auto-generate"
textAlignVertical="top"
className="min-h-[128px] rounded-[20px] px-4 py-3.5 font-sans text-[15px]"
style={{
minHeight: 128,
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
</View>
<View className="flex-row gap-3">
<View className="flex-1">
<SheetActionButton
icon="arrow.branch"
label="Commit on new branch"
disabled={noneSelected || busy}
onPress={() => void runCommitAction(true)}
/>
</View>
<View className="flex-1">
<SheetActionButton
icon="checkmark.circle"
label="Commit"
tone="primary"
disabled={noneSelected || busy}
onPress={() => void runCommitAction(false)}
/>
</View>
</View>
</ScrollView>
);
}
@@ -0,0 +1,123 @@
import { resolveDefaultBranchActionDialogCopy } from "@t3tools/client-runtime";
import { resolveAutoFeatureBranchName } from "@t3tools/shared/git";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo } from "react";
import { View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../../components/AppText";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
import { SheetActionButton } from "./gitSheetComponents";
export function GitConfirmSheet() {
const router = useRouter();
const insets = useSafeAreaInsets();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const params = useLocalSearchParams<{
confirmAction?: string;
branchName?: string;
includesCommit?: string;
commitMessage?: string;
filePaths?: string;
}>();
const confirmAction = params.confirmAction as
| "push"
| "create_pr"
| "commit_push"
| "commit_push_pr"
| undefined;
const branchName = params.branchName ?? "";
const includesCommit = params.includesCommit === "true";
const copy = useMemo(
() =>
confirmAction
? resolveDefaultBranchActionDialogCopy({
action: confirmAction,
branchName,
includesCommit,
})
: null,
[branchName, confirmAction, includesCommit],
);
const continuePendingAction = useCallback(async () => {
if (!confirmAction) return;
router.dismissAll();
await gitActions.onRunSelectedThreadGitAction({
action: confirmAction,
...(params.commitMessage ? { commitMessage: params.commitMessage } : {}),
...(params.filePaths ? { filePaths: params.filePaths.split(",") } : {}),
});
}, [confirmAction, gitActions, params, router]);
const movePendingActionToFeatureBranch = useCallback(async () => {
if (!confirmAction) return;
router.dismissAll();
if (includesCommit) {
await gitActions.onRunSelectedThreadGitAction({
action: confirmAction,
featureBranch: true,
...(params.commitMessage ? { commitMessage: params.commitMessage } : {}),
...(params.filePaths ? { filePaths: params.filePaths.split(",") } : {}),
});
return;
}
const branches =
gitState.selectedThreadBranches.length > 0
? gitState.selectedThreadBranches
: await gitActions.refreshSelectedThreadBranches();
const newBranchName = resolveAutoFeatureBranchName(
branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
);
await gitActions.onCreateSelectedThreadBranch(newBranchName);
await gitActions.onRunSelectedThreadGitAction({ action: confirmAction });
}, [confirmAction, gitActions, gitState.selectedThreadBranches, includesCommit, params, router]);
return (
<View
collapsable={false}
className="flex-1 bg-sheet"
>
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
Confirm
</Text>
<Text className="text-center text-[28px] font-t3-bold">
{copy?.title ?? "Run action on default branch?"}
</Text>
<Text className="text-center text-foreground-secondary text-[13px] font-medium leading-[19px]">
{copy?.description ?? "Choose how to continue."}
</Text>
</View>
<View
className="gap-3 px-5"
style={{ paddingBottom: Math.max(insets.bottom, 18) + 8, paddingTop: 8 }}
>
<SheetActionButton
icon="arrow.right.circle"
label={copy?.continueLabel ?? "Continue"}
onPress={() => void continuePendingAction()}
/>
<SheetActionButton
icon="arrow.branch"
label="Feature branch & continue"
tone="primary"
onPress={() => void movePendingActionToFeatureBranch()}
/>
</View>
</View>
);
}
@@ -0,0 +1,249 @@
import type { GitRunStackedActionResult } from "@t3tools/contracts";
import {
type GitActionRequestInput,
buildMenuItems,
getGitActionDisabledReason,
requiresDefaultBranchConfirmation,
} from "@t3tools/client-runtime";
import { useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo } from "react";
import { Alert, Linking, 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 { StatusPill } from "../../../components/StatusPill";
import { useGitStatus } from "../../../state/use-git-status";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents";
export function GitOverviewSheet() {
const router = useRouter();
const insets = useSafeAreaInsets();
const { environmentId, threadId } = useLocalSearchParams<{
environmentId: string;
threadId: string;
}>();
const { selectedThread, selectedThreadProject } = useThreadSelection();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const iconColor = useThemeColor("--color-icon");
const borderColor = useThemeColor("--color-border");
const gitStatus = useGitStatus({
environmentId: selectedThread?.environmentId ?? "",
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
});
const currentBranchLabel = gitStatus.data?.branch ?? selectedThread?.branch ?? "Detached HEAD";
const currentWorktreePath = selectedThread?.worktreePath ?? null;
const gitOperationLabel = gitState.gitOperationLabel;
const busy = gitOperationLabel !== null;
const isRepo = gitStatus.data?.isRepo ?? true;
const hasOriginRemote = gitStatus.data?.hasOriginRemote ?? false;
const isDefaultBranch = gitStatus.data?.isDefaultBranch ?? false;
const menuItems = useMemo(
() => (isRepo ? buildMenuItems(gitStatus.data, busy, hasOriginRemote) : []),
[busy, gitStatus.data, hasOriginRemote, isRepo],
);
const sheetMenuItems = useMemo(
() =>
menuItems.map((item) => ({
item,
disabledReason: getGitActionDisabledReason({
item,
gitStatus: gitStatus.data,
isBusy: busy,
hasOriginRemote,
}),
})),
[busy, gitStatus.data, hasOriginRemote, menuItems],
);
useEffect(() => {
void gitActions.refreshSelectedThreadGitStatus({ quiet: true });
}, [gitActions]);
const openExistingPr = useCallback(async () => {
const prUrl = gitStatus.data?.pr?.state === "open" ? gitStatus.data.pr.url : null;
if (!prUrl) {
Alert.alert("No open PR", "This branch does not have an open pull request.");
return;
}
try {
await Linking.openURL(prUrl);
} catch (error) {
Alert.alert(
"Unable to open PR",
error instanceof Error ? error.message : "An error occurred.",
);
}
}, [gitStatus.data]);
const runActionWithPrompt = useCallback(
async (input: GitActionRequestInput) => {
const confirmableAction =
input.action === "push" ||
input.action === "create_pr" ||
input.action === "commit_push" ||
input.action === "commit_push_pr"
? input.action
: null;
const branchName = gitStatus.data?.branch;
if (
branchName &&
confirmableAction &&
!input.featureBranch &&
requiresDefaultBranchConfirmation(input.action, isDefaultBranch)
) {
router.push({
pathname: "/threads/[environmentId]/[threadId]/git-confirm",
params: {
environmentId,
threadId,
confirmAction: confirmableAction,
branchName,
includesCommit: String(
input.action === "commit_push" || input.action === "commit_push_pr",
),
},
});
return;
}
router.dismiss();
await gitActions.onRunSelectedThreadGitAction(input);
},
[environmentId, gitActions, gitStatus.data, isDefaultBranch, router, threadId],
);
const onPressMenuItem = useCallback(
async (item: (typeof menuItems)[number]) => {
if (item.disabled) return;
if (item.kind === "open_pr") {
await openExistingPr();
return;
}
if (item.dialogAction === "commit") {
router.push({
pathname: "/threads/[environmentId]/[threadId]/git/commit",
params: { environmentId, threadId },
});
return;
}
if (item.dialogAction === "push") {
await runActionWithPrompt({ action: "push" });
return;
}
if (item.dialogAction === "create_pr") {
await runActionWithPrompt({ action: "create_pr" });
}
},
[environmentId, openExistingPr, router, runActionWithPrompt, threadId],
);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
<Pressable
className="absolute right-3 top-4 h-9 w-9 items-center justify-center rounded-full bg-subtle"
style={{ zIndex: 1, opacity: busy ? 0.45 : 1 }}
disabled={busy}
onPress={() => void gitActions.refreshSelectedThreadGitStatus()}
>
<SymbolView
name="arrow.clockwise"
size={16}
tintColor={iconColor}
type="monochrome"
weight="medium"
/>
</Pressable>
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
Branch
</Text>
<Text className="text-[28px] font-t3-bold">{currentBranchLabel}</Text>
<Text className="text-foreground-secondary text-[13px] font-medium leading-[19px]">
{statusSummary(gitStatus.data)}
</Text>
</View>
<ScrollView
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 8,
paddingBottom: Math.max(insets.bottom, 18) + 18,
gap: 14,
}}
>
<View className="overflow-hidden rounded-[22px] border border-border bg-card px-4 py-1">
{sheetMenuItems.map(({ item, disabledReason }, index) => (
<View key={`${item.id}-${item.label}`}>
{index > 0 ? (
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
) : null}
<SheetListRow
icon={menuItemIconName(item.icon)}
title={item.label}
subtitle={disabledReason}
disabled={item.disabled}
onPress={() => void onPressMenuItem(item)}
/>
</View>
))}
{(gitStatus.data?.behindCount ?? 0) > 0 ? (
<>
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
<SheetListRow
icon="arrow.down.circle"
title="Pull latest"
subtitle="Sync this branch with upstream"
disabled={busy || !isRepo}
onPress={() => void gitActions.onPullSelectedThreadBranch()}
/>
</>
) : null}
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
<SheetListRow
icon="point.topleft.down.curvedto.point.bottomright.up"
title="Branches & worktrees"
subtitle="Switch branch, create branch, or move to a worktree"
disabled={busy || !isRepo}
onPress={() =>
router.push({
pathname: "/threads/[environmentId]/[threadId]/git/branches",
params: { environmentId, threadId },
})
}
/>
</View>
{currentWorktreePath ? <MetaCard label="Worktree" value={currentWorktreePath} /> : null}
{gitOperationLabel ? (
<View className="self-start">
<StatusPill
label={gitOperationLabel}
pillClassName="bg-neutral-900/8"
textClassName="text-neutral-700"
size="compact"
/>
</View>
) : null}
</ScrollView>
</View>
);
}
@@ -0,0 +1,152 @@
import { SymbolView } from "expo-symbols";
import type { ComponentProps } from "react";
import { Pressable, View } from "react-native";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text } from "../../../components/AppText";
/* ─── Shared sheet components ──────────────────────────────────────── */
export function SheetActionButton(props: {
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly label: string;
readonly disabled?: boolean;
readonly tone?: "primary" | "secondary" | "danger";
readonly onPress: () => void;
}) {
const primaryBg = useThemeColor("--color-primary");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerBg = useThemeColor("--color-danger");
const dangerBorder = useThemeColor("--color-danger-border");
const dangerFg = useThemeColor("--color-danger-foreground");
const secondaryBg = useThemeColor("--color-secondary");
const secondaryBorder = useThemeColor("--color-secondary-border");
const secondaryFg = useThemeColor("--color-secondary-foreground");
const tone = props.tone ?? "secondary";
const colors =
tone === "primary"
? {
backgroundColor: primaryBg,
borderColor: "transparent",
textColor: primaryFg,
}
: tone === "danger"
? {
backgroundColor: dangerBg,
borderColor: dangerBorder,
textColor: dangerFg,
}
: {
backgroundColor: secondaryBg,
borderColor: secondaryBorder,
textColor: secondaryFg,
};
return (
<Pressable
className="min-h-[48px] flex-1 flex-row items-center justify-center gap-2 rounded-[18px] px-4 py-3"
disabled={props.disabled}
style={{
backgroundColor: colors.backgroundColor,
borderWidth: tone === "primary" ? 0 : 1,
borderColor: colors.borderColor,
opacity: props.disabled ? 0.45 : 1,
}}
onPress={props.onPress}
>
<SymbolView name={props.icon} size={16} tintColor={colors.textColor} type="monochrome" />
<Text
className="text-[12px] font-t3-bold uppercase"
style={{ color: colors.textColor, letterSpacing: 0.9 }}
>
{props.label}
</Text>
</Pressable>
);
}
export function MetaCard(props: { readonly label: string; readonly value: string }) {
return (
<View className="rounded-[18px] border border-border bg-card px-4 py-3">
<Text
className="text-foreground-muted text-[11px] font-t3-bold uppercase"
style={{ letterSpacing: 0.9 }}
>
{props.label}
</Text>
<Text selectable className="text-foreground text-[13px] font-medium" numberOfLines={1}>
{props.value}
</Text>
</View>
);
}
export function SheetListRow(props: {
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly title: string;
readonly subtitle?: string | null;
readonly disabled?: boolean;
readonly onPress: () => void;
}) {
const iconColor = useThemeColor("--color-icon");
const iconSubtleColor = useThemeColor("--color-icon-subtle");
return (
<Pressable
className="flex-row items-center gap-3 px-1 py-3"
disabled={props.disabled}
style={{ opacity: props.disabled ? 0.45 : 1 }}
onPress={props.onPress}
>
<View className="bg-subtle h-9 w-9 items-center justify-center rounded-full">
<SymbolView name={props.icon} size={16} tintColor={iconColor} type="monochrome" />
</View>
<View className="flex-1 gap-0.5">
<Text className="text-foreground text-[16px] font-t3-bold">{props.title}</Text>
{props.subtitle ? (
<Text className="text-foreground-muted text-[12px] leading-[17px]">{props.subtitle}</Text>
) : null}
</View>
<SymbolView name="chevron.right" size={13} tintColor={iconSubtleColor} type="monochrome" />
</Pressable>
);
}
/* ─── Shared utilities ──────────────────────────────────────────────── */
export function menuItemIconName(
icon: "commit" | "push" | "pr",
): ComponentProps<typeof SymbolView>["name"] {
if (icon === "commit") return "checkmark.circle";
if (icon === "push") return "arrow.up.circle";
return "arrow.up.right.circle";
}
export function statusSummary(gitStatus: { readonly isRepo?: boolean; readonly hasWorkingTreeChanges?: boolean; readonly workingTree?: { readonly files: readonly { readonly path: string }[] }; readonly aheadCount?: number; readonly behindCount?: number; readonly pr?: { readonly state?: string; readonly number?: number } | null } | null): string {
if (!gitStatus) {
return "Loading branch status\u2026";
}
if (!gitStatus.isRepo) {
return "Not a git repository";
}
const parts: string[] = [];
if (gitStatus.hasWorkingTreeChanges) {
const fileCount = gitStatus.workingTree?.files.length ?? 0;
parts.push(`${fileCount} file${fileCount === 1 ? "" : "s"} changed`);
} else {
parts.push("Clean");
}
if ((gitStatus.aheadCount ?? 0) > 0) {
parts.push(`${gitStatus.aheadCount} ahead`);
}
if ((gitStatus.behindCount ?? 0) > 0) {
parts.push(`${gitStatus.behindCount} behind`);
}
if (gitStatus.pr?.state === "open") {
parts.push(`PR #${gitStatus.pr.number} open`);
}
return parts.join(" \u00b7 ");
}
@@ -15,7 +15,8 @@ import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import type { ScopedMobileProject } from "../../lib/scopedEntities";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { useProjectActions } from "../../state/use-project-actions";
import { useRemoteEnvironmentStore } from "../../state/remote-environment-store";
import { gitBranchManager, useGitBranches } from "../../state/use-git-branches";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
export type { ModelOption, ProviderGroup };
@@ -110,7 +111,9 @@ const NewTaskFlowContext = React.createContext<NewTaskFlowContextValue | null>(n
export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const { projects, serverConfigByEnvironmentId, threads } = useRemoteCatalog();
const { onListProjectBranches } = useProjectActions();
const setPendingConnectionError = useRemoteEnvironmentStore(
(state) => state.setPendingConnectionError,
);
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
@@ -142,8 +145,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const [attachments, setAttachments] = useState<ReadonlyArray<DraftComposerImageAttachment>>([]);
const [submitting, setSubmitting] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const [branchesLoading, setBranchesLoading] = useState(false);
const [availableBranches, setAvailableBranches] = useState<ReadonlyArray<GitBranch>>([]);
const [runtimeMode, setRuntimeMode] = useState<RuntimeMode>(DEFAULT_RUNTIME_MODE);
const [interactionMode, setInteractionMode] = useState<ProviderInteractionMode>(
DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -190,8 +191,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
clearAttachments();
setSubmitting(false);
setBranchQuery("");
setBranchesLoading(false);
setAvailableBranches([]);
setRuntimeMode(DEFAULT_RUNTIME_MODE);
setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE);
setEffort("high");
@@ -262,6 +261,20 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
) ?? null;
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
const branchTarget = useMemo(
() => ({
environmentId: selectedProject?.environmentId ?? null,
cwd: selectedProject?.workspaceRoot ?? null,
query: null,
}),
[selectedProject?.environmentId, selectedProject?.workspaceRoot],
);
const branchState = useGitBranches(branchTarget);
const branchesLoading = branchState.isPending;
const availableBranches = useMemo(
() => (branchState.data?.branches ?? []).filter((branch) => !branch.isRemote),
[branchState.data?.branches],
);
const filteredBranches = useMemo(() => {
const query = branchQuery.trim().toLowerCase();
@@ -299,10 +312,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
return;
}
setBranchesLoading(true);
try {
const branches = await onListProjectBranches(selectedProject);
setAvailableBranches(branches);
const result = await gitBranchManager.load({
environmentId: selectedProject.environmentId,
cwd: selectedProject.workspaceRoot,
query: null,
});
setPendingConnectionError(null);
const branches = (result?.branches ?? []).filter((branch) => !branch.isRemote);
if (workspaceMode === "worktree" && !selectedBranchName) {
const preferredBranch =
@@ -313,10 +330,10 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setSelectedBranchName(preferredBranch);
}
}
} finally {
setBranchesLoading(false);
} catch {
setPendingConnectionError("Failed to load branches.");
}
}, [onListProjectBranches, selectedBranchName, selectedProject, workspaceMode]);
}, [selectedBranchName, selectedProject, setPendingConnectionError, workspaceMode]);
const value = useMemo<NewTaskFlowContextValue>(
() => ({
-42
View File
@@ -1,42 +0,0 @@
export function sortCopy<T>(
values: ReadonlyArray<T>,
compareFn: (left: T, right: T) => number,
): T[] {
const next = [...values];
for (let index = 1; index < next.length; index += 1) {
const current = next[index];
if (current === undefined) {
continue;
}
let insertionIndex = index - 1;
while (insertionIndex >= 0) {
const candidate = next[insertionIndex];
if (candidate !== undefined && compareFn(candidate, current) <= 0) {
break;
}
next[insertionIndex + 1] = candidate;
insertionIndex -= 1;
}
next[insertionIndex + 1] = current;
}
return next;
}
export function reverseCopy<T>(values: ReadonlyArray<T>): T[] {
const reversed = Array.from({ length: values.length }) as T[];
for (let index = 0; index < values.length; index += 1) {
const value = values[index];
if (value === undefined) {
continue;
}
reversed[values.length - 1 - index] = value;
}
return reversed;
}
-3
View File
@@ -1,3 +0,0 @@
export function cx(...parts: Array<string | false | null | undefined>): string {
return parts.filter(Boolean).join(" ");
}
-6
View File
@@ -1,6 +0,0 @@
import * as Effect from "effect/Effect";
import * as Random from "effect/Random";
export function newClientId(prefix: string): string {
return `${prefix}-${Effect.runSync(Random.nextUUIDv4)}`;
}
+6
View File
@@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
+4 -5
View File
@@ -3,8 +3,7 @@ import {
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
type UploadChatImageAttachment,
} from "@t3tools/contracts";
import { newClientId } from "./clientId";
import { uuidv4 } from "./uuid";
export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
readonly id: string;
@@ -101,7 +100,7 @@ export async function pickComposerImages(input: { readonly existingCount: number
}
nextImages.push({
id: newClientId("attachment"),
id: uuidv4(),
type: "image",
name: asset.fileName ?? "image",
mimeType,
@@ -165,7 +164,7 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
return {
images: [
{
id: newClientId("attachment"),
id: uuidv4(),
type: "image",
name: "pasted-image.png",
mimeType: "image/png",
@@ -233,7 +232,7 @@ export async function convertPastedImagesToAttachments(input: {
}
const mimeType = mimeTypeFromUri(uri);
results.push({
id: newClientId("attachment"),
id: uuidv4(),
type: "image",
name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`,
mimeType,
+37
View File
@@ -0,0 +1,37 @@
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
export type MobileLayoutVariant = "compact" | "split";
export interface MobileLayout {
readonly variant: MobileLayoutVariant;
readonly usesSplitView: boolean;
readonly listPaneWidth: number | null;
readonly shellPadding: number;
}
export function deriveMobileLayout(input: {
readonly width: number;
readonly height: number;
}): MobileLayout {
const { width, height } = input;
const shortestEdge = Math.min(width, height);
const wideEnoughForSplit = width >= 900 || (width >= 700 && shortestEdge >= 700);
if (!wideEnoughForSplit) {
return {
variant: "compact",
usesSplitView: false,
listPaneWidth: null,
shellPadding: 0,
};
}
return {
variant: "split",
usesSplitView: true,
listPaneWidth: clamp(Math.round(width * 0.34), 320, 420),
shellPadding: width >= 1180 ? 20 : 14,
};
}
+11 -74
View File
@@ -2,9 +2,7 @@ import * as SecureStore from "expo-secure-store";
import type { SavedRemoteConnection } from "./connection";
const CONNECTIONS_KEY = "t3code:connections";
type SavedRemoteConnectionMetadata = Omit<SavedRemoteConnection, "bearerToken">;
const CONNECTIONS_KEY = "t3code.connections";
async function readStorageItem(key: string): Promise<string | null> {
return await SecureStore.getItemAsync(key);
@@ -14,31 +12,7 @@ async function writeStorageItem(key: string, value: string): Promise<void> {
await SecureStore.setItemAsync(key, value);
}
async function removeStorageItem(key: string): Promise<void> {
await SecureStore.deleteItemAsync(key);
}
function connectionTokenKey(environmentId: string): string {
return `t3code:bearer-token:${environmentId}`;
}
async function loadSecureToken(environmentId: string): Promise<string> {
return (await readStorageItem(connectionTokenKey(environmentId))) ?? "";
}
async function storeSecureToken(environmentId: string, token: string): Promise<void> {
const tokenKey = connectionTokenKey(environmentId);
if (token.trim().length === 0) {
await removeStorageItem(tokenKey);
return;
}
await writeStorageItem(tokenKey, token);
}
async function loadSavedConnectionMetadata(): Promise<
ReadonlyArray<SavedRemoteConnectionMetadata>
> {
export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteConnection>> {
const raw = (await readStorageItem(CONNECTIONS_KEY)) ?? "";
if (!raw.trim()) {
return [];
@@ -46,64 +20,27 @@ async function loadSavedConnectionMetadata(): Promise<
try {
const parsed = JSON.parse(raw) as {
readonly connections?: ReadonlyArray<SavedRemoteConnectionMetadata>;
readonly connections?: ReadonlyArray<SavedRemoteConnection>;
};
return parsed.connections ?? [];
return (parsed.connections ?? []).filter((c) => c.environmentId && c.bearerToken?.trim());
} catch {
return [];
}
}
async function saveSavedConnectionMetadata(
connections: ReadonlyArray<SavedRemoteConnectionMetadata>,
): Promise<void> {
await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections }));
}
export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteConnection>> {
const metadata = await loadSavedConnectionMetadata();
const resolved = await Promise.all(
metadata.map(async (connection): Promise<SavedRemoteConnection | null> => {
const bearerToken = (await loadSecureToken(connection.environmentId)).trim();
if (!bearerToken) {
return null;
}
return Object.assign({}, connection, {
bearerToken,
});
}),
);
return resolved.filter((connection): connection is SavedRemoteConnection => connection !== null);
}
export async function saveConnection(connection: SavedRemoteConnection): Promise<void> {
const current = await loadSavedConnectionMetadata();
const nextConnection: SavedRemoteConnectionMetadata = {
environmentId: connection.environmentId,
environmentLabel: connection.environmentLabel,
pairingUrl: connection.pairingUrl.trim(),
displayUrl: connection.displayUrl.trim(),
httpBaseUrl: connection.httpBaseUrl.trim(),
wsBaseUrl: connection.wsBaseUrl.trim(),
};
const current = await loadSavedConnections();
const next = current.some((entry) => entry.environmentId === connection.environmentId)
? current.map((entry) =>
entry.environmentId === connection.environmentId ? nextConnection : entry,
entry.environmentId === connection.environmentId ? connection : entry,
)
: [...current, nextConnection];
: [...current, connection];
await Promise.all([
saveSavedConnectionMetadata(next),
storeSecureToken(connection.environmentId, connection.bearerToken.trim()),
]);
await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
}
export async function clearSavedConnection(environmentId: string): Promise<void> {
const current = await loadSavedConnectionMetadata();
await Promise.all([
saveSavedConnectionMetadata(current.filter((entry) => entry.environmentId !== environmentId)),
storeSecureToken(environmentId, ""),
]);
const current = await loadSavedConnections();
const next = current.filter((entry) => entry.environmentId !== environmentId);
await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
}
-187
View File
@@ -1,187 +0,0 @@
import { useColorScheme } from "react-native";
/**
* Centralized app color palette that adapts to light/dark system appearance.
* Modeled after the `makeConnectionSheetPalette` pattern used in connection sheets.
*
* Usage:
* const isDarkMode = useColorScheme() === "dark";
* const palette = makeAppPalette(isDarkMode);
*/
export function makeAppPalette(isDarkMode: boolean) {
if (isDarkMode) {
return {
// Page backgrounds — matches web's neutral-950 dark palette
screenBackground: "#0a0a0a",
sheetBackground: "rgba(14,14,14,0.98)",
// Card / surface
card: "#171717",
cardAlt: "#1c1c1c",
cardTranslucent: "rgba(17,17,17,0.94)",
// Text — neutral scale (matches web's neutral-100 / neutral-500)
text: "#f5f5f5",
textSecondary: "#a3a3a3",
textMuted: "#737373",
textTertiary: "#525252",
// Borders & separators — matches web's --border (white/6%) / --input (white/8%)
border: "rgba(255,255,255,0.06)",
borderSubtle: "rgba(255,255,255,0.04)",
separator: "rgba(255,255,255,0.03)",
// Subtle backgrounds (badges, pills, overlays)
subtleBg: "rgba(255,255,255,0.04)",
subtleBgStrong: "rgba(255,255,255,0.08)",
// Primary action (inverted in dark mode)
primaryButton: "#f5f5f5",
primaryButtonText: "#0a0a0a",
primaryButtonShadow: "rgba(0,0,0,0.22)",
// Secondary action
secondaryButton: "rgba(255,255,255,0.04)",
secondaryButtonText: "#f5f5f5",
secondaryButtonBorder: "rgba(255,255,255,0.06)",
// Danger
dangerButton: "rgba(239,68,68,0.14)",
dangerBorder: "rgba(248,113,113,0.18)",
dangerText: "#fca5a5",
// Inputs
inputBackground: "#141414",
inputBorder: "rgba(255,255,255,0.08)",
placeholder: "#737373",
// Icons
icon: "#f5f5f5",
iconMuted: "#a3a3a3",
iconSubtle: "#737373",
// Header / glass chrome — fully opaque to prevent content bleed-through
headerBackground: "rgba(10,10,10,0.97)",
headerBorder: "rgba(255,255,255,0.06)",
// StatusBar
statusBarBackground: "#0a0a0a",
statusBarStyle: "light-content" as const,
// Markdown
markdownBody: "#e5e5e5",
markdownStrong: "#f5f5f5",
markdownLink: "#60a5fa",
markdownBlockquoteBorder: "rgba(255,255,255,0.08)",
markdownCodeBg: "rgba(255,255,255,0.06)",
markdownCodeText: "#e5e5e5",
markdownUserCodeBg: "rgba(255,255,255,0.08)",
markdownUserCodeText: "#e5e5e5",
// Drawer / modal backdrop
backdrop: "rgba(0,0,0,0.48)",
drawerBackground: "rgba(14,14,14,0.99)",
drawerShadow: "rgba(0,0,0,0.32)",
// Dot separator
dotSeparator: "rgba(255,255,255,0.20)",
// SVG / wordmark fill
wordmarkFill: "#f5f5f5",
// Chevron / disclosure
chevronColor: "rgba(255,255,255,0.20)",
} as const;
}
return {
// Page backgrounds — matches web's white/neutral palette
screenBackground: "#ffffff",
sheetBackground: "rgba(255,255,255,0.98)",
// Card / surface
card: "#ffffff",
cardAlt: "#f5f5f5",
cardTranslucent: "rgba(255,255,255,0.94)",
// Text — neutral scale (matches web's neutral-800 / neutral-500)
text: "#262626",
textSecondary: "#525252",
textMuted: "#737373",
textTertiary: "#a3a3a3",
// Borders & separators — matches web's --border / --input
border: "rgba(0,0,0,0.08)",
borderSubtle: "rgba(0,0,0,0.06)",
separator: "rgba(0,0,0,0.04)",
// Subtle backgrounds (badges, pills, overlays)
subtleBg: "rgba(0,0,0,0.04)",
subtleBgStrong: "rgba(0,0,0,0.08)",
// Primary action
primaryButton: "#262626",
primaryButtonText: "#ffffff",
primaryButtonShadow: "rgba(0,0,0,0.18)",
// Secondary action
secondaryButton: "#ffffff",
secondaryButtonText: "#262626",
secondaryButtonBorder: "rgba(0,0,0,0.08)",
// Danger
dangerButton: "#fef2f2",
dangerBorder: "rgba(239,68,68,0.12)",
dangerText: "#dc2626",
// Inputs
inputBackground: "#ffffff",
inputBorder: "rgba(0,0,0,0.10)",
placeholder: "#a3a3a3",
// Icons
icon: "#262626",
iconMuted: "#525252",
iconSubtle: "#a3a3a3",
// Header / glass chrome — fully opaque to prevent content bleed-through
headerBackground: "rgba(255,255,255,0.97)",
headerBorder: "rgba(0,0,0,0.06)",
// StatusBar
statusBarBackground: "#ffffff",
statusBarStyle: "dark-content" as const,
// Markdown
markdownBody: "#262626",
markdownStrong: "#171717",
markdownLink: "#2563eb",
markdownBlockquoteBorder: "rgba(0,0,0,0.08)",
markdownCodeBg: "rgba(0,0,0,0.04)",
markdownCodeText: "#262626",
markdownUserCodeBg: "rgba(255,255,255,0.55)",
markdownUserCodeText: "#262626",
// Drawer / modal backdrop
backdrop: "rgba(0,0,0,0.22)",
drawerBackground: "rgba(255,255,255,0.99)",
drawerShadow: "rgba(0,0,0,0.12)",
// Dot separator
dotSeparator: "rgba(0,0,0,0.20)",
// SVG / wordmark fill
wordmarkFill: "#262626",
// Chevron / disclosure
chevronColor: "rgba(0,0,0,0.20)",
} as const;
}
export type AppPalette = ReturnType<typeof makeAppPalette>;
/** Convenience hook that returns the palette for the current color scheme. */
export function useAppPalette(): AppPalette {
const isDarkMode = useColorScheme() === "dark";
return makeAppPalette(isDarkMode);
}
+7 -6
View File
@@ -1,5 +1,7 @@
import type {
ApprovalRequestId,
CommandId,
MessageId,
OrchestrationThread,
OrchestrationThreadActivity,
ThreadId,
@@ -29,11 +31,10 @@ export interface PendingUserInputDraftAnswer {
}
export interface QueuedThreadMessage {
readonly id: string;
readonly environmentId: string;
readonly threadId: ThreadId;
readonly messageId: string;
readonly commandId: string;
readonly messageId: MessageId;
readonly commandId: CommandId;
readonly text: string;
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly createdAt: string;
@@ -380,7 +381,7 @@ export function buildPendingUserInputAnswers(
export function buildThreadFeed(
thread: OrchestrationThread,
queuedMessages: ReadonlyArray<QueuedThreadMessage>,
dispatchingQueuedMessageId: string | null,
dispatchingQueuedMessageId: MessageId | null,
options?: {
readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
},
@@ -398,10 +399,10 @@ export function buildThreadFeed(
})),
...queuedMessages.map<RawThreadFeedEntry>((queuedMessage) => ({
type: "queued-message",
id: queuedMessage.id,
id: queuedMessage.messageId,
createdAt: queuedMessage.createdAt,
queuedMessage,
sending: queuedMessage.id === dispatchingQueuedMessageId,
sending: queuedMessage.messageId === dispatchingQueuedMessageId,
})),
...thread.activities
.filter((activity) => {
+12
View File
@@ -0,0 +1,12 @@
import type { ColorValue } from "react-native";
import { useCSSVariable } from "uniwind";
/**
* Typed wrapper around `useCSSVariable` that returns a `ColorValue` for use
* in React Native style props (backgroundColor, tintColor, etc.).
*
* Usage: `const color = useThemeColor("--color-icon");`
*/
export function useThemeColor(variable: `--color-${string}`): ColorValue {
return useCSSVariable(variable) as string as ColorValue;
}
+4
View File
@@ -0,0 +1,4 @@
import * as Effect from "effect/Effect";
import * as Random from "effect/Random";
export const uuidv4 = () => Effect.runSync(Random.nextUUIDv4);
+9
View File
@@ -0,0 +1,9 @@
import { RegistryContext } from "@effect/atom-react";
import { AtomRegistry } from "effect/unstable/reactivity";
import type { ReactNode } from "react";
export const appAtomRegistry = AtomRegistry.make();
export function AppAtomRegistryProvider({ children }: { readonly children: ReactNode }) {
return <RegistryContext.Provider value={appAtomRegistry}>{children}</RegistryContext.Provider>;
}
@@ -1,4 +1,4 @@
import type { ThreadId } from "@t3tools/contracts";
import type { MessageId, ThreadId } from "@t3tools/contracts";
import { useStore } from "zustand";
import { createStore } from "zustand/vanilla";
@@ -10,7 +10,7 @@ interface ThreadComposerStoreState {
readonly nowTick: number;
readonly draftMessageByThreadKey: Record<string, string>;
readonly draftAttachmentsByThreadKey: Record<string, ReadonlyArray<DraftComposerImageAttachment>>;
readonly dispatchingQueuedMessageId: string | null;
readonly dispatchingQueuedMessageId: MessageId | null;
readonly queuedMessagesByThreadKey: Record<string, ReadonlyArray<QueuedThreadMessage>>;
readonly setNowTick: (tick: number) => void;
@@ -22,13 +22,13 @@ interface ThreadComposerStoreState {
readonly appendDraftMessage: (threadKey: string, value: string) => void;
readonly clearDraft: (threadKey: string) => void;
readonly removeDraftImage: (threadKey: string, imageId: string) => void;
readonly beginDispatchingQueuedMessage: (queuedMessageId: string) => void;
readonly finishDispatchingQueuedMessage: (queuedMessageId: string) => void;
readonly beginDispatchingQueuedMessage: (queuedMessageId: MessageId) => void;
readonly finishDispatchingQueuedMessage: (queuedMessageId: MessageId) => void;
readonly enqueueQueuedMessage: (message: QueuedThreadMessage) => void;
readonly removeQueuedMessage: (
environmentId: string,
threadId: ThreadId,
queuedMessageId: string,
queuedMessageId: MessageId,
) => void;
}
@@ -107,7 +107,7 @@ export const threadComposerStore = createStore<ThreadComposerStoreState>()((set)
if (!existing) {
return state;
}
const nextQueue = existing.filter((entry) => entry.id !== queuedMessageId);
const nextQueue = existing.filter((entry) => entry.messageId !== queuedMessageId);
const next = { ...state.queuedMessagesByThreadKey };
if (nextQueue.length === 0) {
delete next[threadKey];
-45
View File
@@ -1,45 +0,0 @@
import type { GitStatusResult } from "@t3tools/contracts";
import { useStore } from "zustand";
import { createStore } from "zustand/vanilla";
interface ThreadGitStoreState {
readonly gitStatusByThreadKey: Record<string, GitStatusResult | null>;
readonly gitOperationLabelByThreadKey: Record<string, string | null>;
readonly setThreadGitStatus: (threadKey: string, status: GitStatusResult | null) => void;
readonly setThreadGitOperationLabel: (threadKey: string, label: string | null) => void;
readonly clearThreadGitState: (threadKey: string) => void;
}
export const threadGitStore = createStore<ThreadGitStoreState>()((set) => ({
gitStatusByThreadKey: {},
gitOperationLabelByThreadKey: {},
setThreadGitStatus: (threadKey, status) =>
set((state) => ({
gitStatusByThreadKey: {
...state.gitStatusByThreadKey,
[threadKey]: status,
},
})),
setThreadGitOperationLabel: (threadKey, label) =>
set((state) => ({
gitOperationLabelByThreadKey: {
...state.gitOperationLabelByThreadKey,
[threadKey]: label,
},
})),
clearThreadGitState: (threadKey) =>
set((state) => {
const nextStatus = { ...state.gitStatusByThreadKey };
const nextLabel = { ...state.gitOperationLabelByThreadKey };
delete nextStatus[threadKey];
delete nextLabel[threadKey];
return {
gitStatusByThreadKey: nextStatus,
gitOperationLabelByThreadKey: nextLabel,
};
}),
}));
export function useThreadGitStore<T>(selector: (state: ThreadGitStoreState) => T): T {
return useStore(threadGitStore, selector);
}
@@ -0,0 +1,31 @@
import { useAtomValue } from "@effect/atom-react";
import {
type GitActionState,
type GitActionTarget,
EMPTY_GIT_ACTION_ATOM,
EMPTY_GIT_ACTION_STATE,
createGitActionManager,
getGitActionTargetKey,
gitActionStateAtom,
} from "@t3tools/client-runtime";
import { uuidv4 } from "../lib/uuid";
import { appAtomRegistry } from "./atomRegistry";
import { getEnvironmentClient } from "./use-remote-environment-registry";
export const gitActionManager = createGitActionManager({
getRegistry: () => appAtomRegistry,
getClient: (environmentId) => {
const client = getEnvironmentClient(environmentId);
return client ? client.git : null;
},
getActionId: uuidv4,
});
export function useGitActionState(target: GitActionTarget): GitActionState {
const targetKey = getGitActionTargetKey(target);
const state = useAtomValue(
targetKey !== null ? gitActionStateAtom(targetKey) : EMPTY_GIT_ACTION_ATOM,
);
return targetKey === null ? EMPTY_GIT_ACTION_STATE : state;
}
+29
View File
@@ -0,0 +1,29 @@
import { useAtomValue } from "@effect/atom-react";
import {
type GitBranchState,
type GitBranchTarget,
EMPTY_GIT_BRANCH_ATOM,
EMPTY_GIT_BRANCH_STATE,
createGitBranchManager,
getGitBranchTargetKey,
gitBranchStateAtom,
} from "@t3tools/client-runtime";
import { appAtomRegistry } from "./atomRegistry";
import { getEnvironmentClient } from "./use-remote-environment-registry";
export const gitBranchManager = createGitBranchManager({
getRegistry: () => appAtomRegistry,
getClient: (environmentId) => {
const client = getEnvironmentClient(environmentId);
return client ? client.git : null;
},
});
export function useGitBranches(target: GitBranchTarget): GitBranchState {
const targetKey = getGitBranchTargetKey(target);
const state = useAtomValue(
targetKey !== null ? gitBranchStateAtom(targetKey) : EMPTY_GIT_BRANCH_ATOM,
);
return targetKey === null ? EMPTY_GIT_BRANCH_STATE : state;
}
+62
View File
@@ -0,0 +1,62 @@
import { useAtomValue } from "@effect/atom-react";
import {
type GitStatusState,
type GitStatusTarget,
EMPTY_GIT_STATUS_ATOM,
EMPTY_GIT_STATUS_STATE,
createGitStatusManager,
getGitStatusTargetKey,
gitStatusStateAtom,
} from "@t3tools/client-runtime";
import { useEffect } from "react";
import { appAtomRegistry } from "./atomRegistry";
import {
getEnvironmentClient,
subscribeEnvironmentConnections,
} from "./use-remote-environment-registry";
/**
* Singleton git status manager for the mobile app.
*
* Uses ref-counted `onStatus` subscriptions (one per unique cwd)
* rather than one-shot `refreshStatus` RPCs. Multiple threads
* sharing the same cwd (i.e. same project, no worktree) share
* a single WS subscription.
*
* `subscribeClientChanges` ensures subscriptions are established
* even when the WS connection isn't ready at mount time, and
* re-established on reconnection.
*/
export const gitStatusManager = createGitStatusManager({
getRegistry: () => appAtomRegistry,
getClient: (environmentId) => {
const client = getEnvironmentClient(environmentId);
return client ? client.git : null;
},
getClientIdentity: (environmentId) => {
return getEnvironmentClient(environmentId) ? environmentId : null;
},
subscribeClientChanges: subscribeEnvironmentConnections,
});
/**
* Subscribe to live git status for a target (environmentId + cwd).
*
* Mirrors the web's `useGitStatus` hook. Automatically subscribes
* on mount, ref-counts shared cwds, and unsubscribes on unmount.
* Returns reactive `GitStatusState` via Effect atoms.
*/
export function useGitStatus(target: GitStatusTarget): GitStatusState {
const targetKey = getGitStatusTargetKey(target);
useEffect(
() => gitStatusManager.watch({ environmentId: target.environmentId, cwd: target.cwd }),
[target.environmentId, target.cwd],
);
const state = useAtomValue(
targetKey !== null ? gitStatusStateAtom(targetKey) : EMPTY_GIT_STATUS_ATOM,
);
return targetKey === null ? EMPTY_GIT_STATUS_STATE : state;
}
+19 -12
View File
@@ -14,11 +14,12 @@ import {
import { sanitizeFeatureBranchName } from "@t3tools/shared/git";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { newClientId } from "../lib/clientId";
import { uuidv4 } from "../lib/uuid";
import type { ScopedMobileProject } from "../lib/scopedEntities";
import { buildTemporaryWorktreeBranchName } from "../lib/worktrees";
import { deriveThreadTitleFromPrompt } from "./remote-runtime-types";
import { useRemoteEnvironmentStore } from "./remote-environment-store";
import { gitBranchManager } from "./use-git-branches";
import { useRemoteCatalog } from "./use-remote-catalog";
import { getEnvironmentClient, useRemoteEnvironmentState } from "./use-remote-environment-registry";
import { useThreadSelectionStore } from "./thread-selection-store";
@@ -90,7 +91,7 @@ export function useProjectActions() {
return null;
}
const threadId = ThreadId.makeUnsafe(newClientId("thread"));
const threadId = ThreadId.makeUnsafe(uuidv4());
const createdAt = new Date().toISOString();
const initialMessageText = input.initialMessageText.trim();
const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
@@ -102,10 +103,10 @@ export function useProjectActions() {
await client.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe(newClientId("command")),
commandId: CommandId.makeUnsafe(uuidv4()),
threadId,
message: {
messageId: MessageId.makeUnsafe(newClientId("message")),
messageId: MessageId.makeUnsafe(uuidv4()),
role: "user",
text: initialMessageText,
attachments: input.initialAttachments,
@@ -137,7 +138,7 @@ export function useProjectActions() {
} else {
await client.orchestration.dispatchCommand({
type: "thread.create",
commandId: CommandId.makeUnsafe(newClientId("command")),
commandId: CommandId.makeUnsafe(uuidv4()),
threadId,
projectId: input.project.id,
title: nextTitle,
@@ -152,10 +153,10 @@ export function useProjectActions() {
if (initialMessageText.length > 0 || input.initialAttachments.length > 0) {
await client.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe(newClientId("command")),
commandId: CommandId.makeUnsafe(uuidv4()),
threadId,
message: {
messageId: MessageId.makeUnsafe(newClientId("message")),
messageId: MessageId.makeUnsafe(uuidv4()),
role: "user",
text: initialMessageText,
attachments: input.initialAttachments,
@@ -217,11 +218,12 @@ export function useProjectActions() {
}
try {
const result = await client.git.listBranches({
cwd: project.workspaceRoot,
limit: 100,
});
return result.branches.filter((branch) => !branch.isRemote);
const result = await gitBranchManager.load(
{ environmentId: project.environmentId, cwd: project.workspaceRoot, query: null },
client.git,
{ limit: 100 },
);
return (result?.branches ?? []).filter((branch) => !branch.isRemote);
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to load branches.",
@@ -255,6 +257,11 @@ export function useProjectActions() {
newBranch: sanitizeFeatureBranchName(nextWorktree.newBranch),
path: null,
});
gitBranchManager.invalidate({
environmentId: project.environmentId,
cwd: project.workspaceRoot,
query: null,
});
return {
branch: result.worktree.branch,
worktreePath: result.worktree.path,
+19 -11
View File
@@ -1,8 +1,8 @@
import { useMemo } from "react";
import type { ServerConfig as T3ServerConfig } from "@t3tools/contracts";
import { sortCopy } from "../lib/arrayCompat";
import * as Order from "effect/Order";
import * as Arr from "effect/Array";
import type { ScopedMobileProject, ScopedMobileThread } from "../lib/scopedEntities";
import {
deriveOverallConnectionState,
@@ -13,13 +13,26 @@ import {
useRemoteEnvironmentState,
} from "./use-remote-environment-registry";
const projectsSortOrder = Order.make<ScopedMobileProject>(
(left, right) =>
(left.title.localeCompare(right.title) as -1 | 0 | 1) ||
(left.environmentLabel.localeCompare(right.environmentLabel) as -1 | 0 | 1),
);
const threadsSortOrder = Order.make<ScopedMobileThread>(
(left, right) =>
((new Date(right.updatedAt ?? right.createdAt).getTime() -
new Date(left.updatedAt ?? left.createdAt).getTime()) as -1 | 0 | 1) ||
(left.environmentLabel.localeCompare(right.environmentLabel) as -1 | 0 | 1),
);
export function useRemoteCatalog() {
const { connectedEnvironments, connectionState } = useRemoteConnectionStatus();
const { environmentStateById, savedConnectionsById } = useRemoteEnvironmentState();
const projects = useMemo<ReadonlyArray<ScopedMobileProject>>(
() =>
sortCopy(
Arr.sort(
Object.values(savedConnectionsById).flatMap((connection) =>
(environmentStateById[connection.environmentId]?.snapshot?.projects ?? [])
.filter((project) => project.deletedAt === null)
@@ -30,16 +43,14 @@ export function useRemoteCatalog() {
}),
),
),
(left, right) =>
left.title.localeCompare(right.title) ||
left.environmentLabel.localeCompare(right.environmentLabel),
projectsSortOrder,
),
[environmentStateById, savedConnectionsById],
);
const threads = useMemo<ReadonlyArray<ScopedMobileThread>>(
() =>
sortCopy(
Arr.sort(
Object.values(savedConnectionsById).flatMap((connection) =>
(environmentStateById[connection.environmentId]?.snapshot?.threads ?? [])
.filter((thread) => thread.deletedAt === null)
@@ -50,10 +61,7 @@ export function useRemoteCatalog() {
}),
),
),
(left, right) =>
new Date(right.updatedAt ?? right.createdAt).getTime() -
new Date(left.updatedAt ?? left.createdAt).getTime() ||
right.environmentLabel.localeCompare(left.environmentLabel),
threadsSortOrder,
),
[environmentStateById, savedConnectionsById],
);
@@ -10,8 +10,8 @@ import {
import { EnvironmentId, type OrchestrationReadModel } from "@t3tools/contracts";
import { resolveRemoteWebSocketConnectionUrl } from "@t3tools/shared/remote";
import { useShallow } from "zustand/react/shallow";
import { sortCopy } from "../lib/arrayCompat";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { type SavedRemoteConnection, bootstrapRemoteConnection } from "../lib/connection";
import { applyRealtimeEvent, requiresSnapshotRefresh } from "../lib/orchestration";
import { clearSavedConnection, loadSavedConnections, saveConnection } from "../lib/storage";
@@ -25,6 +25,22 @@ import { remoteEnvironmentStore, useRemoteEnvironmentStore } from "./remote-envi
import { useThreadSelectionStore } from "./thread-selection-store";
const environmentSessions = new Map<string, EnvironmentSession>();
const environmentConnectionListeners = new Set<() => void>();
function notifyEnvironmentConnectionListeners() {
for (const listener of environmentConnectionListeners) listener();
}
/**
* Subscribe to environment-connection changes (connect / disconnect / reconnect).
* Returns an unsubscribe function.
*/
export function subscribeEnvironmentConnections(listener: () => void): () => void {
environmentConnectionListeners.add(listener);
return () => {
environmentConnectionListeners.delete(listener);
};
}
function setEnvironmentConnectionStatus(
environmentId: string,
@@ -48,6 +64,7 @@ export async function disconnectEnvironment(
) {
const session = environmentSessions.get(environmentId);
environmentSessions.delete(environmentId);
notifyEnvironmentConnectionListeners();
await session?.connection.dispose();
remoteEnvironmentStore.getState().removeEnvironmentRuntimeState(environmentId);
@@ -176,6 +193,7 @@ export async function connectSavedEnvironment(
client,
connection: environmentConnection,
});
notifyEnvironmentConnectionListeners();
try {
await environmentConnection.ensureBootstrapped();
@@ -188,11 +206,15 @@ export async function connectSavedEnvironment(
}
}
const environmentsSortOrder = Order.make<ConnectedEnvironmentSummary>(
(left, right) => left.environmentLabel.localeCompare(right.environmentLabel) as -1 | 0 | 1,
);
function deriveConnectedEnvironments(
savedConnectionsById: Record<string, SavedRemoteConnection>,
environmentStateById: ReturnType<typeof remoteEnvironmentStore.getState>["environmentStateById"],
): ReadonlyArray<ConnectedEnvironmentSummary> {
return sortCopy(
return Arr.sort(
Object.values(savedConnectionsById).map((connection) => {
const runtime = environmentStateById[connection.environmentId];
return {
@@ -203,7 +225,7 @@ function deriveConnectedEnvironments(
connectionError: runtime?.connectionError ?? null,
};
}),
(left, right) => left.environmentLabel.localeCompare(right.environmentLabel),
environmentsSortOrder,
);
}
@@ -250,6 +272,7 @@ export function useRemoteEnvironmentBootstrap() {
void session.connection.dispose();
}
environmentSessions.clear();
notifyEnvironmentConnectionListeners();
};
}, [replaceSavedConnections, setIsLoadingSavedConnection]);
}
@@ -9,7 +9,7 @@ import {
type RuntimeMode,
} from "@t3tools/contracts";
import { newClientId } from "../lib/clientId";
import { uuidv4 } from "../lib/uuid";
import { useThreadSelection } from "./use-thread-selection";
import { useRemoteEnvironmentStore } from "./remote-environment-store";
import { getEnvironmentClient, useRemoteEnvironmentState } from "./use-remote-environment-registry";
@@ -102,7 +102,7 @@ export function useSelectedThreadCommands(input: {
await client.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe(newClientId("command")),
commandId: CommandId.makeUnsafe(uuidv4()),
threadId: selectedThread.id,
modelSelection,
});
@@ -123,7 +123,7 @@ export function useSelectedThreadCommands(input: {
await client.orchestration.dispatchCommand({
type: "thread.runtime-mode.set",
commandId: CommandId.makeUnsafe(newClientId("command")),
commandId: CommandId.makeUnsafe(uuidv4()),
threadId: selectedThread.id,
runtimeMode,
createdAt: new Date().toISOString(),
@@ -145,7 +145,7 @@ export function useSelectedThreadCommands(input: {
await client.orchestration.dispatchCommand({
type: "thread.interaction-mode.set",
commandId: CommandId.makeUnsafe(newClientId("command")),
commandId: CommandId.makeUnsafe(uuidv4()),
threadId: selectedThread.id,
interactionMode,
createdAt: new Date().toISOString(),
@@ -173,7 +173,7 @@ export function useSelectedThreadCommands(input: {
await client.orchestration.dispatchCommand({
type: "thread.turn.interrupt",
commandId: CommandId.makeUnsafe(newClientId("command")),
commandId: CommandId.makeUnsafe(uuidv4()),
threadId: selectedThread.id,
...(selectedThread.session?.activeTurnId
? { turnId: selectedThread.session.activeTurnId }
@@ -200,7 +200,7 @@ export function useSelectedThreadCommands(input: {
await client.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe(newClientId("command")),
commandId: CommandId.makeUnsafe(uuidv4()),
threadId: selectedThread.id,
title: trimmed,
});
@@ -223,7 +223,7 @@ export function useSelectedThreadCommands(input: {
try {
await client.orchestration.dispatchCommand({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe(newClientId("command")),
commandId: CommandId.makeUnsafe(uuidv4()),
threadId: selectedThread.id,
requestId,
decision,
@@ -250,7 +250,7 @@ export function useSelectedThreadCommands(input: {
try {
await client.orchestration.dispatchCommand({
type: "thread.user-input.respond",
commandId: CommandId.makeUnsafe(newClientId("command")),
commandId: CommandId.makeUnsafe(uuidv4()),
threadId: selectedThread.id,
requestId: activePendingUserInput.requestId,
answers: activePendingUserInputAnswers,
@@ -0,0 +1,321 @@
import { useCallback, useEffect } from "react";
import { type GitActionRequestInput } from "@t3tools/client-runtime";
import {
CommandId,
type GitBranch,
type GitRunStackedActionResult,
ThreadId,
} from "@t3tools/contracts";
import {
dedupeRemoteBranchesWithLocalMatches,
sanitizeFeatureBranchName,
} from "@t3tools/shared/git";
import { uuidv4 } from "../lib/uuid";
import { type ScopedMobileProject, type ScopedMobileThread } from "../lib/scopedEntities";
import { useRemoteEnvironmentStore } from "./remote-environment-store";
import { getEnvironmentClient } from "./use-remote-environment-registry";
import { gitActionManager } from "./use-git-action-state";
import { gitBranchManager } from "./use-git-branches";
import { gitStatusManager } from "./use-git-status";
import { useThreadSelection } from "./use-thread-selection";
export function useSelectedThreadGitActions() {
const { selectedThread, selectedThreadProject } = useThreadSelection();
const setPendingConnectionError = useRemoteEnvironmentStore(
(state) => state.setPendingConnectionError,
);
const selectedThreadGitRootCwd = selectedThreadProject?.workspaceRoot ?? null;
const updateThreadGitContext = useCallback(
async (
thread: NonNullable<typeof selectedThread>,
nextState: {
readonly branch?: string | null;
readonly worktreePath?: string | null;
},
) => {
const client = getEnvironmentClient(thread.environmentId);
if (!client) {
return;
}
await client.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe(uuidv4()),
threadId: ThreadId.makeUnsafe(thread.id),
...(nextState.branch !== undefined ? { branch: nextState.branch } : {}),
...(nextState.worktreePath !== undefined ? { worktreePath: nextState.worktreePath } : {}),
});
},
[],
);
const refreshSelectedThreadGitStatus = useCallback(
async (options?: { readonly quiet?: boolean; readonly cwd?: string | null }) => {
if (!selectedThread || !selectedThreadProject) {
return null;
}
const cwd =
options?.cwd ?? selectedThread.worktreePath ?? selectedThreadProject.workspaceRoot;
if (!cwd) {
return null;
}
try {
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return null;
}
const status = await gitActionManager.refreshStatus(
{ environmentId: selectedThread.environmentId, cwd },
client.git,
options,
);
setPendingConnectionError(null);
return status;
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to refresh git status.";
setPendingConnectionError(message);
return null;
}
},
[selectedThread, selectedThreadProject, setPendingConnectionError],
);
useEffect(() => {
if (!selectedThread || !selectedThreadProject) {
return;
}
void refreshSelectedThreadGitStatus({ quiet: true });
}, [refreshSelectedThreadGitStatus, selectedThread, selectedThreadProject]);
const runSelectedThreadGitMutation = useCallback(
async <T>(
operation: (input: {
readonly thread: ScopedMobileThread;
readonly project: ScopedMobileProject;
readonly cwd: string;
}) => Promise<T>,
): Promise<T | null> => {
if (!selectedThread || !selectedThreadProject) {
return null;
}
const cwd = selectedThread.worktreePath ?? selectedThreadProject.workspaceRoot;
if (!cwd) {
return null;
}
try {
setPendingConnectionError(null);
return await operation({
thread: selectedThread,
project: selectedThreadProject,
cwd,
});
} catch (error) {
setPendingConnectionError(error instanceof Error ? error.message : "Git action failed.");
return null;
}
},
[selectedThread, selectedThreadProject, setPendingConnectionError],
);
const refreshSelectedThreadBranches = useCallback(async (): Promise<ReadonlyArray<GitBranch>> => {
if (!selectedThread || !selectedThreadProject || !selectedThreadGitRootCwd) {
return [];
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return [];
}
try {
const result = await gitBranchManager.load(
{ environmentId: selectedThread.environmentId, cwd: selectedThreadGitRootCwd, query: null },
client.git,
{ limit: 100 },
);
return dedupeRemoteBranchesWithLocalMatches(result?.branches ?? []).filter(
(branch) => !branch.isRemote,
);
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to load branches.",
);
return [];
}
}, [selectedThread, selectedThreadGitRootCwd, selectedThreadProject, setPendingConnectionError]);
const syncSelectedThreadBranchState = useCallback(
async (input: {
readonly thread: ScopedMobileThread;
readonly cwd: string;
readonly branchRootCwd?: string | null;
readonly nextThreadState?: {
readonly branch?: string | null;
readonly worktreePath?: string | null;
};
}) => {
if (input.nextThreadState) {
await updateThreadGitContext(input.thread, input.nextThreadState);
}
const branchRootCwd = input.branchRootCwd ?? selectedThreadProject?.workspaceRoot ?? null;
if (branchRootCwd) {
gitBranchManager.invalidate({
environmentId: input.thread.environmentId,
cwd: branchRootCwd,
query: null,
});
await refreshSelectedThreadBranches();
}
await refreshSelectedThreadGitStatus({ quiet: true, cwd: input.cwd });
},
[
refreshSelectedThreadBranches,
refreshSelectedThreadGitStatus,
selectedThreadProject?.workspaceRoot,
updateThreadGitContext,
],
);
const onCheckoutSelectedThreadBranch = useCallback(
async (branch: string) => {
await runSelectedThreadGitMutation(async ({ thread, cwd }) => {
const result = await gitActionManager.checkout(
{ environmentId: thread.environmentId, cwd },
{ branch },
);
await syncSelectedThreadBranchState({
thread,
cwd,
nextThreadState: {
branch: result?.branch ?? thread.branch,
worktreePath: thread.worktreePath,
},
});
});
},
[runSelectedThreadGitMutation, syncSelectedThreadBranchState],
);
const onCreateSelectedThreadBranch = useCallback(
async (branch: string) => {
await runSelectedThreadGitMutation(async ({ thread, cwd }) => {
const result = await gitActionManager.createBranch(
{ environmentId: thread.environmentId, cwd },
{
branch,
checkout: true,
},
);
await syncSelectedThreadBranchState({
thread,
cwd,
nextThreadState: {
branch: result?.branch ?? thread.branch,
worktreePath: thread.worktreePath,
},
});
});
},
[runSelectedThreadGitMutation, syncSelectedThreadBranchState],
);
const onCreateSelectedThreadWorktree = useCallback(
async (nextWorktree: { readonly baseBranch: string; readonly newBranch: string }) => {
await runSelectedThreadGitMutation(async ({ thread, project }) => {
const result = await gitActionManager.createWorktree(
{ environmentId: thread.environmentId, cwd: project.workspaceRoot },
{
branch: nextWorktree.baseBranch,
newBranch: sanitizeFeatureBranchName(nextWorktree.newBranch),
path: null,
},
);
if (!result) {
return;
}
await syncSelectedThreadBranchState({
thread,
cwd: result.worktree.path,
branchRootCwd: project.workspaceRoot,
nextThreadState: {
branch: result.worktree.branch,
worktreePath: result.worktree.path,
},
});
});
},
[runSelectedThreadGitMutation, syncSelectedThreadBranchState],
);
const onPullSelectedThreadBranch = useCallback(async () => {
await runSelectedThreadGitMutation(async ({ thread, cwd }) => {
await gitActionManager.pull({ environmentId: thread.environmentId, cwd });
await refreshSelectedThreadGitStatus({ quiet: true, cwd });
});
}, [refreshSelectedThreadGitStatus, runSelectedThreadGitMutation]);
const onRunSelectedThreadGitAction = useCallback(
async (input: GitActionRequestInput): Promise<GitRunStackedActionResult | null> => {
return await runSelectedThreadGitMutation(async ({ thread, cwd }) => {
const result = await gitActionManager.runStackedAction(
{ environmentId: thread.environmentId, cwd },
{
actionId: uuidv4(),
action: input.action,
...(input.commitMessage ? { commitMessage: input.commitMessage } : {}),
...(input.featureBranch ? { featureBranch: input.featureBranch } : {}),
...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}),
},
{
gitStatus: gitStatusManager.getSnapshot({
environmentId: thread.environmentId,
cwd,
}).data,
},
);
if (!result) {
return null;
}
if (result.branch.status === "created" && result.branch.name) {
await syncSelectedThreadBranchState({
thread,
cwd,
nextThreadState: {
branch: result.branch.name,
worktreePath: thread.worktreePath,
},
});
return result;
}
await refreshSelectedThreadGitStatus({ quiet: true, cwd });
return result;
});
},
[refreshSelectedThreadGitStatus, runSelectedThreadGitMutation, syncSelectedThreadBranchState],
);
return {
refreshSelectedThreadGitStatus,
refreshSelectedThreadBranches,
onCheckoutSelectedThreadBranch,
onCreateSelectedThreadBranch,
onCreateSelectedThreadWorktree,
onPullSelectedThreadBranch,
onRunSelectedThreadGitAction,
};
}
@@ -0,0 +1,47 @@
import { useMemo } from "react";
import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
import { useGitActionState } from "./use-git-action-state";
import { useGitBranches } from "./use-git-branches";
import { useThreadSelection } from "./use-thread-selection";
export function useSelectedThreadGitState() {
const { selectedThread, selectedThreadProject } = useThreadSelection();
const selectedThreadGitTarget = useMemo(
() => ({
environmentId: selectedThread?.environmentId ?? null,
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
}),
[
selectedThread?.environmentId,
selectedThread?.worktreePath,
selectedThreadProject?.workspaceRoot,
],
);
const gitActionState = useGitActionState(selectedThreadGitTarget);
const selectedThreadBranchTarget = useMemo(
() => ({
environmentId: selectedThread?.environmentId ?? null,
cwd: selectedThreadProject?.workspaceRoot ?? null,
query: null,
}),
[selectedThread?.environmentId, selectedThreadProject?.workspaceRoot],
);
const selectedThreadBranchState = useGitBranches(selectedThreadBranchTarget);
const selectedThreadBranches = useMemo(
() =>
dedupeRemoteBranchesWithLocalMatches(selectedThreadBranchState.data?.branches ?? []).filter(
(branch) => !branch.isRemote,
),
[selectedThreadBranchState.data?.branches],
);
return {
gitOperationLabel: gitActionState.currentLabel,
selectedThreadBranches,
selectedThreadBranchesLoading: selectedThreadBranchState.isPending,
};
}
@@ -1,409 +0,0 @@
import { useCallback, useEffect } from "react";
import {
buildGitActionProgressStages,
type GitActionRequestInput,
type WsRpcClient,
} from "@t3tools/client-runtime";
import {
CommandId,
type GitBranch,
type GitRunStackedActionResult,
ThreadId,
} from "@t3tools/contracts";
import {
dedupeRemoteBranchesWithLocalMatches,
sanitizeFeatureBranchName,
} from "@t3tools/shared/git";
import { newClientId } from "../lib/clientId";
import {
scopedThreadKey,
type ScopedMobileProject,
type ScopedMobileThread,
} from "../lib/scopedEntities";
import { useRemoteEnvironmentStore } from "./remote-environment-store";
import { useThreadSelection } from "./use-thread-selection";
import { getEnvironmentClient } from "./use-remote-environment-registry";
import { useThreadGitStore } from "./thread-git-store";
export function useSelectedThreadGit() {
const { selectedThread, selectedThreadProject } = useThreadSelection();
const setPendingConnectionError = useRemoteEnvironmentStore(
(state) => state.setPendingConnectionError,
);
const selectedThreadGitRootCwd = selectedThreadProject?.workspaceRoot ?? null;
const selectedThreadKey = selectedThread
? scopedThreadKey(selectedThread.environmentId, selectedThread.id)
: null;
const selectedThreadGitStatus = useThreadGitStore((state) =>
selectedThreadKey ? (state.gitStatusByThreadKey[selectedThreadKey] ?? null) : null,
);
const gitOperationLabel = useThreadGitStore((state) =>
selectedThreadKey ? (state.gitOperationLabelByThreadKey[selectedThreadKey] ?? null) : null,
);
const setThreadGitStatus = useThreadGitStore((state) => state.setThreadGitStatus);
const setThreadGitOperationLabel = useThreadGitStore((state) => state.setThreadGitOperationLabel);
const clearThreadGitState = useThreadGitStore((state) => state.clearThreadGitState);
const updateThreadGitContext = useCallback(
async (
thread: NonNullable<typeof selectedThread>,
nextState: {
readonly branch?: string | null;
readonly worktreePath?: string | null;
},
) => {
const client = getEnvironmentClient(thread.environmentId);
if (!client) {
return;
}
await client.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe(newClientId("command")),
threadId: ThreadId.makeUnsafe(thread.id),
...(nextState.branch !== undefined ? { branch: nextState.branch } : {}),
...(nextState.worktreePath !== undefined ? { worktreePath: nextState.worktreePath } : {}),
});
},
[],
);
const refreshSelectedThreadGitStatus = useCallback(
async (options?: { readonly quiet?: boolean; readonly cwd?: string | null }) => {
if (!selectedThread || !selectedThreadProject) {
if (selectedThreadKey) {
clearThreadGitState(selectedThreadKey);
}
return null;
}
const cwd =
options?.cwd ?? selectedThread.worktreePath ?? selectedThreadProject.workspaceRoot;
if (!cwd) {
if (selectedThreadKey) {
clearThreadGitState(selectedThreadKey);
}
return null;
}
if (!options?.quiet && selectedThreadKey) {
setThreadGitOperationLabel(selectedThreadKey, "Refreshing git status");
}
try {
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return null;
}
const status = await client.git.refreshStatus({ cwd });
if (selectedThreadKey) {
setThreadGitStatus(selectedThreadKey, status);
}
setPendingConnectionError(null);
return status;
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to refresh git status.";
setPendingConnectionError(message);
return null;
} finally {
if (!options?.quiet && selectedThreadKey) {
setThreadGitOperationLabel(selectedThreadKey, null);
}
}
},
[
clearThreadGitState,
selectedThreadKey,
selectedThread,
selectedThreadProject,
setPendingConnectionError,
setThreadGitOperationLabel,
setThreadGitStatus,
],
);
useEffect(() => {
if (!selectedThread || !selectedThreadProject) {
if (selectedThreadKey) {
clearThreadGitState(selectedThreadKey);
}
return;
}
void refreshSelectedThreadGitStatus({ quiet: true });
}, [
clearThreadGitState,
refreshSelectedThreadGitStatus,
selectedThreadKey,
selectedThread,
selectedThreadProject,
]);
const runSelectedThreadGitMutation = useCallback(
async <T>(
label: string,
operation: (input: {
readonly client: WsRpcClient;
readonly thread: ScopedMobileThread;
readonly project: ScopedMobileProject;
}) => Promise<T>,
): Promise<T | null> => {
if (!selectedThread || !selectedThreadProject) {
return null;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return null;
}
if (selectedThreadKey) {
setThreadGitOperationLabel(selectedThreadKey, label);
}
try {
setPendingConnectionError(null);
return await operation({
client,
thread: selectedThread,
project: selectedThreadProject,
});
} catch (error) {
setPendingConnectionError(error instanceof Error ? error.message : "Git action failed.");
return null;
} finally {
if (selectedThreadKey) {
setThreadGitOperationLabel(selectedThreadKey, null);
}
}
},
[
selectedThreadKey,
selectedThread,
selectedThreadProject,
setPendingConnectionError,
setThreadGitOperationLabel,
],
);
const onListSelectedThreadBranches = useCallback(async (): Promise<ReadonlyArray<GitBranch>> => {
if (!selectedThread || !selectedThreadProject || !selectedThreadGitRootCwd) {
return [];
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return [];
}
try {
const result = await client.git.listBranches({
cwd: selectedThreadGitRootCwd,
limit: 100,
});
return dedupeRemoteBranchesWithLocalMatches(result.branches).filter(
(branch) => !branch.isRemote,
);
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to load branches.",
);
return [];
}
}, [selectedThread, selectedThreadGitRootCwd, selectedThreadProject, setPendingConnectionError]);
const onListProjectBranches = useCallback(
async (project: ScopedMobileProject): Promise<ReadonlyArray<GitBranch>> => {
const client = getEnvironmentClient(project.environmentId);
if (!client) {
return [];
}
try {
const result = await client.git.listBranches({
cwd: project.workspaceRoot,
limit: 100,
});
return dedupeRemoteBranchesWithLocalMatches(result.branches).filter(
(branch) => !branch.isRemote,
);
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to load branches.",
);
return [];
}
},
[setPendingConnectionError],
);
const onCreateProjectWorktree = useCallback(
async (
project: ScopedMobileProject,
nextWorktree: {
readonly baseBranch: string;
readonly newBranch: string;
},
): Promise<{
readonly branch: string;
readonly worktreePath: string;
} | null> => {
const client = getEnvironmentClient(project.environmentId);
if (!client) {
return null;
}
try {
const result = await client.git.createWorktree({
cwd: project.workspaceRoot,
branch: nextWorktree.baseBranch,
newBranch: sanitizeFeatureBranchName(nextWorktree.newBranch),
path: null,
});
return {
branch: result.worktree.branch,
worktreePath: result.worktree.path,
};
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to create worktree.",
);
return null;
}
},
[setPendingConnectionError],
);
const onCheckoutSelectedThreadBranch = useCallback(
async (branch: string) => {
await runSelectedThreadGitMutation(
"Checking out branch",
async ({ client, thread, project }) => {
const cwd = thread.worktreePath ?? project.workspaceRoot;
const result = await client.git.checkout({ cwd, branch });
await updateThreadGitContext(thread, {
branch: result.branch,
worktreePath: thread.worktreePath,
});
await refreshSelectedThreadGitStatus({ quiet: true, cwd });
},
);
},
[refreshSelectedThreadGitStatus, runSelectedThreadGitMutation, updateThreadGitContext],
);
const onCreateSelectedThreadBranch = useCallback(
async (branch: string) => {
await runSelectedThreadGitMutation("Creating branch", async ({ client, thread, project }) => {
const cwd = thread.worktreePath ?? project.workspaceRoot;
const result = await client.git.createBranch({
cwd,
branch,
checkout: true,
});
await updateThreadGitContext(thread, {
branch: result.branch,
worktreePath: thread.worktreePath,
});
await refreshSelectedThreadGitStatus({ quiet: true, cwd });
});
},
[refreshSelectedThreadGitStatus, runSelectedThreadGitMutation, updateThreadGitContext],
);
const onCreateSelectedThreadWorktree = useCallback(
async (nextWorktree: { readonly baseBranch: string; readonly newBranch: string }) => {
await runSelectedThreadGitMutation(
"Creating worktree",
async ({ client, thread, project }) => {
const result = await client.git.createWorktree({
cwd: project.workspaceRoot,
branch: nextWorktree.baseBranch,
newBranch: sanitizeFeatureBranchName(nextWorktree.newBranch),
path: null,
});
await updateThreadGitContext(thread, {
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
await refreshSelectedThreadGitStatus({ quiet: true, cwd: result.worktree.path });
},
);
},
[refreshSelectedThreadGitStatus, runSelectedThreadGitMutation, updateThreadGitContext],
);
const onPullSelectedThreadBranch = useCallback(async () => {
await runSelectedThreadGitMutation(
"Pulling latest changes",
async ({ client, thread, project }) => {
const cwd = thread.worktreePath ?? project.workspaceRoot;
await client.git.pull({ cwd });
await refreshSelectedThreadGitStatus({ quiet: true, cwd });
},
);
}, [refreshSelectedThreadGitStatus, runSelectedThreadGitMutation]);
const onRunSelectedThreadGitAction = useCallback(
async (input: GitActionRequestInput): Promise<GitRunStackedActionResult | null> => {
const [firstStage] = buildGitActionProgressStages({
action: input.action,
hasCustomCommitMessage: Boolean(input.commitMessage?.trim()),
hasWorkingTreeChanges: selectedThreadGitStatus?.hasWorkingTreeChanges ?? false,
featureBranch: input.featureBranch ?? false,
shouldPushBeforePr:
input.action === "create_pr" &&
((selectedThreadGitStatus?.aheadCount ?? 0) > 0 ||
!(selectedThreadGitStatus?.hasUpstream ?? false)),
});
return await runSelectedThreadGitMutation(
firstStage ?? "Running git action",
async ({ client, thread, project }) => {
const cwd = thread.worktreePath ?? project.workspaceRoot;
const result = await client.git.runStackedAction({
actionId: newClientId("git-action"),
cwd,
action: input.action,
...(input.commitMessage ? { commitMessage: input.commitMessage } : {}),
...(input.featureBranch ? { featureBranch: input.featureBranch } : {}),
...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}),
});
if (result.branch.status === "created" && result.branch.name) {
await updateThreadGitContext(thread, {
branch: result.branch.name,
worktreePath: thread.worktreePath,
});
}
await refreshSelectedThreadGitStatus({ quiet: true, cwd });
return result;
},
);
},
[
refreshSelectedThreadGitStatus,
runSelectedThreadGitMutation,
selectedThreadGitStatus,
updateThreadGitContext,
],
);
return {
selectedThreadGitStatus,
gitOperationLabel,
refreshSelectedThreadGitStatus,
onListProjectBranches,
onCreateProjectWorktree,
onListSelectedThreadBranches,
onCheckoutSelectedThreadBranch,
onCreateSelectedThreadBranch,
onCreateSelectedThreadWorktree,
onPullSelectedThreadBranch,
onRunSelectedThreadGitAction,
};
}
@@ -18,7 +18,7 @@ import {
derivePendingUserInputs,
type QueuedThreadMessage,
} from "../lib/threadActivity";
import { newClientId } from "../lib/clientId";
import { uuidv4 } from "../lib/uuid";
import type { ConnectedEnvironmentSummary } from "./remote-runtime-types";
import { useRemoteEnvironmentStore } from "./remote-environment-store";
import { getEnvironmentClient, useRemoteConnectionStatus } from "./use-remote-environment-registry";
@@ -238,7 +238,7 @@ export function useThreadComposerState() {
return;
}
beginDispatchingQueuedMessage(queuedMessage.id);
beginDispatchingQueuedMessage(queuedMessage.messageId);
try {
await client.orchestration.dispatchCommand({
type: "thread.turn.start",
@@ -255,7 +255,11 @@ export function useThreadComposerState() {
createdAt: queuedMessage.createdAt,
});
removeQueuedMessage(queuedMessage.environmentId, queuedMessage.threadId, queuedMessage.id);
removeQueuedMessage(
queuedMessage.environmentId,
queuedMessage.threadId,
queuedMessage.messageId,
);
patchEnvironmentRuntimeState(queuedMessage.environmentId, (runtime) => ({
...runtime,
snapshot: runtime.snapshot
@@ -269,12 +273,16 @@ export function useThreadComposerState() {
: runtime.snapshot,
}));
} catch (error) {
removeQueuedMessage(queuedMessage.environmentId, queuedMessage.threadId, queuedMessage.id);
removeQueuedMessage(
queuedMessage.environmentId,
queuedMessage.threadId,
queuedMessage.messageId,
);
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to send message.",
);
} finally {
finishDispatchingQueuedMessage(queuedMessage.id);
finishDispatchingQueuedMessage(queuedMessage.messageId);
}
},
[
@@ -309,11 +317,10 @@ export function useThreadComposerState() {
const createdAt = new Date().toISOString();
enqueueQueuedMessage({
id: newClientId("queued-message"),
environmentId: selectedThread.environmentId,
threadId: selectedThread.id,
messageId: newClientId("message"),
commandId: newClientId("command"),
messageId: MessageId.makeUnsafe(uuidv4()),
commandId: CommandId.makeUnsafe(uuidv4()),
text,
attachments,
createdAt,
+10
View File
@@ -0,0 +1,10 @@
// NOTE: This file is generated by uniwind and it should not be edited manually.
/// <reference types="uniwind/types" />
declare module 'uniwind' {
export interface UniwindConfig {
themes: readonly ['light', 'dark']
}
}
export {}
-325
View File
@@ -1,325 +0,0 @@
import { EnvironmentId, type GitStatusResult } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { WsRpcClient } from "../rpc/wsRpcClient";
import { resetAppAtomRegistryForTests } from "../rpc/atomRegistry";
import {
getGitStatusSnapshot,
resetGitStatusStateForTests,
refreshGitStatus,
watchGitStatus,
} from "./gitStatusState";
const serviceHarness = vi.hoisted(() => ({
connections: new Map<string, any>(),
listeners: new Set<() => void>(),
}));
vi.mock("../environments/runtime/service", () => ({
readEnvironmentConnection: (environmentId: string) =>
serviceHarness.connections.get(environmentId) ?? null,
subscribeEnvironmentConnections: (listener: () => void) => {
serviceHarness.listeners.add(listener);
return () => {
serviceHarness.listeners.delete(listener);
};
},
}));
function registerListener<T>(listeners: Set<(event: T) => void>, listener: (event: T) => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
const gitStatusListeners = new Set<(event: GitStatusResult) => void>();
const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
const OTHER_ENVIRONMENT_ID = EnvironmentId.make("environment-remote");
const TARGET = { environmentId: ENVIRONMENT_ID, cwd: "/repo" } as const;
const FRESH_TARGET = { environmentId: ENVIRONMENT_ID, cwd: "/fresh" } as const;
const BASE_STATUS: GitStatusResult = {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/push-status",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
const gitClient = {
refreshStatus: vi.fn(async (input: { cwd: string }) => ({
...BASE_STATUS,
branch: `${input.cwd}-refreshed`,
})),
onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) =>
registerListener(gitStatusListeners, listener),
),
};
function emitGitStatus(event: GitStatusResult) {
for (const listener of gitStatusListeners) {
listener(event);
}
}
function createRegisteredGitStatusClient(environmentId: EnvironmentId) {
const listeners = new Set<(event: GitStatusResult) => void>();
const client = {
dispose: vi.fn(async () => undefined),
reconnect: vi.fn(async () => undefined),
terminal: {
open: vi.fn(async () => undefined),
write: vi.fn(async () => undefined),
resize: vi.fn(async () => undefined),
clear: vi.fn(async () => undefined),
restart: vi.fn(async () => undefined),
close: vi.fn(async () => undefined),
onEvent: vi.fn(() => () => undefined),
},
projects: {
searchEntries: vi.fn(async () => []),
writeFile: vi.fn(async () => undefined),
},
shell: {
openInEditor: vi.fn(async () => undefined),
},
git: {
pull: vi.fn(async () => undefined),
refreshStatus: vi.fn(async (input: { cwd: string }) => ({
...BASE_STATUS,
branch: `${input.cwd}-refreshed`,
})),
onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
registerListener(listeners, listener),
),
runStackedAction: vi.fn(async () => ({}) as any),
listBranches: vi.fn(async () => []),
createWorktree: vi.fn(async () => undefined),
removeWorktree: vi.fn(async () => undefined),
createBranch: vi.fn(async () => undefined),
checkout: vi.fn(async () => undefined),
init: vi.fn(async () => undefined),
resolvePullRequest: vi.fn(async () => undefined),
preparePullRequestThread: vi.fn(async () => undefined),
},
server: {
getConfig: vi.fn(async () => ({
environment: {
environmentId,
},
})),
refreshProviders: vi.fn(async () => undefined),
upsertKeybinding: vi.fn(async () => undefined),
getSettings: vi.fn(async () => undefined),
updateSettings: vi.fn(async () => undefined),
subscribeConfig: vi.fn(() => () => undefined),
subscribeLifecycle: vi.fn(() => () => undefined),
subscribeAuthAccess: vi.fn(() => () => undefined),
},
orchestration: {
dispatchCommand: vi.fn(async () => undefined),
getTurnDiff: vi.fn(async () => undefined),
getFullThreadDiff: vi.fn(async () => undefined),
subscribeShell: vi.fn(() => () => undefined),
subscribeThread: vi.fn(() => () => undefined),
},
} as unknown as WsRpcClient;
serviceHarness.connections.set(environmentId, {
kind: "saved" as const,
knownEnvironment: {
id: environmentId,
label: `Environment ${environmentId}`,
source: "manual" as const,
environmentId,
target: {
httpBaseUrl: "http://example.test",
wsBaseUrl: "ws://example.test",
},
},
client,
environmentId,
ensureBootstrapped: async () => undefined,
reconnect: async () => undefined,
dispose: async () => undefined,
});
for (const listener of serviceHarness.listeners) {
listener();
}
return {
client,
emit: (event: GitStatusResult) => {
for (const listener of listeners) {
listener(event);
}
},
};
}
afterEach(async () => {
gitStatusListeners.clear();
serviceHarness.connections.clear();
serviceHarness.listeners.clear();
gitClient.onStatus.mockClear();
gitClient.refreshStatus.mockClear();
resetGitStatusStateForTests();
resetAppAtomRegistryForTests();
});
describe("gitStatusState", () => {
it("starts fresh cwd state in a pending state", () => {
expect(getGitStatusSnapshot(FRESH_TARGET)).toEqual({
data: null,
error: null,
cause: null,
isPending: true,
});
});
it("shares one live subscription per cwd and updates the per-cwd atom snapshot", () => {
const releaseA = watchGitStatus(TARGET, gitClient);
const releaseB = watchGitStatus(TARGET, gitClient);
expect(gitClient.onStatus).toHaveBeenCalledOnce();
expect(getGitStatusSnapshot(TARGET)).toEqual({
data: null,
error: null,
cause: null,
isPending: true,
});
emitGitStatus(BASE_STATUS);
expect(getGitStatusSnapshot(TARGET)).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: false,
});
releaseA();
expect(gitStatusListeners.size).toBe(1);
releaseB();
expect(gitStatusListeners.size).toBe(0);
});
it("refreshes git status through the unary RPC without restarting the stream", async () => {
const release = watchGitStatus(TARGET, gitClient);
emitGitStatus(BASE_STATUS);
const refreshed = await refreshGitStatus(TARGET, gitClient);
expect(gitClient.onStatus).toHaveBeenCalledOnce();
expect(gitClient.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
expect(refreshed).toEqual({ ...BASE_STATUS, branch: "/repo-refreshed" });
expect(getGitStatusSnapshot(TARGET)).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: false,
});
release();
});
it("keeps git status subscriptions isolated by environment when cwds match", () => {
const localListeners = new Set<(event: GitStatusResult) => void>();
const remoteListeners = new Set<(event: GitStatusResult) => void>();
const localClient = {
refreshStatus: vi.fn(),
onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
registerListener(localListeners, listener),
),
};
const remoteClient = {
refreshStatus: vi.fn(),
onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
registerListener(remoteListeners, listener),
),
};
const remoteTarget = { environmentId: OTHER_ENVIRONMENT_ID, cwd: "/repo" } as const;
const releaseLocal = watchGitStatus(TARGET, localClient);
const releaseRemote = watchGitStatus(remoteTarget, remoteClient);
for (const listener of localListeners) {
listener(BASE_STATUS);
}
for (const listener of remoteListeners) {
listener({ ...BASE_STATUS, branch: "remote-branch" });
}
expect(getGitStatusSnapshot(TARGET).data?.branch).toBe("feature/push-status");
expect(getGitStatusSnapshot(remoteTarget).data?.branch).toBe("remote-branch");
releaseLocal();
releaseRemote();
});
it("waits for a delayed environment client registration instead of throwing", () => {
const release = watchGitStatus(TARGET);
expect(getGitStatusSnapshot(TARGET)).toEqual({
data: null,
error: null,
cause: null,
isPending: true,
});
const registered = createRegisteredGitStatusClient(ENVIRONMENT_ID);
registered.emit(BASE_STATUS);
expect(getGitStatusSnapshot(TARGET)).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: false,
});
release();
});
it("resubscribes after the environment client is removed and re-registered", async () => {
const firstClient = createRegisteredGitStatusClient(ENVIRONMENT_ID);
const release = watchGitStatus(TARGET);
firstClient.emit(BASE_STATUS);
expect(getGitStatusSnapshot(TARGET).data?.branch).toBe("feature/push-status");
serviceHarness.connections.delete(ENVIRONMENT_ID);
for (const listener of serviceHarness.listeners) {
listener();
}
expect(getGitStatusSnapshot(TARGET)).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: true,
});
const secondClient = createRegisteredGitStatusClient(ENVIRONMENT_ID);
secondClient.emit({ ...BASE_STATUS, branch: "reconnected-branch" });
expect(getGitStatusSnapshot(TARGET)).toEqual({
data: { ...BASE_STATUS, branch: "reconnected-branch" },
error: null,
cause: null,
isPending: false,
});
release();
});
it("returns the cached snapshot when refresh is requested before the client is registered", async () => {
await expect(refreshGitStatus(TARGET)).resolves.toBeNull();
});
});
+28 -256
View File
@@ -1,11 +1,15 @@
import { useAtomValue } from "@effect/atom-react";
import {
type EnvironmentId,
type GitManagerServiceError,
type GitStatusResult,
} from "@t3tools/contracts";
import { Cause } from "effect";
import { Atom } from "effect/unstable/reactivity";
type GitStatusClient,
type GitStatusState,
type GitStatusTarget,
EMPTY_GIT_STATUS_ATOM,
EMPTY_GIT_STATUS_STATE,
createGitStatusManager,
getGitStatusTargetKey,
gitStatusStateAtom,
} from "@t3tools/client-runtime";
import { type EnvironmentId } from "@t3tools/contracts";
import { useEffect } from "react";
import { appAtomRegistry } from "../rpc/atomRegistry";
@@ -13,159 +17,38 @@ import {
readEnvironmentConnection,
subscribeEnvironmentConnections,
} from "../environments/runtime";
import type { WsRpcClient } from "~/rpc/wsRpcClient";
interface GitStatusState {
readonly data: GitStatusResult | null;
readonly error: GitManagerServiceError | null;
readonly cause: Cause.Cause<GitManagerServiceError> | null;
readonly isPending: boolean;
}
export type { GitStatusState, GitStatusTarget };
type GitStatusClient = Pick<WsRpcClient["git"], "onStatus" | "refreshStatus">;
interface ResolvedGitStatusClient {
readonly clientIdentity: string;
readonly client: GitStatusClient;
}
/* ─── Manager singleton ─────────────────────────────────────────────── */
interface WatchedGitStatus {
refCount: number;
unsubscribe: () => void;
}
interface GitStatusTarget {
readonly environmentId: EnvironmentId | null;
readonly cwd: string | null;
}
const EMPTY_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
data: null,
error: null,
cause: null,
isPending: false,
});
const INITIAL_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
...EMPTY_GIT_STATUS_STATE,
isPending: true,
});
const EMPTY_GIT_STATUS_ATOM = Atom.make(EMPTY_GIT_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel("git-status:null"),
);
const NOOP: () => void = () => undefined;
const watchedGitStatuses = new Map<string, WatchedGitStatus>();
const knownGitStatusKeys = new Set<string>();
const gitStatusRefreshInFlight = new Map<string, Promise<GitStatusResult>>();
const gitStatusLastRefreshAtByKey = new Map<string, number>();
const GIT_STATUS_REFRESH_DEBOUNCE_MS = 1_000;
const gitStatusStateAtom = Atom.family((key: string) => {
knownGitStatusKeys.add(key);
return Atom.make(INITIAL_GIT_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel(`git-status:${key}`),
);
const manager = createGitStatusManager({
getRegistry: () => appAtomRegistry,
getClient: (environmentId) => {
const connection = readEnvironmentConnection(environmentId as EnvironmentId);
return connection ? connection.client.git : null;
},
getClientIdentity: (environmentId) => {
const connection = readEnvironmentConnection(environmentId as EnvironmentId);
return connection ? connection.environmentId : null;
},
subscribeClientChanges: subscribeEnvironmentConnections,
});
function getGitStatusTargetKey(target: GitStatusTarget): string | null {
if (target.environmentId === null || target.cwd === null) {
return null;
}
/* ─── Public API (preserves existing call-sites) ────────────────────── */
return `${target.environmentId}:${target.cwd}`;
}
function readResolvedGitStatusClient(target: GitStatusTarget): ResolvedGitStatusClient | null {
if (target.environmentId === null) {
return null;
}
const connection = readEnvironmentConnection(target.environmentId);
return connection
? { clientIdentity: connection.environmentId, client: connection.client.git }
: null;
}
export function getGitStatusSnapshot(target: GitStatusTarget): GitStatusState {
const targetKey = getGitStatusTargetKey(target);
if (targetKey === null) {
return EMPTY_GIT_STATUS_STATE;
}
return appAtomRegistry.get(gitStatusStateAtom(targetKey));
}
export function watchGitStatus(target: GitStatusTarget, client?: GitStatusClient): () => void {
const targetKey = getGitStatusTargetKey(target);
if (targetKey === null) {
return NOOP;
}
const watched = watchedGitStatuses.get(targetKey);
if (watched) {
watched.refCount += 1;
return () => unwatchGitStatus(targetKey);
}
watchedGitStatuses.set(targetKey, {
refCount: 1,
unsubscribe: subscribeToGitStatusTarget(targetKey, target, client),
});
return () => unwatchGitStatus(targetKey);
}
export function refreshGitStatus(
target: GitStatusTarget,
client?: GitStatusClient,
): Promise<GitStatusResult | null> {
const targetKey = getGitStatusTargetKey(target);
if (targetKey === null || target.cwd === null) {
return Promise.resolve(null);
}
const resolvedClient = client ?? readResolvedGitStatusClient(target)?.client;
if (!resolvedClient) {
return Promise.resolve(getGitStatusSnapshot(target).data);
}
const currentInFlight = gitStatusRefreshInFlight.get(targetKey);
if (currentInFlight) {
return currentInFlight;
}
const lastRequestedAt = gitStatusLastRefreshAtByKey.get(targetKey) ?? 0;
if (Date.now() - lastRequestedAt < GIT_STATUS_REFRESH_DEBOUNCE_MS) {
return Promise.resolve(getGitStatusSnapshot(target).data);
}
gitStatusLastRefreshAtByKey.set(targetKey, Date.now());
const refreshPromise = resolvedClient.refreshStatus({ cwd: target.cwd }).finally(() => {
gitStatusRefreshInFlight.delete(targetKey);
});
gitStatusRefreshInFlight.set(targetKey, refreshPromise);
return refreshPromise;
export function refreshGitStatus(target: GitStatusTarget, client?: GitStatusClient) {
return manager.refresh(target, client);
}
export function resetGitStatusStateForTests(): void {
for (const watched of watchedGitStatuses.values()) {
watched.unsubscribe();
}
watchedGitStatuses.clear();
gitStatusRefreshInFlight.clear();
gitStatusLastRefreshAtByKey.clear();
for (const key of knownGitStatusKeys) {
appAtomRegistry.set(gitStatusStateAtom(key), INITIAL_GIT_STATUS_STATE);
}
knownGitStatusKeys.clear();
manager.reset();
}
export function useGitStatus(target: GitStatusTarget): GitStatusState {
const targetKey = getGitStatusTargetKey(target);
useEffect(
() => watchGitStatus({ environmentId: target.environmentId, cwd: target.cwd }),
() => manager.watch({ environmentId: target.environmentId, cwd: target.cwd }),
[target.environmentId, target.cwd],
);
@@ -174,114 +57,3 @@ export function useGitStatus(target: GitStatusTarget): GitStatusState {
);
return targetKey === null ? EMPTY_GIT_STATUS_STATE : state;
}
function unwatchGitStatus(targetKey: string): void {
const watched = watchedGitStatuses.get(targetKey);
if (!watched) {
return;
}
watched.refCount -= 1;
if (watched.refCount > 0) {
return;
}
watched.unsubscribe();
watchedGitStatuses.delete(targetKey);
}
function subscribeToGitStatusTarget(
targetKey: string,
target: GitStatusTarget,
providedClient?: GitStatusClient,
): () => void {
if (target.cwd === null) {
return NOOP;
}
const cwd = target.cwd;
let currentClientIdentity: string | null = null;
let currentUnsubscribe = NOOP;
const syncClientSubscription = () => {
const resolved = providedClient
? {
clientIdentity: `provided:${targetKey}`,
client: providedClient,
}
: readResolvedGitStatusClient(target);
if (!resolved) {
if (currentClientIdentity !== null) {
currentUnsubscribe();
currentUnsubscribe = NOOP;
currentClientIdentity = null;
}
markGitStatusPending(targetKey);
return;
}
if (currentClientIdentity === resolved.clientIdentity) {
return;
}
currentUnsubscribe();
currentClientIdentity = resolved.clientIdentity;
currentUnsubscribe = subscribeToGitStatus(targetKey, cwd, resolved.client);
};
const unsubscribeRegistry = providedClient
? NOOP
: subscribeEnvironmentConnections(syncClientSubscription);
syncClientSubscription();
return () => {
unsubscribeRegistry();
currentUnsubscribe();
};
}
function subscribeToGitStatus(targetKey: string, cwd: string, client: GitStatusClient): () => void {
markGitStatusPending(targetKey);
return client.onStatus(
{ cwd },
(status: GitStatusResult) => {
appAtomRegistry.set(gitStatusStateAtom(targetKey), {
data: status,
error: null,
cause: null,
isPending: false,
});
},
{
onResubscribe: () => {
markGitStatusPending(targetKey);
},
},
);
}
function markGitStatusPending(targetKey: string): void {
const atom = gitStatusStateAtom(targetKey);
const current = appAtomRegistry.get(atom);
const next =
current.data === null
? INITIAL_GIT_STATUS_STATE
: {
...current,
error: null,
cause: null,
isPending: true,
};
if (
current.data === next.data &&
current.error === next.error &&
current.cause === next.cause &&
current.isPending === next.isPending
) {
return;
}
appAtomRegistry.set(atom, next);
}
+26 -49
View File
@@ -45,6 +45,7 @@
"version": "0.0.0",
"dependencies": {
"@callstack/liquid-glass": "^0.7.1",
"@effect/atom-react": "catalog:",
"@expo-google-fonts/dm-sans": "^0.4.2",
"@gorhom/bottom-sheet": "^5",
"@legendapp/list": "^3.0.0-beta.44",
@@ -54,6 +55,7 @@
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"clsx": "^2.1.1",
"effect": "catalog:",
"expo": "~55.0.14",
"expo-camera": "~55.0.15",
@@ -73,12 +75,10 @@
"expo-splash-screen": "~55.0.13",
"expo-symbols": "~55.0.5",
"expo-updates": "~55.0.16",
"nativewind": "5.0.0-preview.3",
"punycode": "^2.3.1",
"react": "19.2.0",
"react-dom": "19.2.0",
"react-native": "0.83.4",
"react-native-css": "3.0.7",
"react-native-gesture-handler": "~2.30.0",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.20.7",
@@ -88,14 +88,13 @@
"react-native-screens": "~4.23.0",
"react-native-svg": "15.15.3",
"react-native-worklets": "0.7.2",
"tailwind-merge": "^3.5.0",
"uniwind": "^1.6.2",
"zustand": "^5.0.12",
},
"devDependencies": {
"@tailwindcss/postcss": "4.1.12",
"@types/react": "~19.2.10",
"babel-preset-expo": "~55.0.8",
"lightningcss": "1.30.1",
"postcss": "^8.5.8",
"tailwindcss": "4.1.12",
"typescript": "~5.9.2",
},
@@ -272,8 +271,6 @@
"vitest": "^4.0.0",
},
"packages": {
"@alloc/quick-lru": ["@alloc/[email protected]", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "@anthropic-ai/sdk": "^0.81.0", "@modelcontextprotocol/sdk": "^1.29.0" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "^0.34.2", "@img/sharp-darwin-x64": "^0.34.2", "@img/sharp-linux-arm": "^0.34.2", "@img/sharp-linux-arm64": "^0.34.2", "@img/sharp-linux-x64": "^0.34.2", "@img/sharp-linuxmusl-arm64": "^0.34.2", "@img/sharp-linuxmusl-x64": "^0.34.2", "@img/sharp-win32-arm64": "^0.34.2", "@img/sharp-win32-x64": "^0.34.2" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-lVm+nS79r6WWlDnv5AgRzTtAlbP8O6M6kkWmDZAWE3nt9agmngxls9frJFvH55uzws2+6l0yyup/JYspfijkzw=="],
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-D4K5PvEV6wPiRtVlVsJHIUhHAmOZ6IT/I9rKlTf84gR7GyyAurPJK7z9BOf/AZqC5d1DhYQGJNKRmV+q8dGhgw=="],
@@ -738,8 +735,6 @@
"@ioredis/commands": ["@ioredis/[email protected]", "", {}, "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw=="],
"@isaacs/fs-minipass": ["@isaacs/[email protected]", "", { "dependencies": { "minipass": "^7.0.4" } }, "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w=="],
"@isaacs/ttlcache": ["@isaacs/[email protected]", "", {}, "sha512-RQgQ4uQ+pLbqXfOmieB91ejmLwvSgv9nLx6sT6sD83s7umBypgg+OIBOBbEUiJXrfpnp9j0mRhYYdzp9uqq3lA=="],
"@istanbuljs/load-nyc-config": ["@istanbuljs/[email protected]", "", { "dependencies": { "camelcase": "^5.3.1", "find-up": "^4.1.0", "get-package-type": "^0.1.0", "js-yaml": "^3.13.1", "resolve-from": "^5.0.0" } }, "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ=="],
@@ -1096,35 +1091,33 @@
"@t3tools/web": ["@t3tools/web@workspace:apps/web"],
"@tailwindcss/node": ["@tailwindcss/node@4.1.12", "", { "dependencies": { "@jridgewell/remapping": "^2.3.4", "enhanced-resolve": "^5.18.3", "jiti": "^2.5.1", "lightningcss": "1.30.1", "magic-string": "^0.30.17", "source-map-js": "^1.2.1", "tailwindcss": "4.1.12" } }, "sha512-3hm9brwvQkZFe++SBt+oLjo4OLDtkvlE8q2WalaD/7QWaeM7KEJbAiY/LJZUaCs7Xa8aUu4xy3uoyX4q54UVdQ=="],
"@tailwindcss/node": ["@tailwindcss/node@4.2.1", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.19.0", "jiti": "^2.6.1", "lightningcss": "1.31.1", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.2.1" } }, "sha512-jlx6sLk4EOwO6hHe1oCGm1Q4AN/s0rSrTTPBGPM0/RQ6Uylwq17FuU8IeJJKEjtc6K6O07zsvP+gDO6MMWo7pg=="],
"@tailwindcss/oxide": ["@tailwindcss/oxide@4.1.12", "", { "dependencies": { "detect-libc": "^2.0.4", "tar": "^7.4.3" }, "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.1.12", "@tailwindcss/oxide-darwin-arm64": "4.1.12", "@tailwindcss/oxide-darwin-x64": "4.1.12", "@tailwindcss/oxide-freebsd-x64": "4.1.12", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.1.12", "@tailwindcss/oxide-linux-arm64-gnu": "4.1.12", "@tailwindcss/oxide-linux-arm64-musl": "4.1.12", "@tailwindcss/oxide-linux-x64-gnu": "4.1.12", "@tailwindcss/oxide-linux-x64-musl": "4.1.12", "@tailwindcss/oxide-wasm32-wasi": "4.1.12", "@tailwindcss/oxide-win32-arm64-msvc": "4.1.12", "@tailwindcss/oxide-win32-x64-msvc": "4.1.12" } }, "sha512-gM5EoKHW/ukmlEtphNwaGx45fGoEmP10v51t9unv55voWh6WrOL19hfuIdo2FjxIaZzw776/BUQg7Pck++cIVw=="],
"@tailwindcss/oxide": ["@tailwindcss/oxide@4.2.1", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.2.1", "@tailwindcss/oxide-darwin-arm64": "4.2.1", "@tailwindcss/oxide-darwin-x64": "4.2.1", "@tailwindcss/oxide-freebsd-x64": "4.2.1", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.2.1", "@tailwindcss/oxide-linux-arm64-gnu": "4.2.1", "@tailwindcss/oxide-linux-arm64-musl": "4.2.1", "@tailwindcss/oxide-linux-x64-gnu": "4.2.1", "@tailwindcss/oxide-linux-x64-musl": "4.2.1", "@tailwindcss/oxide-wasm32-wasi": "4.2.1", "@tailwindcss/oxide-win32-arm64-msvc": "4.2.1", "@tailwindcss/oxide-win32-x64-msvc": "4.2.1" } }, "sha512-yv9jeEFWnjKCI6/T3Oq50yQEOqmpmpfzG1hcZsAOaXFQPfzWprWrlHSdGPEF3WQTi8zu8ohC9Mh9J470nT5pUw=="],
"@tailwindcss/oxide-android-arm64": ["@tailwindcss/oxide-android-arm64@4.1.12", "", { "os": "android", "cpu": "arm64" }, "sha512-oNY5pq+1gc4T6QVTsZKwZaGpBb2N1H1fsc1GD4o7yinFySqIuRZ2E4NvGasWc6PhYJwGK2+5YT1f9Tp80zUQZQ=="],
"@tailwindcss/oxide-android-arm64": ["@tailwindcss/oxide-android-arm64@4.2.1", "", { "os": "android", "cpu": "arm64" }, "sha512-eZ7G1Zm5EC8OOKaesIKuw77jw++QJ2lL9N+dDpdQiAB/c/B2wDh0QPFHbkBVrXnwNugvrbJFk1gK2SsVjwWReg=="],
"@tailwindcss/oxide-darwin-arm64": ["@tailwindcss/oxide-darwin-arm64@4.1.12", "", { "os": "darwin", "cpu": "arm64" }, "sha512-cq1qmq2HEtDV9HvZlTtrj671mCdGB93bVY6J29mwCyaMYCP/JaUBXxrQQQm7Qn33AXXASPUb2HFZlWiiHWFytw=="],
"@tailwindcss/oxide-darwin-arm64": ["@tailwindcss/oxide-darwin-arm64@4.2.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-q/LHkOstoJ7pI1J0q6djesLzRvQSIfEto148ppAd+BVQK0JYjQIFSK3JgYZJa+Yzi0DDa52ZsQx2rqytBnf8Hw=="],
"@tailwindcss/oxide-darwin-x64": ["@tailwindcss/oxide-darwin-x64@4.1.12", "", { "os": "darwin", "cpu": "x64" }, "sha512-6UCsIeFUcBfpangqlXay9Ffty9XhFH1QuUFn0WV83W8lGdX8cD5/+2ONLluALJD5+yJ7k8mVtwy3zMZmzEfbLg=="],
"@tailwindcss/oxide-darwin-x64": ["@tailwindcss/oxide-darwin-x64@4.2.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-/f/ozlaXGY6QLbpvd/kFTro2l18f7dHKpB+ieXz+Cijl4Mt9AI2rTrpq7V+t04nK+j9XBQHnSMdeQRhbGyt6fw=="],
"@tailwindcss/oxide-freebsd-x64": ["@tailwindcss/oxide-freebsd-x64@4.1.12", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JOH/f7j6+nYXIrHobRYCtoArJdMJh5zy5lr0FV0Qu47MID/vqJAY3r/OElPzx1C/wdT1uS7cPq+xdYYelny1ww=="],
"@tailwindcss/oxide-freebsd-x64": ["@tailwindcss/oxide-freebsd-x64@4.2.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-5e/AkgYJT/cpbkys/OU2Ei2jdETCLlifwm7ogMC7/hksI2fC3iiq6OcXwjibcIjPung0kRtR3TxEITkqgn0TcA=="],
"@tailwindcss/oxide-linux-arm-gnueabihf": ["@tailwindcss/oxide-linux-arm-gnueabihf@4.1.12", "", { "os": "linux", "cpu": "arm" }, "sha512-v4Ghvi9AU1SYgGr3/j38PD8PEe6bRfTnNSUE3YCMIRrrNigCFtHZ2TCm8142X8fcSqHBZBceDx+JlFJEfNg5zQ=="],
"@tailwindcss/oxide-linux-arm-gnueabihf": ["@tailwindcss/oxide-linux-arm-gnueabihf@4.2.1", "", { "os": "linux", "cpu": "arm" }, "sha512-Uny1EcVTTmerCKt/1ZuKTkb0x8ZaiuYucg2/kImO5A5Y/kBz41/+j0gxUZl+hTF3xkWpDmHX+TaWhOtba2Fyuw=="],
"@tailwindcss/oxide-linux-arm64-gnu": ["@tailwindcss/oxide-linux-arm64-gnu@4.1.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-YP5s1LmetL9UsvVAKusHSyPlzSRqYyRB0f+Kl/xcYQSPLEw/BvGfxzbH+ihUciePDjiXwHh+p+qbSP3SlJw+6g=="],
"@tailwindcss/oxide-linux-arm64-gnu": ["@tailwindcss/oxide-linux-arm64-gnu@4.2.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-CTrwomI+c7n6aSSQlsPL0roRiNMDQ/YzMD9EjcR+H4f0I1SQ8QqIuPnsVp7QgMkC1Qi8rtkekLkOFjo7OlEFRQ=="],
"@tailwindcss/oxide-linux-arm64-musl": ["@tailwindcss/oxide-linux-arm64-musl@4.1.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-V8pAM3s8gsrXcCv6kCHSuwyb/gPsd863iT+v1PGXC4fSL/OJqsKhfK//v8P+w9ThKIoqNbEnsZqNy+WDnwQqCA=="],
"@tailwindcss/oxide-linux-arm64-musl": ["@tailwindcss/oxide-linux-arm64-musl@4.2.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-WZA0CHRL/SP1TRbA5mp9htsppSEkWuQ4KsSUumYQnyl8ZdT39ntwqmz4IUHGN6p4XdSlYfJwM4rRzZLShHsGAQ=="],
"@tailwindcss/oxide-linux-x64-gnu": ["@tailwindcss/oxide-linux-x64-gnu@4.1.12", "", { "os": "linux", "cpu": "x64" }, "sha512-xYfqYLjvm2UQ3TZggTGrwxjYaLB62b1Wiysw/YE3Yqbh86sOMoTn0feF98PonP7LtjsWOWcXEbGqDL7zv0uW8Q=="],
"@tailwindcss/oxide-linux-x64-gnu": ["@tailwindcss/oxide-linux-x64-gnu@4.2.1", "", { "os": "linux", "cpu": "x64" }, "sha512-qMFzxI2YlBOLW5PhblzuSWlWfwLHaneBE0xHzLrBgNtqN6mWfs+qYbhryGSXQjFYB1Dzf5w+LN5qbUTPhW7Y5g=="],
"@tailwindcss/oxide-linux-x64-musl": ["@tailwindcss/oxide-linux-x64-musl@4.1.12", "", { "os": "linux", "cpu": "x64" }, "sha512-ha0pHPamN+fWZY7GCzz5rKunlv9L5R8kdh+YNvP5awe3LtuXb5nRi/H27GeL2U+TdhDOptU7T6Is7mdwh5Ar3A=="],
"@tailwindcss/oxide-linux-x64-musl": ["@tailwindcss/oxide-linux-x64-musl@4.2.1", "", { "os": "linux", "cpu": "x64" }, "sha512-5r1X2FKnCMUPlXTWRYpHdPYUY6a1Ar/t7P24OuiEdEOmms5lyqjDRvVY1yy9Rmioh+AunQ0rWiOTPE8F9A3v5g=="],
"@tailwindcss/oxide-wasm32-wasi": ["@tailwindcss/oxide-wasm32-wasi@4.1.12", "", { "dependencies": { "@emnapi/core": "^1.4.5", "@emnapi/runtime": "^1.4.5", "@emnapi/wasi-threads": "^1.0.4", "@napi-rs/wasm-runtime": "^0.2.12", "@tybys/wasm-util": "^0.10.0", "tslib": "^2.8.0" }, "cpu": "none" }, "sha512-4tSyu3dW+ktzdEpuk6g49KdEangu3eCYoqPhWNsZgUhyegEda3M9rG0/j1GV/JjVVsj+lG7jWAyrTlLzd/WEBg=="],
"@tailwindcss/oxide-wasm32-wasi": ["@tailwindcss/oxide-wasm32-wasi@4.2.1", "", { "dependencies": { "@emnapi/core": "^1.8.1", "@emnapi/runtime": "^1.8.1", "@emnapi/wasi-threads": "^1.1.0", "@napi-rs/wasm-runtime": "^1.1.1", "@tybys/wasm-util": "^0.10.1", "tslib": "^2.8.1" }, "cpu": "none" }, "sha512-MGFB5cVPvshR85MTJkEvqDUnuNoysrsRxd6vnk1Lf2tbiqNlXpHYZqkqOQalydienEWOHHFyyuTSYRsLfxFJ2Q=="],
"@tailwindcss/oxide-win32-arm64-msvc": ["@tailwindcss/oxide-win32-arm64-msvc@4.1.12", "", { "os": "win32", "cpu": "arm64" }, "sha512-iGLyD/cVP724+FGtMWslhcFyg4xyYyM+5F4hGvKA7eifPkXHRAUDFaimu53fpNg9X8dfP75pXx/zFt/jlNF+lg=="],
"@tailwindcss/oxide-win32-arm64-msvc": ["@tailwindcss/oxide-win32-arm64-msvc@4.2.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-YlUEHRHBGnCMh4Nj4GnqQyBtsshUPdiNroZj8VPkvTZSoHsilRCwXcVKnG9kyi0ZFAS/3u+qKHBdDc81SADTRA=="],
"@tailwindcss/oxide-win32-x64-msvc": ["@tailwindcss/oxide-win32-x64-msvc@4.1.12", "", { "os": "win32", "cpu": "x64" }, "sha512-NKIh5rzw6CpEodv/++r0hGLlfgT/gFN+5WNdZtvh6wpU2BpGNgdjvj6H2oFc8nCM839QM1YOhjpgbAONUb4IxA=="],
"@tailwindcss/postcss": ["@tailwindcss/[email protected]", "", { "dependencies": { "@alloc/quick-lru": "^5.2.0", "@tailwindcss/node": "4.1.12", "@tailwindcss/oxide": "4.1.12", "postcss": "^8.4.41", "tailwindcss": "4.1.12" } }, "sha512-5PpLYhCAwf9SJEeIsSmCDLgyVfdBhdBpzX1OJ87anT9IVR0Z9pjM0FNixCAUAHGnMBGB8K99SwAheXrT0Kh6QQ=="],
"@tailwindcss/oxide-win32-x64-msvc": ["@tailwindcss/oxide-win32-x64-msvc@4.2.1", "", { "os": "win32", "cpu": "x64" }, "sha512-rbO34G5sMWWyrN/idLeVxAZgAKWrn5LiR3/I90Q9MkA67s6T1oB0xtTe+0heoBvHSpbU9Mk7i6uwJnpo4u21XQ=="],
"@tailwindcss/vite": ["@tailwindcss/[email protected]", "", { "dependencies": { "@tailwindcss/node": "4.2.2", "@tailwindcss/oxide": "4.2.2", "tailwindcss": "4.2.2" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-mEiF5HO1QqCLXoNEfXVA1Tzo+cYsrqV7w9Juj2wdUFyW07JRenqMG225MvPwr3ZD9N1bFQj46X7r33iHxLUW0w=="],
@@ -1320,8 +1313,6 @@
"array-iterate": ["[email protected]", "", {}, "sha512-I1jXZMjAgCMmxT4qxXfPXa6SthSoE8h6gkSI9BGGNv8mP8G/v0blc+qFnZu6K42vTOiuME596QaLO0TP3Lk0xg=="],
"array-timsort": ["[email protected]", "", {}, "sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ=="],
"asap": ["[email protected]", "", {}, "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA=="],
"assertion-error": ["[email protected]", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="],
@@ -1440,8 +1431,6 @@
"chokidar": ["[email protected]", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="],
"chownr": ["[email protected]", "", {}, "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g=="],
"chrome-launcher": ["[email protected]", "", { "dependencies": { "@types/node": "*", "escape-string-regexp": "^4.0.0", "is-wsl": "^2.2.0", "lighthouse-logger": "^1.0.0" }, "bin": { "print-chrome-path": "bin/print-chrome-path.js" } }, "sha512-zdLEwNo3aUVzIhKhTtXfxhdvZhUghrnmkvcAq2NoDd+LeOHKf03H5jwZ8T/STsAlzyALkBVK552iaG1fGf1xVQ=="],
"chromium-edge-launcher": ["[email protected]", "", { "dependencies": { "@types/node": "*", "escape-string-regexp": "^4.0.0", "is-wsl": "^2.2.0", "lighthouse-logger": "^1.0.0", "mkdirp": "^1.0.4", "rimraf": "^3.0.2" } }, "sha512-JfJjUnq25y9yg4FABRRVPmBGWPZZi+AQXT4mxupb67766/0UlhG8PAZCz6xzEMXTbW3CsSoE8PcCWA49n35mKg=="],
@@ -1476,14 +1465,10 @@
"color-string": ["[email protected]", "", { "dependencies": { "color-name": "^1.0.0", "simple-swizzle": "^0.2.2" } }, "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg=="],
"colorjs.io": ["[email protected]", "", {}, "sha512-c/h/8uAmPydQcriRdX8UTAFHj6SpSHFHBA8LvMikvYWAVApPTwg/pyOXNsGmaCBd6L/EeDlRHSNhTtnIFp/qsg=="],
"comma-separated-tokens": ["[email protected]", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="],
"commander": ["[email protected]", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="],
"comment-json": ["[email protected]", "", { "dependencies": { "array-timsort": "^1.0.3", "esprima": "^4.0.1" } }, "sha512-R2rze/hDX30uul4NZoIZ76ImSJLFxn/1/ZxtKC1L77y2X1k+yYu1joKbAtMA2Fg3hZrTOiw0I5mwVMo0cf250w=="],
"common-ancestor-path": ["[email protected]", "", {}, "sha512-dnN3ibLeoRf2HNC+OlCiNc5d2zxbLJXOtiZUudNFSXZrNSydxcCsSpRzXwfu7BBWCIfHPw+xTayeBvJCP/D8Ng=="],
"compressible": ["[email protected]", "", { "dependencies": { "mime-db": ">= 1.43.0 < 2" } }, "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg=="],
@@ -1528,6 +1513,8 @@
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"culori": ["[email protected]", "", {}, "sha512-1+BhOB8ahCn4O0cep0Sh2l9KCOfOdY+BXJnKMHFFzDEouSr/el18QwXEMRlOj9UY5nCeA8UN3a/82rUWRBeyBw=="],
"date-fns": ["[email protected]", "", {}, "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg=="],
"debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
@@ -2240,8 +2227,6 @@
"minipass": ["[email protected]", "", {}, "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="],
"minizlib": ["[email protected]", "", { "dependencies": { "minipass": "^7.1.2" } }, "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw=="],
"mkdirp": ["[email protected]", "", { "bin": { "mkdirp": "bin/cmd.js" } }, "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw=="],
"mrmime": ["[email protected]", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="],
@@ -2264,8 +2249,6 @@
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
"nativewind": ["[email protected]", "", { "dependencies": { "tailwindcss-safe-area": "^1.1.0" }, "peerDependencies": { "react-native-css": "^3.0.1", "tailwindcss": ">4.1.11" } }, "sha512-cbl1GzzY55NL2IG35AaAVfrL4+bCh77sa39aST5/o7xy3TLPthAtzhNPstnrCn+DtIglTnXOlOJGFrX2WdhI6w=="],
"negotiator": ["[email protected]", "", {}, "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg=="],
"neotraverse": ["[email protected]", "", {}, "sha512-Z4SmBUweYa09+o6pG+eASabEpP6QkQ70yHj351pQoEXIs8uHbaU2DWVmzBANKgflPa47A50PtB2+NgRpQvr7vA=="],
@@ -2458,8 +2441,6 @@
"react-native": ["[email protected]", "", { "dependencies": { "@jest/create-cache-key-function": "^29.7.0", "@react-native/assets-registry": "0.83.4", "@react-native/codegen": "0.83.4", "@react-native/community-cli-plugin": "0.83.4", "@react-native/gradle-plugin": "0.83.4", "@react-native/js-polyfills": "0.83.4", "@react-native/normalize-colors": "0.83.4", "@react-native/virtualized-lists": "0.83.4", "abort-controller": "^3.0.0", "anser": "^1.4.9", "ansi-regex": "^5.0.0", "babel-jest": "^29.7.0", "babel-plugin-syntax-hermes-parser": "0.32.0", "base64-js": "^1.5.1", "commander": "^12.0.0", "flow-enums-runtime": "^0.0.6", "glob": "^7.1.1", "hermes-compiler": "0.14.1", "invariant": "^2.2.4", "jest-environment-node": "^29.7.0", "memoize-one": "^5.0.0", "metro-runtime": "^0.83.3", "metro-source-map": "^0.83.3", "nullthrows": "^1.1.1", "pretty-format": "^29.7.0", "promise": "^8.3.0", "react-devtools-core": "^6.1.5", "react-refresh": "^0.14.0", "regenerator-runtime": "^0.13.2", "scheduler": "0.27.0", "semver": "^7.1.3", "stacktrace-parser": "^0.1.10", "whatwg-fetch": "^3.0.0", "ws": "^7.5.10", "yargs": "^17.6.2" }, "peerDependencies": { "@types/react": "^19.1.1", "react": "^19.2.0" }, "optionalPeers": ["@types/react"], "bin": { "react-native": "cli.js" } }, "sha512-H5Wco3UJyY6zZsjoBayY8RM9uiAEQ3FeG4G2NAt+lr9DO43QeqPlVe9xxxYEukMkEmeIhNjR70F6bhXuWArOMQ=="],
"react-native-css": ["[email protected]", "", { "dependencies": { "@types/debug": "^4.1.12", "babel-plugin-react-compiler": "^19.1.0-rc.2", "colorjs.io": "0.6.0-alpha.1", "comment-json": "^4.2.5", "debug": "^4.4.1" }, "peerDependencies": { "@expo/metro-config": ">=54", "lightningcss": ">=1.27.0", "react": ">=19", "react-native": ">=0.81" } }, "sha512-xsU9T5MleHI/DDmY72A7ZikbkDfDNkMrAEichOJW2bBUMxPzAJPrFk9ys4cXYk4gLFaR11y23EccOJ+JT6Iusw=="],
"react-native-fit-image": ["[email protected]", "", { "dependencies": { "prop-types": "^15.5.10" } }, "sha512-Wl3Vq2DQzxgsWKuW4USfck9zS7YzhvLNPpkwUUCF90bL32e1a0zOVQ3WsJILJOwzmPdHfzZmWasiiAUNBkhNkg=="],
"react-native-gesture-handler": ["[email protected]", "", { "dependencies": { "@egjs/hammerjs": "^2.0.17", "hoist-non-react-statics": "^3.3.0", "invariant": "^2.2.4" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-xIUBDo5ktmJs++0fZlavQNvDEE4PsihWhSeJsJtoz4Q6p0MiTM9TgrTgfEgzRR36qGPytFoeq+ShLrVwGdpUdA=="],
@@ -2706,12 +2687,8 @@
"tailwindcss": ["[email protected]", "", {}, "sha512-DzFtxOi+7NsFf7DBtI3BJsynR+0Yp6etH+nRPTbpWnS2pZBaSksv/JGctNwSWzbFjp0vxSqknaUylseZqMDGrA=="],
"tailwindcss-safe-area": ["[email protected]", "", { "peerDependencies": { "tailwindcss": "^4.0.0" } }, "sha512-RoxnW1zAjBWC3XK+row7Qj5toRMRlKNN/p3FLXb6fTGKxDGWT6JP/mcNX1yf09xRficQ308hbwiedgniepSp1Q=="],
"tapable": ["[email protected]", "", {}, "sha512-1MOpMXuhGzGL5TTCZFItxCc0AARf1EZFQkGqMm7ERKj8+Hgr5oLvJOVFcC+lRmR8hCe2S3jC4T5D7Vg/d7/fhA=="],
"tar": ["[email protected]", "", { "dependencies": { "@isaacs/fs-minipass": "^4.0.0", "chownr": "^3.0.0", "minipass": "^7.1.2", "minizlib": "^3.1.0", "yallist": "^5.0.0" } }, "sha512-tOG/7GyXpFevhXVh8jOPJrmtRpOTsYqUIkVdVooZYJS/z8WhfQUX8RJILmeuJNinGAMSu1veBr4asSHFt5/hng=="],
"terminal-link": ["[email protected]", "", { "dependencies": { "ansi-escapes": "^4.2.1", "supports-hyperlinks": "^2.0.0" } }, "sha512-un0FmiRUQNr5PJqy9kP7c40F5BOfpGlYTrxonDChEZB7pzZxRNp/bt+ymiy9/npwXya9KH99nJ/GXFIiUkYGFQ=="],
"terser": ["[email protected]", "", { "dependencies": { "@jridgewell/source-map": "^0.3.3", "acorn": "^8.15.0", "commander": "^2.20.0", "source-map-support": "~0.5.20" }, "bin": { "terser": "bin/terser" } }, "sha512-vzCjQO/rgUuK9sf8VJZvjqiqiHFaZLnOiimmUuOKODxWL8mm/xua7viT7aqX7dgPY60otQjUotzFMmCB4VdmqQ=="],
@@ -2830,6 +2807,8 @@
"universalify": ["[email protected]", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="],
"uniwind": ["[email protected]", "", { "dependencies": { "@tailwindcss/node": "4.2.1", "@tailwindcss/oxide": "4.2.1", "culori": "4.0.2", "lightningcss": "1.30.1" }, "peerDependencies": { "react": ">=19.0.0", "react-native": ">=0.81.0", "tailwindcss": ">=4" } }, "sha512-skT0I/PFGajygQPGJ20sYbqc3HxmcOMkfQWy51Ha6eXXJWRJh6vYiy7jUJvLFwdzWlfX1g+Z8oC/SpxgRB5R+g=="],
"unpipe": ["[email protected]", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
"unplugin": ["[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "acorn": "^8.15.0", "picomatch": "^4.0.3", "webpack-virtual-modules": "^0.6.2" } }, "sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww=="],
@@ -2950,7 +2929,7 @@
"y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
"yallist": ["yallist@5.0.0", "", {}, "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw=="],
"yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
"yaml": ["[email protected]", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg=="],
@@ -3056,13 +3035,15 @@
"@shikijs/transformers/@shikijs/types": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ=="],
"@tailwindcss/node/tailwindcss": ["[email protected]", "", {}, "sha512-/tBrSQ36vCleJkAOsy9kbNTgaxvGbyOamC30PRePTQe/o1MFwEKHQk4Cn7BNGaPtjp+PuUrByJehM1hgxfq4sw=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" }, "bundled": true }, "sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/wasi-threads": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w=="],
"@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@0.2.12", "", { "dependencies": { "@emnapi/core": "^1.4.3", "@emnapi/runtime": "^1.4.3", "@tybys/wasm-util": "^0.10.0" }, "bundled": true }, "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ=="],
"@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.3", "", { "dependencies": { "@tybys/wasm-util": "^0.10.1" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" }, "bundled": true }, "sha512-xK9sGVbJWYb08+mTJt3/YV24WxvxpXcXtP6B172paPZ+Ts69Re9dAr7lKwJoeIx8OoeuimEiRZ7umkiUVClmmQ=="],
"@tailwindcss/oxide-wasm32-wasi/@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],
@@ -3212,8 +3193,6 @@
"react-native/glob": ["[email protected]", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="],
"react-native-css/babel-plugin-react-compiler": ["[email protected]", "", { "dependencies": { "@babel/types": "^7.26.0" } }, "sha512-E3kaokBhWDLf7ZD8fuYjYn0ZJHYZ+3EHtAWCdX2hl4lpu1z9S/Xr99sxhx2bTCVB41oIesz9FtM8f4INsrZaOw=="],
"react-native-reanimated/react-native-is-edge-to-edge": ["[email protected]", "", { "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-FLbPWl/MyYQWz+KwqOZsSyj2JmLKglHatd3xLZWskXOpRaio4LfEDEz8E/A6uD8QoTHW6Aobw1jbEwK7KMgR7Q=="],
"react-native-reanimated/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q=="],
@@ -3292,8 +3271,6 @@
"yargs/yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
"@babel/helper-compilation-targets/lru-cache/yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
"@electron/get/fs-extra/jsonfile": ["[email protected]", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],
"@electron/get/fs-extra/universalify": ["[email protected]", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],
@@ -6,6 +6,10 @@ import type {
ServerLifecycleWelcomePayload,
TerminalEvent,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import * as Option from "effect/Option";
import { pipe } from "effect/Function";
import type { KnownEnvironment } from "./knownEnvironment";
import type { WsRpcClient } from "./wsRpcClient";
@@ -137,14 +141,20 @@ function createOrchestrationRecoveryCoordinator() {
markEventBatchApplied<T extends Readonly<{ sequence: number }>>(
events: ReadonlyArray<T>,
): ReadonlyArray<T> {
const nextEvents = events
.filter((event) => event.sequence > state.latestSequence)
.toSorted((left, right) => left.sequence - right.sequence);
const nextEvents = pipe(
events,
Arr.filter((event) => event.sequence > state.latestSequence),
Arr.sortWith((event) => event.sequence, Order.Number),
);
if (nextEvents.length === 0) {
return [];
}
const latestSequence = nextEvents.at(-1)?.sequence ?? state.latestSequence;
const latestSequence = Arr.last(nextEvents).pipe(
Option.map((event) => event.sequence),
Option.getOrElse(() => state.latestSequence),
);
state = {
...state,
latestSequence,
@@ -0,0 +1,264 @@
import type {
GitActionProgressEvent,
GitCreateBranchResult,
GitCreateWorktreeResult,
GitCheckoutResult,
GitPullResult,
GitRunStackedActionResult,
GitStatusResult,
} from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
type GitActionClient,
createGitActionManager,
EMPTY_GIT_ACTION_STATE,
} from "./gitActionState";
let atomRegistry = AtomRegistry.make();
function resetAtomRegistry() {
atomRegistry.dispose();
atomRegistry = AtomRegistry.make();
}
function createDeferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
const TARGET = { environmentId: "env-local", cwd: "/repo" } as const;
const BASE_STATUS: GitStatusResult = {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/test",
hasWorkingTreeChanges: true,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
function createPhaseStartedEvent(): Extract<GitActionProgressEvent, { kind: "phase_started" }> {
return {
actionId: "action-123",
cwd: "/repo",
action: "commit_push",
kind: "phase_started",
phase: "commit",
label: "Committing...",
};
}
function createHookStartedEvent(): Extract<GitActionProgressEvent, { kind: "hook_started" }> {
return {
actionId: "action-123",
cwd: "/repo",
action: "commit_push",
kind: "hook_started",
hookName: "post-commit",
};
}
function createHookOutputEvent(): Extract<GitActionProgressEvent, { kind: "hook_output" }> {
return {
actionId: "action-123",
cwd: "/repo",
action: "commit_push",
kind: "hook_output",
hookName: "post-commit",
stream: "stdout",
text: "hook output",
};
}
function createHookFinishedEvent(): Extract<GitActionProgressEvent, { kind: "hook_finished" }> {
return {
actionId: "action-123",
cwd: "/repo",
action: "commit_push",
kind: "hook_finished",
hookName: "post-commit",
exitCode: 0,
durationMs: 12,
};
}
function createActionFinishedEvent(): Extract<GitActionProgressEvent, { kind: "action_finished" }> {
return {
actionId: "action-123",
cwd: "/repo",
action: "commit_push",
kind: "action_finished",
result: {
action: "commit_push",
branch: { status: "skipped_not_requested" },
commit: { status: "created", commitSha: "abc123", subject: "Test commit" },
push: {
status: "pushed",
branch: "feature/test",
upstreamBranch: "origin/feature/test",
},
pr: { status: "skipped_not_requested" },
toast: {
title: "Done",
description: "Action finished",
cta: { kind: "none" },
},
} satisfies GitRunStackedActionResult,
};
}
function createMockClient() {
const refreshDeferred = createDeferred<GitStatusResult>();
const pullDeferred = createDeferred<GitPullResult>();
const checkoutDeferred = createDeferred<GitCheckoutResult>();
const createBranchDeferred = createDeferred<GitCreateBranchResult>();
const createWorktreeDeferred = createDeferred<GitCreateWorktreeResult>();
const initDeferred = createDeferred<void>();
const runStackedActionDeferred = createDeferred<GitRunStackedActionResult>();
let runStackedActionProgressListener: ((event: GitActionProgressEvent) => void) | null = null;
const client: GitActionClient = {
refreshStatus: vi.fn(() => refreshDeferred.promise),
pull: vi.fn(() => pullDeferred.promise),
checkout: vi.fn(() => checkoutDeferred.promise),
createBranch: vi.fn(() => createBranchDeferred.promise),
createWorktree: vi.fn(() => createWorktreeDeferred.promise),
init: vi.fn(() => initDeferred.promise),
runStackedAction: vi.fn((_, options) => {
runStackedActionProgressListener = options?.onProgress ?? null;
return runStackedActionDeferred.promise;
}),
};
return {
client,
refreshDeferred,
pullDeferred,
checkoutDeferred,
createBranchDeferred,
createWorktreeDeferred,
initDeferred,
runStackedActionDeferred,
emitProgress(event: GitActionProgressEvent) {
runStackedActionProgressListener?.(event);
},
};
}
describe("createGitActionManager", () => {
afterEach(() => {
resetAtomRegistry();
});
it("tracks refreshStatus progress and clears state on success", async () => {
const mock = createMockClient();
const manager = createGitActionManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
const promise = manager.refreshStatus(TARGET, mock.client);
expect(manager.getSnapshot(TARGET)).toMatchObject({
isRunning: true,
operation: "refresh_status",
currentLabel: "Refreshing git status",
error: null,
});
mock.refreshDeferred.resolve(BASE_STATUS);
await expect(promise).resolves.toEqual(BASE_STATUS);
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_GIT_ACTION_STATE);
});
it("tracks runStackedAction progress events", async () => {
const mock = createMockClient();
const manager = createGitActionManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
getActionId: () => "action-123",
});
const promise = manager.runStackedAction(
TARGET,
{ action: "commit_push", commitMessage: "Test commit" },
{ client: mock.client, gitStatus: BASE_STATUS },
);
expect(manager.getSnapshot(TARGET)).toMatchObject({
isRunning: true,
operation: "run_stacked_action",
actionId: "action-123",
currentLabel: "Committing...",
error: null,
});
mock.emitProgress(createPhaseStartedEvent());
expect(manager.getSnapshot(TARGET).currentLabel).toBe("Committing...");
mock.emitProgress(createHookStartedEvent());
expect(manager.getSnapshot(TARGET)).toMatchObject({
currentLabel: "Running post-commit...",
hookName: "post-commit",
isRunning: true,
});
mock.emitProgress(createHookOutputEvent());
expect(manager.getSnapshot(TARGET).lastOutputLine).toBe("hook output");
mock.emitProgress(createHookFinishedEvent());
expect(manager.getSnapshot(TARGET)).toMatchObject({
currentLabel: "Committing...",
hookName: null,
lastOutputLine: null,
});
const result = createActionFinishedEvent().result;
mock.runStackedActionDeferred.resolve(result);
await expect(promise).resolves.toEqual(result);
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_GIT_ACTION_STATE);
});
it("stores the error when an operation fails", async () => {
const mock = createMockClient();
const manager = createGitActionManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
const promise = manager.pull(TARGET, mock.client);
mock.pullDeferred.reject(new Error("Pull failed."));
await expect(promise).rejects.toThrow("Pull failed.");
expect(manager.getSnapshot(TARGET)).toMatchObject({
isRunning: false,
operation: "pull",
currentLabel: null,
error: "Pull failed.",
});
});
it("returns null when no client is available", async () => {
const manager = createGitActionManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
await expect(manager.checkout(TARGET, { branch: "main" })).resolves.toBeNull();
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_GIT_ACTION_STATE);
});
});
@@ -0,0 +1,444 @@
import type {
GitActionProgressEvent,
GitCreateBranchInput,
GitCreateBranchResult,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
GitCheckoutInput,
GitCheckoutResult,
GitPullInput,
GitPullResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStackedAction,
GitStatusResult,
} from "@t3tools/contracts";
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
import { buildGitActionProgressStages } from "./gitActions";
import type { WsRpcClient } from "./wsRpcClient";
export type GitActionOperation =
| "refresh_status"
| "run_stacked_action"
| "pull"
| "checkout"
| "create_branch"
| "create_worktree"
| "init";
export interface GitActionState {
readonly isRunning: boolean;
readonly operation: GitActionOperation | null;
readonly actionId: string | null;
readonly action: GitStackedAction | null;
readonly currentLabel: string | null;
readonly currentPhaseLabel: string | null;
readonly hookName: string | null;
readonly lastOutputLine: string | null;
readonly phaseStartedAtMs: number | null;
readonly hookStartedAtMs: number | null;
readonly error: string | null;
}
export interface GitActionTarget {
readonly environmentId: string | null;
readonly cwd: string | null;
}
export type GitActionClient = Pick<
WsRpcClient["git"],
| "refreshStatus"
| "runStackedAction"
| "pull"
| "checkout"
| "createBranch"
| "createWorktree"
| "init"
>;
export const EMPTY_GIT_ACTION_STATE = Object.freeze<GitActionState>({
isRunning: false,
operation: null,
actionId: null,
action: null,
currentLabel: null,
currentPhaseLabel: null,
hookName: null,
lastOutputLine: null,
phaseStartedAtMs: null,
hookStartedAtMs: null,
error: null,
});
const knownGitActionKeys = new Set<string>();
export const gitActionStateAtom = Atom.family((key: string) => {
knownGitActionKeys.add(key);
return Atom.make(EMPTY_GIT_ACTION_STATE).pipe(
Atom.keepAlive,
Atom.withLabel(`git-action:${key}`),
);
});
export const EMPTY_GIT_ACTION_ATOM = Atom.make(EMPTY_GIT_ACTION_STATE).pipe(
Atom.keepAlive,
Atom.withLabel("git-action:null"),
);
export function getGitActionTargetKey(target: GitActionTarget): string | null {
if (target.environmentId === null || target.cwd === null) {
return null;
}
return `${target.environmentId}:${target.cwd}`;
}
export function applyGitActionProgressEvent(
current: GitActionState,
event: GitActionProgressEvent,
): GitActionState {
const now = Date.now();
switch (event.kind) {
case "action_started":
return {
...current,
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
phaseStartedAtMs: now,
hookStartedAtMs: null,
hookName: null,
lastOutputLine: null,
error: null,
};
case "phase_started":
return {
...current,
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
currentLabel: event.label,
currentPhaseLabel: event.label,
phaseStartedAtMs: now,
hookStartedAtMs: null,
hookName: null,
lastOutputLine: null,
error: null,
};
case "hook_started":
return {
...current,
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
currentLabel: `Running ${event.hookName}...`,
hookName: event.hookName,
hookStartedAtMs: now,
lastOutputLine: null,
error: null,
};
case "hook_output":
return {
...current,
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
lastOutputLine: event.text,
error: null,
};
case "hook_finished":
return {
...current,
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
currentLabel: current.currentPhaseLabel,
hookName: null,
hookStartedAtMs: null,
lastOutputLine: null,
error: null,
};
case "action_finished":
return {
...current,
isRunning: false,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
error: null,
};
case "action_failed":
return {
...EMPTY_GIT_ACTION_STATE,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
error: event.message,
};
}
}
export interface GitActionManagerConfig {
readonly getRegistry: () => AtomRegistry.AtomRegistry;
readonly getClient: (environmentId: string) => GitActionClient | null;
readonly getActionId?: () => string;
}
export function createGitActionManager(config: GitActionManagerConfig) {
function setState(targetKey: string, nextState: GitActionState): void {
config.getRegistry().set(gitActionStateAtom(targetKey), nextState);
}
function startOperation(
targetKey: string,
input: {
readonly operation: GitActionOperation;
readonly actionId?: string;
readonly action?: GitStackedAction;
readonly label: string;
},
): void {
setState(targetKey, {
isRunning: true,
operation: input.operation,
actionId: input.actionId ?? null,
action: input.action ?? null,
currentLabel: input.label,
currentPhaseLabel: input.label,
hookName: null,
lastOutputLine: null,
phaseStartedAtMs: Date.now(),
hookStartedAtMs: null,
error: null,
});
}
function finishOperation(targetKey: string): void {
setState(targetKey, EMPTY_GIT_ACTION_STATE);
}
function failOperation(
targetKey: string,
error: unknown,
input: {
readonly operation: GitActionOperation;
readonly actionId?: string;
readonly action?: GitStackedAction;
},
): void {
setState(targetKey, {
...EMPTY_GIT_ACTION_STATE,
operation: input.operation,
actionId: input.actionId ?? null,
action: input.action ?? null,
error: error instanceof Error ? error.message : "Git action failed.",
});
}
async function runOperation<TResult>(
target: GitActionTarget,
input: {
readonly operation: GitActionOperation;
readonly label: string;
readonly actionId?: string;
readonly action?: GitStackedAction;
readonly client?: GitActionClient | undefined;
readonly execute: (client: GitActionClient) => Promise<TResult>;
},
): Promise<TResult | null> {
const targetKey = getGitActionTargetKey(target);
if (targetKey === null || target.environmentId === null || target.cwd === null) {
return null;
}
const resolved = input.client ?? config.getClient(target.environmentId);
if (!resolved) {
return null;
}
startOperation(targetKey, input);
try {
const result = await input.execute(resolved);
finishOperation(targetKey);
return result;
} catch (error) {
failOperation(targetKey, error, input);
throw error;
}
}
function getSnapshot(target: GitActionTarget): GitActionState {
const targetKey = getGitActionTargetKey(target);
if (targetKey === null) {
return EMPTY_GIT_ACTION_STATE;
}
return config.getRegistry().get(gitActionStateAtom(targetKey));
}
async function refreshStatus(
target: GitActionTarget,
client?: GitActionClient,
options?: { readonly quiet?: boolean },
): Promise<Awaited<ReturnType<GitActionClient["refreshStatus"]>> | null> {
if (options?.quiet) {
if (target.environmentId === null || target.cwd === null) {
return null;
}
const resolved = client ?? config.getClient(target.environmentId);
return resolved ? resolved.refreshStatus({ cwd: target.cwd }) : null;
}
return runOperation(target, {
operation: "refresh_status",
label: "Refreshing git status",
client,
execute: (resolved) => resolved.refreshStatus({ cwd: target.cwd! }),
});
}
async function pull(
target: GitActionTarget,
client?: GitActionClient,
options?: { readonly label?: string },
): Promise<GitPullResult | null> {
return runOperation(target, {
operation: "pull",
label: options?.label ?? "Pulling latest changes",
client,
execute: (resolved) => resolved.pull({ cwd: target.cwd! } satisfies GitPullInput),
});
}
async function checkout(
target: GitActionTarget,
input: Omit<GitCheckoutInput, "cwd">,
client?: GitActionClient,
options?: { readonly label?: string },
): Promise<GitCheckoutResult | null> {
return runOperation(target, {
operation: "checkout",
label: options?.label ?? "Checking out branch",
client,
execute: (resolved) => resolved.checkout({ cwd: target.cwd!, ...input }),
});
}
async function createBranch(
target: GitActionTarget,
input: Omit<GitCreateBranchInput, "cwd">,
client?: GitActionClient,
options?: { readonly label?: string },
): Promise<GitCreateBranchResult | null> {
return runOperation(target, {
operation: "create_branch",
label: options?.label ?? "Creating branch",
client,
execute: (resolved) => resolved.createBranch({ cwd: target.cwd!, ...input }),
});
}
async function createWorktree(
target: GitActionTarget,
input: Omit<GitCreateWorktreeInput, "cwd">,
client?: GitActionClient,
options?: { readonly label?: string },
): Promise<GitCreateWorktreeResult | null> {
return runOperation(target, {
operation: "create_worktree",
label: options?.label ?? "Creating worktree",
client,
execute: (resolved) => resolved.createWorktree({ cwd: target.cwd!, ...input }),
});
}
async function init(
target: GitActionTarget,
client?: GitActionClient,
options?: { readonly label?: string },
): Promise<Awaited<ReturnType<GitActionClient["init"]>> | null> {
return runOperation(target, {
operation: "init",
label: options?.label ?? "Initializing git repository",
client,
execute: (resolved) => resolved.init({ cwd: target.cwd! }),
});
}
async function runStackedAction(
target: GitActionTarget,
input: Omit<GitRunStackedActionInput, "cwd" | "actionId"> & { readonly actionId?: string },
options?: {
readonly client?: GitActionClient;
readonly gitStatus?: GitStatusResult | null;
readonly onProgress?: (event: GitActionProgressEvent) => void;
},
): Promise<GitRunStackedActionResult | null> {
const actionId =
input.actionId ??
config.getActionId?.() ??
`git-action-${Date.now()}-${Math.random().toString(36).slice(2)}`;
const targetKey = getGitActionTargetKey(target);
return runOperation(target, {
operation: "run_stacked_action",
label:
buildGitActionProgressStages({
action: input.action,
hasCustomCommitMessage: Boolean(input.commitMessage?.trim()),
hasWorkingTreeChanges: options?.gitStatus?.hasWorkingTreeChanges ?? false,
featureBranch: input.featureBranch ?? false,
shouldPushBeforePr:
input.action === "create_pr" &&
(!(options?.gitStatus?.hasUpstream ?? false) ||
(options?.gitStatus?.aheadCount ?? 0) > 0),
})[0] ?? "Running git action",
actionId,
action: input.action,
client: options?.client,
execute: async (resolved) => {
const result = await resolved.runStackedAction(
{
cwd: target.cwd!,
actionId,
...input,
},
{
onProgress: (event) => {
if (targetKey !== null) {
const current = getSnapshot(target);
setState(targetKey, applyGitActionProgressEvent(current, event));
}
options?.onProgress?.(event);
},
},
);
return result;
},
});
}
function reset(): void {
for (const key of knownGitActionKeys) {
setState(key, EMPTY_GIT_ACTION_STATE);
}
}
return {
getSnapshot,
refreshStatus,
pull,
checkout,
createBranch,
createWorktree,
init,
runStackedAction,
reset,
};
}
@@ -0,0 +1,161 @@
import type { GitListBranchesResult } from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
createGitBranchManager,
EMPTY_GIT_BRANCH_STATE,
gitBranchStateAtom,
type GitBranchClient,
} from "./gitBranchState";
let atomRegistry = AtomRegistry.make();
function resetAtomRegistry() {
atomRegistry.dispose();
atomRegistry = AtomRegistry.make();
}
const TARGET = { environmentId: "env-local", cwd: "/repo" } as const;
const FIRST_PAGE: GitListBranchesResult = {
branches: [
{ name: "main", current: true, isDefault: true, worktreePath: null },
{ name: "feature/a", current: false, isDefault: false, worktreePath: null },
],
isRepo: true,
hasOriginRemote: true,
nextCursor: 2,
totalCount: 3,
};
const SECOND_PAGE: GitListBranchesResult = {
branches: [{ name: "feature/b", current: false, isDefault: false, worktreePath: null }],
isRepo: true,
hasOriginRemote: true,
nextCursor: null,
totalCount: 3,
};
function createMockClient() {
const listBranches = vi.fn(async (input: Parameters<GitBranchClient["listBranches"]>[0]) => {
if (input.query === "feature") {
return {
...FIRST_PAGE,
branches: FIRST_PAGE.branches.filter((branch) => branch.name.includes("feature")),
nextCursor: null,
totalCount: 2,
} satisfies GitListBranchesResult;
}
if (input.cursor === 2) {
return SECOND_PAGE;
}
return FIRST_PAGE;
});
return {
client: { listBranches } satisfies GitBranchClient,
listBranches,
};
}
describe("createGitBranchManager", () => {
afterEach(() => {
resetAtomRegistry();
});
it("loads the first page and stores it in atom state", async () => {
const mock = createMockClient();
const manager = createGitBranchManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
const promise = manager.load(TARGET, mock.client, { limit: 100 });
expect(manager.getSnapshot(TARGET)).toEqual({
data: null,
isPending: true,
error: null,
});
await expect(promise).resolves.toEqual(FIRST_PAGE);
expect(manager.getSnapshot(TARGET)).toEqual({
data: FIRST_PAGE,
isPending: false,
error: null,
});
expect(mock.listBranches).toHaveBeenCalledWith({ cwd: "/repo", limit: 100 });
});
it("loads the next page and appends branches", async () => {
const mock = createMockClient();
const manager = createGitBranchManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
await manager.load(TARGET, mock.client);
const next = await manager.loadNext(TARGET, mock.client);
expect(next).toEqual({
...SECOND_PAGE,
branches: [...FIRST_PAGE.branches, ...SECOND_PAGE.branches],
});
expect(manager.getSnapshot(TARGET)).toEqual({
data: {
...SECOND_PAGE,
branches: [...FIRST_PAGE.branches, ...SECOND_PAGE.branches],
},
isPending: false,
error: null,
});
});
it("stores query-specific state independently", async () => {
const mock = createMockClient();
const manager = createGitBranchManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
const queriedTarget = { ...TARGET, query: "feature" } as const;
const queried = await manager.load(queriedTarget, mock.client);
expect(queried?.branches.map((branch) => branch.name)).toEqual(["feature/a"]);
expect(manager.getSnapshot(TARGET).data).toBeNull();
expect(manager.getSnapshot(queriedTarget).data?.branches.map((branch) => branch.name)).toEqual([
"feature/a",
]);
});
it("returns cached data when no client is available", async () => {
const manager = createGitBranchManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
atomRegistry.set(gitBranchStateAtom("env-local:/repo:"), {
data: FIRST_PAGE,
isPending: false,
error: null,
});
await expect(manager.load(TARGET)).resolves.toEqual(FIRST_PAGE);
});
it("resets state", async () => {
const mock = createMockClient();
const manager = createGitBranchManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
await manager.load(TARGET, mock.client);
manager.reset();
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_GIT_BRANCH_STATE);
});
});
@@ -0,0 +1,227 @@
import type { GitBranch, GitListBranchesInput, GitListBranchesResult } from "@t3tools/contracts";
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
import type { WsRpcClient } from "./wsRpcClient";
export interface GitBranchTarget {
readonly environmentId: string | null;
readonly cwd: string | null;
readonly query?: string | null;
}
export interface GitBranchState {
readonly data: GitListBranchesResult | null;
readonly isPending: boolean;
readonly error: string | null;
}
export type GitBranchClient = Pick<WsRpcClient["git"], "listBranches">;
export const EMPTY_GIT_BRANCH_STATE = Object.freeze<GitBranchState>({
data: null,
isPending: false,
error: null,
});
const INITIAL_GIT_BRANCH_STATE = Object.freeze<GitBranchState>({
data: null,
isPending: true,
error: null,
});
const knownGitBranchKeys = new Set<string>();
export const gitBranchStateAtom = Atom.family((key: string) => {
knownGitBranchKeys.add(key);
return Atom.make(EMPTY_GIT_BRANCH_STATE).pipe(
Atom.keepAlive,
Atom.withLabel(`git-branches:${key}`),
);
});
export const EMPTY_GIT_BRANCH_ATOM = Atom.make(EMPTY_GIT_BRANCH_STATE).pipe(
Atom.keepAlive,
Atom.withLabel("git-branches:null"),
);
function normalizeQuery(query: string | null | undefined): string {
return query?.trim() ?? "";
}
export function getGitBranchTargetKey(target: GitBranchTarget): string | null {
if (target.environmentId === null || target.cwd === null) {
return null;
}
return `${target.environmentId}:${target.cwd}:${normalizeQuery(target.query)}`;
}
function toErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : "Failed to load branches.";
}
function mergeBranches(
previous: ReadonlyArray<GitBranch>,
next: ReadonlyArray<GitBranch>,
): ReadonlyArray<GitBranch> {
const merged = new Map<string, GitBranch>();
for (const branch of previous) {
merged.set(branch.name, branch);
}
for (const branch of next) {
merged.set(branch.name, branch);
}
return [...merged.values()];
}
export interface GitBranchManagerConfig {
readonly getRegistry: () => AtomRegistry.AtomRegistry;
readonly getClient: (environmentId: string) => GitBranchClient | null;
}
export function createGitBranchManager(config: GitBranchManagerConfig) {
const inFlight = new Map<string, Promise<GitListBranchesResult | null>>();
function getSnapshot(target: GitBranchTarget): GitBranchState {
const targetKey = getGitBranchTargetKey(target);
if (targetKey === null) {
return EMPTY_GIT_BRANCH_STATE;
}
return config.getRegistry().get(gitBranchStateAtom(targetKey));
}
function setState(targetKey: string, nextState: GitBranchState): void {
config.getRegistry().set(gitBranchStateAtom(targetKey), nextState);
}
function markPending(targetKey: string): void {
const current = config.getRegistry().get(gitBranchStateAtom(targetKey));
setState(
targetKey,
current.data === null
? INITIAL_GIT_BRANCH_STATE
: { ...current, isPending: true, error: null },
);
}
function setData(targetKey: string, data: GitListBranchesResult): void {
setState(targetKey, {
data,
isPending: false,
error: null,
});
}
function setError(targetKey: string, error: unknown): void {
const current = config.getRegistry().get(gitBranchStateAtom(targetKey));
setState(targetKey, {
data: current.data,
isPending: false,
error: toErrorMessage(error),
});
}
async function load(
target: GitBranchTarget,
client?: GitBranchClient,
options?: {
readonly cursor?: number;
readonly limit?: number;
readonly append?: boolean;
},
): Promise<GitListBranchesResult | null> {
const targetKey = getGitBranchTargetKey(target);
if (targetKey === null || target.environmentId === null || target.cwd === null) {
return null;
}
const resolved = client ?? config.getClient(target.environmentId);
if (!resolved) {
return getSnapshot(target).data;
}
const inFlightKey = `${targetKey}:${options?.cursor ?? "start"}:${options?.append ? "append" : "replace"}`;
const existing = inFlight.get(inFlightKey);
if (existing) {
return existing;
}
markPending(targetKey);
const current = getSnapshot(target).data;
const request: GitListBranchesInput = {
cwd: target.cwd,
...(normalizeQuery(target.query).length > 0 ? { query: normalizeQuery(target.query) } : {}),
...(options?.cursor !== undefined ? { cursor: options.cursor } : {}),
...(options?.limit !== undefined ? { limit: options.limit } : {}),
};
const promise = resolved.listBranches(request).then(
(result) => {
const nextData =
options?.append && current
? {
...result,
branches: mergeBranches(current.branches, result.branches),
}
: result;
setData(targetKey, nextData);
return nextData;
},
(error) => {
setError(targetKey, error);
throw error;
},
);
inFlight.set(inFlightKey, promise);
try {
return await promise;
} finally {
inFlight.delete(inFlightKey);
}
}
async function loadNext(
target: GitBranchTarget,
client?: GitBranchClient,
options?: { readonly limit?: number },
): Promise<GitListBranchesResult | null> {
const current = getSnapshot(target).data;
if (!current?.nextCursor && current?.nextCursor !== 0) {
return current ?? null;
}
return load(target, client, {
cursor: current.nextCursor,
append: true,
...(options?.limit !== undefined ? { limit: options.limit } : {}),
});
}
function invalidate(target?: GitBranchTarget): void {
if (target) {
const targetKey = getGitBranchTargetKey(target);
if (targetKey !== null) {
setState(targetKey, EMPTY_GIT_BRANCH_STATE);
}
return;
}
for (const key of knownGitBranchKeys) {
setState(key, EMPTY_GIT_BRANCH_STATE);
}
}
function reset(): void {
invalidate();
}
return {
getSnapshot,
load,
loadNext,
invalidate,
reset,
};
}
@@ -0,0 +1,330 @@
import type { GitStatusResult } from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
import { afterEach, describe, expect, it, vi } from "vitest";
import { type GitStatusClient, createGitStatusManager } from "./gitStatusState";
/* ─── Test helpers ──────────────────────────────────────────────────── */
let atomRegistry = AtomRegistry.make();
function resetAtomRegistry() {
atomRegistry.dispose();
atomRegistry = AtomRegistry.make();
}
function registerListener<T>(listeners: Set<(event: T) => void>, listener: (event: T) => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
const BASE_STATUS: GitStatusResult = {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/push-status",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
function createMockClient(): {
client: GitStatusClient;
listeners: Set<(event: GitStatusResult) => void>;
emit: (event: GitStatusResult) => void;
} {
const listeners = new Set<(event: GitStatusResult) => void>();
const client: GitStatusClient = {
refreshStatus: vi.fn(async (input: { cwd: string }) => ({
...BASE_STATUS,
branch: `${input.cwd}-refreshed`,
})),
onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
registerListener(listeners, listener),
),
};
return {
client,
listeners,
emit: (event) => {
for (const listener of listeners) listener(event);
},
};
}
const PENDING = { data: null, error: null, cause: null, isPending: true };
const EMPTY = { data: null, error: null, cause: null, isPending: false };
const TARGET = { environmentId: "env-local", cwd: "/repo" } as const;
const FRESH_TARGET = { environmentId: "env-local", cwd: "/fresh" } as const;
const OTHER_ENV_TARGET = { environmentId: "env-remote", cwd: "/repo" } as const;
/* ─── Tests ─────────────────────────────────────────────────────────── */
describe("createGitStatusManager", () => {
afterEach(() => {
resetAtomRegistry();
});
describe("with explicit client (no reconnection)", () => {
it("starts in a pending state when watching", () => {
const { client } = createMockClient();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
manager.watch(TARGET, client);
expect(manager.getSnapshot(TARGET)).toEqual(PENDING);
manager.reset();
});
it("shares one subscription per cwd and updates the snapshot", () => {
const { client, listeners, emit } = createMockClient();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
const releaseA = manager.watch(TARGET, client);
const releaseB = manager.watch(TARGET, client);
expect(client.onStatus).toHaveBeenCalledOnce();
expect(manager.getSnapshot(TARGET)).toEqual(PENDING);
emit(BASE_STATUS);
expect(manager.getSnapshot(TARGET)).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: false,
});
releaseA();
expect(listeners.size).toBe(1);
releaseB();
expect(listeners.size).toBe(0);
});
it("refreshes via unary RPC without restarting the stream", async () => {
const { client, emit } = createMockClient();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
const release = manager.watch(TARGET, client);
emit(BASE_STATUS);
const refreshed = await manager.refresh(TARGET, client);
expect(client.onStatus).toHaveBeenCalledOnce();
expect(client.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
expect(refreshed).toEqual({ ...BASE_STATUS, branch: "/repo-refreshed" });
// Snapshot still reflects stream data, not the refresh response
expect(manager.getSnapshot(TARGET)).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: false,
});
release();
});
it("keeps subscriptions isolated by environment when cwds match", () => {
const local = createMockClient();
const remote = createMockClient();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
const releaseLocal = manager.watch(TARGET, local.client);
const releaseRemote = manager.watch(OTHER_ENV_TARGET, remote.client);
local.emit(BASE_STATUS);
remote.emit({ ...BASE_STATUS, branch: "remote-branch" });
expect(manager.getSnapshot(TARGET).data?.branch).toBe("feature/push-status");
expect(manager.getSnapshot(OTHER_ENV_TARGET).data?.branch).toBe("remote-branch");
releaseLocal();
releaseRemote();
});
it("returns null from refresh when no client is available", async () => {
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
await expect(manager.refresh(TARGET)).resolves.toBeNull();
});
it("returns empty state for null targets", () => {
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
expect(manager.getSnapshot({ environmentId: null, cwd: null })).toEqual(EMPTY);
});
});
describe("with subscribeClientChanges (reconnection)", () => {
it("waits for a delayed client registration", () => {
const connectionListeners = new Set<() => void>();
const clients = new Map<string, ReturnType<typeof createMockClient>>();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: (envId) => clients.get(envId)?.client ?? null,
getClientIdentity: (envId) => (clients.has(envId) ? envId : null),
subscribeClientChanges: (listener) => {
connectionListeners.add(listener);
return () => connectionListeners.delete(listener);
},
});
const release = manager.watch(TARGET);
expect(manager.getSnapshot(TARGET)).toEqual(PENDING);
// Register the client
const mock = createMockClient();
clients.set("env-local", mock);
for (const listener of connectionListeners) listener();
mock.emit(BASE_STATUS);
expect(manager.getSnapshot(TARGET)).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: false,
});
release();
});
it("resubscribes after client is removed and re-registered", () => {
const connectionListeners = new Set<() => void>();
const clients = new Map<string, ReturnType<typeof createMockClient>>();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: (envId) => clients.get(envId)?.client ?? null,
getClientIdentity: (envId) =>
clients.get(envId) ? `identity:${envId}:${clients.size}` : null,
subscribeClientChanges: (listener) => {
connectionListeners.add(listener);
return () => connectionListeners.delete(listener);
},
});
// Register first client and watch
const first = createMockClient();
clients.set("env-local", first);
const release = manager.watch(TARGET);
first.emit(BASE_STATUS);
expect(manager.getSnapshot(TARGET).data?.branch).toBe("feature/push-status");
// Remove client
clients.delete("env-local");
for (const listener of connectionListeners) listener();
expect(manager.getSnapshot(TARGET)).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: true,
});
// Register new client (different identity)
const second = createMockClient();
clients.set("env-local", second);
for (const listener of connectionListeners) listener();
second.emit({ ...BASE_STATUS, branch: "reconnected-branch" });
expect(manager.getSnapshot(TARGET).data?.branch).toBe("reconnected-branch");
release();
});
it("cleans up connection listener on unwatch", () => {
const connectionListeners = new Set<() => void>();
const mock = createMockClient();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
getClientIdentity: () => "id",
subscribeClientChanges: (listener) => {
connectionListeners.add(listener);
return () => connectionListeners.delete(listener);
},
});
const release = manager.watch(TARGET);
expect(connectionListeners.size).toBe(1);
release();
expect(connectionListeners.size).toBe(0);
expect(mock.listeners.size).toBe(0);
});
});
describe("with getClient config (one-shot)", () => {
it("resolves client from config and subscribes", () => {
const mock = createMockClient();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: (envId) => (envId === "env-local" ? mock.client : null),
});
const release = manager.watch(TARGET);
expect(mock.client.onStatus).toHaveBeenCalledOnce();
mock.emit(BASE_STATUS);
expect(manager.getSnapshot(TARGET).data?.branch).toBe("feature/push-status");
release();
expect(mock.listeners.size).toBe(0);
});
it("returns noop when client is not available", () => {
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
const release = manager.watch(TARGET);
expect(manager.getSnapshot(TARGET)).toEqual(PENDING);
release(); // should not throw
});
});
describe("reset", () => {
it("tears down all active subscriptions", () => {
const mock = createMockClient();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
manager.watch(TARGET);
manager.watch(FRESH_TARGET);
expect(mock.listeners.size).toBe(2);
manager.reset();
expect(mock.listeners.size).toBe(0);
});
});
});
@@ -0,0 +1,289 @@
import type { GitManagerServiceError, GitStatusResult } from "@t3tools/contracts";
import type { Cause } from "effect";
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
import type { WsRpcClient } from "./wsRpcClient";
/* ─── Types ─────────────────────────────────────────────────────────── */
export interface GitStatusState {
readonly data: GitStatusResult | null;
readonly error: GitManagerServiceError | null;
readonly cause: Cause.Cause<GitManagerServiceError> | null;
readonly isPending: boolean;
}
export interface GitStatusTarget {
readonly environmentId: string | null;
readonly cwd: string | null;
}
export type GitStatusClient = Pick<WsRpcClient["git"], "onStatus" | "refreshStatus">;
interface WatchedEntry {
refCount: number;
teardown: () => void;
}
/* ─── Constants ─────────────────────────────────────────────────────── */
const NOOP: () => void = () => undefined;
export const EMPTY_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
data: null,
error: null,
cause: null,
isPending: false,
});
const INITIAL_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
data: null,
error: null,
cause: null,
isPending: true,
});
/* ─── Atoms ─────────────────────────────────────────────────────────── */
const knownGitStatusKeys = new Set<string>();
export const gitStatusStateAtom = Atom.family((key: string) => {
knownGitStatusKeys.add(key);
return Atom.make(INITIAL_GIT_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel(`git-status:${key}`),
);
});
export const EMPTY_GIT_STATUS_ATOM = Atom.make(EMPTY_GIT_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel("git-status:null"),
);
/* ─── Helpers ───────────────────────────────────────────────────────── */
export function getGitStatusTargetKey(target: GitStatusTarget): string | null {
if (target.environmentId === null || target.cwd === null) {
return null;
}
return `${target.environmentId}:${target.cwd}`;
}
/* ─── Subscription manager ──────────────────────────────────────────── */
export interface GitStatusManagerConfig {
/**
* Get the atom registry to read/write git status atoms.
*/
readonly getRegistry: () => AtomRegistry.AtomRegistry;
/** Resolve a git client for an environment. */
readonly getClient: (environmentId: string) => GitStatusClient | null;
/**
* Optional: get a stable identity for the current client.
* Used to detect reconnections — when the identity changes the
* manager tears down the old `onStatus` stream and subscribes anew.
*/
readonly getClientIdentity?: (environmentId: string) => string | null;
/**
* Optional: subscribe to environment-connection changes.
* When provided the manager reacts to client appear / disappear /
* reconnect events instead of doing a one-shot resolution.
*/
readonly subscribeClientChanges?: (listener: () => void) => () => void;
}
const GIT_STATUS_REFRESH_DEBOUNCE_MS = 1_000;
export function createGitStatusManager(config: GitStatusManagerConfig) {
const watched = new Map<string, WatchedEntry>();
const refreshInFlight = new Map<string, Promise<GitStatusResult>>();
const lastRefreshAt = new Map<string, number>();
/* ── Atom helpers ───────────────────────────────────────────────── */
function markPending(targetKey: string): void {
const atom = gitStatusStateAtom(targetKey);
const current = config.getRegistry().get(atom);
const next: GitStatusState =
current.data === null
? INITIAL_GIT_STATUS_STATE
: { ...current, error: null, cause: null, isPending: true };
if (
current.data === next.data &&
current.error === next.error &&
current.cause === next.cause &&
current.isPending === next.isPending
) {
return;
}
config.getRegistry().set(atom, next);
}
function setData(targetKey: string, status: GitStatusResult): void {
config.getRegistry().set(gitStatusStateAtom(targetKey), {
data: status,
error: null,
cause: null,
isPending: false,
});
}
/* ── Core subscription ──────────────────────────────────────────── */
function subscribeStream(targetKey: string, cwd: string, client: GitStatusClient): () => void {
markPending(targetKey);
return client.onStatus({ cwd }, (status) => setData(targetKey, status), {
onResubscribe: () => markPending(targetKey),
});
}
/* ── Dynamic subscription (handles reconnection) ────────────────── */
function createDynamicSubscription(targetKey: string, target: GitStatusTarget): () => void {
const environmentId = target.environmentId!;
const cwd = target.cwd!;
let currentIdentity: string | null = null;
let currentUnsub = NOOP;
const sync = () => {
const client = config.getClient(environmentId);
const identity = client ? (config.getClientIdentity?.(environmentId) ?? environmentId) : null;
if (!client || identity === null) {
if (currentIdentity !== null) {
currentUnsub();
currentUnsub = NOOP;
currentIdentity = null;
}
markPending(targetKey);
return;
}
if (currentIdentity === identity) return;
currentUnsub();
currentIdentity = identity;
currentUnsub = subscribeStream(targetKey, cwd, client);
};
const unsubChanges = config.subscribeClientChanges!(sync);
sync();
return () => {
unsubChanges();
currentUnsub();
};
}
/* ── Public API ─────────────────────────────────────────────────── */
/**
* Begin watching git status for `target`.
*
* Multiple watchers sharing the same `environmentId:cwd` key share
* one `onStatus` WS subscription (ref-counted).
*
* @param target The environment + cwd to watch.
* @param client Optional pre-resolved client — skips `getClient`
* lookup and reconnection handling. Useful in tests.
* @returns An unwatch function.
*/
function watch(target: GitStatusTarget, client?: GitStatusClient): () => void {
const targetKey = getGitStatusTargetKey(target);
if (targetKey === null || target.environmentId === null || target.cwd === null) {
return NOOP;
}
const existing = watched.get(targetKey);
if (existing) {
existing.refCount += 1;
return () => unwatch(targetKey);
}
let teardown: () => void;
if (client) {
// Explicit client — direct subscription, no reconnection handling.
teardown = subscribeStream(targetKey, target.cwd, client);
} else if (config.subscribeClientChanges) {
// Dynamic client — subscribe to connection changes for reconnection.
teardown = createDynamicSubscription(targetKey, target);
} else {
// One-shot client resolution.
const resolved = config.getClient(target.environmentId);
if (!resolved) return NOOP;
teardown = subscribeStream(targetKey, target.cwd, resolved);
}
watched.set(targetKey, { refCount: 1, teardown });
return () => unwatch(targetKey);
}
function unwatch(targetKey: string): void {
const entry = watched.get(targetKey);
if (!entry) return;
entry.refCount -= 1;
if (entry.refCount > 0) return;
entry.teardown();
watched.delete(targetKey);
}
/**
* Trigger a one-shot `refreshStatus` RPC for a target.
* Debounced (1 s) and deduplicated (in-flight).
* The server-side refresh pushes a new event on the existing
* `onStatus` stream, so the subscription picks it up automatically.
*/
function refresh(
target: GitStatusTarget,
client?: GitStatusClient,
): Promise<GitStatusResult | null> {
const targetKey = getGitStatusTargetKey(target);
if (targetKey === null || target.cwd === null) {
return Promise.resolve(null);
}
const resolved =
client ?? (target.environmentId ? config.getClient(target.environmentId) : null);
if (!resolved) {
return Promise.resolve(getSnapshot(target).data);
}
const existing = refreshInFlight.get(targetKey);
if (existing) return existing;
const last = lastRefreshAt.get(targetKey) ?? 0;
if (Date.now() - last < GIT_STATUS_REFRESH_DEBOUNCE_MS) {
return Promise.resolve(getSnapshot(target).data);
}
lastRefreshAt.set(targetKey, Date.now());
const promise = resolved
.refreshStatus({ cwd: target.cwd })
.finally(() => refreshInFlight.delete(targetKey));
refreshInFlight.set(targetKey, promise);
return promise;
}
function getSnapshot(target: GitStatusTarget): GitStatusState {
const targetKey = getGitStatusTargetKey(target);
if (targetKey === null) return EMPTY_GIT_STATUS_STATE;
return config.getRegistry().get(gitStatusStateAtom(targetKey));
}
function reset(): void {
for (const entry of watched.values()) {
entry.teardown();
}
watched.clear();
refreshInFlight.clear();
lastRefreshAt.clear();
for (const key of knownGitStatusKeys) {
config.getRegistry().set(gitStatusStateAtom(key), INITIAL_GIT_STATUS_STATE);
}
knownGitStatusKeys.clear();
}
return { watch, refresh, getSnapshot, reset };
}
+3
View File
@@ -1,6 +1,9 @@
export * from "./knownEnvironment";
export * from "./scoped";
export * from "./gitActions";
export * from "./gitActionState";
export * from "./gitBranchState";
export * from "./gitStatusState";
export * from "./wsRpcProtocol";
export * from "./wsTransport";
export * from "./wsRpcClient";