diff --git a/apps/mobile/babel.config.js b/apps/mobile/babel.config.js index 90f7d460dd..5c85f81242 100644 --- a/apps/mobile/babel.config.js +++ b/apps/mobile/babel.config.js @@ -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 }]], }; }; diff --git a/apps/mobile/global.css b/apps/mobile/global.css index 0bbd6c14e4..387f6b51bd 100644 --- a/apps/mobile/global.css +++ b/apps/mobile/global.css @@ -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; } diff --git a/apps/mobile/metro.config.js b/apps/mobile/metro.config.js index 50cd00959d..126250e02e 100644 --- a/apps/mobile/metro.config.js +++ b/apps/mobile/metro.config.js @@ -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 }, }); diff --git a/apps/mobile/nativewind-env.d.ts b/apps/mobile/nativewind-env.d.ts deleted file mode 100644 index 52b249b9d2..0000000000 --- a/apps/mobile/nativewind-env.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/// - -// NOTE: This file is generated by react-native-css / NativeWind integration. - -declare module "*.css"; diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 5f36c9433f..0d833dc828 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -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" } diff --git a/apps/mobile/postcss.config.mjs b/apps/mobile/postcss.config.mjs deleted file mode 100644 index c2ddf74822..0000000000 --- a/apps/mobile/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - "@tailwindcss/postcss": {}, - }, -}; diff --git a/apps/mobile/src/app/+not-found.tsx b/apps/mobile/src/app/+not-found.tsx index 1a8b0d7503..bdaa655684 100644 --- a/apps/mobile/src/app/+not-found.tsx +++ b/apps/mobile/src/app/+not-found.tsx @@ -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 ( - + Route not found - - Return home - + Return home diff --git a/apps/mobile/src/app/_layout.tsx b/apps/mobile/src/app/_layout.tsx index 2390066872..6338d7dce7 100644 --- a/apps/mobile/src/app/_layout.tsx +++ b/apps/mobile/src/app/_layout.tsx @@ -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 ( <> + - - + + + - {fontsLoaded ? : } + {fontsLoaded ? ( + + ) : ( + + )} - - - + + + ); } diff --git a/apps/mobile/src/app/connections/_layout.tsx b/apps/mobile/src/app/connections/_layout.tsx index 6ffbb446a9..38ec4c11ed 100644 --- a/apps/mobile/src/app/connections/_layout.tsx +++ b/apps/mobile/src/app/connections/_layout.tsx @@ -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 ( diff --git a/apps/mobile/src/app/new/_layout.tsx b/apps/mobile/src/app/new/_layout.tsx index 208175f9a8..7205e74509 100644 --- a/apps/mobile/src/app/new/_layout.tsx +++ b/apps/mobile/src/app/new/_layout.tsx @@ -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 ( diff --git a/apps/mobile/src/app/new/index.tsx b/apps/mobile/src/app/new/index.tsx index 7c9e2b2d3a..cd87abd1cf 100644 --- a/apps/mobile/src/app/new/index.tsx +++ b/apps/mobile/src/app/new/index.tsx @@ -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 ( - - + + + + + + + + New task + + Choose project + + {items.length === 0 ? ( - - - Loading projects… + + + Loading projects... ) : ( - + {items.map((item, index) => { const isFirst = index === 0; const isLast = index === items.length - 1; @@ -85,12 +93,12 @@ export default function NewTaskRoute() { asChild > + - - {item.title} - + {item.title} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId].tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId].tsx deleted file mode 100644 index 626d72342c..0000000000 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId].tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { ThreadRouteScreen } from "../../../features/threads/ThreadRouteScreen"; - -export default function ThreadRoute() { - return ; -} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx new file mode 100644 index 0000000000..b5e83cbad4 --- /dev/null +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx @@ -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 ( + + + + + + ); +} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git-confirm.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git-confirm.tsx new file mode 100644 index 0000000000..3773ce55b2 --- /dev/null +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git-confirm.tsx @@ -0,0 +1,5 @@ +import { GitConfirmSheet } from "../../../../features/threads/git/GitConfirmSheet"; + +export default function GitConfirmRoute() { + return ; +} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx new file mode 100644 index 0000000000..42b3a482b9 --- /dev/null +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx @@ -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 ( + + + + + + ); +} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/branches.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/branches.tsx new file mode 100644 index 0000000000..955e4febd7 --- /dev/null +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/branches.tsx @@ -0,0 +1,5 @@ +import { GitBranchesSheet } from "../../../../../features/threads/git/GitBranchesSheet"; + +export default function GitBranchesRoute() { + return ; +} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/commit.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/commit.tsx new file mode 100644 index 0000000000..4510f81a8c --- /dev/null +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/commit.tsx @@ -0,0 +1,5 @@ +import { GitCommitSheet } from "../../../../../features/threads/git/GitCommitSheet"; + +export default function GitCommitRoute() { + return ; +} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/index.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/index.tsx new file mode 100644 index 0000000000..dd099d80d2 --- /dev/null +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/index.tsx @@ -0,0 +1,5 @@ +import { GitOverviewSheet } from "../../../../../features/threads/git/GitOverviewSheet"; + +export default function GitRoute() { + return ; +} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/index.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/index.tsx new file mode 100644 index 0000000000..4586ee93ca --- /dev/null +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/index.tsx @@ -0,0 +1,5 @@ +import { ThreadRouteScreen } from "../../../../features/threads/ThreadRouteScreen"; + +export default function ThreadRoute() { + return ; +} diff --git a/apps/mobile/src/components/AppText.tsx b/apps/mobile/src/components/AppText.tsx index 175561f0e1..ece05b1df4 100644 --- a/apps/mobile/src/components/AppText.tsx +++ b/apps/mobile/src/components/AppText.tsx @@ -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; +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; - -const borderColorMap = { - "border-neutral-200": "#e5e5e5", - "border-white/8": "rgba(255, 255, 255, 0.08)", -} satisfies Record; - -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 ; } -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 ; -} - -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 ( , style]} /> ); } diff --git a/apps/mobile/src/components/BrandMark.tsx b/apps/mobile/src/components/BrandMark.tsx index d4737826f3..0373cd8932 100644 --- a/apps/mobile/src/components/BrandMark.tsx +++ b/apps/mobile/src/components/BrandMark.tsx @@ -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 T3 Code - + {stageLabel} {!compact ? ( - + Mobile control surface for your live coding environments ) : null} diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx index 2569e5a477..239b03010b 100644 --- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx +++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx @@ -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" /> diff --git a/apps/mobile/src/components/ControlPill.tsx b/apps/mobile/src/components/ControlPill.tsx index e47dd3e6f9..3ebe9fada5 100644 --- a/apps/mobile/src/components/ControlPill.tsx +++ b/apps/mobile/src/components/ControlPill.tsx @@ -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["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: { ) : null} {props.label ? ( - + {props.label} ) : null} diff --git a/apps/mobile/src/components/EmptyState.tsx b/apps/mobile/src/components/EmptyState.tsx index 399e9c3288..30ded6045a 100644 --- a/apps/mobile/src/components/EmptyState.tsx +++ b/apps/mobile/src/components/EmptyState.tsx @@ -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 ( - - - {props.title} - - + + {props.title} + {props.detail} diff --git a/apps/mobile/src/components/LoadingScreen.tsx b/apps/mobile/src/components/LoadingScreen.tsx index e43d70e1c2..8b8083832c 100644 --- a/apps/mobile/src/components/LoadingScreen.tsx +++ b/apps/mobile/src/components/LoadingScreen.tsx @@ -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 ( - + - - {props.message} - + {props.message} ); diff --git a/apps/mobile/src/components/ProjectFavicon.tsx b/apps/mobile/src/components/ProjectFavicon.tsx new file mode 100644 index 0000000000..32297d8d9d --- /dev/null +++ b/apps/mobile/src/components/ProjectFavicon.tsx @@ -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(); + +/* ─── 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 ( + + {/* Folder icon fallback (matches web's FolderIcon) */} + {!showImage ? ( + + ) : null} + + {/* Favicon image (hidden until loaded) */} + {faviconUrl ? ( + { + if (faviconUrl) loadedFaviconUrls.add(faviconUrl); + setStatus("loaded"); + }} + onError={() => setStatus("error")} + /> + ) : null} + + ); +} diff --git a/apps/mobile/src/components/StatusPill.tsx b/apps/mobile/src/components/StatusPill.tsx index e0fb65efbd..34e6f74b60 100644 --- a/apps/mobile/src/components/StatusPill.tsx +++ b/apps/mobile/src/components/StatusPill.tsx @@ -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 ( ; - readonly onRequestClose: () => void; - readonly onUpdateEnvironment: ( - environmentId: string, - updates: { readonly label: string; readonly displayUrl: string }, - ) => Promise; - readonly onRemoveEnvironment: (environmentId: string) => void; -} - -// --------------------------------------------------------------------------- -function EnvironmentCard(props: { - readonly environment: ConnectedEnvironmentSummary; - readonly palette: ConnectionSheetPalette; - readonly onPress: () => void; - readonly onRemove: (environmentId: string) => void; -}) { - return ( - - - - - - {props.environment.environmentLabel} - - - {props.environment.displayUrl} - - - - { - e.stopPropagation(); - props.onRemove(props.environment.environmentId); - }} - hitSlop={4} - > - - - - ); -} - -// --------------------------------------------------------------------------- -// 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(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) => ( - - ), - [], - ); - - const hasChanges = - env !== null && (label.trim() !== env.environmentLabel || displayUrl.trim() !== env.displayUrl); - - return ( - - - - - {env ? ( - - ) : null} - - Edit backend - - - - - - Label - - - - - - - Host - - - - - - - { - if (env) { - props.onSave(env.environmentId, { - label: label.trim(), - displayUrl: displayUrl.trim(), - }); - props.onDismiss(); - } - }} - /> - - - - - - - - - ); -} - -// --------------------------------------------------------------------------- -// 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( - 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 ( - - - {/* Header */} - - - - Backends - - - Manage your connected environments. - - - - - - - - - {/* Backend list */} - {hasEnvironments ? ( - props.connectedEnvironments.map((environment) => ( - setEditingEnvironment(environment)} - onRemove={props.onRemoveEnvironment} - /> - )) - ) : ( - - - - - - No backends connected yet.{"\n"}Tap{" "} - - + - {" "} - to add one. - - - )} - - - {/* Nested: Edit backend */} - setEditingEnvironment(null)} - onSave={(environmentId, updates) => { - void props.onUpdateEnvironment(environmentId, updates); - }} - onRemove={props.onRemoveEnvironment} - /> - - ); -} diff --git a/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx index 319e3925cc..d9813f7f70 100644 --- a/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx +++ b/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx @@ -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; }) { 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 ( - + {props.environment.environmentLabel} - + {props.environment.displayUrl} @@ -61,7 +58,7 @@ function EnvironmentRow(props: { Label @@ -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" /> URL @@ -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" /> - + Save props.onRemove(props.environment.environmentId)} - style={{ - backgroundColor: props.palette.dangerButton, - borderWidth: 1, - borderColor: props.palette.dangerBorder, - }} > - + @@ -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(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 ( - + ( - + @@ -219,19 +182,15 @@ export function ConnectionsRouteScreen() { }} > {hasEnvironments ? ( - + {connectedEnvironments.map((environment, index) => ( handleToggle(environment.environmentId)} onRemove={onRemoveEnvironmentPress} onUpdate={onUpdateEnvironment} - palette={palette} /> ))} ) : ( - - + + - + No backends connected yet.{"\n"}Tap{" "} - - + - {" "} - to add one. + + to add one. )} diff --git a/apps/mobile/src/features/connection/NewConnectionRouteScreen.tsx b/apps/mobile/src/features/connection/NewConnectionRouteScreen.tsx index fbdae544c7..a650747443 100644 --- a/apps/mobile/src/features/connection/NewConnectionRouteScreen.tsx +++ b/apps/mobile/src/features/connection/NewConnectionRouteScreen.tsx @@ -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 ( - + ( { if (showScanner) { closeScanner(); @@ -139,16 +140,11 @@ export function NewConnectionRouteScreen() { void openScanner(); } }} - style={{ - backgroundColor: palette.secondaryButton, - borderWidth: 1, - borderColor: palette.border, - }} > @@ -182,20 +178,16 @@ export function NewConnectionRouteScreen() { ) : ( - + Camera permission is required to scan a QR code. { void openScanner(); @@ -204,15 +196,11 @@ export function NewConnectionRouteScreen() { ) ) : ( - + Host @@ -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" /> Pairing code @@ -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" /> @@ -263,10 +239,9 @@ export function NewConnectionRouteScreen() { { void handleSubmit(); diff --git a/apps/mobile/src/features/connection/connection-sheet-shared.tsx b/apps/mobile/src/features/connection/connection-sheet-shared.tsx index 51a4c26e8a..f9ec97d663 100644 --- a/apps/mobile/src/features/connection/connection-sheet-shared.tsx +++ b/apps/mobile/src/features/connection/connection-sheet-shared.tsx @@ -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; +export { CARD_SHADOW, CARD_SHADOW_DARK }; export function ConnectionSheetButton(props: { readonly icon: React.ComponentProps["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 ( = { + 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 ( - router.push("/connections")} - onOpenNewTask={() => router.push("/new")} - onSelectThread={(thread) => { - onSelectThread(thread); - router.push(buildThreadRoutePath(thread)); - }} - showFloatingConnectionButton - showFloatingNewTaskButton - /> + <> + ( + router.push("/connections")} + hitSlop={8} + style={{ + flexDirection: "row", + alignItems: "center", + gap: 8, + paddingHorizontal: 4, + paddingVertical: 4, + }} + > + + + {CONNECTION_LABEL[connectionState] ?? "Unknown"} + + + ), + headerSearchBarOptions: { + placeholder: "Search threads", + onChangeText: (event) => { + setSearchQuery(event.nativeEvent.text); + }, + allowToolbarIntegration: true, + }, + }} + /> + + {/* Header left: plain text, no Liquid Glass button chrome */} + + + + + T3 Code + + + + Alpha + + + + + + + {/* Bottom toolbar: search + compose, visually split like iMessage */} + + + + router.push("/new")} + separateBackground + /> + + + { + onSelectThread(thread); + router.push(buildThreadRoutePath(thread)); + }} + /> + ); } diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 6f1952f6e5..2142b9806a 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -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; readonly threads: ReadonlyArray; - readonly connectionState: "ready" | "connecting" | "reconnecting" | "disconnected" | "idle"; - readonly connectionPulse: boolean; - readonly onOpenConnectionEditor: () => void; - readonly onOpenNewTask: () => void; + readonly savedConnectionsById: Readonly>; + 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; +} + +/* ─── 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 ( - - + + - - - Recents + {props.project.title} + + + {hiddenCount > 0 ? ( + + + {props.isExpanded ? "Show less" : `${hiddenCount} more`} - - {props.showFloatingConnectionButton ? ( - - - - ) : null} - - - {props.threads.length === 0 ? ( - - ) : ( - - {props.threads.map((thread, index) => { - const projectKey = scopedProjectKey(thread.environmentId, thread.projectId); - const projectLabel = projectLabelsByKey.get(projectKey); - - return ( - props.onSelectThread(thread)} - style={{ - paddingHorizontal: 16, - paddingVertical: 13, - borderTopWidth: index === 0 ? 0 : 1, - borderTopColor: palette.borderSubtle, - }} - > - - - - {thread.title} - - - - - - - - - {projectLabel?.projectTitle ?? thread.title} - - - - {projectLabel?.environmentLabel ?? "Local"} - - - - {relativeTime(thread.updatedAt ?? thread.createdAt)} - - - - ); - })} - - )} - - - {props.showFloatingNewTaskButton ? ( - - { - setNewTaskPressed(true); - void Haptics.selectionAsync(); - }} - onPressOut={() => { - setNewTaskPressed(false); - }} - onPress={props.onOpenNewTask} - > - - - - New task - - - - + ) : null} ); } + +/* ─── Git summary line ──────────────────────────────────────────────── */ + +function gitSummaryParts(gitStatus: GitStatusState): ReadonlyArray { + 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 ( + ({ opacity: pressed ? 0.7 : 1 })}> + + {/* Git status indicator */} + + + + + {/* Content */} + + {/* Title + Status + Timestamp */} + + + {props.thread.title} + + + + + {tone.label} + + + + {timestamp} + + + + + {/* Message preview */} + + {preview} + + + {/* Branch + git info */} + {branch ? ( + + + + {branch} + + {gitParts.length > 0 ? ( + + {" · " + gitParts.join(" · ")} + + ) : null} + + ) : null} + + + + ); +} + +/* ─── Main screen ────────────────────────────────────────────────────── */ + +export function HomeScreen(props: HomeScreenProps) { + const [expandedProjects, setExpandedProjects] = useState>(() => 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(); + 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>(() => { + const byProject = new Map(); + 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 ( + + {!hasAnyThreads ? ( + + ) : !hasResults ? ( + + ) : ( + 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 ( + + toggleExpanded(group.key)} + /> + + {visibleThreads.map((thread, i) => ( + props.onSelectThread(thread)} + isLast={i === visibleThreads.length - 1} + /> + ))} + + + ); + }) + )} + + ); +} diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index 0485b35200..015649a8a1 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -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 ( - + New task - - Loading task - + Loading task ); } return ( - + {flow.logicalProjects.length > 1 ? ( router.back()} > ) : null} New task - - {selectedProject.title} - + {selectedProject.title} @@ -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]" /> @@ -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: { handleModelMenuAction(nativeEvent.event)} + themeVariant={isDarkMode ? "dark" : "light"} > } @@ -487,18 +476,21 @@ export function NewTaskDraftScreen(props: { handleOptionsMenuAction(nativeEvent.event)} + themeVariant={isDarkMode ? "dark" : "light"} > handleEnvironmentMenuAction(nativeEvent.event)} + themeVariant={isDarkMode ? "dark" : "light"} > handleWorkspaceMenuAction(nativeEvent.event)} + themeVariant={isDarkMode ? "dark" : "light"} > diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsx index 2496ad5638..af77ff2922 100644 --- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx +++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx @@ -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 ( ; - readonly threads: ReadonlyArray; - readonly onClose: () => void; - readonly onSelectProject: (project: ScopedMobileProject) => void; -}) { - const isDarkMode = useColorScheme() === "dark"; - const palette = makeAppPalette(isDarkMode); - const insets = useSafeAreaInsets(); - const sheetRef = useRef(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) => ( - - ), - [], - ); - - useEffect(() => { - const sheet = sheetRef.current; - if (!sheet) { - return; - } - - if (props.visible) { - sheet.present(); - return; - } - - sheet.dismiss(); - }, [props.visible]); - - return ( - - - - - New task - - - Choose project - - - - - - {logicalProjects.map((entry, index) => ( - props.onSelectProject(entry.project)} - style={{ - paddingHorizontal: 16, - paddingVertical: 18, - borderTopWidth: index === 0 ? 0 : 1, - borderTopColor: palette.borderSubtle, - }} - > - - - - {entry.project.title} - - - - - ))} - - - - - ); -} diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 920c2c8fdc..302cce9012 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -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(null); const [isFocused, setIsFocused] = useState(false); const wasExpandedBeforePreviewRef = useRef(false); @@ -337,14 +338,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer return ( 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 onPressImage(image.previewUri)}> @@ -442,22 +440,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer ))} {props.draftAttachments.length > 3 ? ( - + +{props.draftAttachments.length - 3} @@ -497,12 +489,14 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer handleModelMenuAction(nativeEvent.event)} + themeVariant={isDarkMode ? "dark" : "light"} > } /> handleOptionsMenuAction(nativeEvent.event)} + themeVariant={isDarkMode ? "dark" : "light"} > @@ -527,8 +521,8 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer {/* Queue count */} {props.queueCount > 0 ? ( ; 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) => Promise; readonly onRemoveDraftImage: (imageId: string) => void; readonly onRefresh: () => Promise; - readonly onRefreshSelectedThreadGitStatus: (options?: { - readonly quiet?: boolean; - }) => Promise; - readonly onListSelectedThreadBranches: () => Promise>; - readonly onCheckoutSelectedThreadBranch: (branch: string) => Promise; - readonly onCreateSelectedThreadBranch: (branch: string) => Promise; - readonly onCreateSelectedThreadWorktree: (input: { - readonly baseBranch: string; - readonly newBranch: string; - }) => Promise; - readonly onPullSelectedThreadBranch: () => Promise; - readonly onRunSelectedThreadGitAction: ( - input: GitActionRequestInput, - ) => Promise; - readonly onRenameThread: (title: string) => Promise; readonly onStopThread: () => Promise; readonly onSendMessage: () => void; readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => Promise; @@ -107,7 +80,6 @@ export interface ThreadDetailScreenProps { customAnswer: string, ) => void; readonly onSubmitUserInput: () => Promise; - readonly showHeader?: boolean; readonly showContent?: boolean; } @@ -182,20 +154,15 @@ function useStreamingHaptics(threadId: string, feed: ReadonlyArray 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 { - const trimmed = renameDraft.trim(); - if (trimmed.length === 0) { - return; - } - - await props.onRenameThread(trimmed); - setRenameVisible(false); - } - return ( - - {showHeader ? ( - - - - - - ) - } - centerSlot={ - - { - setRenameDraft(props.selectedThread.title); - setRenameVisible(true); - }} - > - - {props.selectedThread.title} - - - - {[ - screenTitle(props.serverConfig, null), - props.selectedThread.environmentLabel, - ] - .filter(Boolean) - .join(" · ")} - - - } - rightSlot={ - - } - /> - - - ) : null} - + {/* Feed area — KAV shrinks this when keyboard opens */} {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) { /> ) : null} - - setRenameVisible(false)} - > - - - - - Thread name - - - Rename thread - - - - { - void handleSubmitRename(); - }} - /> - - - { - setRenameDraft(props.selectedThread.title); - setRenameVisible(false); - }} - > - - Cancel - - - { - void handleSubmitRename(); - }} - > - - Save - - - - - - ); diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 0fc44d4d59..b8b14f3501 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -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; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + readonly assistant: Record; +} + +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) => 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) => ( 0 && "border-t border-neutral-200/80 dark:border-white/[0.06]", )} > - + (null); const copyFeedbackTimeoutRef = useRef | null>(null); const [copiedRowId, setCopiedRowId] = useState(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 ( - @@ -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." /> - + ); } @@ -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, }} /> diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx index 2747bee175..88ebe59128 100644 --- a/apps/mobile/src/features/threads/ThreadGitControls.tsx +++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx @@ -1,93 +1,13 @@ +import type { GitRunStackedActionResult, GitStatusResult } from "@t3tools/contracts"; import { - BottomSheetBackdrop, - BottomSheetModal, - BottomSheetScrollView, - BottomSheetView, -} from "@gorhom/bottom-sheet"; -import { MenuView } from "@react-native-menu/menu"; -import type { GitBranch, GitRunStackedActionResult, GitStatusResult } from "@t3tools/contracts"; -import { - buildMenuItems, - getGitActionDisabledReason, type GitActionRequestInput, requiresDefaultBranchConfirmation, - resolveDefaultBranchActionDialogCopy, resolveQuickAction, } from "@t3tools/client-runtime"; -import { resolveAutoFeatureBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git"; -import { SymbolView } from "expo-symbols"; -import type { ComponentProps, RefObject } from "react"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { Alert, Linking, Pressable, useColorScheme, View } from "react-native"; -import { useSafeAreaInsets } from "react-native-safe-area-context"; - -import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText"; -import { StatusPill } from "../../components/StatusPill"; -import { makeAppPalette } from "../../lib/theme"; - -type PendingDefaultBranchAction = { - readonly action: Extract< - GitActionRequestInput["action"], - "push" | "create_pr" | "commit_push" | "commit_push_pr" - >; - readonly branchName: string; - readonly includesCommit: boolean; - readonly commitMessage?: string; - readonly filePaths?: readonly string[]; -}; - -function useSheetVisibility(sheetRef: RefObject, visible: boolean) { - useEffect(() => { - const sheet = sheetRef.current; - if (!sheet) { - return; - } - - if (visible) { - sheet.present(); - return; - } - - sheet.dismiss(); - }, [sheetRef, visible]); -} - -function statusSummary(gitStatus: GitStatusResult | null): string { - if (!gitStatus) { - return "Loading branch status…"; - } - - if (!gitStatus.isRepo) { - return "Not a git repository"; - } - - const parts: string[] = []; - if (gitStatus.hasWorkingTreeChanges) { - parts.push( - `${gitStatus.workingTree.files.length} file${gitStatus.workingTree.files.length === 1 ? "" : "s"} changed`, - ); - } else { - parts.push("Clean"); - } - if (gitStatus.aheadCount > 0) { - parts.push(`${gitStatus.aheadCount} ahead`); - } - if (gitStatus.behindCount > 0) { - parts.push(`${gitStatus.behindCount} behind`); - } - if (gitStatus.pr?.state === "open") { - parts.push(`PR #${gitStatus.pr.number} open`); - } - - return parts.join(" · "); -} - -function deriveAvailableBranchLabel( - currentBranch: string | null, - gitStatus: GitStatusResult | null, -): string { - return gitStatus?.branch ?? currentBranch ?? "Detached HEAD"; -} +import { useLocalSearchParams, useRouter } from "expo-router"; +import Stack from "expo-router/stack"; +import { useCallback, useMemo } from "react"; +import { Alert, Linking } from "react-native"; function truncateMiddle(value: string, maxLength: number): string { if (value.length <= maxLength) { @@ -130,211 +50,26 @@ function compactMenuStatus(gitStatus: GitStatusResult | null): string { return parts.join(" · "); } -function triggerStatusLabel( - gitStatus: GitStatusResult | null, - gitOperationLabel: string | null, -): string { - if (gitOperationLabel) { - return "Working"; - } - if (!gitStatus) { - return "Checking"; - } - if (!gitStatus.isRepo) { - return "No repo"; - } - if (gitStatus.hasWorkingTreeChanges) { - return `${gitStatus.workingTree.files.length} changed`; - } - if (gitStatus.behindCount > 0) { - return `${gitStatus.behindCount} behind`; - } - if (gitStatus.aheadCount > 0) { - return `${gitStatus.aheadCount} ahead`; - } - if (gitStatus.pr?.state === "open") { - return "PR open"; - } - return "Clean"; -} - -function menuItemIconName( - icon: "commit" | "push" | "pr", -): ComponentProps["name"] { - if (icon === "commit") return "checkmark.circle"; - if (icon === "push") return "arrow.up.circle"; - return "arrow.up.right.circle"; -} - -function SheetActionButton(props: { - readonly icon: ComponentProps["name"]; - readonly label: string; - readonly disabled?: boolean; - readonly tone?: "primary" | "secondary" | "danger"; - readonly onPress: () => void; -}) { - const isDarkMode = useColorScheme() === "dark"; - const palette = makeAppPalette(isDarkMode); - const tone = props.tone ?? "secondary"; - const colors = - tone === "primary" - ? { - backgroundColor: palette.primaryButton, - borderColor: "transparent", - textColor: palette.primaryButtonText, - } - : tone === "danger" - ? { - backgroundColor: palette.dangerButton, - borderColor: palette.dangerBorder, - textColor: palette.dangerText, - } - : { - backgroundColor: palette.secondaryButton, - borderColor: palette.secondaryButtonBorder, - textColor: palette.secondaryButtonText, - }; - - return ( - - - - {props.label} - - - ); -} - -function MetaCard(props: { readonly label: string; readonly value: string }) { - const isDarkMode = useColorScheme() === "dark"; - const palette = makeAppPalette(isDarkMode); - return ( - - - {props.label} - - - {props.value} - - - ); -} - -function SheetListRow(props: { - readonly icon: ComponentProps["name"]; - readonly title: string; - readonly subtitle?: string | null; - readonly disabled?: boolean; - readonly onPress: () => void; -}) { - const isDarkMode = useColorScheme() === "dark"; - const palette = makeAppPalette(isDarkMode); - return ( - - - - - - - {props.title} - - {props.subtitle ? ( - - {props.subtitle} - - ) : null} - - - - ); -} - export function ThreadGitControls(props: { readonly currentBranch: string | null; - readonly currentWorktreePath: string | null; readonly gitStatus: GitStatusResult | null; readonly gitOperationLabel: string | null; - readonly onRefreshStatus: (options?: { readonly quiet?: boolean }) => Promise; - readonly onListBranches: () => Promise>; - readonly onCheckoutBranch: (branch: string) => Promise; - readonly onCreateBranch: (branch: string) => Promise; - readonly onCreateWorktree: (input: { - readonly baseBranch: string; - readonly newBranch: string; - }) => Promise; readonly onPull: () => Promise; readonly onRunAction: (input: GitActionRequestInput) => Promise; }) { - const isDarkMode = useColorScheme() === "dark"; - const palette = makeAppPalette(isDarkMode); - const insets = useSafeAreaInsets(); - const { - currentWorktreePath, - gitOperationLabel, - gitStatus, - onCheckoutBranch, - onCreateBranch, - onCreateWorktree, - onListBranches, - onPull, - onRefreshStatus, - onRunAction, - } = props; - const gitSheetRef = useRef(null); - const branchSheetRef = useRef(null); - const commitSheetRef = useRef(null); - const defaultBranchSheetRef = useRef(null); - const [gitSheetVisible, setGitSheetVisible] = useState(false); - const [branchSheetVisible, setBranchSheetVisible] = useState(false); - const [commitSheetVisible, setCommitSheetVisible] = useState(false); - const [defaultBranchSheetVisible, setDefaultBranchSheetVisible] = useState(false); - const [isEditingFiles, setIsEditingFiles] = useState(false); - const [availableBranches, setAvailableBranches] = useState>([]); - const [branchesLoading, setBranchesLoading] = useState(false); - const [newBranchName, setNewBranchName] = useState(""); - const [worktreeBaseBranch, setWorktreeBaseBranch] = useState(""); - const [worktreeBranchName, setWorktreeBranchName] = useState(""); - const [dialogCommitMessage, setDialogCommitMessage] = useState(""); - const [excludedFiles, setExcludedFiles] = useState>(new Set()); - const [pendingDefaultBranchAction, setPendingDefaultBranchAction] = - useState(null); - const currentBranchLabel = deriveAvailableBranchLabel(props.currentBranch, gitStatus); + const router = useRouter(); + const { environmentId, threadId } = useLocalSearchParams<{ + environmentId: string; + threadId: string; + }>(); + const { gitStatus, gitOperationLabel, onPull, onRunAction } = props; + + const currentBranchLabel = gitStatus?.branch ?? props.currentBranch ?? "Detached HEAD"; const busy = gitOperationLabel !== null; const isRepo = gitStatus?.isRepo ?? true; const hasOriginRemote = gitStatus?.hasOriginRemote ?? false; const isDefaultBranch = gitStatus?.isDefaultBranch ?? false; + const quickAction = useMemo( () => isRepo @@ -347,163 +82,21 @@ export function ThreadGitControls(props: { }, [busy, gitStatus, hasOriginRemote, isDefaultBranch, isRepo], ); - const menuItems = useMemo( - () => (isRepo ? buildMenuItems(gitStatus, busy, hasOriginRemote) : []), - [busy, gitStatus, hasOriginRemote, isRepo], - ); + const quickActionHint = quickAction.disabled ? (quickAction.hint ?? "This action is unavailable.") : null; - const triggerStatus = triggerStatusLabel(gitStatus, gitOperationLabel); - const allFiles = gitStatus?.workingTree.files ?? []; - 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 renderBackdrop = useCallback( - (backdropProps: ComponentProps) => ( - - ), - [], - ); - const gitSnapPoints = useMemo<(string | number)[]>(() => ["72%"], []); - const branchSnapPoints = useMemo<(string | number)[]>(() => ["86%"], []); - const commitSnapPoints = useMemo<(string | number)[]>(() => ["88%"], []); - const defaultBranchSnapPoints = useMemo<(string | number)[]>(() => ["40%"], []); - const pendingDefaultBranchActionCopy = pendingDefaultBranchAction - ? resolveDefaultBranchActionDialogCopy({ - action: pendingDefaultBranchAction.action, - branchName: pendingDefaultBranchAction.branchName, - includesCommit: pendingDefaultBranchAction.includesCommit, - }) - : null; - const disabledExistingBranches = useMemo( - () => - new Set( - availableBranches - .filter( - (branch) => branch.worktreePath !== null && branch.worktreePath !== currentWorktreePath, - ) - .map((branch) => branch.name), - ), - [availableBranches, currentWorktreePath], - ); - const sheetMenuItems = useMemo( - () => - menuItems.map((item) => ({ - item, - disabledReason: getGitActionDisabledReason({ - item, - gitStatus, - isBusy: busy, - hasOriginRemote, - }), - })), - [busy, gitStatus, hasOriginRemote, menuItems], - ); - const nativeMenuActions = useMemo< - Array<{ - id: string; - title: string; - subtitle?: string; - state?: "off"; - image?: string; - preferredElementSize?: "small"; - attributes?: { - disabled?: boolean; - }; - }> - >( - () => [ - { - id: "branch", - title: compactMenuBranchLabel(currentBranchLabel), - subtitle: compactMenuStatus(gitStatus), - image: "point.topleft.down.curvedto.point.bottomright.up", - state: "off", - preferredElementSize: "small", - attributes: { disabled: true }, - }, - { - id: "quick", - title: quickAction.label, - image: - quickAction.kind === "run_pull" - ? "arrow.down.circle" - : quickAction.kind === "open_pr" - ? "arrow.up.right.circle" - : quickAction.action === "commit" - ? "checkmark.circle" - : quickAction.action === "push" || quickAction.action === "commit_push" - ? "arrow.up.circle" - : "arrow.up.right.circle", - ...(quickActionHint ? { subtitle: quickActionHint } : {}), - preferredElementSize: "small", - ...(quickAction.disabled ? { attributes: { disabled: true } } : {}), - }, - { - id: "more", - title: "More", - image: "ellipsis.circle", - subtitle: "Commit, files, branches", - preferredElementSize: "small", - }, - ], - [ - currentBranchLabel, - gitStatus, - quickAction.action, - quickAction.disabled, - quickAction.kind, - quickAction.label, - quickActionHint, - ], - ); - useSheetVisibility(gitSheetRef, gitSheetVisible); - useSheetVisibility(branchSheetRef, branchSheetVisible); - useSheetVisibility(commitSheetRef, commitSheetVisible); - useSheetVisibility(defaultBranchSheetRef, defaultBranchSheetVisible); - - useEffect(() => { - if (!gitSheetVisible) { - return; + const quickActionIcon = (() => { + if (quickAction.kind === "run_pull") return "arrow.down.circle"; + if (quickAction.kind === "open_pr") return "arrow.up.right.circle"; + if (quickAction.kind === "run_action") { + if (quickAction.action === "commit") return "checkmark.circle"; + if (quickAction.action === "push" || quickAction.action === "commit_push") + return "arrow.up.circle"; } - void onRefreshStatus({ quiet: true }); - }, [gitSheetVisible, onRefreshStatus]); - - useEffect(() => { - if (!branchSheetVisible) { - return; - } - - setWorktreeBaseBranch(currentBranchLabel === "Detached HEAD" ? "main" : currentBranchLabel); - setBranchesLoading(true); - void onListBranches() - .then((branches) => setAvailableBranches(branches)) - .finally(() => setBranchesLoading(false)); - }, [branchSheetVisible, currentBranchLabel, onListBranches]); - - const closeTransientSheets = useCallback(() => { - setGitSheetVisible(false); - setCommitSheetVisible(false); - setDefaultBranchSheetVisible(false); - }, []); - - const openCommitSheet = useCallback(() => { - setExcludedFiles(new Set()); - setIsEditingFiles(false); - setDialogCommitMessage(""); - setCommitSheetVisible(true); - }, []); + return "arrow.up.right.circle"; + })(); const openExistingPr = useCallback(async () => { const prUrl = gitStatus?.pr?.state === "open" ? gitStatus.pr.url : null; @@ -537,64 +130,26 @@ export function ThreadGitControls(props: { !input.featureBranch && requiresDefaultBranchConfirmation(input.action, isDefaultBranch) ) { - setPendingDefaultBranchAction({ - action: confirmableAction, - branchName, - includesCommit: input.action === "commit_push" || input.action === "commit_push_pr", - ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}), - ...(input.filePaths ? { filePaths: input.filePaths } : {}), + 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", + ), + }, }); - setDefaultBranchSheetVisible(true); return; } - closeTransientSheets(); await onRunAction(input); }, - [closeTransientSheets, gitStatus, isDefaultBranch, onRunAction], + [environmentId, gitStatus, isDefaultBranch, onRunAction, router, threadId], ); - const continuePendingDefaultBranchAction = useCallback(async () => { - if (!pendingDefaultBranchAction) { - return; - } - const action = pendingDefaultBranchAction; - setPendingDefaultBranchAction(null); - setDefaultBranchSheetVisible(false); - await onRunAction({ - action: action.action, - ...(action.commitMessage ? { commitMessage: action.commitMessage } : {}), - ...(action.filePaths ? { filePaths: action.filePaths } : {}), - }); - }, [onRunAction, pendingDefaultBranchAction]); - - const movePendingActionToFeatureBranch = useCallback(async () => { - if (!pendingDefaultBranchAction) { - return; - } - - const action = pendingDefaultBranchAction; - setPendingDefaultBranchAction(null); - setDefaultBranchSheetVisible(false); - - if (action.includesCommit) { - await onRunAction({ - action: action.action, - featureBranch: true, - ...(action.commitMessage ? { commitMessage: action.commitMessage } : {}), - ...(action.filePaths ? { filePaths: action.filePaths } : {}), - }); - return; - } - - const branches = await onListBranches(); - const branchName = resolveAutoFeatureBranchName( - branches.filter((branch) => !branch.isRemote).map((branch) => branch.name), - ); - await onCreateBranch(branchName); - await onRunAction({ action: action.action }); - }, [onCreateBranch, onListBranches, onRunAction, pendingDefaultBranchAction]); - const runQuickAction = useCallback(async () => { if (quickAction.kind === "open_pr") { await openExistingPr(); @@ -609,699 +164,38 @@ export function ThreadGitControls(props: { } }, [onPull, openExistingPr, quickAction, runActionWithPrompt]); - const runCommitAction = useCallback( - async (featureBranch: boolean) => { - const commitMessage = dialogCommitMessage.trim(); - setGitSheetVisible(false); - setCommitSheetVisible(false); - await onRunAction({ - action: "commit", - featureBranch, - ...(commitMessage ? { commitMessage } : {}), - ...(!allSelected ? { filePaths: selectedFiles.map((file) => file.path) } : {}), - }); - setDialogCommitMessage(""); - setExcludedFiles(new Set()); - }, - [allSelected, dialogCommitMessage, onRunAction, selectedFiles], - ); - - const onPressMenuItem = useCallback( - async (item: (typeof menuItems)[number]) => { - if (item.disabled) { - return; - } - if (item.kind === "open_pr") { - await openExistingPr(); - return; - } - if (item.dialogAction === "commit") { - openCommitSheet(); - return; - } - if (item.dialogAction === "push") { - await runActionWithPrompt({ action: "push" }); - return; - } - if (item.dialogAction === "create_pr") { - await runActionWithPrompt({ action: "create_pr" }); - } - }, - [openCommitSheet, openExistingPr, runActionWithPrompt], - ); - - const onPressNativeMenuAction = useCallback( - ({ nativeEvent }: { nativeEvent: { event: string } }) => { - if (nativeEvent.event === "quick") { - void runQuickAction(); - return; - } - if (nativeEvent.event === "more") { - setGitSheetVisible(true); - } - }, - [runQuickAction], - ); - return ( - <> - - + + {}} + subtitle={compactMenuStatus(gitStatus)} > - - - - Git - - - {triggerStatus} - - - - - - - setGitSheetVisible(false)} - backgroundStyle={{ backgroundColor: palette.sheetBackground }} - handleIndicatorStyle={{ backgroundColor: palette.dotSeparator }} - > - - - - - - Branch - - - {currentBranchLabel} - - - {statusSummary(gitStatus)} - - - void onRefreshStatus()} - > - - - - - - - {sheetMenuItems.map(({ item, disabledReason }, index) => ( - - {index > 0 ? ( - - ) : null} - { - void onPressMenuItem(item); - }} - /> - - ))} - {(gitStatus?.behindCount ?? 0) > 0 ? ( - <> - - { - void onPull(); - }} - /> - - ) : null} - - setBranchSheetVisible(true)} - /> - - - - {currentWorktreePath ? : null} - - {gitOperationLabel ? ( - - - - ) : null} - - - - - setCommitSheetVisible(false)} - backgroundStyle={{ backgroundColor: palette.sheetBackground }} - handleIndicatorStyle={{ backgroundColor: palette.dotSeparator }} - > - - - - - Commit changes - - - Review the file set, optionally write a message, then commit here or on a new - feature branch. - - - - - - - Branch - - - {gitStatus?.branch ?? "(detached HEAD)"} - - - {isDefaultBranch ? ( - - Warning: this is the default branch. - - ) : null} - - - - - - - Files - - - {selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions} - - - - {!allSelected && isEditingFiles ? ( - setExcludedFiles(new Set())} - > - - Reset - - - ) : null} - setIsEditingFiles((current) => !current)} - > - - {isEditingFiles ? "Done" : "Edit"} - - - - - - {allFiles.length === 0 ? ( - - No changed files are available to commit. - - ) : !isEditingFiles ? ( - - {selectedFilePreview.map((file) => ( - - - {file.path} - - - +{file.insertions} - - - -{file.deletions} - - - ))} - {selectedFiles.length > selectedFilePreview.length ? ( - - +{selectedFiles.length - selectedFilePreview.length} more files - - ) : null} - - ) : ( - - {allFiles.map((file) => { - const included = !excludedFiles.has(file.path); - return ( - { - setExcludedFiles((current) => { - const next = new Set(current); - if (next.has(file.path)) { - next.delete(file.path); - } else { - next.add(file.path); - } - return next; - }); - }} - > - - - - {file.path} - - {!included ? ( - - Excluded from this commit - - ) : null} - - - - +{file.insertions} - - - -{file.deletions} - - - - - ); - })} - - )} - - - - - Commit message - - - - - - - { - void runCommitAction(true); - }} - /> - - - { - void runCommitAction(false); - }} - /> - - - - - - - setDefaultBranchSheetVisible(false)} - backgroundStyle={{ backgroundColor: palette.sheetBackground }} - handleIndicatorStyle={{ backgroundColor: palette.dotSeparator }} - > - {compactMenuBranchLabel(currentBranchLabel)} + + void runQuickAction()} + subtitle={quickActionHint ?? undefined} > - - - {pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"} - - - {pendingDefaultBranchActionCopy?.description ?? "Choose how to continue."} - - - - - { - void continuePendingDefaultBranchAction(); - }} - /> - { - void movePendingActionToFeatureBranch(); - }} - /> - - - - - setBranchSheetVisible(false)} - backgroundStyle={{ backgroundColor: palette.sheetBackground }} - handleIndicatorStyle={{ backgroundColor: palette.dotSeparator }} - > - - - - - Branches & worktrees - - - Switch this thread, create a branch, or move work onto its own worktree. - - - - - - New branch - - - { - const branch = sanitizeFeatureBranchName(newBranchName.trim()); - if (branch.length === 0) { - return; - } - void onCreateBranch(branch).then(() => { - setNewBranchName(""); - setBranchSheetVisible(false); - }); - }} - /> - - - - - New worktree - - - - { - const baseBranch = worktreeBaseBranch.trim(); - const newBranch = worktreeBranchName.trim(); - if (baseBranch.length === 0 || newBranch.length === 0) { - return; - } - void onCreateWorktree({ - baseBranch, - newBranch, - }).then(() => { - setWorktreeBranchName(""); - setBranchSheetVisible(false); - }); - }} - /> - - - - - Existing branches - - {branchesLoading ? ( - - Loading branches… - - ) : null} - {!branchesLoading && availableBranches.length === 0 ? ( - - No local branches found. - - ) : 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 ( - { - void onCheckoutBranch(branch.name).then(() => { - setBranchSheetVisible(false); - }); - }} - > - - {branch.name} - - - {subtitle} - - - ); - })} - - - - - + {quickAction.label} + + + router.push({ + pathname: "/threads/[environmentId]/[threadId]/git", + params: { environmentId, threadId }, + }) + } + subtitle="Commit, files, branches" + > + More + + + ); } diff --git a/apps/mobile/src/features/threads/ThreadListScreen.tsx b/apps/mobile/src/features/threads/ThreadListScreen.tsx index e9ba822b8c..1e3e80dcfc 100644 --- a/apps/mobile/src/features/threads/ThreadListScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadListScreen.tsx @@ -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 ( {props.label} @@ -108,35 +108,20 @@ function StatCard(props: { readonly value: string; readonly icon: React.ComponentProps["name"]; }) { - const isDarkMode = useColorScheme() === "dark"; - const palette = makeAppPalette(isDarkMode); + const foregroundSecondary = useThemeColor("--color-foreground-secondary"); return ( - + - + {props.label} - - {props.value} - + {props.value} ); } @@ -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(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 ( { @@ -183,13 +169,8 @@ function ThreadRow(props: { > - - {props.thread.title} - - + {props.thread.title} + {lastConversationLine(props.thread)} @@ -197,8 +178,8 @@ function ThreadRow(props: { {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 ( - + - + {props.project.environmentLabel} - + {props.project.workspaceRoot} void props.onCreateThread(props.project)} > New thread @@ -273,13 +248,12 @@ function ProjectSection(props: { {hiddenCount > 0 ? ( setExpanded((current) => !current)} > {expanded ? "Show less" : `Show ${hiddenCount} more`} @@ -297,28 +271,19 @@ function CreateThreadModal(props: { readonly onClose: () => void; readonly onSelectProject: (project: ScopedMobileProject) => Promise; }) { - const isDarkMode = useColorScheme() === "dark"; - const palette = makeAppPalette(isDarkMode); - if (!props.group) { return null; } return ( - - + + - + New thread in {props.group.title} - + Choose which environment should own the new thread. @@ -327,31 +292,24 @@ function CreateThreadModal(props: { {props.group.projects.map(({ project, threads }) => ( { void props.onSelectProject(project).then(props.onClose); }} > - + {project.environmentLabel} - + {project.workspaceRoot} - + {threads.length} thread{threads.length === 1 ? "" : "s"} @@ -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 => { @@ -397,9 +354,8 @@ export function ThreadListScreen(props: ThreadListScreenProps) { return ( {props.heroTitle} - + {isSplitLayout ? "Native workspace" : "Repo board"} - + {isSplitLayout ? "Keep your repositories visible while you move between active threads." : "Your connected repositories, grouped by identity across environments."} @@ -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" > - - {group.title} - + {group.title} {group.subtitle ? ( - + {group.subtitle} ) : null} {group.projectCount} environment{group.projectCount === 1 ? "" : "s"} ·{" "} {group.threadCount} active thread{group.threadCount === 1 ? "" : "s"} @@ -527,8 +465,7 @@ export function ThreadListScreen(props: ThreadListScreenProps) { { if (group.projects.length === 1) { void props.onCreateThread(group.projects[0]!.project); @@ -538,8 +475,8 @@ export function ThreadListScreen(props: ThreadListScreenProps) { }} > New thread diff --git a/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx b/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx index fb26f64abf..8fe5a6adcb 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx @@ -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, ]} > - - Threads - + Threads { 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" > @@ -189,22 +184,16 @@ export function ThreadNavigationDrawer(props: { {groupedThreads.map((group) => ( {group.title} - + {group.threads.length === 0 ? ( - + No threads yet @@ -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} > - + {thread.title} {relativeTime(thread.updatedAt ?? thread.createdAt)} diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 1bc566e02d..81c113c74d 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -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" > runtime.serverConfig)); + const headerSubtitle = [screenTitle(serverConfig, null), selectedThread.environmentLabel] + .filter(Boolean) + .join(" · "); + return ( - - 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); + <> + ( + { + // TODO: trigger rename modal + }} + > + + {selectedThread.title} + + + {headerSubtitle} + + + ), }} - 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} /> - setDrawerVisible(false)} - onSelectThread={(thread) => { - onSelectThread(thread); - router.replace(buildThreadRoutePath(thread)); - }} - onStartNewTask={() => router.push("/new")} + - + + + 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} + /> + + setDrawerVisible(false)} + onSelectThread={(thread) => { + onSelectThread(thread); + router.replace(buildThreadRoutePath(thread)); + }} + onStartNewTask={() => router.push("/new")} + /> + + ); } diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx new file mode 100644 index 0000000000..6591646fb3 --- /dev/null +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx @@ -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 ( + + + + New branch + + + { + const branch = sanitizeFeatureBranchName(newBranchName.trim()); + if (branch.length === 0) return; + void gitActions.onCreateSelectedThreadBranch(branch).then(() => { + setNewBranchName(""); + router.dismiss(); + }); + }} + /> + + + + + New worktree + + + + { + 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(); + }); + }} + /> + + + + + Existing branches + + {branchesLoading ? ( + + Loading branches... + + ) : null} + {!branchesLoading && availableBranches.length === 0 ? ( + + No local branches found. + + ) : 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 ( + { + void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => { + router.dismiss(); + }); + }} + > + + {branch.name} + {subtitle} + + ); + })} + + + ); +} diff --git a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx new file mode 100644 index 0000000000..8b1413f9bb --- /dev/null +++ b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx @@ -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>(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 ( + + + + Branch + + {gitStatus.data?.branch ?? "(detached HEAD)"} + + + {isDefaultBranch ? ( + + Warning: this is the default branch. + + ) : null} + + + + + + Files + + {selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions} + + + + {!allSelected && isEditingFiles ? ( + setExcludedFiles(new Set())} + > + Reset + + ) : null} + setIsEditingFiles((current) => !current)} + > + + {isEditingFiles ? "Done" : "Edit"} + + + + + + {allFiles.length === 0 ? ( + + No changed files are available to commit. + + ) : !isEditingFiles ? ( + + {selectedFilePreview.map((file) => ( + + + {file.path} + + + +{file.insertions} + + + -{file.deletions} + + + ))} + {selectedFiles.length > selectedFilePreview.length ? ( + + +{selectedFiles.length - selectedFilePreview.length} more files + + ) : null} + + ) : ( + + {allFiles.map((file) => { + const included = !excludedFiles.has(file.path); + return ( + { + setExcludedFiles((current) => { + const next = new Set(current); + if (next.has(file.path)) { + next.delete(file.path); + } else { + next.add(file.path); + } + return next; + }); + }} + > + + + + + {file.path} + + {!included ? ( + + Excluded from this commit + + ) : null} + + + + +{file.insertions} + + + -{file.deletions} + + + + + ); + })} + + )} + + + + Commit message + + + + + + void runCommitAction(true)} + /> + + + void runCommitAction(false)} + /> + + + + ); +} diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx new file mode 100644 index 0000000000..38b5d26103 --- /dev/null +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx @@ -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 ( + + + + + + Confirm + + + {copy?.title ?? "Run action on default branch?"} + + + {copy?.description ?? "Choose how to continue."} + + + + + void continuePendingAction()} + /> + void movePendingActionToFeatureBranch()} + /> + + + ); +} diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx new file mode 100644 index 0000000000..9077a3eae3 --- /dev/null +++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx @@ -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 ( + + + + + void gitActions.refreshSelectedThreadGitStatus()} + > + + + + Branch + + {currentBranchLabel} + + {statusSummary(gitStatus.data)} + + + + + + {sheetMenuItems.map(({ item, disabledReason }, index) => ( + + {index > 0 ? ( + + ) : null} + void onPressMenuItem(item)} + /> + + ))} + {(gitStatus.data?.behindCount ?? 0) > 0 ? ( + <> + + void gitActions.onPullSelectedThreadBranch()} + /> + + ) : null} + + + router.push({ + pathname: "/threads/[environmentId]/[threadId]/git/branches", + params: { environmentId, threadId }, + }) + } + /> + + + {currentWorktreePath ? : null} + + {gitOperationLabel ? ( + + + + ) : null} + + + ); +} diff --git a/apps/mobile/src/features/threads/git/gitSheetComponents.tsx b/apps/mobile/src/features/threads/git/gitSheetComponents.tsx new file mode 100644 index 0000000000..8dd8e32ac6 --- /dev/null +++ b/apps/mobile/src/features/threads/git/gitSheetComponents.tsx @@ -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["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 ( + + + + {props.label} + + + ); +} + +export function MetaCard(props: { readonly label: string; readonly value: string }) { + return ( + + + {props.label} + + + {props.value} + + + ); +} + +export function SheetListRow(props: { + readonly icon: ComponentProps["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 ( + + + + + + {props.title} + {props.subtitle ? ( + {props.subtitle} + ) : null} + + + + ); +} + +/* ─── Shared utilities ──────────────────────────────────────────────── */ + +export function menuItemIconName( + icon: "commit" | "push" | "pr", +): ComponentProps["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 "); +} diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx index 49acb77dde..c44108ef34 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx @@ -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(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>([]); const [submitting, setSubmitting] = useState(false); const [branchQuery, setBranchQuery] = useState(""); - const [branchesLoading, setBranchesLoading] = useState(false); - const [availableBranches, setAvailableBranches] = useState>([]); const [runtimeMode, setRuntimeMode] = useState(DEFAULT_RUNTIME_MODE); const [interactionMode, setInteractionMode] = useState( 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( () => ({ diff --git a/apps/mobile/src/lib/arrayCompat.ts b/apps/mobile/src/lib/arrayCompat.ts deleted file mode 100644 index 3343d5e00f..0000000000 --- a/apps/mobile/src/lib/arrayCompat.ts +++ /dev/null @@ -1,42 +0,0 @@ -export function sortCopy( - values: ReadonlyArray, - 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(values: ReadonlyArray): 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; -} diff --git a/apps/mobile/src/lib/classNames.ts b/apps/mobile/src/lib/classNames.ts deleted file mode 100644 index ef515666fc..0000000000 --- a/apps/mobile/src/lib/classNames.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function cx(...parts: Array): string { - return parts.filter(Boolean).join(" "); -} diff --git a/apps/mobile/src/lib/clientId.ts b/apps/mobile/src/lib/clientId.ts deleted file mode 100644 index a962962849..0000000000 --- a/apps/mobile/src/lib/clientId.ts +++ /dev/null @@ -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)}`; -} diff --git a/apps/mobile/src/lib/cn.ts b/apps/mobile/src/lib/cn.ts new file mode 100644 index 0000000000..365058cebd --- /dev/null +++ b/apps/mobile/src/lib/cn.ts @@ -0,0 +1,6 @@ +import { type ClassValue, clsx } from "clsx"; +import { twMerge } from "tailwind-merge"; + +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)); +} diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts index deacc9f302..871982442e 100644 --- a/apps/mobile/src/lib/composerImages.ts +++ b/apps/mobile/src/lib/composerImages.ts @@ -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, diff --git a/apps/mobile/src/lib/mobileLayout.ts b/apps/mobile/src/lib/mobileLayout.ts new file mode 100644 index 0000000000..0ae284e463 --- /dev/null +++ b/apps/mobile/src/lib/mobileLayout.ts @@ -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, + }; +} diff --git a/apps/mobile/src/lib/storage.ts b/apps/mobile/src/lib/storage.ts index 6712881b42..a737ea69bc 100644 --- a/apps/mobile/src/lib/storage.ts +++ b/apps/mobile/src/lib/storage.ts @@ -2,9 +2,7 @@ import * as SecureStore from "expo-secure-store"; import type { SavedRemoteConnection } from "./connection"; -const CONNECTIONS_KEY = "t3code:connections"; - -type SavedRemoteConnectionMetadata = Omit; +const CONNECTIONS_KEY = "t3code.connections"; async function readStorageItem(key: string): Promise { return await SecureStore.getItemAsync(key); @@ -14,31 +12,7 @@ async function writeStorageItem(key: string, value: string): Promise { await SecureStore.setItemAsync(key, value); } -async function removeStorageItem(key: string): Promise { - await SecureStore.deleteItemAsync(key); -} - -function connectionTokenKey(environmentId: string): string { - return `t3code:bearer-token:${environmentId}`; -} - -async function loadSecureToken(environmentId: string): Promise { - return (await readStorageItem(connectionTokenKey(environmentId))) ?? ""; -} - -async function storeSecureToken(environmentId: string, token: string): Promise { - const tokenKey = connectionTokenKey(environmentId); - if (token.trim().length === 0) { - await removeStorageItem(tokenKey); - return; - } - - await writeStorageItem(tokenKey, token); -} - -async function loadSavedConnectionMetadata(): Promise< - ReadonlyArray -> { +export async function loadSavedConnections(): Promise> { 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; + readonly connections?: ReadonlyArray; }; - return parsed.connections ?? []; + return (parsed.connections ?? []).filter((c) => c.environmentId && c.bearerToken?.trim()); } catch { return []; } } -async function saveSavedConnectionMetadata( - connections: ReadonlyArray, -): Promise { - await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections })); -} - -export async function loadSavedConnections(): Promise> { - const metadata = await loadSavedConnectionMetadata(); - const resolved = await Promise.all( - metadata.map(async (connection): Promise => { - 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 { - 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 { - 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 })); } diff --git a/apps/mobile/src/lib/theme.ts b/apps/mobile/src/lib/theme.ts deleted file mode 100644 index 00523c03b6..0000000000 --- a/apps/mobile/src/lib/theme.ts +++ /dev/null @@ -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; - -/** Convenience hook that returns the palette for the current color scheme. */ -export function useAppPalette(): AppPalette { - const isDarkMode = useColorScheme() === "dark"; - return makeAppPalette(isDarkMode); -} diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index a315faa12d..d64baa774b 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -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; readonly createdAt: string; @@ -380,7 +381,7 @@ export function buildPendingUserInputAnswers( export function buildThreadFeed( thread: OrchestrationThread, queuedMessages: ReadonlyArray, - dispatchingQueuedMessageId: string | null, + dispatchingQueuedMessageId: MessageId | null, options?: { readonly loadedMessages?: ReadonlyArray; }, @@ -398,10 +399,10 @@ export function buildThreadFeed( })), ...queuedMessages.map((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) => { diff --git a/apps/mobile/src/lib/useThemeColor.ts b/apps/mobile/src/lib/useThemeColor.ts new file mode 100644 index 0000000000..38dbf6c9b0 --- /dev/null +++ b/apps/mobile/src/lib/useThemeColor.ts @@ -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; +} diff --git a/apps/mobile/src/lib/uuid.ts b/apps/mobile/src/lib/uuid.ts new file mode 100644 index 0000000000..95af0040f1 --- /dev/null +++ b/apps/mobile/src/lib/uuid.ts @@ -0,0 +1,4 @@ +import * as Effect from "effect/Effect"; +import * as Random from "effect/Random"; + +export const uuidv4 = () => Effect.runSync(Random.nextUUIDv4); diff --git a/apps/mobile/src/state/atomRegistry.tsx b/apps/mobile/src/state/atomRegistry.tsx new file mode 100644 index 0000000000..e36da5f3b2 --- /dev/null +++ b/apps/mobile/src/state/atomRegistry.tsx @@ -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 {children}; +} diff --git a/apps/mobile/src/state/thread-composer-store.ts b/apps/mobile/src/state/thread-composer-store.ts index 6f4562114b..848ecc3a8d 100644 --- a/apps/mobile/src/state/thread-composer-store.ts +++ b/apps/mobile/src/state/thread-composer-store.ts @@ -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; readonly draftAttachmentsByThreadKey: Record>; - readonly dispatchingQueuedMessageId: string | null; + readonly dispatchingQueuedMessageId: MessageId | null; readonly queuedMessagesByThreadKey: Record>; 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()((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]; diff --git a/apps/mobile/src/state/thread-git-store.ts b/apps/mobile/src/state/thread-git-store.ts deleted file mode 100644 index 8ec624d8ea..0000000000 --- a/apps/mobile/src/state/thread-git-store.ts +++ /dev/null @@ -1,45 +0,0 @@ -import type { GitStatusResult } from "@t3tools/contracts"; -import { useStore } from "zustand"; -import { createStore } from "zustand/vanilla"; - -interface ThreadGitStoreState { - readonly gitStatusByThreadKey: Record; - readonly gitOperationLabelByThreadKey: Record; - 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()((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(selector: (state: ThreadGitStoreState) => T): T { - return useStore(threadGitStore, selector); -} diff --git a/apps/mobile/src/state/use-git-action-state.ts b/apps/mobile/src/state/use-git-action-state.ts new file mode 100644 index 0000000000..d8e54015f3 --- /dev/null +++ b/apps/mobile/src/state/use-git-action-state.ts @@ -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; +} diff --git a/apps/mobile/src/state/use-git-branches.ts b/apps/mobile/src/state/use-git-branches.ts new file mode 100644 index 0000000000..49595309bf --- /dev/null +++ b/apps/mobile/src/state/use-git-branches.ts @@ -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; +} diff --git a/apps/mobile/src/state/use-git-status.ts b/apps/mobile/src/state/use-git-status.ts new file mode 100644 index 0000000000..54686ed69c --- /dev/null +++ b/apps/mobile/src/state/use-git-status.ts @@ -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; +} diff --git a/apps/mobile/src/state/use-project-actions.ts b/apps/mobile/src/state/use-project-actions.ts index 5c87d7641e..f4f60ec9da 100644 --- a/apps/mobile/src/state/use-project-actions.ts +++ b/apps/mobile/src/state/use-project-actions.ts @@ -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, diff --git a/apps/mobile/src/state/use-remote-catalog.ts b/apps/mobile/src/state/use-remote-catalog.ts index 75da65614c..5427427a4f 100644 --- a/apps/mobile/src/state/use-remote-catalog.ts +++ b/apps/mobile/src/state/use-remote-catalog.ts @@ -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( + (left, right) => + (left.title.localeCompare(right.title) as -1 | 0 | 1) || + (left.environmentLabel.localeCompare(right.environmentLabel) as -1 | 0 | 1), +); + +const threadsSortOrder = Order.make( + (left, right) => + ((new Date(right.updatedAt ?? right.createdAt).getTime() - + new Date(left.updatedAt ?? left.createdAt).getTime()) as -1 | 0 | 1) || + (left.environmentLabel.localeCompare(right.environmentLabel) as -1 | 0 | 1), +); + export function useRemoteCatalog() { const { connectedEnvironments, connectionState } = useRemoteConnectionStatus(); const { environmentStateById, savedConnectionsById } = useRemoteEnvironmentState(); const projects = useMemo>( () => - 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>( () => - 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], ); diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts index a010358852..a1412817e2 100644 --- a/apps/mobile/src/state/use-remote-environment-registry.ts +++ b/apps/mobile/src/state/use-remote-environment-registry.ts @@ -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(); +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( + (left, right) => left.environmentLabel.localeCompare(right.environmentLabel) as -1 | 0 | 1, +); + function deriveConnectedEnvironments( savedConnectionsById: Record, environmentStateById: ReturnType["environmentStateById"], ): ReadonlyArray { - 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]); } diff --git a/apps/mobile/src/state/use-selected-thread-commands.ts b/apps/mobile/src/state/use-selected-thread-commands.ts index 0f0f2ee8c7..104362c794 100644 --- a/apps/mobile/src/state/use-selected-thread-commands.ts +++ b/apps/mobile/src/state/use-selected-thread-commands.ts @@ -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, diff --git a/apps/mobile/src/state/use-selected-thread-git-actions.ts b/apps/mobile/src/state/use-selected-thread-git-actions.ts new file mode 100644 index 0000000000..3134afef70 --- /dev/null +++ b/apps/mobile/src/state/use-selected-thread-git-actions.ts @@ -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, + 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 ( + operation: (input: { + readonly thread: ScopedMobileThread; + readonly project: ScopedMobileProject; + readonly cwd: string; + }) => Promise, + ): Promise => { + 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> => { + 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 => { + 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, + }; +} diff --git a/apps/mobile/src/state/use-selected-thread-git-state.ts b/apps/mobile/src/state/use-selected-thread-git-state.ts new file mode 100644 index 0000000000..099021dbcf --- /dev/null +++ b/apps/mobile/src/state/use-selected-thread-git-state.ts @@ -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, + }; +} diff --git a/apps/mobile/src/state/use-selected-thread-git.ts b/apps/mobile/src/state/use-selected-thread-git.ts deleted file mode 100644 index 971ebcc00f..0000000000 --- a/apps/mobile/src/state/use-selected-thread-git.ts +++ /dev/null @@ -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, - 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 ( - label: string, - operation: (input: { - readonly client: WsRpcClient; - readonly thread: ScopedMobileThread; - readonly project: ScopedMobileProject; - }) => Promise, - ): Promise => { - 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> => { - 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> => { - 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 => { - 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, - }; -} diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 8e785784b5..d411fde8bc 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -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, diff --git a/apps/mobile/uniwind-types.d.ts b/apps/mobile/uniwind-types.d.ts new file mode 100644 index 0000000000..cc099419a9 --- /dev/null +++ b/apps/mobile/uniwind-types.d.ts @@ -0,0 +1,10 @@ +// NOTE: This file is generated by uniwind and it should not be edited manually. +/// + +declare module 'uniwind' { + export interface UniwindConfig { + themes: readonly ['light', 'dark'] + } +} + +export {} diff --git a/apps/web/src/lib/gitStatusState.test.ts b/apps/web/src/lib/gitStatusState.test.ts deleted file mode 100644 index 2e17cd1552..0000000000 --- a/apps/web/src/lib/gitStatusState.test.ts +++ /dev/null @@ -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(), - 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(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(); - }); -}); diff --git a/apps/web/src/lib/gitStatusState.ts b/apps/web/src/lib/gitStatusState.ts index 2c23ae5b82..7ee3e7b1e1 100644 --- a/apps/web/src/lib/gitStatusState.ts +++ b/apps/web/src/lib/gitStatusState.ts @@ -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 | null; - readonly isPending: boolean; -} +export type { GitStatusState, GitStatusTarget }; -type GitStatusClient = Pick; -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({ - data: null, - error: null, - cause: null, - isPending: false, -}); -const INITIAL_GIT_STATUS_STATE = Object.freeze({ - ...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(); -const knownGitStatusKeys = new Set(); -const gitStatusRefreshInFlight = new Map>(); -const gitStatusLastRefreshAtByKey = new Map(); - -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 { - 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); -} diff --git a/bun.lock b/bun.lock index a33b8013db..a87c77e855 100644 --- a/bun.lock +++ b/bun.lock @@ -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/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="], - "@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.2.104", "", { "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/sdk@0.81.0", "", { "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/commands@1.5.1", "", {}, "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw=="], - "@isaacs/fs-minipass": ["@isaacs/fs-minipass@4.0.1", "", { "dependencies": { "minipass": "^7.0.4" } }, "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w=="], - "@isaacs/ttlcache": ["@isaacs/ttlcache@1.4.1", "", {}, "sha512-RQgQ4uQ+pLbqXfOmieB91ejmLwvSgv9nLx6sT6sD83s7umBypgg+OIBOBbEUiJXrfpnp9j0mRhYYdzp9uqq3lA=="], "@istanbuljs/load-nyc-config": ["@istanbuljs/load-nyc-config@1.1.0", "", { "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/postcss@4.1.12", "", { "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/vite@4.2.2", "", { "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": ["array-iterate@2.0.1", "", {}, "sha512-I1jXZMjAgCMmxT4qxXfPXa6SthSoE8h6gkSI9BGGNv8mP8G/v0blc+qFnZu6K42vTOiuME596QaLO0TP3Lk0xg=="], - "array-timsort": ["array-timsort@1.0.3", "", {}, "sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ=="], - "asap": ["asap@2.0.6", "", {}, "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA=="], "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], @@ -1440,8 +1431,6 @@ "chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], - "chownr": ["chownr@3.0.0", "", {}, "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g=="], - "chrome-launcher": ["chrome-launcher@0.15.2", "", { "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": ["chromium-edge-launcher@0.2.0", "", { "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": ["color-string@1.9.1", "", { "dependencies": { "color-name": "^1.0.0", "simple-swizzle": "^0.2.2" } }, "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg=="], - "colorjs.io": ["colorjs.io@0.6.0-alpha.1", "", {}, "sha512-c/h/8uAmPydQcriRdX8UTAFHj6SpSHFHBA8LvMikvYWAVApPTwg/pyOXNsGmaCBd6L/EeDlRHSNhTtnIFp/qsg=="], - "comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="], "commander": ["commander@12.1.0", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="], - "comment-json": ["comment-json@4.6.2", "", { "dependencies": { "array-timsort": "^1.0.3", "esprima": "^4.0.1" } }, "sha512-R2rze/hDX30uul4NZoIZ76ImSJLFxn/1/ZxtKC1L77y2X1k+yYu1joKbAtMA2Fg3hZrTOiw0I5mwVMo0cf250w=="], - "common-ancestor-path": ["common-ancestor-path@2.0.0", "", {}, "sha512-dnN3ibLeoRf2HNC+OlCiNc5d2zxbLJXOtiZUudNFSXZrNSydxcCsSpRzXwfu7BBWCIfHPw+xTayeBvJCP/D8Ng=="], "compressible": ["compressible@2.0.18", "", { "dependencies": { "mime-db": ">= 1.43.0 < 2" } }, "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg=="], @@ -1528,6 +1513,8 @@ "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + "culori": ["culori@4.0.2", "", {}, "sha512-1+BhOB8ahCn4O0cep0Sh2l9KCOfOdY+BXJnKMHFFzDEouSr/el18QwXEMRlOj9UY5nCeA8UN3a/82rUWRBeyBw=="], + "date-fns": ["date-fns@4.1.0", "", {}, "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg=="], "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], @@ -2240,8 +2227,6 @@ "minipass": ["minipass@7.1.3", "", {}, "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="], - "minizlib": ["minizlib@3.1.0", "", { "dependencies": { "minipass": "^7.1.2" } }, "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw=="], - "mkdirp": ["mkdirp@1.0.4", "", { "bin": { "mkdirp": "bin/cmd.js" } }, "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw=="], "mrmime": ["mrmime@2.0.1", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="], @@ -2264,8 +2249,6 @@ "nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="], - "nativewind": ["nativewind@5.0.0-preview.3", "", { "dependencies": { "tailwindcss-safe-area": "^1.1.0" }, "peerDependencies": { "react-native-css": "^3.0.1", "tailwindcss": ">4.1.11" } }, "sha512-cbl1GzzY55NL2IG35AaAVfrL4+bCh77sa39aST5/o7xy3TLPthAtzhNPstnrCn+DtIglTnXOlOJGFrX2WdhI6w=="], - "negotiator": ["negotiator@0.6.3", "", {}, "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg=="], "neotraverse": ["neotraverse@0.6.18", "", {}, "sha512-Z4SmBUweYa09+o6pG+eASabEpP6QkQ70yHj351pQoEXIs8uHbaU2DWVmzBANKgflPa47A50PtB2+NgRpQvr7vA=="], @@ -2458,8 +2441,6 @@ "react-native": ["react-native@0.83.4", "", { "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": ["react-native-css@3.0.7", "", { "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": ["react-native-fit-image@1.5.5", "", { "dependencies": { "prop-types": "^15.5.10" } }, "sha512-Wl3Vq2DQzxgsWKuW4USfck9zS7YzhvLNPpkwUUCF90bL32e1a0zOVQ3WsJILJOwzmPdHfzZmWasiiAUNBkhNkg=="], "react-native-gesture-handler": ["react-native-gesture-handler@2.30.1", "", { "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": ["tailwindcss@4.1.12", "", {}, "sha512-DzFtxOi+7NsFf7DBtI3BJsynR+0Yp6etH+nRPTbpWnS2pZBaSksv/JGctNwSWzbFjp0vxSqknaUylseZqMDGrA=="], - "tailwindcss-safe-area": ["tailwindcss-safe-area@1.3.0", "", { "peerDependencies": { "tailwindcss": "^4.0.0" } }, "sha512-RoxnW1zAjBWC3XK+row7Qj5toRMRlKNN/p3FLXb6fTGKxDGWT6JP/mcNX1yf09xRficQ308hbwiedgniepSp1Q=="], - "tapable": ["tapable@2.3.2", "", {}, "sha512-1MOpMXuhGzGL5TTCZFItxCc0AARf1EZFQkGqMm7ERKj8+Hgr5oLvJOVFcC+lRmR8hCe2S3jC4T5D7Vg/d7/fhA=="], - "tar": ["tar@7.5.13", "", { "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": ["terminal-link@2.1.1", "", { "dependencies": { "ansi-escapes": "^4.2.1", "supports-hyperlinks": "^2.0.0" } }, "sha512-un0FmiRUQNr5PJqy9kP7c40F5BOfpGlYTrxonDChEZB7pzZxRNp/bt+ymiy9/npwXya9KH99nJ/GXFIiUkYGFQ=="], "terser": ["terser@5.46.1", "", { "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": ["universalify@2.0.1", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="], + "uniwind": ["uniwind@1.6.2", "", { "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": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="], "unplugin": ["unplugin@2.3.11", "", { "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": ["y18n@5.0.8", "", {}, "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": ["yaml@2.8.3", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg=="], @@ -3056,13 +3035,15 @@ "@shikijs/transformers/@shikijs/types": ["@shikijs/types@3.23.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ=="], + "@tailwindcss/node/tailwindcss": ["tailwindcss@4.2.1", "", {}, "sha512-/tBrSQ36vCleJkAOsy9kbNTgaxvGbyOamC30PRePTQe/o1MFwEKHQk4Cn7BNGaPtjp+PuUrByJehM1hgxfq4sw=="], + "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.9.2", "", { "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/runtime@1.9.2", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.1", "", { "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/wasm-util@0.10.1", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="], @@ -3212,8 +3193,6 @@ "react-native/glob": ["glob@7.2.3", "", { "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": ["babel-plugin-react-compiler@19.1.0-rc.1-rc-af1b7da-20250421", "", { "dependencies": { "@babel/types": "^7.26.0" } }, "sha512-E3kaokBhWDLf7ZD8fuYjYn0ZJHYZ+3EHtAWCdX2hl4lpu1z9S/Xr99sxhx2bTCVB41oIesz9FtM8f4INsrZaOw=="], - "react-native-reanimated/react-native-is-edge-to-edge": ["react-native-is-edge-to-edge@1.2.1", "", { "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-FLbPWl/MyYQWz+KwqOZsSyj2JmLKglHatd3xLZWskXOpRaio4LfEDEz8E/A6uD8QoTHW6Aobw1jbEwK7KMgR7Q=="], "react-native-reanimated/semver": ["semver@7.7.3", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q=="], @@ -3292,8 +3271,6 @@ "yargs/yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="], - "@babel/helper-compilation-targets/lru-cache/yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], - "@electron/get/fs-extra/jsonfile": ["jsonfile@4.0.0", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="], "@electron/get/fs-extra/universalify": ["universalify@0.1.2", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="], diff --git a/packages/client-runtime/src/environmentConnection.ts b/packages/client-runtime/src/environmentConnection.ts index 93846832ec..01eef725ed 100644 --- a/packages/client-runtime/src/environmentConnection.ts +++ b/packages/client-runtime/src/environmentConnection.ts @@ -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>( events: ReadonlyArray, ): ReadonlyArray { - 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, diff --git a/packages/client-runtime/src/gitActionState.test.ts b/packages/client-runtime/src/gitActionState.test.ts new file mode 100644 index 0000000000..3b82a98ded --- /dev/null +++ b/packages/client-runtime/src/gitActionState.test.ts @@ -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() { + let resolve!: (value: T) => void; + let reject!: (reason?: unknown) => void; + const promise = new Promise((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 { + return { + actionId: "action-123", + cwd: "/repo", + action: "commit_push", + kind: "phase_started", + phase: "commit", + label: "Committing...", + }; +} + +function createHookStartedEvent(): Extract { + return { + actionId: "action-123", + cwd: "/repo", + action: "commit_push", + kind: "hook_started", + hookName: "post-commit", + }; +} + +function createHookOutputEvent(): Extract { + return { + actionId: "action-123", + cwd: "/repo", + action: "commit_push", + kind: "hook_output", + hookName: "post-commit", + stream: "stdout", + text: "hook output", + }; +} + +function createHookFinishedEvent(): Extract { + return { + actionId: "action-123", + cwd: "/repo", + action: "commit_push", + kind: "hook_finished", + hookName: "post-commit", + exitCode: 0, + durationMs: 12, + }; +} + +function createActionFinishedEvent(): Extract { + 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(); + const pullDeferred = createDeferred(); + const checkoutDeferred = createDeferred(); + const createBranchDeferred = createDeferred(); + const createWorktreeDeferred = createDeferred(); + const initDeferred = createDeferred(); + const runStackedActionDeferred = createDeferred(); + 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); + }); +}); diff --git a/packages/client-runtime/src/gitActionState.ts b/packages/client-runtime/src/gitActionState.ts new file mode 100644 index 0000000000..26209e7cba --- /dev/null +++ b/packages/client-runtime/src/gitActionState.ts @@ -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({ + 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(); + +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( + target: GitActionTarget, + input: { + readonly operation: GitActionOperation; + readonly label: string; + readonly actionId?: string; + readonly action?: GitStackedAction; + readonly client?: GitActionClient | undefined; + readonly execute: (client: GitActionClient) => Promise; + }, + ): Promise { + 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> | 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 { + 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, + client?: GitActionClient, + options?: { readonly label?: string }, + ): Promise { + 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, + client?: GitActionClient, + options?: { readonly label?: string }, + ): Promise { + 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, + client?: GitActionClient, + options?: { readonly label?: string }, + ): Promise { + 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> | 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 & { readonly actionId?: string }, + options?: { + readonly client?: GitActionClient; + readonly gitStatus?: GitStatusResult | null; + readonly onProgress?: (event: GitActionProgressEvent) => void; + }, + ): Promise { + 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, + }; +} diff --git a/packages/client-runtime/src/gitBranchState.test.ts b/packages/client-runtime/src/gitBranchState.test.ts new file mode 100644 index 0000000000..be8ccb21a6 --- /dev/null +++ b/packages/client-runtime/src/gitBranchState.test.ts @@ -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[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); + }); +}); diff --git a/packages/client-runtime/src/gitBranchState.ts b/packages/client-runtime/src/gitBranchState.ts new file mode 100644 index 0000000000..0487ff42e0 --- /dev/null +++ b/packages/client-runtime/src/gitBranchState.ts @@ -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; + +export const EMPTY_GIT_BRANCH_STATE = Object.freeze({ + data: null, + isPending: false, + error: null, +}); + +const INITIAL_GIT_BRANCH_STATE = Object.freeze({ + data: null, + isPending: true, + error: null, +}); + +const knownGitBranchKeys = new Set(); + +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, + next: ReadonlyArray, +): ReadonlyArray { + const merged = new Map(); + 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>(); + + 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 { + 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 { + 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, + }; +} diff --git a/packages/client-runtime/src/gitStatusState.test.ts b/packages/client-runtime/src/gitStatusState.test.ts new file mode 100644 index 0000000000..90560085ee --- /dev/null +++ b/packages/client-runtime/src/gitStatusState.test.ts @@ -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(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>(); + + 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>(); + + 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); + }); + }); +}); diff --git a/packages/client-runtime/src/gitStatusState.ts b/packages/client-runtime/src/gitStatusState.ts new file mode 100644 index 0000000000..6fb4faff7c --- /dev/null +++ b/packages/client-runtime/src/gitStatusState.ts @@ -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 | null; + readonly isPending: boolean; +} + +export interface GitStatusTarget { + readonly environmentId: string | null; + readonly cwd: string | null; +} + +export type GitStatusClient = Pick; + +interface WatchedEntry { + refCount: number; + teardown: () => void; +} + +/* ─── Constants ─────────────────────────────────────────────────────── */ + +const NOOP: () => void = () => undefined; + +export const EMPTY_GIT_STATUS_STATE = Object.freeze({ + data: null, + error: null, + cause: null, + isPending: false, +}); + +const INITIAL_GIT_STATUS_STATE = Object.freeze({ + data: null, + error: null, + cause: null, + isPending: true, +}); + +/* ─── Atoms ─────────────────────────────────────────────────────────── */ + +const knownGitStatusKeys = new Set(); + +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(); + const refreshInFlight = new Map>(); + const lastRefreshAt = new Map(); + + /* ── 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 { + 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 }; +} diff --git a/packages/client-runtime/src/index.ts b/packages/client-runtime/src/index.ts index ea68123029..45ae7e2f4d 100644 --- a/packages/client-runtime/src/index.ts +++ b/packages/client-runtime/src/index.ts @@ -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";