diff --git a/apps/mobile/TODO.md b/apps/mobile/TODO.md new file mode 100644 index 0000000000..d2401d531c --- /dev/null +++ b/apps/mobile/TODO.md @@ -0,0 +1,15 @@ +- Expo Router for navigation + - / (Home, list of recent threads) + - /connections (Connections, list of connected environments) + - /connections/new (Add backend, QR code scanner, manual input) + - /new (New thread) + - /new (Sheet, select project) + - /draft (New thread, prompt, select model, environment, workspace etc) + These two is 2 pages in one sheet with sliding animation between them +- effect/rpc for typed rpc +- Uniwind? +- Theme it like the desktop app +- Share more code between web and mobile using @t3tools/client-runtime +- Make sure model list, options etc are server authorative and not hardcoded in the client +- Fix bug where sheet content doesn't scroll +- Allow pasting images into text input diff --git a/apps/mobile/app.json b/apps/mobile/app.json index 8d5dfca49d..245808e254 100644 --- a/apps/mobile/app.json +++ b/apps/mobile/app.json @@ -1,8 +1,8 @@ { "expo": { - "name": "T3 Remote", - "slug": "t3-remote", - "scheme": "t3remote", + "name": "T3 Code", + "slug": "t3-code", + "scheme": "t3code", "version": "0.1.0", "runtimeVersion": { "policy": "appVersion" @@ -12,7 +12,7 @@ "userInterfaceStyle": "automatic", "updates": { "enabled": true, - "url": "https://u.expo.dev/525f875b-b769-4d0b-88d7-c55e97e42943", + "url": "https://u.expo.dev/d763fcb8-d37c-41ea-a773-b54a0ab4a454", "checkAutomatically": "ON_LOAD", "fallbackToCacheTimeout": 0 }, @@ -24,7 +24,7 @@ "ios": { "icon": "./assets/icon.png", "supportsTablet": true, - "bundleIdentifier": "com.t3tools.t3remote", + "bundleIdentifier": "com.t3tools.t3code", "infoPlist": { "NSAppTransportSecurity": { "NSAllowsArbitraryLoads": true @@ -34,7 +34,7 @@ }, "android": { "icon": "./assets/icon.png", - "package": "com.t3tools.t3remote", + "package": "com.t3tools.t3code", "usesCleartextTraffic": true, "adaptiveIcon": { "backgroundColor": "#E6F4FE", @@ -48,6 +48,13 @@ "favicon": "./assets/favicon.png" }, "plugins": [ + [ + "expo-camera", + { + "cameraPermission": "Allow T3 Code to access your camera so you can scan pairing QR codes.", + "barcodeScannerEnabled": true + } + ], [ "expo-splash-screen", { @@ -61,8 +68,9 @@ ], "extra": { "eas": { - "projectId": "525f875b-b769-4d0b-88d7-c55e97e42943" + "projectId": "d763fcb8-d37c-41ea-a773-b54a0ab4a454" } - } + }, + "owner": "pingdotgg" } } diff --git a/apps/mobile/assets/android-icon-background.png b/apps/mobile/assets/android-icon-background.png index cb14e561ee..b33d7978d7 100644 Binary files a/apps/mobile/assets/android-icon-background.png and b/apps/mobile/assets/android-icon-background.png differ diff --git a/apps/mobile/assets/android-icon-foreground.png b/apps/mobile/assets/android-icon-foreground.png index 0b521bbdac..b33d7978d7 100644 Binary files a/apps/mobile/assets/android-icon-foreground.png and b/apps/mobile/assets/android-icon-foreground.png differ diff --git a/apps/mobile/assets/android-icon-monochrome.png b/apps/mobile/assets/android-icon-monochrome.png index f995ae17b9..b33d7978d7 100644 Binary files a/apps/mobile/assets/android-icon-monochrome.png and b/apps/mobile/assets/android-icon-monochrome.png differ diff --git a/apps/mobile/assets/favicon.png b/apps/mobile/assets/favicon.png index f8b453334b..e0e1b9659b 100644 Binary files a/apps/mobile/assets/favicon.png and b/apps/mobile/assets/favicon.png differ diff --git a/apps/mobile/assets/icon.png b/apps/mobile/assets/icon.png index 56b5934117..b33d6f337b 100644 Binary files a/apps/mobile/assets/icon.png and b/apps/mobile/assets/icon.png differ diff --git a/apps/mobile/assets/splash-icon.png b/apps/mobile/assets/splash-icon.png index 56b5934117..b33d6f337b 100644 Binary files a/apps/mobile/assets/splash-icon.png and b/apps/mobile/assets/splash-icon.png differ diff --git a/apps/mobile/index.ts b/apps/mobile/index.ts index 828b356984..64ebbbc6e8 100644 --- a/apps/mobile/index.ts +++ b/apps/mobile/index.ts @@ -1,3 +1,4 @@ +import "react-native-gesture-handler"; import { registerRootComponent } from "expo"; import App from "./App"; diff --git a/apps/mobile/metro.config.js b/apps/mobile/metro.config.js index 6ebd265808..50cd00959d 100644 --- a/apps/mobile/metro.config.js +++ b/apps/mobile/metro.config.js @@ -1,8 +1,12 @@ +const path = require("node:path"); const { getDefaultConfig } = require("expo/metro-config"); const { withNativewind } = require("nativewind/metro"); /** @type {import("expo/metro-config").MetroConfig} */ const config = getDefaultConfig(__dirname); +const workspaceRoot = path.resolve(__dirname, "../.."); + +config.watchFolders = [...new Set([...(config.watchFolders ?? []), workspaceRoot])]; module.exports = withNativewind(config, { input: "./global.css", diff --git a/apps/mobile/nativewind-env.d.ts b/apps/mobile/nativewind-env.d.ts index c3e758c04b..52b249b9d2 100644 --- a/apps/mobile/nativewind-env.d.ts +++ b/apps/mobile/nativewind-env.d.ts @@ -1,3 +1,5 @@ /// // 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 1d59c763a8..c3260b10fc 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -13,14 +13,18 @@ }, "dependencies": { "@expo-google-fonts/dm-sans": "^0.4.2", + "@gorhom/bottom-sheet": "^5", "@react-native-async-storage/async-storage": "2.2.0", "@react-native-masked-view/masked-view": "0.3.2", + "@react-native-menu/menu": "^2.0.0", "@sethwebster/react-ethereal-input": "^0.4.0", "@shopify/flash-list": "2.0.2", + "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", "@t3tools/shared": "workspace:*", "effect": "catalog:", "expo": "~55.0.8", + "expo-camera": "~55.0.15", "expo-clipboard": "~55.0.9", "expo-constants": "^55.0.9", "expo-font": "^55.0.4", @@ -36,6 +40,7 @@ "react": "19.2.0", "react-native": "0.83.4", "react-native-css": "3.0.7", + "react-native-gesture-handler": "~2.31.1", "react-native-markdown-display": "^7.0.2", "react-native-reanimated": "4.2.1", "react-native-safe-area-context": "~5.6.2", diff --git a/apps/mobile/src/app/App.tsx b/apps/mobile/src/app/App.tsx index 6897fa6650..c0f67791bc 100644 --- a/apps/mobile/src/app/App.tsx +++ b/apps/mobile/src/app/App.tsx @@ -1,6 +1,14 @@ import { useColorScheme } from "react-native"; import "./../../global.css"; +import { + DMSans_400Regular, + DMSans_500Medium, + DMSans_700Bold, + useFonts, +} from "@expo-google-fonts/dm-sans"; +import { BottomSheetModalProvider } from "@gorhom/bottom-sheet"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; import { SafeAreaProvider } from "react-native-safe-area-context"; import { LoadingScreen } from "../components/LoadingScreen"; @@ -10,10 +18,15 @@ import { useRemoteAppState } from "./useRemoteAppState"; export default function App() { const colorScheme = useColorScheme(); const isDarkMode = colorScheme !== "light"; + const [fontsLoaded] = useFonts({ + DMSans_400Regular, + DMSans_500Medium, + DMSans_700Bold, + }); const app = useRemoteAppState(); let content; - if (app.isLoadingSavedConnection) { + if (!fontsLoaded || app.isLoadingSavedConnection) { content = ; } else if (app.reconnectingScreenVisible) { content = ; @@ -21,5 +34,11 @@ export default function App() { content = ; } - return {content}; + return ( + + + {content} + + + ); } diff --git a/apps/mobile/src/app/MobileAppShell.tsx b/apps/mobile/src/app/MobileAppShell.tsx index 811d0b49ee..91415937aa 100644 --- a/apps/mobile/src/app/MobileAppShell.tsx +++ b/apps/mobile/src/app/MobileAppShell.tsx @@ -1,198 +1,28 @@ -import { useCallback, useEffect, useRef, useState } from "react"; -import { StatusBar, useWindowDimensions, View } from "react-native"; -import Animated, { - Easing, - interpolate, - runOnJS, - useAnimatedStyle, - useSharedValue, - withTiming, -} from "react-native-reanimated"; +import { useState } from "react"; +import { StatusBar, View } from "react-native"; import { ConnectionSheet } from "../features/connection/ConnectionSheet"; +import { HomeScreen } from "../features/home/HomeScreen"; +import { NewTaskSheet } from "../features/threads/NewTaskSheet"; import { ThreadDetailScreen } from "../features/threads/ThreadDetailScreen"; -import { ThreadListScreen, type TransitionSourceFrame } from "../features/threads/ThreadListScreen"; -import type { ScopedMobileThread } from "../lib/scopedEntities"; +import { ThreadNavigationDrawer } from "../features/threads/ThreadNavigationDrawer"; +import { scopedThreadKey } from "../lib/scopedEntities"; import type { RemoteAppModel } from "./useRemoteAppState"; -function revealCenter( - sourceFrame: TransitionSourceFrame | null, - width: number, - height: number, -): { readonly x: number; readonly y: number } { - "worklet"; - if (!sourceFrame) { - return { - x: width / 2, - y: height / 2, - }; - } - - return { - x: sourceFrame.x + sourceFrame.width / 2, - y: sourceFrame.y + sourceFrame.height / 2, - }; -} - -function revealRadius(centerX: number, centerY: number, width: number, height: number): number { - "worklet"; - const distances = [ - Math.hypot(centerX, centerY), - Math.hypot(width - centerX, centerY), - Math.hypot(centerX, height - centerY), - Math.hypot(width - centerX, height - centerY), - ]; - - return Math.max(...distances); -} - -function useRevealTransition( - selectedThread: ScopedMobileThread | null, - onSelectThread: (thread: ScopedMobileThread) => void, - onBackFromThread: () => void, - width: number, - height: number, -) { - const [transitionSource, setTransitionSource] = useState(null); - const [transitionPhase, setTransitionPhase] = useState<"idle" | "opening" | "closing">("idle"); - const revealProgress = useSharedValue(1); - const openingAnimationFrameRef = useRef(null); - - const revealMaskStyle = useAnimatedStyle(() => { - const center = revealCenter(transitionSource, width, height); - const startRadius = transitionSource - ? Math.max(transitionSource.width, transitionSource.height) * 0.3 - : 20; - const endRadius = revealRadius(center.x, center.y, width, height); - const radius = startRadius + (endRadius - startRadius) * revealProgress.value; - - return { - position: "absolute", - left: center.x - radius, - top: center.y - radius, - width: radius * 2, - height: radius * 2, - borderRadius: radius, - overflow: "hidden", - opacity: interpolate(revealProgress.value, [0, 0.12, 1], [0, 1, 1]), - }; - }); - - const revealContentStyle = useAnimatedStyle(() => { - const center = revealCenter(transitionSource, width, height); - const startRadius = transitionSource - ? Math.max(transitionSource.width, transitionSource.height) * 0.3 - : 20; - const endRadius = revealRadius(center.x, center.y, width, height); - const radius = startRadius + (endRadius - startRadius) * revealProgress.value; - - return { - width, - height, - transform: [{ translateX: -(center.x - radius) }, { translateY: -(center.y - radius) }], - }; - }); - - const handleSelectThread = useCallback( - (thread: ScopedMobileThread, sourceFrame: TransitionSourceFrame | null): void => { - setTransitionSource(sourceFrame); - setTransitionPhase("opening"); - revealProgress.value = 0; - onSelectThread(thread); - }, - [onSelectThread, revealProgress], - ); - - const handleBackFromThread = useCallback((): void => { - if (!selectedThread) { - return; - } - - setTransitionPhase("closing"); - revealProgress.value = withTiming( - 0, - { - duration: 260, - easing: Easing.inOut(Easing.cubic), - }, - (finished) => { - if (!finished) { - return; - } - runOnJS(onBackFromThread)(); - runOnJS(setTransitionPhase)("idle"); - runOnJS(setTransitionSource)(null); - revealProgress.value = 1; - }, - ); - }, [onBackFromThread, revealProgress, selectedThread]); - - useEffect(() => { - if (transitionPhase !== "opening" || !selectedThread) { - return; - } - - if (openingAnimationFrameRef.current !== null) { - cancelAnimationFrame(openingAnimationFrameRef.current); - } - - openingAnimationFrameRef.current = requestAnimationFrame(() => { - openingAnimationFrameRef.current = null; - revealProgress.value = withTiming( - 1, - { - duration: 420, - easing: Easing.out(Easing.cubic), - }, - (finished) => { - if (!finished) { - return; - } - runOnJS(setTransitionPhase)("idle"); - }, - ); - }); - - return () => { - if (openingAnimationFrameRef.current !== null) { - cancelAnimationFrame(openingAnimationFrameRef.current); - openingAnimationFrameRef.current = null; - } - }; - }, [selectedThread, revealProgress, transitionPhase]); - - return { - transitionPhase, - revealMaskStyle, - revealContentStyle, - handleSelectThread, - handleBackFromThread, - }; -} - export function MobileAppShell(props: { readonly app: RemoteAppModel; readonly isDarkMode: boolean; }) { const { app } = props; - const { width, height } = useWindowDimensions(); - const backgroundColor = props.isDarkMode ? "#020617" : "#f8fafc"; + const [threadsSheetVisible, setThreadsSheetVisible] = useState(false); + const [newTaskVisible, setNewTaskVisible] = useState(false); + const backgroundColor = props.isDarkMode ? "#020617" : "#f6f4ef"; - const { - transitionPhase, - revealMaskStyle, - revealContentStyle, - handleSelectThread, - handleBackFromThread, - } = useRevealTransition( - app.selectedThread, - app.onSelectThread, - app.onBackFromThread, - width, - height, - ); + const selectedThreadKey = app.selectedThread + ? scopedThreadKey(app.selectedThread.environmentId, app.selectedThread.id) + : null; - const sharedDetailProps = app.selectedThread + const selectedThreadDetailProps = app.selectedThread ? { selectedThread: app.selectedThread, screenTone: app.screenTone, @@ -211,14 +41,24 @@ export function MobileAppShell(props: { draftAttachments: app.draftAttachments, connectionStateLabel: app.connectionState, activeThreadBusy: app.activeThreadBusy, + selectedThreadGitStatus: app.selectedThreadGitStatus, + gitOperationLabel: app.gitOperationLabel, selectedThreadQueueCount: app.selectedThreadQueueCount, - onBack: handleBackFromThread, + onBack: app.onBackFromThread, + onOpenDrawer: () => setThreadsSheetVisible(true), onOpenConnectionEditor: app.onOpenConnectionEditor, onChangeDraftMessage: app.onChangeDraftMessage, onPickDraftImages: app.onPickDraftImages, onPasteIntoDraft: app.onPasteIntoDraft, onRemoveDraftImage: app.onRemoveDraftImage, onRefresh: app.onRefresh, + onRefreshSelectedThreadGitStatus: app.onRefreshSelectedThreadGitStatus, + onListSelectedThreadBranches: app.onListSelectedThreadBranches, + onCheckoutSelectedThreadBranch: app.onCheckoutSelectedThreadBranch, + onCreateSelectedThreadBranch: app.onCreateSelectedThreadBranch, + onCreateSelectedThreadWorktree: app.onCreateSelectedThreadWorktree, + onPullSelectedThreadBranch: app.onPullSelectedThreadBranch, + onRunSelectedThreadGitAction: app.onRunSelectedThreadGitAction, onRenameThread: app.onRenameThread, onStopThread: app.onStopThread, onSendMessage: app.onSendMessage, @@ -237,47 +77,19 @@ export function MobileAppShell(props: { translucent /> - - + ) : ( + setNewTaskVisible(true)} + onSelectThread={app.onSelectThread} /> - - - {app.selectedThread && sharedDetailProps ? ( - - - {transitionPhase !== "idle" ? ( - - - - - - ) : null} - - ) : null} + )} + + setThreadsSheetVisible(false)} + onSelectThread={app.onSelectThread} + onStartNewTask={() => setNewTaskVisible(true)} + /> + + {newTaskVisible ? ( + setNewTaskVisible(false)} + onCreateThreadWithOptions={app.onCreateThreadWithOptions} + onListProjectBranches={app.onListProjectBranches} + /> + ) : null} ); } diff --git a/apps/mobile/src/app/useRemoteAppState.ts b/apps/mobile/src/app/useRemoteAppState.ts index f233fbd9df..e9c546c66d 100644 --- a/apps/mobile/src/app/useRemoteAppState.ts +++ b/apps/mobile/src/app/useRemoteAppState.ts @@ -1,17 +1,28 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Alert } from "react-native"; +import { buildGitActionProgressStages, type GitActionRequestInput } from "@t3tools/client-runtime"; import { ApprovalRequestId, CommandId, DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, + type GitBranch, + type GitRunStackedActionResult, + type GitStatusResult, MessageId, + type ModelSelection, type OrchestrationReadModel, type ProviderApprovalDecision, + type ProviderInteractionMode, + type RuntimeMode, type ServerConfig as T3ServerConfig, ThreadId, } from "@t3tools/contracts"; +import { + dedupeRemoteBranchesWithLocalMatches, + sanitizeFeatureBranchName, +} from "@t3tools/shared/git"; import { deriveActiveWorkStartedAt, formatElapsed } from "@t3tools/shared/orchestrationTiming"; import { connectionTone } from "../features/connection/connectionTone"; @@ -46,6 +57,7 @@ import { } from "../lib/threadActivity"; import { sortCopy } from "../lib/arrayCompat"; import { newClientId } from "../lib/clientId"; +import { buildTemporaryWorktreeBranchName } from "../lib/worktrees"; export interface ConnectedEnvironmentSummary { readonly environmentId: string; @@ -65,6 +77,7 @@ export interface RemoteAppModel { readonly connectedEnvironments: ReadonlyArray; readonly connectedEnvironmentCount: number; readonly serverConfig: T3ServerConfig | null; + readonly serverConfigByEnvironmentId: Readonly>; readonly projects: ReadonlyArray; readonly threads: ReadonlyArray; readonly selectedThread: ScopedMobileThread | null; @@ -81,6 +94,8 @@ export interface RemoteAppModel { readonly draftAttachments: ReadonlyArray; readonly screenTone: ReturnType; readonly activeThreadBusy: boolean; + readonly selectedThreadGitStatus: GitStatusResult | null; + readonly gitOperationLabel: string | null; readonly hasRemoteActivity: boolean; readonly selectedEnvironmentBaseUrl: string | null; readonly selectedEnvironmentBearerToken: string | null; @@ -92,15 +107,57 @@ export interface RemoteAppModel { readonly onRequestCloseConnectionEditor: () => void; readonly onChangeConnectionPairingUrl: (pairingUrl: string) => void; readonly onConnectPress: () => void; + readonly onUpdateEnvironment: ( + environmentId: string, + updates: { readonly label: string; readonly displayUrl: string }, + ) => Promise; readonly onRemoveEnvironmentPress: (environmentId: string) => void; readonly onRefresh: () => Promise; readonly onCreateThread: (project: ScopedMobileProject) => Promise; + readonly onCreateThreadWithOptions: (input: { + readonly project: ScopedMobileProject; + readonly modelSelection: ModelSelection; + readonly envMode: "local" | "worktree"; + readonly branch: string | null; + readonly worktreePath: string | null; + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + readonly initialMessageText: string; + readonly initialAttachments: ReadonlyArray; + }) => Promise; readonly onSelectThread: (thread: ScopedMobileThread) => void; readonly onBackFromThread: () => void; readonly onChangeDraftMessage: (value: string) => void; readonly onPickDraftImages: () => Promise; readonly onPasteIntoDraft: () => Promise; readonly onRemoveDraftImage: (imageId: string) => void; + readonly onRefreshSelectedThreadGitStatus: (options?: { + readonly quiet?: boolean; + }) => Promise; + readonly onListProjectBranches: ( + project: ScopedMobileProject, + ) => Promise>; + readonly onCreateProjectWorktree: ( + project: ScopedMobileProject, + input: { + readonly baseBranch: string; + readonly newBranch: string; + }, + ) => Promise<{ + readonly branch: string; + readonly worktreePath: string; + } | null>; + 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 onSendMessage: () => void; readonly onRenameThread: (title: string) => Promise; readonly onStopThread: () => Promise; @@ -147,6 +204,16 @@ function firstNonNull(values: ReadonlyArray): T | null return null; } +function deriveThreadTitleFromPrompt(value: string): string { + const trimmed = value.trim(); + if (trimmed.length === 0) { + return "New thread"; + } + + const compact = trimmed.replace(/\s+/g, " "); + return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`; +} + function deriveOverallConnectionState( environments: ReadonlyArray, ): RemoteClientConnectionState { @@ -268,6 +335,10 @@ export function useRemoteAppState(): RemoteAppModel { null, ); const [dispatchingQueuedMessageId, setDispatchingQueuedMessageId] = useState(null); + const [selectedThreadGitStatus, setSelectedThreadGitStatus] = useState( + null, + ); + const [gitOperationLabel, setGitOperationLabel] = useState(null); const [queuedMessagesByThreadKey, setQueuedMessagesByThreadKey] = useState< Record> >({}); @@ -516,6 +587,333 @@ export function useRemoteAppState(): RemoteAppModel { setSelectedThreadRef(null); }, [selectedThread, selectedThreadRef]); + const selectedThreadProject = useMemo( + () => + selectedThread + ? (projects.find( + (project) => + project.environmentId === selectedThread.environmentId && + project.id === selectedThread.projectId, + ) ?? null) + : null, + [projects, selectedThread], + ); + + const selectedThreadGitRootCwd = selectedThreadProject?.workspaceRoot ?? null; + + const updateThreadGitContext = useCallback( + async ( + thread: ScopedMobileThread, + input: { + readonly branch?: string | null; + readonly worktreePath?: string | null; + }, + ) => { + const client = clientsRef.current.get(thread.environmentId); + if (!client) { + return; + } + + await client.dispatchCommand({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe(newClientId("command")), + threadId: ThreadId.makeUnsafe(thread.id), + ...(input.branch !== undefined ? { branch: input.branch } : {}), + ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}), + }); + }, + [], + ); + + const refreshSelectedThreadGitStatus = useCallback( + async (options?: { readonly quiet?: boolean; readonly cwd?: string | null }) => { + if (!selectedThread || !selectedThreadProject) { + setSelectedThreadGitStatus(null); + return null; + } + + const cwd = + options?.cwd ?? selectedThread.worktreePath ?? selectedThreadProject.workspaceRoot; + if (!cwd) { + setSelectedThreadGitStatus(null); + return null; + } + + if (!options?.quiet) { + setGitOperationLabel("Refreshing git status"); + } + + try { + const client = clientsRef.current.get(selectedThread.environmentId); + if (!client) { + return null; + } + const status = await client.gitRefreshStatus({ cwd }); + setSelectedThreadGitStatus(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) { + setGitOperationLabel(null); + } + } + }, + [selectedThread, selectedThreadProject], + ); + + useEffect(() => { + if (!selectedThread || !selectedThreadProject) { + setSelectedThreadGitStatus(null); + return; + } + + void refreshSelectedThreadGitStatus({ quiet: true }); + }, [refreshSelectedThreadGitStatus, selectedThread, selectedThreadProject]); + + const runSelectedThreadGitMutation = useCallback( + async ( + label: string, + operation: (input: { + readonly client: RemoteClient; + readonly thread: ScopedMobileThread; + readonly project: ScopedMobileProject; + }) => Promise, + ): Promise => { + if (!selectedThread || !selectedThreadProject) { + return null; + } + + const client = clientsRef.current.get(selectedThread.environmentId); + if (!client) { + return null; + } + + setGitOperationLabel(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 { + setGitOperationLabel(null); + } + }, + [selectedThread, selectedThreadProject], + ); + + const onListSelectedThreadBranches = useCallback(async (): Promise> => { + if (!selectedThread || !selectedThreadProject || !selectedThreadGitRootCwd) { + return []; + } + + const client = clientsRef.current.get(selectedThread.environmentId); + if (!client) { + return []; + } + + try { + const result = await client.gitListBranches({ + 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]); + + const onListProjectBranches = useCallback( + async (project: ScopedMobileProject): Promise> => { + const client = clientsRef.current.get(project.environmentId); + if (!client) { + return []; + } + + try { + const result = await client.gitListBranches({ + 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 []; + } + }, + [], + ); + + const onCreateProjectWorktree = useCallback( + async ( + project: ScopedMobileProject, + input: { + readonly baseBranch: string; + readonly newBranch: string; + }, + ): Promise<{ + readonly branch: string; + readonly worktreePath: string; + } | null> => { + const client = clientsRef.current.get(project.environmentId); + if (!client) { + return null; + } + + try { + const result = await client.gitCreateWorktree({ + cwd: project.workspaceRoot, + branch: input.baseBranch, + newBranch: sanitizeFeatureBranchName(input.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; + } + }, + [], + ); + + 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.gitCheckout({ 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.gitCreateBranch({ + 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 (input: { readonly baseBranch: string; readonly newBranch: string }) => { + await runSelectedThreadGitMutation( + "Creating worktree", + async ({ client, thread, project }) => { + const result = await client.gitCreateWorktree({ + cwd: project.workspaceRoot, + branch: input.baseBranch, + newBranch: sanitizeFeatureBranchName(input.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.gitPull({ 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.gitRunStackedAction({ + 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, + ], + ); + const selectedThreadKey = selectedThread ? scopedThreadKey(selectedThread.environmentId, selectedThread.id) : null; @@ -740,15 +1138,115 @@ export function useRemoteAppState(): RemoteAppModel { } }), ); - }, [savedConnectionsById, selectedThread]); + if (selectedThread) { + await refreshSelectedThreadGitStatus({ quiet: true }); + } + }, [refreshSelectedThreadGitStatus, savedConnectionsById, selectedThread]); - const onCreateThread = useCallback( - async (project: ScopedMobileProject) => { - const client = clientsRef.current.get(project.environmentId); + const onCreateThreadWithOptions = useCallback( + async (input: { + readonly project: ScopedMobileProject; + readonly modelSelection: ModelSelection; + readonly envMode: "local" | "worktree"; + readonly branch: string | null; + readonly worktreePath: string | null; + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + readonly initialMessageText: string; + readonly initialAttachments: ReadonlyArray; + }) => { + const client = clientsRef.current.get(input.project.environmentId); if (!client) { return; } + const threadId = ThreadId.makeUnsafe(newClientId("thread")); + const createdAt = new Date().toISOString(); + const initialMessageText = input.initialMessageText.trim(); + const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText); + if (input.envMode === "worktree") { + if (!input.branch || initialMessageText.length === 0) { + return; + } + + await client.dispatchCommand({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe(newClientId("command")), + threadId, + message: { + messageId: MessageId.makeUnsafe(newClientId("message")), + role: "user", + text: initialMessageText, + attachments: input.initialAttachments, + }, + modelSelection: input.modelSelection, + titleSeed: nextTitle, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + bootstrap: { + createThread: { + projectId: input.project.id, + title: nextTitle, + modelSelection: input.modelSelection, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + branch: input.branch, + worktreePath: null, + createdAt, + }, + prepareWorktree: { + projectCwd: input.project.workspaceRoot, + baseBranch: input.branch, + branch: buildTemporaryWorktreeBranchName(), + }, + runSetupScript: true, + }, + createdAt: new Date().toISOString(), + }); + } else { + await client.dispatchCommand({ + type: "thread.create", + commandId: CommandId.makeUnsafe(newClientId("command")), + threadId, + projectId: input.project.id, + title: nextTitle, + modelSelection: input.modelSelection, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + branch: input.branch, + worktreePath: input.worktreePath, + createdAt, + }); + + if (initialMessageText.length > 0 || input.initialAttachments.length > 0) { + await client.dispatchCommand({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe(newClientId("command")), + threadId, + message: { + messageId: MessageId.makeUnsafe(newClientId("message")), + role: "user", + text: initialMessageText, + attachments: input.initialAttachments, + }, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + createdAt: new Date().toISOString(), + }); + } + } + + setSelectedThreadRef({ + environmentId: input.project.environmentId, + threadId, + }); + await onRefresh(); + }, + [onRefresh], + ); + + const onCreateThread = useCallback( + async (project: ScopedMobileProject) => { const latestProjectThread = threads.find( (thread) => @@ -761,28 +1259,19 @@ export function useRemoteAppState(): RemoteAppModel { return; } - const threadId = ThreadId.makeUnsafe(newClientId("thread")); - const createdAt = new Date().toISOString(); - await client.dispatchCommand({ - type: "thread.create", - commandId: CommandId.makeUnsafe(newClientId("command")), - threadId, - projectId: project.id, - title: "New thread", + await onCreateThreadWithOptions({ + project, modelSelection, - runtimeMode: DEFAULT_RUNTIME_MODE, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + envMode: "local", branch: null, worktreePath: null, - createdAt, + runtimeMode: DEFAULT_RUNTIME_MODE, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + initialMessageText: "", + initialAttachments: [], }); - setSelectedThreadRef({ - environmentId: project.environmentId, - threadId, - }); - await onRefresh(); }, - [onRefresh, threads], + [onCreateThreadWithOptions, threads], ); const onConnectPress = useCallback(() => { @@ -825,6 +1314,31 @@ export function useRemoteAppState(): RemoteAppModel { [disconnectEnvironment, savedConnectionsById], ); + const onUpdateEnvironment = useCallback( + async ( + environmentId: string, + updates: { readonly label: string; readonly displayUrl: string }, + ) => { + const connection = savedConnectionsById[environmentId]; + if (!connection) { + return; + } + + const updated: SavedRemoteConnection = { + ...connection, + environmentLabel: updates.label.trim() || connection.environmentLabel, + displayUrl: updates.displayUrl.trim() || connection.displayUrl, + }; + + await saveConnection(updated); + setSavedConnectionsById((current) => ({ + ...current, + [environmentId]: updated, + })); + }, + [savedConnectionsById], + ); + const onSendMessage = useCallback(() => { if (!selectedThread) { return; @@ -1105,6 +1619,16 @@ export function useRemoteAppState(): RemoteAppModel { const serverConfig = selectedEnvironmentRuntime?.serverConfig ?? firstNonNull(Object.values(environmentStateById).map((runtime) => runtime.serverConfig)); + const serverConfigByEnvironmentId = useMemo( + () => + Object.fromEntries( + Object.entries(environmentStateById).map(([environmentId, runtime]) => [ + environmentId, + runtime.serverConfig ?? null, + ]), + ), + [environmentStateById], + ); const hasClient = connectedEnvironments.length > 0; return { @@ -1117,6 +1641,7 @@ export function useRemoteAppState(): RemoteAppModel { connectedEnvironments, connectedEnvironmentCount: connectedEnvironments.length, serverConfig, + serverConfigByEnvironmentId, projects, threads, selectedThread, @@ -1133,6 +1658,8 @@ export function useRemoteAppState(): RemoteAppModel { draftAttachments, screenTone, activeThreadBusy, + selectedThreadGitStatus, + gitOperationLabel, hasRemoteActivity, selectedEnvironmentBaseUrl: selectedEnvironmentConnection?.httpBaseUrl ?? null, selectedEnvironmentBearerToken: selectedEnvironmentConnection?.bearerToken ?? null, @@ -1148,9 +1675,11 @@ export function useRemoteAppState(): RemoteAppModel { }, onChangeConnectionPairingUrl: (pairingUrl: string) => setConnectionInput({ pairingUrl }), onConnectPress, + onUpdateEnvironment, onRemoveEnvironmentPress, onRefresh, onCreateThread, + onCreateThreadWithOptions, onSelectThread: (thread) => setSelectedThreadRef({ environmentId: thread.environmentId, @@ -1161,6 +1690,17 @@ export function useRemoteAppState(): RemoteAppModel { onPickDraftImages, onPasteIntoDraft, onRemoveDraftImage, + onRefreshSelectedThreadGitStatus: async (options) => { + await refreshSelectedThreadGitStatus(options); + }, + onListProjectBranches, + onCreateProjectWorktree, + onListSelectedThreadBranches, + onCheckoutSelectedThreadBranch, + onCreateSelectedThreadBranch, + onCreateSelectedThreadWorktree, + onPullSelectedThreadBranch, + onRunSelectedThreadGitAction, onSendMessage, onRenameThread, onStopThread, diff --git a/apps/mobile/src/components/AppText.tsx b/apps/mobile/src/components/AppText.tsx index 08c7574c68..73cb4f0855 100644 --- a/apps/mobile/src/components/AppText.tsx +++ b/apps/mobile/src/components/AppText.tsx @@ -55,6 +55,7 @@ function activeToken(token: string, isDarkMode: boolean) { function resolveTextStyle(className: string | undefined, isDarkMode: boolean): TextStyle { const style: TextStyle = { color: isDarkMode ? "#f8fafc" : "#020617", + fontFamily: "DMSans_400Regular", }; let hasLeadingNone = false; @@ -70,37 +71,37 @@ function resolveTextStyle(className: string | undefined, isDarkMode: boolean): T } if (token === "font-sans") { - style.fontWeight = "400"; + style.fontFamily = "DMSans_400Regular"; continue; } if (token === "font-medium") { - style.fontWeight = "500"; + style.fontFamily = "DMSans_500Medium"; continue; } if (token === "font-bold") { - style.fontWeight = "700"; + style.fontFamily = "DMSans_700Bold"; continue; } if (token === "font-extrabold") { - style.fontWeight = "800"; + style.fontFamily = "DMSans_700Bold"; continue; } if (token === "font-t3-medium") { - style.fontWeight = "500"; + style.fontFamily = "DMSans_500Medium"; continue; } if (token === "font-t3-bold") { - style.fontWeight = "700"; + style.fontFamily = "DMSans_700Bold"; continue; } if (token === "font-t3-extrabold") { - style.fontWeight = "800"; + style.fontFamily = "DMSans_700Bold"; continue; } @@ -197,6 +198,7 @@ function resolveTextInputStyle( paddingHorizontal: 14, paddingVertical: 12, fontSize: 15, + fontFamily: "DMSans_400Regular", minHeight: 54, }; @@ -252,7 +254,7 @@ function resolveTextInputStyle( } if (token === "font-sans") { - style.fontWeight = "400"; + style.fontFamily = "DMSans_400Regular"; continue; } diff --git a/apps/mobile/src/components/BrandMark.tsx b/apps/mobile/src/components/BrandMark.tsx new file mode 100644 index 0000000000..ca11392afc --- /dev/null +++ b/apps/mobile/src/components/BrandMark.tsx @@ -0,0 +1,60 @@ +import { Image, View } from "react-native"; + +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; + readonly dark?: boolean; +}) { + const compact = props.compact ?? false; + const iconSize = compact ? 32 : 44; + const stageLabel = props.stageLabel ?? "Alpha"; + const textColor = props.dark ? "#f5f5f4" : "#171717"; + const mutedColor = props.dark ? "rgba(245,245,244,0.72)" : "rgba(23,23,23,0.6)"; + const stageBackground = props.dark ? "rgba(255,255,255,0.08)" : "rgba(23,23,23,0.06)"; + + return ( + + + + + + T3 Code + + + + {stageLabel} + + + + {!compact ? ( + + Mobile control surface for your live coding environments + + ) : null} + + + ); +} diff --git a/apps/mobile/src/components/LoadingScreen.tsx b/apps/mobile/src/components/LoadingScreen.tsx index 33357620ca..a22a64991e 100644 --- a/apps/mobile/src/components/LoadingScreen.tsx +++ b/apps/mobile/src/components/LoadingScreen.tsx @@ -2,6 +2,7 @@ import { ActivityIndicator, StatusBar, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "./AppText"; +import { BrandMark } from "./BrandMark"; export function LoadingScreen(props: { readonly isDarkMode: boolean; readonly message: string }) { const insets = useSafeAreaInsets(); @@ -14,7 +15,8 @@ export function LoadingScreen(props: { readonly isDarkMode: boolean; readonly me backgroundColor={backgroundColor} translucent /> - + + {props.message} diff --git a/apps/mobile/src/components/StatusPill.tsx b/apps/mobile/src/components/StatusPill.tsx index ce8db639db..e0fb65efbd 100644 --- a/apps/mobile/src/components/StatusPill.tsx +++ b/apps/mobile/src/components/StatusPill.tsx @@ -9,10 +9,29 @@ export interface StatusTone { readonly textClassName: string; } -export function StatusPill(props: StatusTone) { +export function StatusPill( + props: StatusTone & { + readonly size?: "default" | "compact"; + }, +) { + const size = props.size ?? "default"; return ( - - {props.label} + + + {props.label} + ); } diff --git a/apps/mobile/src/features/connection/ConnectionSheet.tsx b/apps/mobile/src/features/connection/ConnectionSheet.tsx index b0e641cd2e..9f63441085 100644 --- a/apps/mobile/src/features/connection/ConnectionSheet.tsx +++ b/apps/mobile/src/features/connection/ConnectionSheet.tsx @@ -1,11 +1,23 @@ -import { Modal, Pressable, ScrollView, View } from "react-native"; -import { useColorScheme } from "react-native"; +import { + BottomSheetBackdrop, + BottomSheetModal, + BottomSheetScrollView, + BottomSheetView, +} from "@gorhom/bottom-sheet"; +import { MenuView } from "@react-native-menu/menu"; +import { CameraView, type BarcodeScanningResult, useCameraPermissions } from "expo-camera"; +import { SymbolView } from "expo-symbols"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { Linking, Platform, Pressable, View, useColorScheme } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; +import type { ConnectedEnvironmentSummary } from "../../app/useRemoteAppState"; import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText"; import { ErrorBanner } from "../../components/ErrorBanner"; -import type { ConnectedEnvironmentSummary } from "../../app/useRemoteAppState"; import type { RemoteConnectionInput } from "../../lib/connection"; +import { extractPairingUrlFromQrPayload } from "../../lib/pairingQr"; import type { RemoteClientConnectionState } from "../../lib/remoteClient"; +import { ConnectionStatusDot } from "./ConnectionStatusDot"; export interface ConnectionSheetProps { readonly visible: boolean; @@ -16,82 +28,196 @@ export interface ConnectionSheetProps { readonly onRequestClose: () => void; readonly onChangePairingUrl: (pairingUrl: string) => void; readonly onConnect: () => void; - readonly onClose: () => void; + readonly onUpdateEnvironment: ( + environmentId: string, + updates: { readonly label: string; readonly displayUrl: string }, + ) => Promise; readonly onRemoveEnvironment: (environmentId: string) => void; } +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function parsePairingUrl(url: string): { host: string; code: string } { + const trimmed = url.trim(); + if (!trimmed) return { host: "", code: "" }; + + try { + const parsed = new URL(trimmed); + const hashParams = new URLSearchParams(parsed.hash.slice(1)); + const hashToken = hashParams.get("token"); + const queryToken = parsed.searchParams.get("token"); + const code = hashToken || queryToken || ""; + + parsed.hash = ""; + parsed.search = ""; + parsed.pathname = "/"; + return { host: parsed.toString().replace(/\/$/, ""), code }; + } catch { + return { host: trimmed, code: "" }; + } +} + +function buildPairingUrl(host: string, code: string): string { + const h = host.trim(); + const c = code.trim(); + if (!h) return ""; + if (!c) return h; + + try { + const url = new URL(h.includes("://") ? h : `https://${h}`); + url.hash = new URLSearchParams([["token", c]]).toString(); + return url.toString(); + } catch { + return `${h}#token=${c}`; + } +} + +// --------------------------------------------------------------------------- +// Palette +// --------------------------------------------------------------------------- + function makePalette(isDarkMode: boolean) { if (isDarkMode) { return { - sheet: "#151618", - panel: "#1d1e21", - border: "rgba(255,255,255,0.08)", - text: "#f4f3ef", - muted: "#8f918f", - input: "#1f2230", - inputText: "#f8fafc", - placeholder: "#6b7280", - action: "#f97316", - actionText: "#fff7ed", - secondary: "#303440", - secondaryText: "#f8fafc", - danger: "#381624", + 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", - accent: "#d8b27a", + 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)", }; } return { - sheet: "#f2ece4", - panel: "#fbf7f1", - border: "#d7cdbf", - text: "#1f1b17", - muted: "#847b71", - input: "#ffffff", - inputText: "#1f2937", + 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", - action: "#2c2a2d", - actionText: "#f8f4ee", - secondary: "#ffffff", - secondaryText: "#1f1b17", - danger: "#fde7e7", - dangerText: "#a11d33", - accent: "#9a6b30", + 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)", }; } -function ActionButton(props: { +// --------------------------------------------------------------------------- +// Shared button +// --------------------------------------------------------------------------- + +function SheetButton(props: { + readonly icon: React.ComponentProps["name"]; readonly label: string; - readonly onPress: () => void; - readonly palette: ReturnType; + readonly disabled?: boolean; readonly tone?: "primary" | "secondary" | "danger"; + readonly compact?: boolean; + readonly palette: ReturnType; + readonly onPress: () => void; }) { const tone = props.tone ?? "secondary"; - const styles = + const colors = tone === "primary" ? { - backgroundColor: props.palette.action, - color: props.palette.actionText, + backgroundColor: props.palette.primaryButton, + borderColor: "transparent", + textColor: props.palette.primaryButtonText, } : tone === "danger" ? { - backgroundColor: props.palette.danger, - color: props.palette.dangerText, + backgroundColor: props.palette.dangerButton, + borderColor: props.palette.dangerBorder, + textColor: props.palette.dangerText, } : { - backgroundColor: props.palette.secondary, - color: props.palette.secondaryText, + backgroundColor: props.palette.secondaryButton, + borderColor: props.palette.border, + textColor: props.palette.secondaryButtonText, }; + const primaryShadow = + tone === "primary" + ? Platform.select({ + ios: { + shadowColor: "#000", + shadowOffset: { width: 0, height: 3 }, + shadowOpacity: 0.14, + shadowRadius: 6, + }, + android: { elevation: 3 }, + }) + : undefined; + return ( + {props.label} @@ -99,151 +225,799 @@ function ActionButton(props: { ); } -export function ConnectionSheet(props: ConnectionSheetProps) { - const isDarkMode = useColorScheme() === "dark"; - const palette = makePalette(isDarkMode); +// --------------------------------------------------------------------------- +// Environment card (compact single row) +// --------------------------------------------------------------------------- + +function EnvironmentCard(props: { + readonly environment: ConnectedEnvironmentSummary; + readonly palette: ReturnType; + 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: ReturnType; + 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(); + } + }} + /> + + + + + + + + + ); +} + +// --------------------------------------------------------------------------- +// Add backend (nested sheet — manual entry + optional QR scanner) +// --------------------------------------------------------------------------- + +function AddBackendSheet(props: { + readonly visible: boolean; + readonly startWithScanner: boolean; + readonly connectionState: RemoteClientConnectionState; + readonly connectionError: string | null; + readonly palette: ReturnType; + readonly bottomInset: number; + readonly onDismiss: () => void; + readonly onChangePairingUrl: (url: string) => void; + readonly onConnect: () => void; +}) { + const sheetRef = useRef(null); + const [cameraPermission, requestCameraPermission] = useCameraPermissions(); + const [hostInput, setHostInput] = useState(""); + const [codeInput, setCodeInput] = useState(""); + const [scannerVisible, setScannerVisible] = useState(false); + const [scannerError, setScannerError] = useState(null); + const [scannerPaused, setScannerPaused] = useState(false); + + const connectDisabled = + props.connectionState === "connecting" || hostInput.trim().length === 0; + + const snapPoints = useMemo<(string | number)[]>( + () => [scannerVisible ? "82%" : "54%"], + [scannerVisible], + ); + + // Present / dismiss + useEffect(() => { + const sheet = sheetRef.current; + if (!sheet) return; + if (props.visible) { + setHostInput(""); + setCodeInput(""); + setScannerError(null); + setScannerPaused(false); + + if (props.startWithScanner) { + setScannerVisible(true); + if (!cameraPermission?.granted && cameraPermission?.canAskAgain !== false) { + void requestCameraPermission().catch(() => {}); + } + } else { + setScannerVisible(false); + } + + sheet.present(); + } else { + sheet.dismiss(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [props.visible]); + + // Sync fields → parent + const syncUrl = useCallback( + (host: string, code: string) => { + props.onChangePairingUrl(buildPairingUrl(host, code)); + }, + [props.onChangePairingUrl], + ); + + const handleHostChange = useCallback( + (v: string) => { + setHostInput(v); + syncUrl(v, codeInput); + }, + [codeInput, syncUrl], + ); + + const handleCodeChange = useCallback( + (v: string) => { + setCodeInput(v); + syncUrl(hostInput, v); + }, + [hostInput, syncUrl], + ); + + const handleToggleScanner = useCallback(() => { + setScannerVisible((v) => { + if (!v) { + setScannerError(null); + setScannerPaused(false); + if (!cameraPermission?.granted && cameraPermission?.canAskAgain !== false) { + void requestCameraPermission().catch(() => {}); + } + } + return !v; + }); + }, [cameraPermission?.canAskAgain, cameraPermission?.granted, requestCameraPermission]); + + const handleBarcodeScanned = useCallback( + (result: BarcodeScanningResult) => { + if (scannerPaused) return; + setScannerPaused(true); + try { + const url = extractPairingUrlFromQrPayload(result.data); + const { host, code } = parsePairingUrl(url); + setHostInput(host); + setCodeInput(code); + props.onChangePairingUrl(url); + setScannerVisible(false); + } catch (error) { + setScannerError( + error instanceof Error + ? error.message + : "Could not read a pairing URL from that QR code.", + ); + setScannerPaused(false); + } + }, + [props.onChangePairingUrl, scannerPaused], + ); + + const renderBackdrop = useCallback( + (backdropProps: React.ComponentProps) => ( + + ), + [], + ); + + return ( + + + + + Add backend + + + {/* QR scanner */} + {scannerVisible ? ( + - + {!cameraPermission ? ( - Pair environment + Checking camera permission… - - Add another backend - - - Paste the pairing link from the web or desktop app. The mobile client will keep a - separate live connection for each paired environment. - - + ) : cameraPermission.granted ? ( + <> + + setScannerError(error.message)} + style={{ flex: 1 }} + /> + + + Point the camera at a pairing QR code. + + {scannerPaused ? ( + { + setScannerError(null); + setScannerPaused(false); + }} + /> + ) : null} + + ) : ( + <> + + Camera access is required to scan a pairing QR code. + + {cameraPermission.canAskAgain ? ( + void requestCameraPermission().catch(() => {})} + /> + ) : ( + void Linking.openSettings().catch(() => {})} + /> + )} + + )} + {scannerError ? : null} + + ) : null} - - - Pairing URL - + {/* Host field */} + + + Host + + + - - - - - - {props.connectedEnvironments.length > 0 ? ( - - - - ) : null} - - - - {props.connectionError ? : null} - - {props.connectedEnvironments.length > 0 ? ( - - - Connected backends - - - {props.connectedEnvironments.map((environment) => ( - - - - {environment.environmentLabel} - - - {environment.displayUrl} - - - {environment.connectionState} - - - - {environment.connectionError ? ( - - {environment.connectionError} - - ) : null} - - props.onRemoveEnvironment(environment.environmentId)} - palette={palette} - tone="danger" - /> - - ))} - - ) : null} + + + - - - + + {/* Pairing code field */} + + + Pairing code + + + + + {props.connectionError ? : null} + + + + + + ); +} + +// --------------------------------------------------------------------------- +// Main connection sheet +// --------------------------------------------------------------------------- + +const ADD_MENU_ACTIONS = [ + { + id: "scan_qr", + title: "Scan QR Code", + image: "qrcode.viewfinder", + }, + { + id: "enter_manually", + title: "Enter Manually", + image: "keyboard", + }, +] as const; + +export function ConnectionSheet(props: ConnectionSheetProps) { + const insets = useSafeAreaInsets(); + const isDarkMode = useColorScheme() === "dark"; + const palette = makePalette(isDarkMode); + const sheetRef = useRef(null); + + const [editingEnvironment, setEditingEnvironment] = + useState(null); + const [addSheetVisible, setAddSheetVisible] = useState(false); + const [addSheetStartWithScanner, setAddSheetStartWithScanner] = useState(false); + + const dismissible = props.connectedEnvironments.length > 0; + const hasEnvironments = props.connectedEnvironments.length > 0; + + const snapPoints = useMemo<(string | number)[]>( + () => [hasEnvironments ? "52%" : "38%"], + [hasEnvironments], + ); + + const renderBackdrop = useCallback( + (backdropProps: React.ComponentProps) => ( + + ), + [dismissible], + ); + + useEffect(() => { + const sheet = sheetRef.current; + if (!sheet) return; + if (props.visible) { + sheet.present(); + } else { + sheet.dismiss(); + } + }, [props.visible]); + + useEffect(() => { + if (!props.visible) { + setEditingEnvironment(null); + setAddSheetVisible(false); + } + }, [props.visible]); + + // When there are no backends, open the add flow automatically + useEffect(() => { + if (props.visible && !dismissible) { + setAddSheetStartWithScanner(false); + setAddSheetVisible(true); + } + }, [props.visible, dismissible]); + + const handleMenuAction = useCallback( + ({ nativeEvent }: { nativeEvent: { event: string } }) => { + if (nativeEvent.event === "scan_qr") { + setAddSheetStartWithScanner(true); + setAddSheetVisible(true); + } else if (nativeEvent.event === "enter_manually") { + setAddSheetStartWithScanner(false); + setAddSheetVisible(true); + } + }, + [], + ); + + return ( + + + {/* Header */} + + + + Backends + + + Manage your connected environments. + + + + {/* + button with native menu */} + + + + + + + + {/* Backend list */} + + {hasEnvironments ? ( + props.connectedEnvironments.map((environment) => ( + setEditingEnvironment(environment)} + onRemove={props.onRemoveEnvironment} + /> + )) + ) : ( + + + + + + No backends connected yet.{"\n"}Tap{" "} + + + + {" "} + to add one. + + + )} + + + + {/* Nested: Add backend */} + setAddSheetVisible(false)} + onChangePairingUrl={props.onChangePairingUrl} + onConnect={props.onConnect} + /> + + {/* Nested: Edit backend */} + setEditingEnvironment(null)} + onSave={(environmentId, updates) => { + void props.onUpdateEnvironment(environmentId, updates); + }} + onRemove={props.onRemoveEnvironment} + /> + ); } diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx new file mode 100644 index 0000000000..72adb3bf65 --- /dev/null +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -0,0 +1,171 @@ +import { SymbolView } from "expo-symbols"; +import { useMemo } from "react"; +import { Pressable, ScrollView, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { AppText as Text } from "../../components/AppText"; +import { EmptyState } from "../../components/EmptyState"; +import { StatusPill } from "../../components/StatusPill"; +import { groupProjectsByRepository } from "../../lib/repositoryGroups"; +import type { ScopedMobileProject, ScopedMobileThread } from "../../lib/scopedEntities"; +import { scopedProjectKey } from "../../lib/scopedEntities"; +import { relativeTime } from "../../lib/time"; +import { ConnectionStatusDot } from "../connection/ConnectionStatusDot"; +import { threadStatusTone } from "../threads/threadPresentation"; + +export function HomeScreen(props: { + readonly projects: ReadonlyArray; + readonly threads: ReadonlyArray; + readonly connectionState: "ready" | "connecting" | "reconnecting" | "disconnected" | "idle"; + readonly connectionPulse: boolean; + readonly onOpenConnectionEditor: () => void; + readonly onOpenNewTask: () => void; + readonly onSelectThread: (thread: ScopedMobileThread) => void; +}) { + const insets = useSafeAreaInsets(); + 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]); + + return ( + + + + + Recents + + + + + + + + {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: "rgba(23,23,23,0.06)", + }} + > + + + + {thread.title} + + + + + + + + + {projectLabel?.projectTitle ?? thread.title} + + + + {projectLabel?.environmentLabel ?? "Local"} + + + + {relativeTime(thread.updatedAt ?? thread.createdAt)} + + + + ); + })} + + )} + + + + + + + New task + + + + + ); +} diff --git a/apps/mobile/src/features/threads/NewTaskSheet.tsx b/apps/mobile/src/features/threads/NewTaskSheet.tsx new file mode 100644 index 0000000000..86ae050960 --- /dev/null +++ b/apps/mobile/src/features/threads/NewTaskSheet.tsx @@ -0,0 +1,1270 @@ +import { + BottomSheetBackdrop, + BottomSheetModal, + BottomSheetScrollView, + BottomSheetView, +} from "@gorhom/bottom-sheet"; +import type { + ClaudeCodeEffort, + GitBranch, + ModelSelection, + ProviderInteractionMode, + RuntimeMode, + ServerConfig as T3ServerConfig, +} from "@t3tools/contracts"; +import { + CLAUDE_CODE_EFFORT_OPTIONS, + DEFAULT_PROVIDER_INTERACTION_MODE, + DEFAULT_RUNTIME_MODE, +} from "@t3tools/contracts"; +import { SymbolView } from "expo-symbols"; +import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + Image, + KeyboardAvoidingView, + Platform, + Pressable, + ScrollView, + View, +} from "react-native"; +import Reanimated, { SlideInLeft, SlideInRight, SlideOutLeft, SlideOutRight } from "react-native-reanimated"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText"; +import type { DraftComposerImageAttachment } from "../../lib/composerImages"; +import { pickComposerImages } from "../../lib/composerImages"; +import { groupProjectsByRepository } from "../../lib/repositoryGroups"; +import type { ScopedMobileProject, ScopedMobileThread } from "../../lib/scopedEntities"; +import { scopedProjectKey } from "../../lib/scopedEntities"; + +type WorkspaceMode = "local" | "worktree"; + +type ModelOption = { + readonly key: string; + readonly label: string; + readonly subtitle: string; + readonly providerKey: string; + readonly providerLabel: string; + readonly selection: ModelSelection; +}; + +type ProviderGroup = { + readonly providerKey: string; + readonly providerLabel: string; + readonly models: ReadonlyArray; +}; + +function normalizeSelectedWorktreePath( + project: ScopedMobileProject, + branch: GitBranch, +): string | null { + if (!branch.worktreePath) { + return null; + } + + return branch.worktreePath === project.workspaceRoot ? null : branch.worktreePath; +} + +function branchBadgeLabel(input: { + readonly branch: GitBranch; + readonly project: ScopedMobileProject | null; +}): string | null { + if (input.branch.current) { + return "current"; + } + if (input.branch.worktreePath && input.branch.worktreePath !== input.project?.workspaceRoot) { + return "worktree"; + } + if (input.branch.isDefault) { + return "default"; + } + if (input.branch.isRemote) { + return "remote"; + } + return null; +} + +function providerDisplayLabel(provider: string): string { + if (provider === "codex") return "Codex"; + if (provider === "claudeAgent") return "Claude"; + return provider; +} + +function buildModelOptions( + config: T3ServerConfig | null | undefined, + fallbackModelSelection: ModelSelection | null, +): ReadonlyArray { + const options = new Map(); + + for (const provider of config?.providers ?? []) { + if (!provider.enabled || !provider.installed || provider.auth.status === "unauthenticated") { + continue; + } + + const pLabel = providerDisplayLabel(provider.provider); + for (const model of provider.models) { + const key = `${provider.provider}:${model.slug}`; + options.set(key, { + key, + label: model.name, + subtitle: pLabel, + providerKey: provider.provider, + providerLabel: pLabel, + selection: { + provider: provider.provider, + model: model.slug, + }, + }); + } + } + + if (fallbackModelSelection) { + const key = `${fallbackModelSelection.provider}:${fallbackModelSelection.model}`; + if (!options.has(key)) { + const pLabel = providerDisplayLabel(fallbackModelSelection.provider); + options.set(key, { + key, + label: fallbackModelSelection.model, + subtitle: pLabel, + providerKey: fallbackModelSelection.provider, + providerLabel: pLabel, + selection: fallbackModelSelection, + }); + } + } + + return [...options.values()]; +} + +function groupByProvider(options: ReadonlyArray): ReadonlyArray { + const groups = new Map(); + for (const option of options) { + const existing = groups.get(option.providerKey); + if (existing) { + existing.models.push(option); + } else { + groups.set(option.providerKey, { + providerLabel: option.providerLabel, + models: [option], + }); + } + } + return [...groups.entries()].map(([providerKey, group]) => ({ + providerKey, + providerLabel: group.providerLabel, + models: group.models, + })); +} + +function compactModelLabel(option: ModelOption | null): string { + if (!option) { + return "AI"; + } + + const versionMatch = option.selection.model.match(/(\d+(?:\.\d+)?)/); + if (versionMatch?.[1]) { + return versionMatch[1]; + } + + const lastToken = option.label.split(/\s+/).at(-1)?.trim(); + return lastToken && lastToken.length <= 6 ? lastToken : "AI"; +} + +function ControlPill(props: { + readonly icon: React.ComponentProps["name"]; + readonly label?: string; + readonly onPress: () => void; + readonly variant?: "circle" | "pill" | "primary"; + readonly disabled?: boolean; +}) { + const variant = props.variant ?? "circle"; + const backgroundColor = + variant === "primary" + ? props.disabled + ? "rgba(23,23,23,0.14)" + : "#171717" + : "rgba(23,23,23,0.06)"; + const iconTintColor = variant === "primary" ? "#fafaf9" : "#171717"; + const textColor = variant === "primary" ? "#fafaf9" : "#171717"; + + return ( + + + {props.label ? ( + + {props.label} + + ) : null} + + ); +} + +function BottomSelectorSheet(props: { + readonly visible: boolean; + readonly title: string; + readonly onClose: () => void; + readonly children: ReactNode; + readonly snapPoints?: ReadonlyArray; +}) { + const sheetRef = useRef(null); + const snapPoints = useMemo<(string | number)[]>( + () => [...(props.snapPoints ?? ["72%"])], + [props.snapPoints], + ); + 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 ( + + + + + {props.title} + + + {props.children} + + + ); +} + +// --------------------------------------------------------------------------- +// Main NewTaskSheet — two-step: project picker → task form +// --------------------------------------------------------------------------- + +export function NewTaskSheet(props: { + readonly visible: boolean; + readonly projects: ReadonlyArray; + readonly threads: ReadonlyArray; + readonly serverConfigByEnvironmentId: Readonly>; + readonly onRequestClose: () => void; + readonly onCreateThreadWithOptions: (input: { + readonly project: ScopedMobileProject; + readonly modelSelection: ModelSelection; + readonly envMode: WorkspaceMode; + readonly branch: string | null; + readonly worktreePath: string | null; + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + readonly initialMessageText: string; + readonly initialAttachments: ReadonlyArray; + }) => Promise; + readonly onListProjectBranches: ( + project: ScopedMobileProject, + ) => Promise>; +}) { + const insets = useSafeAreaInsets(); + const sheetRef = useRef(null); + + // Step state + const [step, setStep] = useState<"project" | "task">("project"); + + // Project picker state + 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], + ); + + // Task form state + const [selectedEnvironmentId, setSelectedEnvironmentId] = useState( + props.projects[0]?.environmentId ?? "", + ); + const [selectedProjectKey, setSelectedProjectKey] = useState(null); + const [selectedModelKey, setSelectedModelKey] = useState(null); + const [workspaceMode, setWorkspaceMode] = useState("local"); + const [selectedBranchName, setSelectedBranchName] = useState(null); + const [selectedWorktreePath, setSelectedWorktreePath] = useState(null); + const [prompt, setPrompt] = useState(""); + const [attachments, setAttachments] = useState>([]); + const [submitting, setSubmitting] = useState(false); + const [projectPickerVisible, setProjectPickerVisible] = useState(false); + const [environmentPickerVisible, setEnvironmentPickerVisible] = useState(false); + const [modelPickerVisible, setModelPickerVisible] = useState(false); + const [optionsPickerVisible, setOptionsPickerVisible] = useState(false); + const [branchPickerVisible, setBranchPickerVisible] = 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); + const [effort, setEffort] = useState("high"); + const [fastMode, setFastMode] = useState(false); + const [contextWindow, setContextWindow] = useState("1M"); + const [expandedProvider, setExpandedProvider] = useState(null); + + const environments = useMemo( + () => + [ + ...new Map( + props.projects.map((project) => [project.environmentId, project.environmentLabel]), + ).entries(), + ].map(([environmentId, environmentLabel]) => ({ + environmentId, + environmentLabel, + })), + [props.projects], + ); + + const projectsForEnvironment = useMemo( + () => props.projects.filter((project) => project.environmentId === selectedEnvironmentId), + [props.projects, selectedEnvironmentId], + ); + const logicalProjectsForEnvironment = useMemo( + () => + groupProjectsByRepository({ projects: projectsForEnvironment, threads: [] }) + .map((group) => group.projects[0]?.project ?? null) + .filter((project) => project !== null), + [projectsForEnvironment], + ); + + const selectedProject = + projectsForEnvironment.find( + (project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey, + ) ?? + projectsForEnvironment[0] ?? + null; + + const modelOptions = useMemo( + () => + buildModelOptions( + selectedProject + ? (props.serverConfigByEnvironmentId[selectedProject.environmentId] ?? null) + : null, + selectedProject?.defaultModelSelection ?? null, + ), + [props.serverConfigByEnvironmentId, selectedProject], + ); + + const selectedModel = + modelOptions.find((option) => option.key === selectedModelKey)?.selection ?? + selectedProject?.defaultModelSelection ?? + modelOptions[0]?.selection ?? + null; + const selectedModelOption = + modelOptions.find( + (option) => + selectedModel && + option.selection.provider === selectedModel.provider && + option.selection.model === selectedModel.model, + ) ?? null; + + const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]); + + const filteredBranches = useMemo(() => { + const query = branchQuery.trim().toLowerCase(); + if (query.length === 0) return availableBranches; + return availableBranches.filter((branch) => branch.name.toLowerCase().includes(query)); + }, [availableBranches, branchQuery]); + + const headerSubtitle = useMemo(() => { + if (!selectedProject) return null; + if (workspaceMode === "worktree") { + return `${selectedProject.title} @ ${selectedBranchName ?? "Select base branch"}`; + } + if (selectedBranchName) { + return `${selectedProject.title} @ ${selectedBranchName}`; + } + return `${selectedProject.title} · ${selectedProject.environmentLabel}`; + }, [selectedBranchName, selectedProject, workspaceMode]); + + const renderBackdrop = useCallback( + (backdropProps: React.ComponentProps) => ( + + ), + [], + ); + + // Present / dismiss / reset + useEffect(() => { + const sheet = sheetRef.current; + if (!sheet) return; + + if (props.visible) { + // Reset state + setPrompt(""); + setAttachments([]); + setSelectedModelKey(null); + setSelectedBranchName(null); + setSelectedWorktreePath(null); + setWorkspaceMode("local"); + setRuntimeMode(DEFAULT_RUNTIME_MODE); + setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE); + setEffort("high"); + setFastMode(false); + setContextWindow("1M"); + setExpandedProvider(null); + setSubmitting(false); + + // If only one project, skip to step 2 + if (logicalProjects.length === 1) { + const only = logicalProjects[0]!; + setSelectedEnvironmentId(only.project.environmentId); + setSelectedProjectKey(scopedProjectKey(only.project.environmentId, only.project.id)); + setStep("task"); + } else { + setStep("project"); + } + + sheet.present(); + } else { + sheet.dismiss(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [props.visible]); + + // Step transitions + const goToTask = useCallback((project: ScopedMobileProject) => { + setSelectedEnvironmentId(project.environmentId); + setSelectedProjectKey(scopedProjectKey(project.environmentId, project.id)); + setStep("task"); + }, []); + + const goBackToProjects = useCallback(() => { + setStep("project"); + }, []); + + // Actions + async function handlePickImages(): Promise { + const result = await pickComposerImages({ existingCount: attachments.length }); + if (result.images.length > 0) { + setAttachments((current) => [...current, ...result.images]); + } + } + + async function openBranchPicker(): Promise { + if (!selectedProject) return; + setBranchPickerVisible(true); + setBranchesLoading(true); + try { + const branches = await props.onListProjectBranches(selectedProject); + setAvailableBranches(branches); + if (workspaceMode === "worktree" && !selectedBranchName) { + const preferredBranch = + branches.find((branch) => branch.current)?.name ?? + branches.find((branch) => branch.isDefault)?.name ?? + null; + if (preferredBranch) setSelectedBranchName(preferredBranch); + } + } finally { + setBranchesLoading(false); + } + } + + async function handleStart(): Promise { + if ( + !selectedProject || + !selectedModel || + prompt.trim().length === 0 || + submitting || + (workspaceMode === "worktree" && !selectedBranchName) + ) { + return; + } + + setSubmitting(true); + try { + const modelWithOptions: ModelSelection = + selectedModel.provider === "claudeAgent" + ? { + ...selectedModel, + options: { effort, fastMode: fastMode || undefined, contextWindow }, + } + : selectedModel.provider === "codex" + ? { ...selectedModel, options: { fastMode: fastMode || undefined } } + : selectedModel; + + await props.onCreateThreadWithOptions({ + project: selectedProject, + modelSelection: modelWithOptions, + envMode: workspaceMode, + branch: selectedBranchName, + worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath, + runtimeMode, + interactionMode, + initialMessageText: prompt.trim(), + initialAttachments: attachments, + }); + props.onRequestClose(); + } finally { + setSubmitting(false); + } + } + + return ( + <> + + + {step === "project" ? ( + + + + New task + + + Choose project + + + + + + {logicalProjects.map((entry, index) => ( + goToTask(entry.project)} + style={{ + paddingHorizontal: 16, + paddingVertical: 18, + borderTopWidth: index === 0 ? 0 : 1, + borderTopColor: "rgba(23,23,23,0.06)", + }} + > + + + + {entry.project.title} + + + + + + ))} + + + + ) : ( + + + + {/* Header with back button */} + + {logicalProjects.length > 1 ? ( + + + + ) : null} + + New task + + + {selectedProject?.title ?? "New task"} + + + + + + + {attachments.length > 0 ? ( + + + {attachments.map((attachment) => ( + + + + setAttachments((current) => + current.filter((candidate) => candidate.id !== attachment.id), + ) + } + > + + Remove + + + + ))} + + + ) : null} + + + + + void handlePickImages()} /> + setModelPickerVisible(true)} + variant="pill" + /> + setOptionsPickerVisible(true)} + /> + setEnvironmentPickerVisible(true)} + /> + void openBranchPicker()} + /> + void handleStart()} + variant="primary" + disabled={ + !selectedProject || + !selectedModel || + prompt.trim().length === 0 || + submitting || + (workspaceMode === "worktree" && !selectedBranchName) + } + /> + + + + + + )} + + + + {/* Sub-pickers (environment, project, model, branch) */} + setEnvironmentPickerVisible(false)} + > + + + {environments.map((environment, index) => ( + { + setSelectedEnvironmentId(environment.environmentId); + setSelectedProjectKey(null); + setSelectedBranchName(null); + setSelectedWorktreePath(null); + setEnvironmentPickerVisible(false); + }} + style={{ + paddingHorizontal: 16, + paddingVertical: 18, + borderTopWidth: index === 0 ? 0 : 1, + borderTopColor: "rgba(23,23,23,0.06)", + }} + > + + {environment.environmentLabel} + + + ))} + + + + + setProjectPickerVisible(false)} + > + + + {logicalProjectsForEnvironment.map((project, index) => ( + { + setSelectedProjectKey(scopedProjectKey(project.environmentId, project.id)); + setSelectedBranchName(null); + setSelectedWorktreePath(null); + setProjectPickerVisible(false); + }} + style={{ + paddingHorizontal: 16, + paddingVertical: 18, + borderTopWidth: index === 0 ? 0 : 1, + borderTopColor: "rgba(23,23,23,0.06)", + }} + > + + {project.title} + + + ))} + + + + + {/* Model picker — provider + model only */} + { + setModelPickerVisible(false); + setExpandedProvider(null); + }} + > + + + {providerGroups.map((group) => { + const isExpanded = expandedProvider === group.providerKey; + const hasSelected = group.models.some( + (m) => + selectedModel && + m.selection.provider === selectedModel.provider && + m.selection.model === selectedModel.model, + ); + + return ( + + + setExpandedProvider(isExpanded ? null : group.providerKey) + } + className="flex-row items-center justify-between rounded-[16px] px-4 py-3.5" + style={{ + backgroundColor: isExpanded + ? "rgba(23,23,23,0.06)" + : hasSelected + ? "rgba(23,23,23,0.04)" + : "#ffffff", + borderWidth: hasSelected && !isExpanded ? 1 : 0, + borderColor: "rgba(23,23,23,0.08)", + }} + > + + + {group.providerLabel} + + {hasSelected && !isExpanded ? ( + + {selectedModelOption?.label} + + ) : null} + + + + + {isExpanded ? ( + + {group.models.map((option, index) => { + const isSelected = + selectedModel && + option.selection.provider === selectedModel.provider && + option.selection.model === selectedModel.model; + return ( + { + setSelectedModelKey(option.key); + setModelPickerVisible(false); + setExpandedProvider(null); + }} + style={{ + paddingHorizontal: 16, + paddingVertical: 14, + borderTopWidth: index === 0 ? 0 : 1, + borderTopColor: "rgba(23,23,23,0.06)", + backgroundColor: isSelected ? "rgba(23,23,23,0.04)" : "transparent", + }} + > + + + {option.label} + + {isSelected ? ( + + ) : null} + + + ); + })} + + ) : null} + + ); + })} + + + + + {/* Options picker — effort, fast mode, context window, mode, access */} + setOptionsPickerVisible(false)} + snapPoints={["82%"]} + > + + + {/* ── Effort ── */} + + + Effort + + + {CLAUDE_CODE_EFFORT_OPTIONS.map((level, index) => ( + setEffort(level)} + style={{ + paddingHorizontal: 16, + paddingVertical: 13, + borderTopWidth: index === 0 ? 0 : 1, + borderTopColor: "rgba(23,23,23,0.06)", + }} + > + + + {level}{level === "high" ? " (default)" : ""} + + {effort === level ? ( + + ) : null} + + + ))} + + + + {/* ── Fast Mode ── */} + + + Fast Mode + + + {([false, true] as const).map((value, index) => ( + setFastMode(value)} + style={{ + paddingHorizontal: 16, + paddingVertical: 13, + borderTopWidth: index === 0 ? 0 : 1, + borderTopColor: "rgba(23,23,23,0.06)", + }} + > + + + {value ? "On" : "Off"} + + {fastMode === value ? ( + + ) : null} + + + ))} + + + + {/* ── Context Window ── */} + + + Context Window + + + {(["200k", "1M"] as const).map((value, index) => ( + setContextWindow(value)} + style={{ + paddingHorizontal: 16, + paddingVertical: 13, + borderTopWidth: index === 0 ? 0 : 1, + borderTopColor: "rgba(23,23,23,0.06)", + }} + > + + + {value}{value === "1M" ? " (default)" : ""} + + {contextWindow === value ? ( + + ) : null} + + + ))} + + + + {/* ── Mode ── */} + + + Mode + + + {( + [ + { value: "default" as const, label: "Chat" }, + { value: "plan" as const, label: "Plan" }, + ] as const + ).map((option, index) => ( + setInteractionMode(option.value)} + style={{ + paddingHorizontal: 16, + paddingVertical: 13, + borderTopWidth: index === 0 ? 0 : 1, + borderTopColor: "rgba(23,23,23,0.06)", + }} + > + + + {option.label} + + {interactionMode === option.value ? ( + + ) : null} + + + ))} + + + + {/* ── Access ── */} + + + Access + + + {( + [ + { value: "approval-required" as const, label: "Supervised", desc: "Ask before commands and file changes" }, + { value: "auto-accept-edits" as const, label: "Auto-accept edits", desc: "Auto-approve edits, ask before other actions" }, + { value: "full-access" as const, label: "Full access", desc: "Allow commands and edits without prompts" }, + ] as const + ).map((option, index) => ( + setRuntimeMode(option.value)} + style={{ + paddingHorizontal: 16, + paddingVertical: 13, + borderTopWidth: index === 0 ? 0 : 1, + borderTopColor: "rgba(23,23,23,0.06)", + }} + > + + + + {option.label} + + + {option.desc} + + + {runtimeMode === option.value ? ( + + ) : null} + + + ))} + + + + + + + setBranchPickerVisible(false)} + > + + + setWorkspaceMode("local")} + className="flex-1 rounded-full px-4 py-3" + style={{ + backgroundColor: + workspaceMode === "local" ? "rgba(23,23,23,0.08)" : "rgba(23,23,23,0.04)", + }} + > + + Current checkout + + + { + setWorkspaceMode("worktree"); + setSelectedWorktreePath(null); + }} + className="flex-1 rounded-full px-4 py-3" + style={{ + backgroundColor: + workspaceMode === "worktree" ? "rgba(23,23,23,0.08)" : "rgba(23,23,23,0.04)", + }} + > + + New worktree + + + + + + + + + {branchesLoading ? ( + + + Loading branches... + + + ) : ( + filteredBranches.map((branch, index) => { + const normalizedWorktreePath = selectedProject + ? normalizeSelectedWorktreePath(selectedProject, branch) + : null; + const selected = + selectedBranchName === branch.name && + (workspaceMode === "worktree" + ? selectedWorktreePath === null + : (selectedWorktreePath ?? null) === normalizedWorktreePath); + const badge = branchBadgeLabel({ branch, project: selectedProject }); + + return ( + { + setSelectedBranchName(branch.name); + setSelectedWorktreePath( + workspaceMode === "worktree" ? null : normalizedWorktreePath, + ); + setBranchPickerVisible(false); + }} + style={{ + paddingHorizontal: 16, + paddingVertical: 18, + borderTopWidth: index === 0 ? 0 : 1, + borderTopColor: "rgba(23,23,23,0.06)", + }} + > + + + + {branch.name} + + + {workspaceMode === "worktree" + ? "Base branch for new worktree" + : normalizedWorktreePath + ? "Existing worktree" + : "Current checkout"} + + + + {badge ? ( + + {badge} + + ) : null} + {selected ? ( + + ) : null} + + + + ); + }) + )} + + + + + + ); +} diff --git a/apps/mobile/src/features/threads/ProjectPickerSheet.tsx b/apps/mobile/src/features/threads/ProjectPickerSheet.tsx new file mode 100644 index 0000000000..edc2963f39 --- /dev/null +++ b/apps/mobile/src/features/threads/ProjectPickerSheet.tsx @@ -0,0 +1,129 @@ +import { + BottomSheetBackdrop, + BottomSheetModal, + BottomSheetScrollView, + BottomSheetView, +} from "@gorhom/bottom-sheet"; +import { useCallback, useEffect, useMemo, useRef } from "react"; +import { Pressable, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { AppText as Text } from "../../components/AppText"; +import { groupProjectsByRepository } from "../../lib/repositoryGroups"; +import type { ScopedMobileProject, ScopedMobileThread } from "../../lib/scopedEntities"; + +export function ProjectPickerSheet(props: { + readonly visible: boolean; + readonly projects: ReadonlyArray; + readonly threads: ReadonlyArray; + readonly onClose: () => void; + readonly onSelectProject: (project: ScopedMobileProject) => void; +}) { + 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: "rgba(23,23,23,0.06)", + }} + > + + + + {entry.project.title} + + + + + ))} + + + + + ); +} diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index facdb9a64b..c03372df15 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -6,6 +6,7 @@ import { Image, Pressable, ScrollView, View } from "react-native"; import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText"; import { cx } from "../../lib/classNames"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; +import type { MobileLayoutVariant } from "../../lib/mobileLayout"; import type { RemoteClientConnectionState } from "../../lib/remoteClient"; function ComposerAction(props: { @@ -47,6 +48,7 @@ export interface ThreadComposerProps { readonly selectedThread: OrchestrationThread; readonly queueCount: number; readonly activeThreadBusy: boolean; + readonly layoutVariant?: MobileLayoutVariant; readonly onChangeDraftMessage: (value: string) => void; readonly onPickDraftImages: () => Promise; readonly onPasteIntoDraft: () => Promise; @@ -64,13 +66,17 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer props.selectedThread.session?.status === "running" || props.selectedThread.session?.status === "starting" || props.queueCount > 0; + const isSplitLayout = props.layoutVariant === "split"; return ( - + void props.onPickDraftImages()} /> void props.onPasteIntoDraft()} /> void props.onRefresh()} /> @@ -117,7 +123,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer : "paperplane.fill" } backgroundClassName={cx( - canSend ? "bg-orange-500" : "bg-slate-200 dark:bg-slate-700/60", + canSend ? "bg-neutral-900" : "bg-slate-200 dark:bg-slate-700/60", )} iconTintColor="#ffffff" disabled={!canSend} @@ -127,7 +133,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer {props.draftAttachments.length > 0 ? ( - + {props.draftAttachments.map((image) => ( @@ -150,7 +160,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer ) : null} {props.queueCount > 0 ? ( - + {props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send automatically. diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 19d3a48a41..89919ddcff 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -1,23 +1,39 @@ -import type { ApprovalRequestId, ProviderApprovalDecision } from "@t3tools/contracts"; +import type { + ApprovalRequestId, + GitBranch, + GitRunStackedActionResult, + GitStatusResult, + ProviderApprovalDecision, +} from "@t3tools/contracts"; +import type { GitActionRequestInput } from "@t3tools/client-runtime"; import * as Haptics from "expo-haptics"; -import { useEffect, useRef, useState } from "react"; +import { SymbolView } from "expo-symbols"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { KeyboardAvoidingView, Modal, Platform, Pressable, useColorScheme, + useWindowDimensions, View, } from "react-native"; +import { Gesture, GestureDetector } from "react-native-gesture-handler"; import { useSafeAreaInsets } from "react-native-safe-area-context"; -import Animated from "react-native-reanimated"; +import Animated, { + interpolate, + runOnJS, + useAnimatedStyle, + useSharedValue, + withSpring, + withTiming, +} from "react-native-reanimated"; import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText"; -import { ErrorBanner } from "../../components/ErrorBanner"; import { GlassSafeAreaView } from "../../components/GlassSafeAreaView"; import type { StatusTone } from "../../components/StatusPill"; -import { ConnectionStatusDot } from "../connection/ConnectionStatusDot"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; +import type { MobileLayoutVariant } from "../../lib/mobileLayout"; import type { ScopedMobileThread } from "../../lib/scopedEntities"; import type { PendingApproval, @@ -26,6 +42,7 @@ import type { ThreadFeedEntry, } from "../../lib/threadActivity"; import { PendingApprovalCard } from "./PendingApprovalCard"; +import { ThreadGitControls } from "./ThreadGitControls"; import { PendingUserInputCard } from "./PendingUserInputCard"; import { ThreadComposer } from "./ThreadComposer"; import { ThreadFeed } from "./ThreadFeed"; @@ -48,14 +65,32 @@ export interface ThreadDetailScreenProps { readonly draftAttachments: ReadonlyArray; readonly connectionStateLabel: "ready" | "connecting" | "reconnecting" | "disconnected" | "idle"; readonly activeThreadBusy: boolean; + readonly selectedThreadGitStatus: GitStatusResult | null; + readonly gitOperationLabel: string | null; readonly selectedThreadQueueCount: number; + readonly layoutVariant?: MobileLayoutVariant; readonly onBack: () => void; + readonly onOpenDrawer: () => void; readonly onOpenConnectionEditor: () => void; readonly onChangeDraftMessage: (value: string) => void; readonly onPickDraftImages: () => Promise; readonly onPasteIntoDraft: () => 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; @@ -94,16 +129,6 @@ function latestStreamingAssistantMessage( return null; } -function useRenameDraftSync(threadId: string, threadTitle: string) { - const [renameDraft, setRenameDraft] = useState(threadTitle); - - useEffect(() => { - setRenameDraft(threadTitle); - }, [threadId, threadTitle]); - - return [renameDraft, setRenameDraft] as const; -} - function useStreamingHaptics(threadId: string, feed: ReadonlyArray) { const lastStreamingAssistantRef = useRef<{ readonly id: string; @@ -155,28 +180,117 @@ function useStreamingHaptics(threadId: string, feed: ReadonlyArray { + void Haptics.selectionAsync(); + onOpenDrawer(); + }, [onOpenDrawer]); + + const completeBackGesture = useCallback(() => { + void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); + onBack(); + }, [onBack]); + + const handleRefresh = useCallback(async (): Promise => { + if (refreshing) { + return; + } + + setRefreshing(true); + try { + await onRefresh(); + await onRefreshSelectedThreadGitStatus(); + } finally { + setRefreshing(false); + } + }, [onRefresh, onRefreshSelectedThreadGitStatus, refreshing]); + + const edgeSwipeGesture = useMemo( + () => + Gesture.Pan() + .enabled(!isSplitLayout) + .hitSlop({ left: 0, width: 40 }) + .activeOffsetX([10, 999]) + .failOffsetY([-24, 24]) + .onUpdate((event) => { + edgeSwipeTranslation.value = Math.max(event.translationX, 0); + }) + .onEnd((event) => { + const translationX = Math.max(event.translationX, 0); + const shouldOpenDrawer = event.y < headerOverlayHeight && translationX > 56; + const shouldGoBack = translationX > Math.min(width * 0.26, 120); + + if (shouldOpenDrawer) { + edgeSwipeTranslation.value = withSpring(0, { + damping: 20, + stiffness: 220, + }); + runOnJS(completeDrawerGesture)(); + return; + } + + if (shouldGoBack) { + edgeSwipeTranslation.value = withTiming(width, { duration: 180 }, (finished) => { + if (!finished) { + return; + } + + edgeSwipeTranslation.value = 0; + runOnJS(completeBackGesture)(); + }); + return; + } + + edgeSwipeTranslation.value = withSpring(0, { + damping: 20, + stiffness: 220, + }); + }), + [ + completeBackGesture, + completeDrawerGesture, + edgeSwipeTranslation, + headerOverlayHeight, + isSplitLayout, + width, + ], + ); + + const edgeSwipeStyle = useAnimatedStyle(() => { + const borderRadius = interpolate(edgeSwipeTranslation.value, [0, width], [0, 28], "clamp"); + + return { + flex: 1, + transform: [{ translateX: edgeSwipeTranslation.value }], + borderTopLeftRadius: borderRadius, + borderBottomLeftRadius: borderRadius, + overflow: "hidden", + }; + }); + async function handleSubmitRename(): Promise { const trimmed = renameDraft.trim(); if (trimmed.length === 0) { @@ -188,216 +302,243 @@ export function ThreadDetailScreen(props: ThreadDetailScreenProps) { } return ( - - {showHeader ? ( - - - - Back - - - } - centerSlot={ - - setRenameVisible(true)}> - - {props.selectedThread.title} - - - - {props.activeWorkDurationLabel ? props.activeWorkDurationLabel : ""} - - - } - rightSlot={ - - - - } - /> - - ) : null} - - {showContent && props.connectionError ? ( - + + - - - ) : null} - - {showContent ? ( - <> - - - - - {props.activePendingApproval || props.activePendingUserInput ? ( - - {props.activePendingApproval ? ( - + + + + + ) + } + centerSlot={ + + { + setRenameDraft(props.selectedThread.title); + setRenameVisible(true); + }} + > + + {props.selectedThread.title} + + + + {props.activeWorkDurationLabel ? props.activeWorkDurationLabel : ""} + + + } + rightSlot={ + + } /> - ) : null} - {props.activePendingUserInput ? ( - - ) : null} + ) : null} - - - ) : ( - - )} + {showContent ? ( + <> + + void handleRefresh()} + /> + - setRenameVisible(false)} - > - - + {props.activePendingApproval ? ( + + ) : null} + {props.activePendingUserInput ? ( + + ) : null} + + ) : null} + + + + ) : ( + + )} + + setRenameVisible(false)} > - - - Thread name - - - Rename thread - - - - { - void handleSubmitRename(); - }} - /> - - - + { - setRenameDraft(props.selectedThread.title); - setRenameVisible(false); + backgroundColor: modalPanelColor, }} > - - Cancel - - - { - void handleSubmitRename(); - }} - > - - Save - - + + + 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 ea863110ed..d174b603fe 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -1,11 +1,23 @@ +import * as Clipboard from "expo-clipboard"; +import * as Haptics from "expo-haptics"; import { FlashList, type FlashListRef, type ListRenderItemInfo } from "@shopify/flash-list"; -import { memo, useCallback, useEffect, useRef } from "react"; +import { SymbolView } from "expo-symbols"; +import { memo, useCallback, useEffect, useState, useRef } from "react"; import Markdown from "react-native-markdown-display"; -import { Image, type NativeScrollEvent, type NativeSyntheticEvent, View } from "react-native"; +import { + Image, + Pressable, + RefreshControl, + ScrollView, + type NativeScrollEvent, + type NativeSyntheticEvent, + View, +} from "react-native"; import { AppText as Text } from "../../components/AppText"; import { EmptyState } from "../../components/EmptyState"; import { cx } from "../../lib/classNames"; +import type { MobileLayoutVariant } from "../../lib/mobileLayout"; import type { ThreadFeedEntry } from "../../lib/threadActivity"; import { relativeTime } from "../../lib/time"; import { messageImageUrl } from "./threadPresentation"; @@ -18,6 +30,9 @@ export interface ThreadFeedProps { readonly agentLabel: string; readonly contentTopInset?: number; readonly contentBottomInset?: number; + readonly refreshing?: boolean; + readonly onRefresh?: () => void; + readonly layoutVariant?: MobileLayoutVariant; } function stripShellWrapper(value: string): string { @@ -31,13 +46,18 @@ function compactActivityDetail(detail: string | null): string | null { return null; } - const cleaned = stripShellWrapper(detail); + const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim(); return cleaned.length > 0 ? cleaned : null; } +function normalizeCompactActivityLabel(value: string): string { + return value.replace(/\s+(?:started|complete|completed)\s*$/i, "").trim(); +} + function buildActivityRows( activities: ReadonlyArray<{ readonly id: string; + readonly createdAt: string; readonly summary: string; readonly detail: string | null; readonly status: string | null; @@ -45,19 +65,20 @@ function buildActivityRows( ) { const rows: Array<{ id: string; - label: string; + createdAt: string; + summary: string; detail: string | null; status: string | null; }> = []; for (const activity of activities) { const detail = compactActivityDetail(activity.detail); - const label = detail ?? activity.summary; const previous = rows.at(-1); - if (previous && previous.label === label) { + if (previous && previous.summary === activity.summary) { rows[rows.length - 1] = { ...previous, + createdAt: activity.createdAt, detail, status: activity.status ?? previous.status, }; @@ -66,7 +87,8 @@ function buildActivityRows( rows.push({ id: activity.id, - label, + createdAt: activity.createdAt, + summary: activity.summary, detail, status: activity.status, }); @@ -75,6 +97,8 @@ function buildActivityRows( return rows; } +const MAX_VISIBLE_WORK_LOG_ENTRIES = 6; + const MARKDOWN_BASE = { body: { color: "#020617", @@ -144,7 +168,12 @@ const ASSISTANT_MARKDOWN_STYLES = { function renderFeedEntry( info: ListRenderItemInfo, - props: Pick, + props: Pick & { + readonly copiedRowId: string | null; + readonly expandedWorkGroups: Record; + readonly onCopyWorkRow: (rowId: string, value: string) => void; + readonly onToggleWorkGroup: (groupId: string) => void; + }, ) { const entry = info.item; @@ -152,29 +181,54 @@ function renderFeedEntry( const { message } = entry; const isUser = message.role === "user"; const markdownStyles = isUser ? USER_MARKDOWN_STYLES : ASSISTANT_MARKDOWN_STYLES; + const timestampLabel = `${relativeTime(message.createdAt)}${message.streaming ? " • live" : ""}`; + const attachments = message.attachments ?? []; - return ( - - - - {isUser ? "You" : props.agentLabel} - - - {relativeTime(message.createdAt)} - {message.streaming ? " • live" : ""} + if (isUser) { + return ( + + + {message.text.trim().length > 0 ? ( + {message.text} + ) : null} + {attachments.map((attachment) => { + const uri = messageImageUrl(props.httpBaseUrl, attachment.id); + if (!uri) { + return null; + } + + return ( + + ); + })} + + + {timestampLabel} + ); + } + + return ( + {message.text.trim().length > 0 ? ( {message.text} ) : null} - {message.attachments?.map((attachment) => { + {attachments.map((attachment) => { const uri = messageImageUrl(props.httpBaseUrl, attachment.id); if (!uri) { return null; @@ -198,65 +252,94 @@ function renderFeedEntry( /> ); })} + + {timestampLabel} + ); } if (entry.type === "queued-message") { return ( - - - - {entry.sending ? "Sending next" : "Queued"} - - - {entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`} + + + + {entry.queuedMessage.text} + {entry.queuedMessage.attachments.length > 0 ? ( + + {entry.queuedMessage.attachments.length} image + {entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached + + ) : null} - - {entry.queuedMessage.text} + + {entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`} - {entry.queuedMessage.attachments.length > 0 ? ( - - {entry.queuedMessage.attachments.length} image - {entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached - - ) : null} ); } const rows = buildActivityRows(entry.activities); + const isExpanded = props.expandedWorkGroups[entry.id] ?? false; + const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES; + const visibleRows = hasOverflow && !isExpanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows; + const hiddenCount = rows.length - visibleRows.length; + const showHeader = hasOverflow; return ( - - - - Command center - - - {relativeTime(entry.createdAt)} - - - {rows.map((row, index) => ( + + {showHeader ? ( + + + Tool calls ({rows.length}) + + props.onToggleWorkGroup(entry.id)}> + + {isExpanded ? "Show less" : `Show ${hiddenCount} more`} + + + + ) : null} + {visibleRows.map((row, index) => ( 0 && "border-t border-slate-200/80 dark:border-white/4", )} > - - - {row.label} - - - {row.status ? row.status.replaceAll("_", " ") : "done"} - + + - {row.detail && row.detail !== row.label ? ( - - {row.detail} + + { + const copyValue = row.detail ?? normalizeCompactActivityLabel(row.summary); + props.onCopyWorkRow(row.id, copyValue); + }} + style={{ + fontFamily: "ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, monospace", + }} + > + {row.detail + ? `${normalizeCompactActivityLabel(row.summary)} - ${row.detail}` + : normalizeCompactActivityLabel(row.summary)} + + + {props.copiedRowId === row.id ? ( + + Copied ) : null} @@ -307,14 +390,71 @@ function useAutoScrollToLatest( export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const listRef = useRef>(null); + const copyFeedbackTimeoutRef = useRef | null>(null); + const [copiedRowId, setCopiedRowId] = useState(null); + const [expandedWorkGroups, setExpandedWorkGroups] = useState>({}); const updateFollowLatest = useAutoScrollToLatest(listRef, props.threadId, props.feed); + const horizontalPadding = props.layoutVariant === "split" ? 20 : 16; + + useEffect(() => { + setCopiedRowId(null); + setExpandedWorkGroups({}); + }, [props.threadId]); + + useEffect(() => { + return () => { + if (copyFeedbackTimeoutRef.current) { + clearTimeout(copyFeedbackTimeoutRef.current); + } + }; + }, []); + + const onCopyWorkRow = useCallback((rowId: string, value: string) => { + void Clipboard.setStringAsync(value); + void Haptics.selectionAsync(); + setCopiedRowId(rowId); + if (copyFeedbackTimeoutRef.current) { + clearTimeout(copyFeedbackTimeoutRef.current); + } + copyFeedbackTimeoutRef.current = setTimeout(() => { + setCopiedRowId((current) => (current === rowId ? null : current)); + copyFeedbackTimeoutRef.current = null; + }, 1200); + }, []); + + const onToggleWorkGroup = useCallback((groupId: string) => { + setExpandedWorkGroups((current) => ({ + ...current, + [groupId]: !(current[groupId] ?? false), + })); + }, []); + const renderItem = useCallback( + (info: ListRenderItemInfo) => + renderFeedEntry(info, { + bearerToken: props.bearerToken, + copiedRowId, + httpBaseUrl: props.httpBaseUrl, + expandedWorkGroups, + onCopyWorkRow, + onToggleWorkGroup, + }), + [ + copiedRowId, + expandedWorkGroups, + onCopyWorkRow, + onToggleWorkGroup, + props.bearerToken, + props.httpBaseUrl, + ], + ); if (props.feed.length === 0) { return ( renderFeedEntry(info, props)} + renderItem={renderItem} keyExtractor={(entry) => `${entry.type}:${entry.id}`} keyboardShouldPersistTaps="handled" onScroll={updateFollowLatest} scrollEventThrottle={16} + refreshControl={ + props.onRefresh ? ( + + ) : undefined + } maintainVisibleContentPosition={{ autoscrollToBottomThreshold: 0.2, animateAutoScrollToBottom: true, startRenderingFromBottom: true, }} contentContainerStyle={{ - paddingHorizontal: 16, + paddingHorizontal: horizontalPadding, paddingTop: props.contentTopInset ?? 18, paddingBottom: props.contentBottomInset ?? 18, }} diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx new file mode 100644 index 0000000000..6710d96546 --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx @@ -0,0 +1,1259 @@ +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, 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"; + +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"; +} + +function truncateMiddle(value: string, maxLength: number): string { + if (value.length <= maxLength) { + return value; + } + + const headLength = Math.ceil((maxLength - 1) / 2); + const tailLength = Math.floor((maxLength - 1) / 2); + return `${value.slice(0, headLength)}…${value.slice(value.length - tailLength)}`; +} + +function compactMenuBranchLabel(branch: string): string { + return truncateMiddle(branch, 24); +} + +function compactMenuStatus(gitStatus: GitStatusResult | null): string { + if (!gitStatus) { + return "Checking status"; + } + if (!gitStatus.isRepo) { + return "Not a repo"; + } + + const parts: string[] = []; + if (gitStatus.hasWorkingTreeChanges) { + parts.push(`${gitStatus.workingTree.files.length} changed`); + } else if (gitStatus.aheadCount === 0 && gitStatus.behindCount === 0) { + 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}`); + } + + 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 tone = props.tone ?? "secondary"; + const colors = + tone === "primary" + ? { + backgroundColor: "#171717", + borderColor: "transparent", + textColor: "#fafaf9", + } + : tone === "danger" + ? { + backgroundColor: "#fff1f2", + borderColor: "rgba(225,29,72,0.12)", + textColor: "#be123c", + } + : { + backgroundColor: "#ffffff", + borderColor: "rgba(23,23,23,0.08)", + textColor: "#171717", + }; + + return ( + + + + {props.label} + + + ); +} + +function MetaCard(props: { readonly label: string; readonly value: string }) { + 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; +}) { + 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 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 busy = gitOperationLabel !== null; + const isRepo = gitStatus?.isRepo ?? true; + const hasOriginRemote = gitStatus?.hasOriginRemote ?? false; + const isDefaultBranch = gitStatus?.isDefaultBranch ?? false; + const quickAction = useMemo( + () => + isRepo + ? resolveQuickAction(gitStatus, busy, isDefaultBranch, hasOriginRemote) + : { + label: "Git unavailable", + disabled: true, + kind: "show_hint" as const, + hint: "This workspace is not a git repository.", + }, + [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; + } + 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); + }, []); + + const openExistingPr = useCallback(async () => { + const prUrl = gitStatus?.pr?.state === "open" ? gitStatus.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]); + + 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?.branch; + if ( + branchName && + confirmableAction && + !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 } : {}), + }); + setDefaultBranchSheetVisible(true); + return; + } + + closeTransientSheets(); + await onRunAction(input); + }, + [closeTransientSheets, gitStatus, isDefaultBranch, onRunAction], + ); + + 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(); + return; + } + if (quickAction.kind === "run_pull") { + await onPull(); + return; + } + if (quickAction.kind === "run_action" && quickAction.action) { + await runActionWithPrompt({ action: quickAction.action }); + } + }, [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 ( + <> + + + + + + Git + + + {triggerStatus} + + + + + + + setGitSheetVisible(false)} + backgroundStyle={{ backgroundColor: "rgba(247,247,245,0.98)" }} + handleIndicatorStyle={{ backgroundColor: "rgba(120,113,108,0.32)" }} + > + + + + + + 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: "rgba(247,247,245,0.98)" }} + handleIndicatorStyle={{ backgroundColor: "rgba(120,113,108,0.32)" }} + > + + + + + 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: "rgba(247,247,245,0.98)" }} + handleIndicatorStyle={{ backgroundColor: "rgba(120,113,108,0.32)" }} + > + + + + {pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"} + + + {pendingDefaultBranchActionCopy?.description ?? "Choose how to continue."} + + + + + { + void continuePendingDefaultBranchAction(); + }} + /> + { + void movePendingActionToFeatureBranch(); + }} + /> + + + + + setBranchSheetVisible(false)} + backgroundStyle={{ backgroundColor: "rgba(247,247,245,0.98)" }} + handleIndicatorStyle={{ backgroundColor: "rgba(120,113,108,0.32)" }} + > + + + + + 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} + + + ); + })} + + + + + + ); +} diff --git a/apps/mobile/src/features/threads/ThreadListScreen.tsx b/apps/mobile/src/features/threads/ThreadListScreen.tsx index 048e9860e7..b756ce3fa1 100644 --- a/apps/mobile/src/features/threads/ThreadListScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadListScreen.tsx @@ -1,25 +1,30 @@ import { SymbolView } from "expo-symbols"; -import { useRef, useState } from "react"; -import { Pressable, ScrollView, View, type View as RNView } from "react-native"; -import { useColorScheme } from "react-native"; -import Animated, { FadeInDown, FadeOutUp, LinearTransition } from "react-native-reanimated"; -import Svg, { Path } from "react-native-svg"; +import { useCallback, useMemo, useRef, useState } from "react"; +import { + Modal, + Pressable, + RefreshControl, + ScrollView, + View, + useColorScheme, + type View as RNView, +} from "react-native"; +import Animated, { FadeInDown, LinearTransition } from "react-native-reanimated"; +import { BrandMark } from "../../components/BrandMark"; import { AppText as Text } from "../../components/AppText"; import { EmptyState } from "../../components/EmptyState"; -import { ErrorBanner } from "../../components/ErrorBanner"; import { GlassSafeAreaView } from "../../components/GlassSafeAreaView"; import { StatusPill } from "../../components/StatusPill"; -import { cx } from "../../lib/classNames"; -import { sortCopy } from "../../lib/arrayCompat"; +import type { MobileLayout } from "../../lib/mobileLayout"; import { - scopedProjectKey, scopedThreadKey, type ScopedMobileProject, type ScopedMobileThread, } from "../../lib/scopedEntities"; import type { RemoteClientConnectionState } from "../../lib/remoteClient"; import { relativeTime } from "../../lib/time"; +import { groupProjectsByRepository, type MobileRepositoryGroup } from "../../lib/repositoryGroups"; import { ConnectionStatusDot } from "../connection/ConnectionStatusDot"; import { lastConversationLine, threadStatusTone } from "./threadPresentation"; @@ -38,7 +43,9 @@ export interface ThreadListScreenProps { readonly connectedEnvironmentCount: number; readonly hasClient: boolean; readonly hasServerConfig: boolean; + readonly layout: MobileLayout; readonly hiddenThreadKey?: string | null; + readonly selectedThreadKey?: string | null; readonly connectionError: string | null; readonly onOpenConnectionEditor: () => void; readonly onRefresh: () => Promise; @@ -56,221 +63,35 @@ export interface TransitionSourceFrame { readonly height: number; } -function T3Wordmark(props: { readonly color: string }) { - return ( - - - - ); -} - -type GlyphName = - | "link" - | "stack" - | "folder" - | "refresh" - | "arrow-up-right" - | "chevron-down" - | "chevron-up" - | "device" - | "spark"; - -const GLYPH_SYMBOL_NAMES = { - link: "link", - stack: "square.stack.3d.up", - folder: "folder", - refresh: "arrow.clockwise", - "arrow-up-right": "arrow.up.right", - "chevron-down": "chevron.down", - "chevron-up": "chevron.up", - device: "iphone", - spark: "sparkles", -} as const; - -const GLYPH_PATHS: Record = { - link: "M6.1 9.9 9.9 6.1M5.2 11.8H4a2.8 2.8 0 1 1 0-5.6h1.2M10.8 4.2H12a2.8 2.8 0 1 1 0 5.6h-1.2", - stack: "M2.5 5.2 8 2.5l5.5 2.7L8 7.9 2.5 5.2ZM2.5 8 8 10.7 13.5 8M2.5 10.8 8 13.5l5.5-2.7", - folder: "M1.8 4.5h4l1.4 1.6h7v5.7a1 1 0 0 1-1 1H2.8a1 1 0 0 1-1-1V4.5Z", - refresh: "M13.2 5.2V2.8M13.2 2.8h-2.4M13.2 2.8 10.8 5.2M12.3 8A4.3 4.3 0 1 1 8 3.7", - "arrow-up-right": "M5 11 11 5M6 5h5v5", - "chevron-down": "m3.5 5.8 4.5 4.4 4.5-4.4", - "chevron-up": "m3.5 10.2 4.5-4.4 4.5 4.4", - device: - "M4.2 2.5h7.6a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4.2a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1ZM6.4 11.7h3.2", - spark: "M8 2.4 9.1 6.9 13.6 8l-4.5 1.1L8 13.6 6.9 9.1 2.4 8l4.5-1.1L8 2.4Z", -}; - -const GLYPH_STROKE_JOIN: Partial> = { - folder: "round", -}; - -function Glyph(props: { - readonly name: GlyphName; - readonly color: string; - readonly size?: number; -}) { - const size = props.size ?? 16; - const strokeWidth = 1.8; - const symbolName = GLYPH_SYMBOL_NAMES[props.name]; - const path = GLYPH_PATHS[props.name]; - const strokeLinejoin = GLYPH_STROKE_JOIN[props.name] ?? "round"; - - const fallback = ( - - - - ); - - return ( - - ); -} - -function ExpandThreadsToggle(props: { - readonly expanded: boolean; - readonly hiddenCount: number; - readonly palette: ReturnType; - readonly onPress: () => void; -}) { - const label = props.expanded ? "Show less" : `Show ${props.hiddenCount} more`; - - return ( - - - - - - {label} - - - - - - - ); -} - -function toneStyles(label: string) { - const value = label.toLowerCase(); - - if (value.includes("error") || value.includes("disconnect")) { - return { - dot: "bg-rose-500", - line: "bg-rose-300/80", - chip: "bg-rose-100/90", - text: "text-rose-700", - }; - } - - if (value.includes("run")) { - return { - dot: "bg-orange-500", - line: "bg-orange-300/80", - chip: "bg-orange-100/90", - text: "text-orange-700", - }; - } - - if (value.includes("connect") || value.includes("ready") || value.includes("start")) { - return { - dot: "bg-sky-500", - line: "bg-sky-300/80", - chip: "bg-sky-100/90", - text: "text-sky-700", - }; - } - - return { - dot: "bg-slate-500", - line: "bg-slate-300/80", - chip: "bg-slate-200/90", - text: "text-slate-700", - }; -} - -function StatCell(props: { - readonly icon: React.ComponentProps["name"]; +function ActionButton(props: { + readonly icon: React.ComponentProps["name"]; readonly label: string; - readonly value: string; - readonly palette: ReturnType; -}) { - return ( - - - - - {props.label} - - - - {props.value} - - - ); -} - -function ProjectActionButton(props: { - readonly palette: ReturnType; - readonly label: string; - readonly icon: React.ComponentProps["name"]; + readonly primary?: boolean; readonly onPress: () => void; }) { return ( - + {props.label} @@ -278,24 +99,54 @@ function ProjectActionButton(props: { ); } +function StatCard(props: { + readonly label: string; + readonly value: string; + readonly icon: React.ComponentProps["name"]; +}) { + return ( + + + + + {props.label} + + + + {props.value} + + + ); +} + function ThreadRow(props: { readonly thread: ScopedMobileThread; - readonly isLast: boolean; readonly hidden?: boolean; + readonly selected?: boolean; readonly onPress: (sourceFrame: TransitionSourceFrame | null) => void; - readonly palette: ReturnType; }) { const containerRef = useRef(null); - const threadTone = threadStatusTone(props.thread); - const styles = toneStyles(threadTone.label); + const tone = threadStatusTone(props.thread); + const backgroundColor = props.selected ? "rgba(249,115,22,0.09)" : "#ffffff"; + const borderColor = props.selected ? "rgba(249,115,22,0.28)" : "rgba(23,23,23,0.08)"; return ( { @@ -308,394 +159,379 @@ function ThreadRow(props: { }); }} > - - - - - - - {props.thread.title} - - - - - {lastConversationLine(props.thread)} - - - - - - - - - - {props.thread.environmentLabel} · {props.thread.modelSelection.provider} ·{" "} - {props.thread.modelSelection.model} ·{" "} - {relativeTime(props.thread.updatedAt ?? props.thread.createdAt)} - - - - + + + + {props.thread.title} + + + {lastConversationLine(props.thread)} + + + + + {props.thread.environmentLabel} · {props.thread.modelSelection.provider} ·{" "} + {relativeTime(props.thread.updatedAt ?? props.thread.createdAt)} + ); } -function SectionPanel(props: { - readonly children: React.ReactNode; - readonly palette: ReturnType; +function ProjectSection(props: { + readonly project: ScopedMobileProject; + readonly threads: ReadonlyArray; + readonly hiddenThreadKey?: string | null; + readonly selectedThreadKey?: string | null; + readonly onCreateThread: (project: ScopedMobileProject) => Promise; + readonly onSelectThread: ( + thread: ScopedMobileThread, + sourceFrame: TransitionSourceFrame | null, + ) => void; }) { + const [expanded, setExpanded] = useState(false); + const visibleThreads = expanded ? props.threads : props.threads.slice(0, 2); + const hiddenCount = Math.max(props.threads.length - visibleThreads.length, 0); + return ( - {props.children} + + + + {props.project.environmentLabel} + + + {props.project.workspaceRoot} + + + void props.onCreateThread(props.project)} + > + + New thread + + + + + {props.threads.length === 0 ? ( + + ) : ( + + {visibleThreads.map((thread) => ( + + )} ); } -function orderThreadsByRecency(threads: ReadonlyArray) { - return sortCopy(threads, (left, right) => { - const leftTime = new Date(left.updatedAt ?? left.createdAt).getTime(); - const rightTime = new Date(right.updatedAt ?? right.createdAt).getTime(); - return rightTime - leftTime; - }); -} - -function makePalette(isDarkMode: boolean) { - if (isDarkMode) { - return { - canvas: "#11100e", - panel: "#1a1815", - panelAlt: "#221f1b", - border: "rgba(255,255,255,0.08)", - text: "#f5f1ea", - muted: "#a69e92", - rule: "rgba(255,255,255,0.1)", - tabActive: "#f5f1ea", - tabActiveText: "#171512", - tabInactive: "#2a2723", - tabInactiveText: "#b2ab9f", - rail: "#201d19", - action: "#f5f1ea", - actionText: "#171512", - actionSecondary: "#2b2823", - actionSecondaryText: "#f5f1ea", - }; +function CreateThreadModal(props: { + readonly group: MobileRepositoryGroup | null; + readonly visible: boolean; + readonly onClose: () => void; + readonly onSelectProject: (project: ScopedMobileProject) => Promise; +}) { + if (!props.group) { + return null; } - return { - canvas: "#efe7dc", - panel: "#fbf7f1", - panelAlt: "#f3ede3", - border: "#d8cec1", - text: "#1f1b17", - muted: "#8a8175", - rule: "#ddd2c5", - tabActive: "#2c2a2d", - tabActiveText: "#f8f4ee", - tabInactive: "#ffffff", - tabInactiveText: "#b0a79b", - rail: "#f3ede3", - action: "#2c2a2d", - actionText: "#f8f4ee", - actionSecondary: "#ffffff", - actionSecondaryText: "#1f1b17", - }; + return ( + + + + + + New thread in {props.group.title} + + + Choose which environment should own the new thread. + + + + + {props.group.projects.map(({ project, threads }) => ( + { + void props.onSelectProject(project).then(props.onClose); + }} + > + + + + {project.environmentLabel} + + + {project.workspaceRoot} + + + + + {threads.length} thread{threads.length === 1 ? "" : "s"} + + + + + ))} + + + + + + + ); } export function ThreadListScreen(props: ThreadListScreenProps) { const isDarkMode = useColorScheme() === "dark"; - const palette = makePalette(isDarkMode); - const [expandedProjectIds, setExpandedProjectIds] = useState>(new Set()); - const groupedProjects = props.projects.map((project) => ({ - project, - scopedProjectId: scopedProjectKey(project.environmentId, project.id), - threads: props.threads.filter( - (thread) => thread.environmentId === project.environmentId && thread.projectId === project.id, - ), - })); + const repositoryGroups = useMemo( + () => groupProjectsByRepository({ projects: props.projects, threads: props.threads }), + [props.projects, props.threads], + ); + const [createTarget, setCreateTarget] = useState(null); + const [refreshing, setRefreshing] = useState(false); + const isSplitLayout = props.layout.usesSplitView; + const contentHorizontalPadding = isSplitLayout ? 18 : 20; + const panelBorderColor = isSplitLayout ? "rgba(23,23,23,0.08)" : "transparent"; + const panelBackgroundColor = isDarkMode ? "#0c1118" : "#f7f7f5"; + const refreshThreads = props.onRefresh; + + const handleRefresh = useCallback(async (): Promise => { + if (refreshing) { + return; + } + + setRefreshing(true); + try { + await refreshThreads(); + } finally { + setRefreshing(false); + } + }, [refreshThreads, refreshing]); return ( - + - - - Code - - - } + leftSlot={props.showBrandWordmark ? : null} /> - - - - {props.connectionError ? : null} - - - - - - - Control board - - - - - - - - - - - - - - - - - - - {props.hasClient ? "Connected" : "Awaiting connection"} - - - - - - - - {props.hasClient ? "Link" : "Connect"} - - - - {props.hasClient ? ( - void props.onRefresh()} - > - - - Refresh - - - ) : null} - - - - - - {props.threads.length === 0 ? ( - - ) : null} - - {groupedProjects.map(({ project, scopedProjectId, threads }) => { - const sortedThreads = orderThreadsByRecency(threads); - const latestThread = sortedThreads[0]; - const remainingThreads = sortedThreads.slice(1); - const isExpanded = expandedProjectIds.has(scopedProjectId); - - return ( - - - - - - - - {project.title} - - - - - - - {threads.length} - - - - - - {project.environmentLabel} · {project.workspaceRoot} - - - void props.onCreateThread(project)} - /> - - - - {latestThread ? ( - - - - ); - })} + void handleRefresh()} /> + } + contentContainerStyle={{ + gap: 16, + paddingHorizontal: contentHorizontalPadding, + paddingBottom: isSplitLayout ? 32 : 48, + paddingTop: isSplitLayout ? 112 : 124, + }} + > + + + + + {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."} + + + - + + + + + + + + + + void handleRefresh()} + /> + + + + {repositoryGroups.length === 0 ? ( + + ) : null} + + {repositoryGroups.map((group, index) => ( + + + + + {group.title} + + {group.subtitle ? ( + + {group.subtitle} + + ) : null} + + {group.projectCount} environment{group.projectCount === 1 ? "" : "s"} ·{" "} + {group.threadCount} active thread{group.threadCount === 1 ? "" : "s"} + + + + { + if (group.projects.length === 1) { + void props.onCreateThread(group.projects[0]!.project); + return; + } + setCreateTarget(group); + }} + > + + New thread + + + + + + {group.projects.map(({ project, threads }) => ( + + ))} + + + ))} + + setCreateTarget(null)} + onSelectProject={props.onCreateThread} + /> ); } diff --git a/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx b/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx new file mode 100644 index 0000000000..057ef9da8f --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx @@ -0,0 +1,250 @@ +import { SymbolView } from "expo-symbols"; +import { useCallback, useEffect, useMemo, useState } from "react"; +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, { + runOnJS, + useAnimatedStyle, + useSharedValue, + withTiming, +} from "react-native-reanimated"; + +import { AppText as Text } from "../../components/AppText"; +import { StatusPill } from "../../components/StatusPill"; +import { groupProjectsByRepository } from "../../lib/repositoryGroups"; +import type { ScopedMobileProject, ScopedMobileThread } from "../../lib/scopedEntities"; +import { scopedThreadKey } from "../../lib/scopedEntities"; +import { relativeTime } from "../../lib/time"; +import { threadStatusTone } from "./threadPresentation"; + +function compareThreadActivity(left: ScopedMobileThread, right: ScopedMobileThread): number { + return ( + new Date(right.updatedAt ?? right.createdAt).getTime() - + new Date(left.updatedAt ?? left.createdAt).getTime() || left.title.localeCompare(right.title) + ); +} + +export function ThreadNavigationDrawer(props: { + readonly visible: boolean; + readonly projects: ReadonlyArray; + readonly threads: ReadonlyArray; + readonly selectedThreadKey: string | null; + readonly onClose: () => void; + readonly onSelectThread: (thread: ScopedMobileThread) => void; + readonly onStartNewTask: () => void; +}) { + 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 repositoryGroups = useMemo( + () => groupProjectsByRepository({ projects: props.projects, threads: props.threads }), + [props.projects, props.threads], + ); + const groupedThreads = useMemo( + () => + repositoryGroups.map((group) => ({ + key: group.key, + title: group.projects[0]?.project.title ?? group.title, + threads: group.projects + .flatMap((projectGroup) => projectGroup.threads) + .sort(compareThreadActivity), // oxlint-disable-line eslint-plugin-unicorn/no-array-sort + })), + [repositoryGroups], + ); + + useEffect(() => { + if (props.visible) { + setMounted(true); + translateX.value = withTiming(0, { duration: 240 }); + overlayOpacity.value = withTiming(1, { duration: 220 }); + return; + } + + overlayOpacity.value = withTiming(0, { duration: 180 }); + translateX.value = withTiming(-drawerWidth, { duration: 220 }, (finished) => { + if (finished) { + runOnJS(setMounted)(false); + } + }); + }, [drawerWidth, overlayOpacity, props.visible, translateX]); + + const closeDrawer = useCallback(() => { + props.onClose(); + }, [props]); + + const panGesture = useMemo( + () => + Gesture.Pan() + .activeOffsetX([-12, 12]) + .failOffsetY([-24, 24]) + .onUpdate((event) => { + translateX.value = Math.min(0, event.translationX); + }) + .onEnd((event) => { + const shouldClose = event.translationX < -drawerWidth * 0.2 || event.velocityX < -500; + if (shouldClose) { + runOnJS(closeDrawer)(); + return; + } + + translateX.value = withTiming(0, { duration: 180 }); + }), + [closeDrawer, drawerWidth, translateX], + ); + + const drawerStyle = useAnimatedStyle(() => ({ + transform: [{ translateX: translateX.value }], + })); + + const backdropStyle = useAnimatedStyle(() => ({ + opacity: overlayOpacity.value, + })); + + if (!mounted) { + return null; + } + + return ( + + + + + + + + + + Threads + + { + props.onClose(); + props.onStartNewTask(); + }} + className="h-11 w-11 items-center justify-center rounded-full" + style={{ backgroundColor: "#171717" }} + > + + + + + + {groupedThreads.map((group) => ( + + + {group.title} + + + + {group.threads.length === 0 ? ( + + + No threads yet + + + ) : ( + group.threads.map((thread, index) => { + const threadKey = scopedThreadKey(thread.environmentId, thread.id); + const selected = props.selectedThreadKey === threadKey; + + return ( + { + props.onSelectThread(thread); + props.onClose(); + }} + style={{ + paddingHorizontal: 16, + paddingVertical: 15, + borderTopWidth: index === 0 ? 0 : 1, + borderTopColor: "rgba(23,23,23,0.06)", + backgroundColor: selected ? "rgba(23,23,23,0.04)" : "transparent", + }} + > + + + + {thread.title} + + + {relativeTime(thread.updatedAt ?? thread.createdAt)} + + + + + + ); + }) + )} + + + ))} + + + + + + ); +} diff --git a/apps/mobile/src/features/threads/threadPresentation.ts b/apps/mobile/src/features/threads/threadPresentation.ts index 8982d1a83f..88fe9a7ed5 100644 --- a/apps/mobile/src/features/threads/threadPresentation.ts +++ b/apps/mobile/src/features/threads/threadPresentation.ts @@ -76,5 +76,5 @@ export function screenTitle(config: T3ServerConfig | null, serverUrl: string | n const candidate = segments.at(-1) ?? config.cwd; return /^t3[-_\s]?code$/i.test(candidate) ? "T3 Code" : candidate; } - return serverUrl ?? "T3 Remote"; + return serverUrl ?? "T3 Code"; } diff --git a/apps/mobile/src/lib/mobileLayout.test.ts b/apps/mobile/src/lib/mobileLayout.test.ts new file mode 100644 index 0000000000..38146336bc --- /dev/null +++ b/apps/mobile/src/lib/mobileLayout.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest"; + +import { deriveMobileLayout } from "./mobileLayout"; + +describe("deriveMobileLayout", () => { + it("keeps phones in compact mode", () => { + expect(deriveMobileLayout({ width: 393, height: 852 })).toEqual({ + variant: "compact", + usesSplitView: false, + listPaneWidth: null, + shellPadding: 0, + }); + }); + + it("avoids split mode in short landscape phone layouts", () => { + expect(deriveMobileLayout({ width: 852, height: 393 }).variant).toBe("compact"); + }); + + it("enables split mode on tablet-sized displays", () => { + expect(deriveMobileLayout({ width: 744, height: 1133 })).toMatchObject({ + variant: "split", + usesSplitView: true, + listPaneWidth: 320, + shellPadding: 14, + }); + }); + + it("caps the sidebar width on large tablets", () => { + expect(deriveMobileLayout({ width: 1366, height: 1024 })).toMatchObject({ + variant: "split", + usesSplitView: true, + listPaneWidth: 420, + shellPadding: 20, + }); + }); +}); 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/orchestration.test.ts b/apps/mobile/src/lib/orchestration.test.ts new file mode 100644 index 0000000000..c87b2e24f4 --- /dev/null +++ b/apps/mobile/src/lib/orchestration.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it } from "vitest"; + +import { EventId, ProjectId } from "@t3tools/contracts"; +import type { OrchestrationReadModel } from "@t3tools/contracts"; + +import { applyRealtimeEvent } from "./orchestration"; + +const baseSnapshot: OrchestrationReadModel = { + snapshotSequence: 0, + updatedAt: "2026-04-01T00:00:00.000Z", + projects: [], + threads: [], +}; + +const baseEventFields = { + eventId: EventId.makeUnsafe("event-1"), + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, +} as const; + +describe("applyRealtimeEvent project identity handling", () => { + it("preserves repository identity on project.created", () => { + const next = applyRealtimeEvent(baseSnapshot, { + ...baseEventFields, + sequence: 1, + occurredAt: "2026-04-01T01:00:00.000Z", + aggregateKind: "project", + aggregateId: ProjectId.makeUnsafe("project-1"), + type: "project.created", + payload: { + projectId: ProjectId.makeUnsafe("project-1"), + title: "T3 Code", + workspaceRoot: "/repo", + repositoryIdentity: { + canonicalKey: "github.com/t3tools/t3code", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "git@github.com:t3tools/t3code.git", + }, + provider: "github", + owner: "t3tools", + name: "t3code", + }, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-04-01T01:00:00.000Z", + updatedAt: "2026-04-01T01:00:00.000Z", + }, + }); + + expect(next.projects[0]?.repositoryIdentity?.canonicalKey).toBe("github.com/t3tools/t3code"); + }); + + it("applies repository identity updates on project.meta-updated", () => { + const seeded = applyRealtimeEvent(baseSnapshot, { + ...baseEventFields, + sequence: 1, + occurredAt: "2026-04-01T01:00:00.000Z", + aggregateKind: "project", + aggregateId: ProjectId.makeUnsafe("project-1"), + type: "project.created", + payload: { + projectId: ProjectId.makeUnsafe("project-1"), + title: "T3 Code", + workspaceRoot: "/repo", + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-04-01T01:00:00.000Z", + updatedAt: "2026-04-01T01:00:00.000Z", + }, + }); + + const next = applyRealtimeEvent(seeded, { + ...baseEventFields, + eventId: EventId.makeUnsafe("event-2"), + sequence: 2, + occurredAt: "2026-04-01T02:00:00.000Z", + aggregateKind: "project", + aggregateId: ProjectId.makeUnsafe("project-1"), + type: "project.meta-updated", + payload: { + projectId: ProjectId.makeUnsafe("project-1"), + repositoryIdentity: { + canonicalKey: "github.com/t3tools/t3code", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "git@github.com:t3tools/t3code.git", + }, + provider: "github", + owner: "t3tools", + name: "t3code", + }, + updatedAt: "2026-04-01T02:00:00.000Z", + }, + }); + + expect(next.projects[0]?.repositoryIdentity?.canonicalKey).toBe("github.com/t3tools/t3code"); + }); +}); diff --git a/apps/mobile/src/lib/orchestration.ts b/apps/mobile/src/lib/orchestration.ts index 1320402f96..ea5c8eb14f 100644 --- a/apps/mobile/src/lib/orchestration.ts +++ b/apps/mobile/src/lib/orchestration.ts @@ -71,6 +71,7 @@ export function applyRealtimeEvent( id: event.payload.projectId, title: event.payload.title, workspaceRoot: event.payload.workspaceRoot, + repositoryIdentity: event.payload.repositoryIdentity ?? null, defaultModelSelection: event.payload.defaultModelSelection, scripts: event.payload.scripts, createdAt: event.payload.createdAt, @@ -88,6 +89,9 @@ export function applyRealtimeEvent( ...(event.payload.workspaceRoot !== undefined ? { workspaceRoot: event.payload.workspaceRoot } : {}), + ...(event.payload.repositoryIdentity !== undefined + ? { repositoryIdentity: event.payload.repositoryIdentity } + : {}), ...(event.payload.defaultModelSelection !== undefined ? { defaultModelSelection: event.payload.defaultModelSelection } : {}), diff --git a/apps/mobile/src/lib/pairingQr.test.ts b/apps/mobile/src/lib/pairingQr.test.ts new file mode 100644 index 0000000000..d4a8b2a637 --- /dev/null +++ b/apps/mobile/src/lib/pairingQr.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "vitest"; + +import { extractPairingUrlFromQrPayload } from "./pairingQr"; + +describe("extractPairingUrlFromQrPayload", () => { + it("trims raw pairing urls from qr payloads", () => { + expect( + extractPairingUrlFromQrPayload(" https://remote.example.com/pair#token=pairing-token "), + ).toBe("https://remote.example.com/pair#token=pairing-token"); + }); + + it("unwraps mobile deep links that carry an encoded pairing url", () => { + expect( + extractPairingUrlFromQrPayload( + "t3code://pair?pairingUrl=https%3A%2F%2Fremote.example.com%2Fpair%23token%3Dpairing-token", + ), + ).toBe("https://remote.example.com/pair#token=pairing-token"); + }); + + it("rejects empty qr payloads", () => { + expect(() => extractPairingUrlFromQrPayload(" ")).toThrow( + "Scanned QR code did not contain a pairing URL.", + ); + }); +}); diff --git a/apps/mobile/src/lib/pairingQr.ts b/apps/mobile/src/lib/pairingQr.ts new file mode 100644 index 0000000000..fe5565fdc9 --- /dev/null +++ b/apps/mobile/src/lib/pairingQr.ts @@ -0,0 +1,22 @@ +const MOBILE_PAIRING_URL_PARAM = "pairingUrl"; + +export function extractPairingUrlFromQrPayload(payload: string): string { + const trimmed = payload.trim(); + if (!trimmed) { + throw new Error("Scanned QR code did not contain a pairing URL."); + } + + try { + const url = new URL(trimmed); + if (url.protocol === "t3code:") { + const pairingUrl = url.searchParams.get(MOBILE_PAIRING_URL_PARAM)?.trim() ?? ""; + if (pairingUrl.length > 0) { + return pairingUrl; + } + } + } catch { + // Treat non-URL payloads as raw pairing-url text so the normal input validation can decide. + } + + return trimmed; +} diff --git a/apps/mobile/src/lib/remoteClient.ts b/apps/mobile/src/lib/remoteClient.ts index 5fd43dd3b7..b2a3109766 100644 --- a/apps/mobile/src/lib/remoteClient.ts +++ b/apps/mobile/src/lib/remoteClient.ts @@ -1,5 +1,19 @@ import { type ClientOrchestrationCommand, + type GitCheckoutInput, + type GitCheckoutResult, + type GitCreateBranchInput, + type GitCreateBranchResult, + type GitCreateWorktreeInput, + type GitCreateWorktreeResult, + type GitListBranchesInput, + type GitListBranchesResult, + type GitPullInput, + type GitPullResult, + type GitRunStackedActionInput, + type GitRunStackedActionResult, + type GitStatusInput, + type GitStatusResult, ORCHESTRATION_WS_METHODS, type OrchestrationEvent, type OrchestrationReadModel, @@ -260,6 +274,54 @@ export class RemoteClient { ); } + async gitRefreshStatus(input: GitStatusInput): Promise { + return await this.request( + WS_METHODS.gitRefreshStatus, + input, + "Request timed out: git.refreshStatus", + ); + } + + async gitListBranches(input: GitListBranchesInput): Promise { + return await this.request( + WS_METHODS.gitListBranches, + input, + "Request timed out: git.listBranches", + ); + } + + async gitCreateBranch(input: GitCreateBranchInput): Promise { + return await this.request( + WS_METHODS.gitCreateBranch, + input, + "Request timed out: git.createBranch", + ); + } + + async gitCheckout(input: GitCheckoutInput): Promise { + return await this.request(WS_METHODS.gitCheckout, input, "Request timed out: git.checkout"); + } + + async gitCreateWorktree(input: GitCreateWorktreeInput): Promise { + return await this.request( + WS_METHODS.gitCreateWorktree, + input, + "Request timed out: git.createWorktree", + ); + } + + async gitPull(input: GitPullInput): Promise { + return await this.request(WS_METHODS.gitPull, input, "Request timed out: git.pull"); + } + + async gitRunStackedAction(input: GitRunStackedActionInput): Promise { + return await this.request( + WS_METHODS.gitRunStackedAction, + input, + "Request timed out: git.runStackedAction", + ); + } + private emit(event: RemoteClientEvent): void { for (const listener of this.listeners) { try { diff --git a/apps/mobile/src/lib/repositoryGroups.test.ts b/apps/mobile/src/lib/repositoryGroups.test.ts new file mode 100644 index 0000000000..3b3b3bd6af --- /dev/null +++ b/apps/mobile/src/lib/repositoryGroups.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, it } from "vitest"; + +import { ProjectId, ThreadId } from "@t3tools/contracts"; + +import type { ScopedMobileProject, ScopedMobileThread } from "./scopedEntities"; +import { groupProjectsByRepository } from "./repositoryGroups"; + +function makeProject( + input: Partial & + Pick, +): ScopedMobileProject { + return { + workspaceRoot: `/workspaces/${input.id}`, + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-04-01T00:00:00.000Z", + updatedAt: "2026-04-01T00:00:00.000Z", + deletedAt: null, + ...input, + }; +} + +function makeThread( + input: Partial & + Pick< + ScopedMobileThread, + "environmentId" | "environmentLabel" | "id" | "projectId" | "title" | "modelSelection" + >, +): ScopedMobileThread { + return { + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + latestTurn: null, + createdAt: "2026-04-01T00:00:00.000Z", + updatedAt: "2026-04-01T00:00:00.000Z", + archivedAt: null, + deletedAt: null, + messages: [], + proposedPlans: [], + activities: [], + checkpoints: [], + session: null, + ...input, + }; +} + +describe("groupProjectsByRepository", () => { + it("groups projects across environments by repository identity", () => { + const repoIdentity = { + canonicalKey: "github.com/t3tools/t3code", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "git@github.com:t3tools/t3code.git", + }, + provider: "github", + owner: "t3tools", + name: "t3code", + displayName: "T3 Code", + }; + + const projects = [ + makeProject({ + environmentId: "env-local", + environmentLabel: "Local", + id: ProjectId.makeUnsafe("project-local"), + title: "T3 Code", + repositoryIdentity: repoIdentity, + }), + makeProject({ + environmentId: "env-staging", + environmentLabel: "Staging", + id: ProjectId.makeUnsafe("project-staging"), + title: "T3 Code", + repositoryIdentity: repoIdentity, + }), + ]; + + const threads = [ + makeThread({ + environmentId: "env-staging", + environmentLabel: "Staging", + id: ThreadId.makeUnsafe("thread-2"), + projectId: ProjectId.makeUnsafe("project-staging"), + title: "Fix reconnect flow", + modelSelection: { provider: "codex", model: "gpt-5.4" }, + updatedAt: "2026-04-02T12:00:00.000Z", + }), + makeThread({ + environmentId: "env-local", + environmentLabel: "Local", + id: ThreadId.makeUnsafe("thread-1"), + projectId: ProjectId.makeUnsafe("project-local"), + title: "Polish mobile shell", + modelSelection: { provider: "codex", model: "gpt-5.4" }, + updatedAt: "2026-04-03T12:00:00.000Z", + }), + ]; + + const groups = groupProjectsByRepository({ projects, threads }); + + expect(groups).toHaveLength(1); + expect(groups[0]).toMatchObject({ + key: "github.com/t3tools/t3code", + title: "T3 Code", + subtitle: "t3tools/t3code", + projectCount: 2, + threadCount: 2, + }); + expect(groups[0]?.projects.map((entry) => entry.project.environmentLabel)).toEqual([ + "Local", + "Staging", + ]); + }); + + it("falls back to a scoped project key when repository identity is unavailable", () => { + const projects = [ + makeProject({ + environmentId: "env-local", + environmentLabel: "Local", + id: ProjectId.makeUnsafe("project-local"), + title: "Scratchpad", + }), + ]; + + const groups = groupProjectsByRepository({ projects, threads: [] }); + + expect(groups).toHaveLength(1); + expect(groups[0]?.key).toBe("env-local:project-local"); + expect(groups[0]?.title).toBe("Scratchpad"); + expect(groups[0]?.subtitle).toBeNull(); + }); +}); diff --git a/apps/mobile/src/lib/repositoryGroups.ts b/apps/mobile/src/lib/repositoryGroups.ts new file mode 100644 index 0000000000..aee01fffed --- /dev/null +++ b/apps/mobile/src/lib/repositoryGroups.ts @@ -0,0 +1,135 @@ +import type { RepositoryIdentity } from "@t3tools/contracts"; + +import { sortCopy } from "./arrayCompat"; +import type { ScopedMobileProject, ScopedMobileThread } from "./scopedEntities"; +import { scopedProjectKey } from "./scopedEntities"; + +export interface MobileRepositoryProjectGroup { + readonly key: string; + readonly project: ScopedMobileProject; + readonly threads: ReadonlyArray; + readonly latestActivityAt: string; +} + +export interface MobileRepositoryGroup { + readonly key: string; + readonly title: string; + readonly subtitle: string | null; + readonly repositoryIdentity: RepositoryIdentity | null; + readonly projectCount: number; + readonly threadCount: number; + readonly latestActivityAt: string; + readonly projects: ReadonlyArray; +} + +function compareIsoDateDescending(left: string, right: string): number { + return new Date(right).getTime() - new Date(left).getTime(); +} + +function deriveRepositoryGroupKey(project: ScopedMobileProject): string { + return ( + project.repositoryIdentity?.canonicalKey ?? scopedProjectKey(project.environmentId, project.id) + ); +} + +function deriveRepositoryTitle(project: ScopedMobileProject): string { + const identity = project.repositoryIdentity; + return identity?.displayName ?? identity?.name ?? project.title; +} + +function deriveRepositorySubtitle(identity: RepositoryIdentity | null | undefined): string | null { + if (!identity) { + return null; + } + if (identity.owner && identity.name) { + return `${identity.owner}/${identity.name}`; + } + return identity.canonicalKey; +} + +function deriveProjectLatestActivity( + project: ScopedMobileProject, + threads: ReadonlyArray, +): string { + const latestThread = threads[0]; + return latestThread?.updatedAt ?? latestThread?.createdAt ?? project.updatedAt; +} + +export function groupProjectsByRepository(input: { + readonly projects: ReadonlyArray; + readonly threads: ReadonlyArray; +}): ReadonlyArray { + const threadsByProjectKey = new Map(); + + for (const thread of input.threads) { + const key = scopedProjectKey(thread.environmentId, thread.projectId); + const existing = threadsByProjectKey.get(key); + if (existing) { + existing.push(thread); + } else { + threadsByProjectKey.set(key, [thread]); + } + } + + const grouped = new Map(); + + for (const project of input.projects) { + const key = deriveRepositoryGroupKey(project); + const projectKey = scopedProjectKey(project.environmentId, project.id); + const threads = sortCopy(threadsByProjectKey.get(projectKey) ?? [], (left, right) => + compareIsoDateDescending( + left.updatedAt ?? left.createdAt, + right.updatedAt ?? right.createdAt, + ), + ); + const latestActivityAt = deriveProjectLatestActivity(project, threads); + const projectGroup: MobileRepositoryProjectGroup = { + key: projectKey, + project, + threads, + latestActivityAt, + }; + + const existing = grouped.get(key); + if (!existing) { + grouped.set(key, { + key, + title: deriveRepositoryTitle(project), + subtitle: deriveRepositorySubtitle(project.repositoryIdentity), + repositoryIdentity: project.repositoryIdentity ?? null, + projectCount: 1, + threadCount: threads.length, + latestActivityAt, + projects: [projectGroup], + }); + continue; + } + + grouped.set(key, { + ...existing, + title: existing.repositoryIdentity ? existing.title : deriveRepositoryTitle(project), + subtitle: existing.subtitle ?? deriveRepositorySubtitle(project.repositoryIdentity), + repositoryIdentity: existing.repositoryIdentity ?? project.repositoryIdentity ?? null, + projectCount: existing.projectCount + 1, + threadCount: existing.threadCount + threads.length, + latestActivityAt: + compareIsoDateDescending(existing.latestActivityAt, latestActivityAt) > 0 + ? latestActivityAt + : existing.latestActivityAt, + projects: sortCopy( + [...existing.projects, projectGroup], + (left, right) => + compareIsoDateDescending(left.latestActivityAt, right.latestActivityAt) || + left.project.environmentLabel.localeCompare(right.project.environmentLabel) || + left.project.title.localeCompare(right.project.title), + ), + }); + } + + return sortCopy( + [...grouped.values()], + (left, right) => + compareIsoDateDescending(left.latestActivityAt, right.latestActivityAt) || + left.title.localeCompare(right.title), + ); +} diff --git a/apps/mobile/src/lib/storage.ts b/apps/mobile/src/lib/storage.ts index c2a5ebeedd..5e7d506e3d 100644 --- a/apps/mobile/src/lib/storage.ts +++ b/apps/mobile/src/lib/storage.ts @@ -2,7 +2,7 @@ import { Platform } from "react-native"; import type { SavedRemoteConnection } from "./connection"; -const CONNECTIONS_KEY = "t3remote:connections"; +const CONNECTIONS_KEY = "t3code:connections"; const memoryStorage = new Map(); type AsyncStorageModule = typeof import("@react-native-async-storage/async-storage"); @@ -89,7 +89,7 @@ async function removeStorageItem(key: string): Promise { } function connectionTokenKey(environmentId: string): string { - return `t3remote:bearer-token:${environmentId}`; + return `t3code:bearer-token:${environmentId}`; } async function loadSecureToken(environmentId: string): Promise { diff --git a/apps/mobile/src/lib/worktrees.ts b/apps/mobile/src/lib/worktrees.ts new file mode 100644 index 0000000000..bb5633b42c --- /dev/null +++ b/apps/mobile/src/lib/worktrees.ts @@ -0,0 +1,14 @@ +const WORKTREE_BRANCH_PREFIX = "t3code"; + +function randomHexToken(): string { + const uuid = globalThis.crypto?.randomUUID?.(); + if (uuid) { + return uuid.replace(/-/g, "").slice(0, 8).toLowerCase(); + } + + return Math.random().toString(16).slice(2, 10).padEnd(8, "0"); +} + +export function buildTemporaryWorktreeBranchName(): string { + return `${WORKTREE_BRANCH_PREFIX}/${randomHexToken()}`; +} diff --git a/apps/web/src/components/GitActionsControl.logic.ts b/apps/web/src/components/GitActionsControl.logic.ts index b4b0b98b0b..c5323dcfd2 100644 --- a/apps/web/src/components/GitActionsControl.logic.ts +++ b/apps/web/src/components/GitActionsControl.logic.ts @@ -1,363 +1,16 @@ -import type { - GitRunStackedActionResult, - GitStackedAction, - GitStatusResult, -} from "@t3tools/contracts"; +export { + buildGitActionProgressStages, + buildMenuItems, + getGitActionDisabledReason, + type GitActionIconName, + type GitActionMenuItem, + type GitQuickAction, + type DefaultBranchConfirmableAction, + requiresDefaultBranchConfirmation, + resolveDefaultBranchActionDialogCopy, + resolveLiveThreadBranchUpdate, + resolveQuickAction, + resolveThreadBranchUpdate, +} from "@t3tools/client-runtime"; -export type GitActionIconName = "commit" | "push" | "pr"; - -export type GitDialogAction = "commit" | "push" | "create_pr"; - -export interface GitActionMenuItem { - id: "commit" | "push" | "pr"; - label: string; - disabled: boolean; - icon: GitActionIconName; - kind: "open_dialog" | "open_pr"; - dialogAction?: GitDialogAction; -} - -export interface GitQuickAction { - label: string; - disabled: boolean; - kind: "run_action" | "run_pull" | "open_pr" | "show_hint"; - action?: GitStackedAction; - hint?: string; -} - -export interface DefaultBranchActionDialogCopy { - title: string; - description: string; - continueLabel: string; -} - -export type DefaultBranchConfirmableAction = - | "push" - | "create_pr" - | "commit_push" - | "commit_push_pr"; - -export function buildGitActionProgressStages(input: { - action: GitStackedAction; - hasCustomCommitMessage: boolean; - hasWorkingTreeChanges: boolean; - pushTarget?: string; - featureBranch?: boolean; - shouldPushBeforePr?: boolean; -}): string[] { - const branchStages = input.featureBranch ? ["Preparing feature branch..."] : []; - const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing..."; - const prStages = [ - "Preparing PR...", - "Generating PR content...", - "Creating GitHub pull request...", - ]; - - if (input.action === "push") { - return [pushStage]; - } - if (input.action === "create_pr") { - return input.shouldPushBeforePr ? [pushStage, ...prStages] : prStages; - } - - const shouldIncludeCommitStages = input.action === "commit" || input.hasWorkingTreeChanges; - const commitStages = !shouldIncludeCommitStages - ? [] - : input.hasCustomCommitMessage - ? ["Committing..."] - : ["Generating commit message...", "Committing..."]; - if (input.action === "commit") { - return [...branchStages, ...commitStages]; - } - if (input.action === "commit_push") { - return [...branchStages, ...commitStages, pushStage]; - } - return [...branchStages, ...commitStages, pushStage, ...prStages]; -} - -export function buildMenuItems( - gitStatus: GitStatusResult | null, - isBusy: boolean, - hasOriginRemote = true, -): GitActionMenuItem[] { - if (!gitStatus) return []; - - const hasBranch = gitStatus.branch !== null; - const hasChanges = gitStatus.hasWorkingTreeChanges; - const hasOpenPr = gitStatus.pr?.state === "open"; - const isBehind = gitStatus.behindCount > 0; - const canPushWithoutUpstream = hasOriginRemote && !gitStatus.hasUpstream; - const canCommit = !isBusy && hasChanges; - const canPush = - !isBusy && - hasBranch && - !hasChanges && - !isBehind && - gitStatus.aheadCount > 0 && - (gitStatus.hasUpstream || canPushWithoutUpstream); - const canCreatePr = - !isBusy && - hasBranch && - !hasChanges && - !hasOpenPr && - gitStatus.aheadCount > 0 && - !isBehind && - (gitStatus.hasUpstream || canPushWithoutUpstream); - const canOpenPr = !isBusy && hasOpenPr; - - return [ - { - id: "commit", - label: "Commit", - disabled: !canCommit, - icon: "commit", - kind: "open_dialog", - dialogAction: "commit", - }, - { - id: "push", - label: "Push", - disabled: !canPush, - icon: "push", - kind: "open_dialog", - dialogAction: "push", - }, - hasOpenPr - ? { - id: "pr", - label: "View PR", - disabled: !canOpenPr, - icon: "pr", - kind: "open_pr", - } - : { - id: "pr", - label: "Create PR", - disabled: !canCreatePr, - icon: "pr", - kind: "open_dialog", - dialogAction: "create_pr", - }, - ]; -} - -export function resolveQuickAction( - gitStatus: GitStatusResult | null, - isBusy: boolean, - isDefaultBranch = false, - hasOriginRemote = true, -): GitQuickAction { - if (isBusy) { - return { label: "Commit", disabled: true, kind: "show_hint", hint: "Git action in progress." }; - } - - if (!gitStatus) { - return { - label: "Commit", - disabled: true, - kind: "show_hint", - hint: "Git status is unavailable.", - }; - } - - const hasBranch = gitStatus.branch !== null; - const hasChanges = gitStatus.hasWorkingTreeChanges; - const hasOpenPr = gitStatus.pr?.state === "open"; - const isAhead = gitStatus.aheadCount > 0; - const isBehind = gitStatus.behindCount > 0; - const isDiverged = isAhead && isBehind; - - if (!hasBranch) { - return { - label: "Commit", - disabled: true, - kind: "show_hint", - hint: "Create and checkout a branch before pushing or opening a PR.", - }; - } - - if (hasChanges) { - if (!gitStatus.hasUpstream && !hasOriginRemote) { - return { label: "Commit", disabled: false, kind: "run_action", action: "commit" }; - } - if (hasOpenPr || isDefaultBranch) { - return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" }; - } - return { - label: "Commit, push & PR", - disabled: false, - kind: "run_action", - action: "commit_push_pr", - }; - } - - if (!gitStatus.hasUpstream) { - if (!hasOriginRemote) { - if (hasOpenPr && !isAhead) { - return { label: "View PR", disabled: false, kind: "open_pr" }; - } - return { - label: "Push", - disabled: true, - kind: "show_hint", - hint: 'Add an "origin" remote before pushing or creating a PR.', - }; - } - if (!isAhead) { - if (hasOpenPr) { - return { label: "View PR", disabled: false, kind: "open_pr" }; - } - return { - label: "Push", - disabled: true, - kind: "show_hint", - hint: "No local commits to push.", - }; - } - if (hasOpenPr || isDefaultBranch) { - return { - label: "Push", - disabled: false, - kind: "run_action", - action: isDefaultBranch ? "commit_push" : "push", - }; - } - return { - label: "Push & create PR", - disabled: false, - kind: "run_action", - action: "create_pr", - }; - } - - if (isDiverged) { - return { - label: "Sync branch", - disabled: true, - kind: "show_hint", - hint: "Branch has diverged from upstream. Rebase/merge first.", - }; - } - - if (isBehind) { - return { - label: "Pull", - disabled: false, - kind: "run_pull", - }; - } - - if (isAhead) { - if (hasOpenPr || isDefaultBranch) { - return { - label: "Push", - disabled: false, - kind: "run_action", - action: isDefaultBranch ? "commit_push" : "push", - }; - } - return { - label: "Push & create PR", - disabled: false, - kind: "run_action", - action: "create_pr", - }; - } - - if (hasOpenPr && gitStatus.hasUpstream) { - return { label: "View PR", disabled: false, kind: "open_pr" }; - } - - return { - label: "Commit", - disabled: true, - kind: "show_hint", - hint: "Branch is up to date. No action needed.", - }; -} - -export function requiresDefaultBranchConfirmation( - action: GitStackedAction, - isDefaultBranch: boolean, -): boolean { - if (!isDefaultBranch) return false; - return ( - action === "push" || - action === "create_pr" || - action === "commit_push" || - action === "commit_push_pr" - ); -} - -export function resolveDefaultBranchActionDialogCopy(input: { - action: DefaultBranchConfirmableAction; - branchName: string; - includesCommit: boolean; -}): DefaultBranchActionDialogCopy { - const branchLabel = input.branchName; - const suffix = ` on "${branchLabel}". You can continue on this branch or create a feature branch and run the same action there.`; - - if (input.action === "push" || input.action === "commit_push") { - if (input.includesCommit) { - return { - title: "Commit & push to default branch?", - description: `This action will commit and push changes${suffix}`, - continueLabel: `Commit & push to ${branchLabel}`, - }; - } - return { - title: "Push to default branch?", - description: `This action will push local commits${suffix}`, - continueLabel: `Push to ${branchLabel}`, - }; - } - - if (input.includesCommit) { - return { - title: "Commit, push & create PR from default branch?", - description: `This action will commit, push, and create a PR${suffix}`, - continueLabel: `Commit, push & create PR`, - }; - } - return { - title: "Push & create PR from default branch?", - description: `This action will push local commits and create a PR${suffix}`, - continueLabel: "Push & create PR", - }; -} - -export function resolveThreadBranchUpdate( - result: GitRunStackedActionResult, -): { branch: string } | null { - if (result.branch.status !== "created" || !result.branch.name) { - return null; - } - - return { - branch: result.branch.name, - }; -} - -export function resolveLiveThreadBranchUpdate(input: { - threadBranch: string | null; - gitStatus: GitStatusResult | null; -}): { branch: string | null } | null { - if (!input.gitStatus) { - return null; - } - - if (input.gitStatus.branch === null && input.threadBranch !== null) { - return null; - } - - if (input.threadBranch === input.gitStatus.branch) { - return null; - } - - return { - branch: input.gitStatus.branch, - }; -} - -// Re-export from shared for backwards compatibility in this module's exports export { resolveAutoFeatureBranchName } from "@t3tools/shared/git"; diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 6d2312e4aa..1b911ca246 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -12,6 +12,7 @@ import { GitHubIcon } from "./Icons"; import { buildGitActionProgressStages, buildMenuItems, + getGitActionDisabledReason, type GitActionIconName, type GitActionMenuItem, type GitQuickAction, @@ -117,74 +118,6 @@ function resolveProgressDescription(progress: ActiveGitActionProgress): string | return formatElapsedDescription(progress.hookStartedAtMs ?? progress.phaseStartedAtMs); } -function getMenuActionDisabledReason({ - item, - gitStatus, - isBusy, - hasOriginRemote, -}: { - item: GitActionMenuItem; - gitStatus: GitStatusResult | null; - isBusy: boolean; - hasOriginRemote: boolean; -}): string | null { - if (!item.disabled) return null; - if (isBusy) return "Git action in progress."; - if (!gitStatus) return "Git status is unavailable."; - - const hasBranch = gitStatus.branch !== null; - const hasChanges = gitStatus.hasWorkingTreeChanges; - const hasOpenPr = gitStatus.pr?.state === "open"; - const isAhead = gitStatus.aheadCount > 0; - const isBehind = gitStatus.behindCount > 0; - - if (item.id === "commit") { - if (!hasChanges) { - return "Worktree is clean. Make changes before committing."; - } - return "Commit is currently unavailable."; - } - - if (item.id === "push") { - if (!hasBranch) { - return "Detached HEAD: checkout a branch before pushing."; - } - if (hasChanges) { - return "Commit or stash local changes before pushing."; - } - if (isBehind) { - return "Branch is behind upstream. Pull/rebase before pushing."; - } - if (!gitStatus.hasUpstream && !hasOriginRemote) { - return 'Add an "origin" remote before pushing.'; - } - if (!isAhead) { - return "No local commits to push."; - } - return "Push is currently unavailable."; - } - - if (hasOpenPr) { - return "View PR is currently unavailable."; - } - if (!hasBranch) { - return "Detached HEAD: checkout a branch before creating a PR."; - } - if (hasChanges) { - return "Commit local changes before creating a PR."; - } - if (!gitStatus.hasUpstream && !hasOriginRemote) { - return 'Add an "origin" remote before creating a PR.'; - } - if (!isAhead) { - return "No local commits to include in a PR."; - } - if (isBehind) { - return "Branch is behind upstream. Pull/rebase before creating a PR."; - } - return "Create PR is currently unavailable."; -} - const COMMIT_DIALOG_TITLE = "Commit changes"; const COMMIT_DIALOG_DESCRIPTION = "Review and confirm your commit. Leave the message blank to auto-generate one."; @@ -912,7 +845,7 @@ export default function GitActionsControl({ {gitActionMenuItems.map((item) => { - const disabledReason = getMenuActionDisabledReason({ + const disabledReason = getGitActionDisabledReason({ item, gitStatus: gitStatusForActions, isBusy: isGitActionRunning, diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 8c742cbe9b..04ff2b465c 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -284,7 +284,7 @@ export function resolveThreadRowClassName(input: { isSelected: boolean; }): string { const baseClassName = - "h-7 w-full translate-x-0 cursor-pointer justify-start px-2 text-left select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring"; + "h-6 w-full translate-x-0 cursor-pointer justify-start px-2 text-left select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring sm:h-7"; if (input.isSelected && input.isActive) { return cn( diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 2495429efd..f7f6aba0cb 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -410,7 +410,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ); const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? remoteEnvSavedLabel ?? "Remote") - : null; + : "Local"; // For grouped projects, the thread may belong to a different environment // than the representative project. Look up the thread's own project cwd // so git status (and thus PR detection) queries the correct path. @@ -715,21 +715,16 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ) : null} - {isRemoteThread && ( - - - } - > - - - {threadEnvironmentLabel} - - )} + + {threadEnvironmentLabel} + {jumpLabel ? ( {shouldShowThreadPanel && showEmptyThreadState ? ( @@ -1685,7 +1680,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec -
+
+

{activeThreadTitle}

{activeProjectName && ( - + {activeProjectName} )} @@ -89,7 +92,7 @@ export const ChatHeader = memo(function ChatHeader({ )}
-
+
{activeProjectScripts && ( =2.16.1", "react-native-reanimated": ">=3.16.0 || >=4.0.0-" }, "optionalPeers": ["@types/react", "@types/react-native"] }, "sha512-YwieCsEnTQnN2QW4VBKfCGszzxaw2ID7FydusEgqo7qB817fZ45N88kptcuNwZFnnauCjdyzKdrVBWmLmpl9oQ=="], + + "@gorhom/portal": ["@gorhom/portal@1.0.14", "", { "dependencies": { "nanoid": "^3.3.1" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-MXyL4xvCjmgaORr/rtryDNFy3kU4qUbKlwtQqqsygd0xX3mhKjOLn6mQK8wfu0RkoE0pBE0nAasRoHua+/QZ7A=="], + "@hono/node-server": ["@hono/node-server@1.19.14", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="], "@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="], @@ -907,6 +918,8 @@ "@react-native-masked-view/masked-view": ["@react-native-masked-view/masked-view@0.3.2", "", { "peerDependencies": { "react": ">=16", "react-native": ">=0.57" } }, "sha512-XwuQoW7/GEgWRMovOQtX3A4PrXhyaZm0lVUiY8qJDvdngjLms9Cpdck6SmGAUNqQwcj2EadHC1HwL0bEyoa/SQ=="], + "@react-native-menu/menu": ["@react-native-menu/menu@2.0.0", "", { "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-hb8Mirw6aKPGONhgo52IiNpwHtISVrgCT3rMdFX1qS7eOFNzOcQh8d2UDnaH5zVpxN+QuvWtaaiRMGFpIjzdtA=="], + "@react-native/assets-registry": ["@react-native/assets-registry@0.83.4", "", {}, "sha512-aqKtpbJDSQeSX/Dwv0yMe1/Rd2QfXi12lnyZDXNn/OEKz59u6+LuPBVgO/9CRyclHmdlvwg8c7PJ9eX2ZMnjWg=="], "@react-native/babel-plugin-codegen": ["@react-native/babel-plugin-codegen@0.83.4", "", { "dependencies": { "@babel/traverse": "^7.25.3", "@react-native/codegen": "0.83.4" } }, "sha512-UFsK+c1rvT84XZfzpmwKePsc5nTr5LK7hh18TI0DooNlVcztDbMDsQZpDnhO/gmk7aTbWEqO5AB3HJ7tvGp+Jg=="], @@ -1109,12 +1122,16 @@ "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], + "@types/emscripten": ["@types/emscripten@1.41.5", "", {}, "sha512-cMQm7pxu6BxtHyqJ7mQZ2kXWV5SLmugybFdHCBbJ5eHzOo6VhBckEgAT3//rP5FwPHNPeEiq4SmQ5ucBwsOo4Q=="], + "@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="], "@types/estree-jsx": ["@types/estree-jsx@1.0.5", "", { "dependencies": { "@types/estree": "*" } }, "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg=="], "@types/graceful-fs": ["@types/graceful-fs@4.1.9", "", { "dependencies": { "@types/node": "*" } }, "sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ=="], + "@types/hammerjs": ["@types/hammerjs@2.0.46", "", {}, "sha512-ynRvcq6wvqexJ9brDMS4BnBLzmr0e14d6ZJTEShTBWKymQiHwlAyGu0ZPEFI2Fh1U53F7tN9ufClWM5KvqkKOw=="], + "@types/hast": ["@types/hast@3.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ=="], "@types/http-cache-semantics": ["@types/http-cache-semantics@4.2.0", "", {}, "sha512-L3LgimLHXtGkWikKnsPg0/VFx9OGZaC+eN1u4r+OB1XRqH3meBIAVC2zr1WdMH+RHmnRkqliQAOHNJ/E0j/e0Q=="], @@ -1141,6 +1158,8 @@ "@types/react-dom": ["@types/react-dom@19.2.3", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="], + "@types/react-test-renderer": ["@types/react-test-renderer@19.1.0", "", { "dependencies": { "@types/react": "*" } }, "sha512-XD0WZrHqjNrxA/MaR9O22w/RNidWR9YZmBdRGI7wcnWGrv/3dA8wKCJ8m63Sn+tLJhcjmuhOi629N66W6kgWzQ=="], + "@types/responselike": ["@types/responselike@1.0.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw=="], "@types/stack-utils": ["@types/stack-utils@2.0.3", "", {}, "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw=="], @@ -1279,6 +1298,8 @@ "balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], + "barcode-detector": ["barcode-detector@3.1.2", "", { "dependencies": { "zxing-wasm": "3.0.2" } }, "sha512-Q5kjXpVH5I3ItykNzbWmfWnNryFN1ZTWp10k9/PKJuS0RnoKR7jTrHEJODR4fn04bRomq7TJwie/Dr9fj/GoGQ=="], + "base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="], "baseline-browser-mapping": ["baseline-browser-mapping@2.10.18", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-VSnGQAOLtP5mib/DPyg2/t+Tlv65NTBz83BJBJvmLVHHuKJVaDOBvJJykiT5TR++em5nfAySPccDZDa4oSrn8A=="], @@ -1567,6 +1588,8 @@ "expo-asset": ["expo-asset@55.0.15", "", { "dependencies": { "@expo/image-utils": "^0.8.13", "expo-constants": "~55.0.14" }, "peerDependencies": { "expo": "*", "react": "*", "react-native": "*" } }, "sha512-d3FIpHJ6ZngYXxRItYWBGT5H8Wkk7/l4fMe8Mmd2xDyKrO0/CM7c8r/J5M71D+BJr5P3My8wertGYZXHSiZYxQ=="], + "expo-camera": ["expo-camera@55.0.15", "", { "dependencies": { "barcode-detector": "^3.0.0" }, "peerDependencies": { "expo": "*", "react": "*", "react-native": "*", "react-native-web": "*" }, "optionalPeers": ["react-native-web"] }, "sha512-WRVsZf+2p7EsxudwyiUMYijJS8M98t/BVP6yG7N+08JSUotkGjmZcemom1gM36uy27P8QsSVP0hD+FravmQiBA=="], + "expo-clipboard": ["expo-clipboard@55.0.13", "", { "peerDependencies": { "expo": "*", "react": "*", "react-native": "*" } }, "sha512-PrOmmuVsGW4bAkNQmGKtxMXj3invsfN+jfIKmQxHwE/dn7ODqwFWviUTa+PMUjP3XZmYCDLyu/i0GLeu7HF9Ew=="], "expo-constants": ["expo-constants@55.0.14", "", { "dependencies": { "@expo/config": "~55.0.15", "@expo/env": "~2.1.1" }, "peerDependencies": { "expo": "*", "react-native": "*" } }, "sha512-l23QVQCYBPKT5zbxxZdJeuhiunadvWdjcQ9+GC8h+02jCoLmWRk20064nCINnQTP3Hf+uLPteUiwYrJd0e446w=="], @@ -1747,6 +1770,8 @@ "hermes-parser": ["hermes-parser@0.32.1", "", { "dependencies": { "hermes-estree": "0.32.1" } }, "sha512-175dz634X/W5AiwrpLdoMl/MOb17poLHyIqgyExlE8D9zQ1OPnoORnGMB5ltRKnpvQzBjMYvT2rN/sHeIfZW5Q=="], + "hoist-non-react-statics": ["hoist-non-react-statics@3.3.2", "", { "dependencies": { "react-is": "^16.7.0" } }, "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw=="], + "hono": ["hono@4.12.12", "", {}, "sha512-p1JfQMKaceuCbpJKAPKVqyqviZdS0eUxH9v82oWo1kb9xjQ5wA6iP3FNVAPDFlz5/p7d45lO+BpSk1tuSZMF4Q=="], "hookable": ["hookable@6.1.0", "", {}, "sha512-ZoKZSJgu8voGK2geJS+6YtYjvIzu9AOM/KZXsBxr83uhLL++e9pEv/dlgwgy3dvHg06kTz6JOh1hk3C8Ceiymw=="], @@ -2333,6 +2358,8 @@ "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.31.1", "", { "dependencies": { "@egjs/hammerjs": "^2.0.17", "@types/react-test-renderer": "^19.1.0", "hoist-non-react-statics": "^3.3.0", "invariant": "^2.2.4" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-wQDlECdEzHhYKTnQXFnSqWUtJ5TS3MGQi7EWvQczTnEVKfk6XVSBecnpWAoI/CqlYQ7IWMJEyutY6BxwEBoxeg=="], + "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-markdown-display": ["react-native-markdown-display@7.0.2", "", { "dependencies": { "css-to-react-native": "^3.0.0", "markdown-it": "^10.0.0", "prop-types": "^15.7.2", "react-native-fit-image": "^1.5.5" }, "peerDependencies": { "react": ">=16.2.0", "react-native": ">=0.50.4" } }, "sha512-Mn4wotMvMfLAwbX/huMLt202W5DsdpMO/kblk+6eUs55S57VVNni1gzZCh5qpznYLjIQELNh50VIozEfY6fvaQ=="], @@ -2815,6 +2842,8 @@ "zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="], + "zxing-wasm": ["zxing-wasm@3.0.2", "", { "dependencies": { "@types/emscripten": "^1.41.5", "type-fest": "^5.5.0" } }, "sha512-2YMAriaYHX9wrBY2k7H0epSo+dyCaCZg/vOtt+nEDXM9ul480gkXz/9SkwpOeHcD2H5qqDG8lWDSBwpTcZpa6w=="], + "@astrojs/language-server/@astrojs/compiler": ["@astrojs/compiler@2.13.1", "", {}, "sha512-f3FN83d2G/v32ipNClRKgYv30onQlMZX1vCeZMjPsMMPl1mDpmbl0+N5BYo4S/ofzqJyS5hvwacEo0CCVDn/Qg=="], "@babel/code-frame/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.28.5", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="], @@ -2971,6 +3000,8 @@ "h3/cookie-es": ["cookie-es@1.2.3", "", {}, "sha512-lXVyvUvrNXblMqzIRrxHb57UUVmqsSWlxqt3XIjCkUP0wDAf6uicO6KMbEgYrMNtEvWgWHwe42CKxPu9MYAnWw=="], + "hoist-non-react-statics/react-is": ["react-is@16.13.1", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="], + "hosted-git-info/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], "istanbul-lib-instrument/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index bfe2d7828e..83afc7c770 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -3,10 +3,15 @@ "version": "0.0.0-alpha.1", "private": true, "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", "exports": { ".": { "types": "./src/index.ts", - "import": "./src/index.ts" + "react-native": "./src/index.ts", + "import": "./src/index.ts", + "require": "./src/index.ts", + "default": "./src/index.ts" } }, "scripts": { diff --git a/packages/client-runtime/src/gitActions.ts b/packages/client-runtime/src/gitActions.ts new file mode 100644 index 0000000000..97bd22557e --- /dev/null +++ b/packages/client-runtime/src/gitActions.ts @@ -0,0 +1,430 @@ +import type { + GitRunStackedActionInput, + GitRunStackedActionResult, + GitStackedAction, + GitStatusResult, +} from "@t3tools/contracts"; + +export type GitActionIconName = "commit" | "push" | "pr"; + +export type GitDialogAction = "commit" | "push" | "create_pr"; + +export interface GitActionMenuItem { + id: "commit" | "push" | "pr"; + label: string; + disabled: boolean; + icon: GitActionIconName; + kind: "open_dialog" | "open_pr"; + dialogAction?: GitDialogAction; +} + +export interface GitQuickAction { + label: string; + disabled: boolean; + kind: "run_action" | "run_pull" | "open_pr" | "show_hint"; + action?: GitStackedAction; + hint?: string; +} + +export interface DefaultBranchActionDialogCopy { + title: string; + description: string; + continueLabel: string; +} + +export type DefaultBranchConfirmableAction = + | "push" + | "create_pr" + | "commit_push" + | "commit_push_pr"; + +export type GitActionRequestInput = Pick< + GitRunStackedActionInput, + "action" | "commitMessage" | "featureBranch" | "filePaths" +>; + +export function buildGitActionProgressStages(input: { + action: GitStackedAction; + hasCustomCommitMessage: boolean; + hasWorkingTreeChanges: boolean; + pushTarget?: string; + featureBranch?: boolean; + shouldPushBeforePr?: boolean; +}): string[] { + const branchStages = input.featureBranch ? ["Preparing feature branch..."] : []; + const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing..."; + const prStages = [ + "Preparing PR...", + "Generating PR content...", + "Creating GitHub pull request...", + ]; + + if (input.action === "push") { + return [pushStage]; + } + if (input.action === "create_pr") { + return input.shouldPushBeforePr ? [pushStage, ...prStages] : prStages; + } + + const shouldIncludeCommitStages = input.action === "commit" || input.hasWorkingTreeChanges; + const commitStages = !shouldIncludeCommitStages + ? [] + : input.hasCustomCommitMessage + ? ["Committing..."] + : ["Generating commit message...", "Committing..."]; + if (input.action === "commit") { + return [...branchStages, ...commitStages]; + } + if (input.action === "commit_push") { + return [...branchStages, ...commitStages, pushStage]; + } + return [...branchStages, ...commitStages, pushStage, ...prStages]; +} + +export function buildMenuItems( + gitStatus: GitStatusResult | null, + isBusy: boolean, + hasOriginRemote = true, +): GitActionMenuItem[] { + if (!gitStatus) return []; + + const hasBranch = gitStatus.branch !== null; + const hasChanges = gitStatus.hasWorkingTreeChanges; + const hasOpenPr = gitStatus.pr?.state === "open"; + const isBehind = gitStatus.behindCount > 0; + const canPushWithoutUpstream = hasOriginRemote && !gitStatus.hasUpstream; + const canCommit = !isBusy && hasChanges; + const canPush = + !isBusy && + hasBranch && + !hasChanges && + !isBehind && + gitStatus.aheadCount > 0 && + (gitStatus.hasUpstream || canPushWithoutUpstream); + const canCreatePr = + !isBusy && + hasBranch && + !hasChanges && + !hasOpenPr && + gitStatus.aheadCount > 0 && + !isBehind && + (gitStatus.hasUpstream || canPushWithoutUpstream); + const canOpenPr = !isBusy && hasOpenPr; + + return [ + { + id: "commit", + label: "Commit", + disabled: !canCommit, + icon: "commit", + kind: "open_dialog", + dialogAction: "commit", + }, + { + id: "push", + label: "Push", + disabled: !canPush, + icon: "push", + kind: "open_dialog", + dialogAction: "push", + }, + hasOpenPr + ? { + id: "pr", + label: "View PR", + disabled: !canOpenPr, + icon: "pr", + kind: "open_pr", + } + : { + id: "pr", + label: "Create PR", + disabled: !canCreatePr, + icon: "pr", + kind: "open_dialog", + dialogAction: "create_pr", + }, + ]; +} + +export function resolveQuickAction( + gitStatus: GitStatusResult | null, + isBusy: boolean, + isDefaultBranch = false, + hasOriginRemote = true, +): GitQuickAction { + if (isBusy) { + return { label: "Commit", disabled: true, kind: "show_hint", hint: "Git action in progress." }; + } + + if (!gitStatus) { + return { + label: "Commit", + disabled: true, + kind: "show_hint", + hint: "Git status is unavailable.", + }; + } + + const hasBranch = gitStatus.branch !== null; + const hasChanges = gitStatus.hasWorkingTreeChanges; + const hasOpenPr = gitStatus.pr?.state === "open"; + const isAhead = gitStatus.aheadCount > 0; + const isBehind = gitStatus.behindCount > 0; + const isDiverged = isAhead && isBehind; + + if (!hasBranch) { + return { + label: "Commit", + disabled: true, + kind: "show_hint", + hint: "Create and checkout a branch before pushing or opening a PR.", + }; + } + + if (hasChanges) { + if (!gitStatus.hasUpstream && !hasOriginRemote) { + return { label: "Commit", disabled: false, kind: "run_action", action: "commit" }; + } + if (hasOpenPr || isDefaultBranch) { + return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" }; + } + return { + label: "Commit, push & PR", + disabled: false, + kind: "run_action", + action: "commit_push_pr", + }; + } + + if (!gitStatus.hasUpstream) { + if (!hasOriginRemote) { + if (hasOpenPr && !isAhead) { + return { label: "View PR", disabled: false, kind: "open_pr" }; + } + return { + label: "Push", + disabled: true, + kind: "show_hint", + hint: 'Add an "origin" remote before pushing or creating a PR.', + }; + } + if (!isAhead) { + if (hasOpenPr) { + return { label: "View PR", disabled: false, kind: "open_pr" }; + } + return { + label: "Push", + disabled: true, + kind: "show_hint", + hint: "No local commits to push.", + }; + } + if (hasOpenPr || isDefaultBranch) { + return { + label: "Push", + disabled: false, + kind: "run_action", + action: isDefaultBranch ? "commit_push" : "push", + }; + } + return { + label: "Push & create PR", + disabled: false, + kind: "run_action", + action: "create_pr", + }; + } + + if (isDiverged) { + return { + label: "Sync branch", + disabled: true, + kind: "show_hint", + hint: "Branch has diverged from upstream. Rebase/merge first.", + }; + } + + if (isBehind) { + return { + label: "Pull", + disabled: false, + kind: "run_pull", + }; + } + + if (isAhead) { + if (hasOpenPr || isDefaultBranch) { + return { + label: "Push", + disabled: false, + kind: "run_action", + action: isDefaultBranch ? "commit_push" : "push", + }; + } + return { + label: "Push & create PR", + disabled: false, + kind: "run_action", + action: "create_pr", + }; + } + + if (hasOpenPr && gitStatus.hasUpstream) { + return { label: "View PR", disabled: false, kind: "open_pr" }; + } + + return { + label: "Commit", + disabled: true, + kind: "show_hint", + hint: "Branch is up to date. No action needed.", + }; +} + +export function getGitActionDisabledReason(input: { + item: GitActionMenuItem; + gitStatus: GitStatusResult | null; + isBusy: boolean; + hasOriginRemote: boolean; +}): string | null { + const { item, gitStatus, isBusy, hasOriginRemote } = input; + if (!item.disabled) return null; + if (isBusy) return "Git action in progress."; + if (!gitStatus) return "Git status is unavailable."; + + const hasBranch = gitStatus.branch !== null; + const hasChanges = gitStatus.hasWorkingTreeChanges; + const hasOpenPr = gitStatus.pr?.state === "open"; + const isAhead = gitStatus.aheadCount > 0; + const isBehind = gitStatus.behindCount > 0; + + if (item.id === "commit") { + if (!hasChanges) { + return "Worktree is clean. Make changes before committing."; + } + return "Commit is currently unavailable."; + } + + if (item.id === "push") { + if (!hasBranch) { + return "Detached HEAD: checkout a branch before pushing."; + } + if (hasChanges) { + return "Commit or stash local changes before pushing."; + } + if (isBehind) { + return "Branch is behind upstream. Pull/rebase before pushing."; + } + if (!gitStatus.hasUpstream && !hasOriginRemote) { + return 'Add an "origin" remote before pushing.'; + } + if (!isAhead) { + return "No local commits to push."; + } + return "Push is currently unavailable."; + } + + if (hasOpenPr) { + return "View PR is currently unavailable."; + } + if (!hasBranch) { + return "Detached HEAD: checkout a branch before creating a PR."; + } + if (hasChanges) { + return "Commit local changes before creating a PR."; + } + if (!gitStatus.hasUpstream && !hasOriginRemote) { + return 'Add an "origin" remote before creating a PR.'; + } + if (!isAhead) { + return "No local commits to include in a PR."; + } + if (isBehind) { + return "Branch is behind upstream. Pull/rebase before creating a PR."; + } + return "Create PR is currently unavailable."; +} + +export function requiresDefaultBranchConfirmation( + action: GitStackedAction, + isDefaultBranch: boolean, +): boolean { + if (!isDefaultBranch) return false; + return ( + action === "push" || + action === "create_pr" || + action === "commit_push" || + action === "commit_push_pr" + ); +} + +export function resolveDefaultBranchActionDialogCopy(input: { + action: DefaultBranchConfirmableAction; + branchName: string; + includesCommit: boolean; +}): DefaultBranchActionDialogCopy { + const branchLabel = input.branchName; + const suffix = ` on "${branchLabel}". You can continue on this branch or create a feature branch and run the same action there.`; + + if (input.action === "push" || input.action === "commit_push") { + if (input.includesCommit) { + return { + title: "Commit & push to default branch?", + description: `This action will commit and push changes${suffix}`, + continueLabel: `Commit & push to ${branchLabel}`, + }; + } + return { + title: "Push to default branch?", + description: `This action will push local commits${suffix}`, + continueLabel: `Push to ${branchLabel}`, + }; + } + + if (input.includesCommit) { + return { + title: "Commit, push & create PR from default branch?", + description: `This action will commit, push, and create a PR${suffix}`, + continueLabel: "Commit, push & create PR", + }; + } + return { + title: "Push & create PR from default branch?", + description: `This action will push local commits and create a PR${suffix}`, + continueLabel: "Push & create PR", + }; +} + +export function resolveThreadBranchUpdate( + result: GitRunStackedActionResult, +): { branch: string } | null { + if (result.branch.status !== "created" || !result.branch.name) { + return null; + } + + return { + branch: result.branch.name, + }; +} + +export function resolveLiveThreadBranchUpdate(input: { + threadBranch: string | null; + gitStatus: GitStatusResult | null; +}): { branch: string | null } | null { + if (!input.gitStatus) { + return null; + } + + if (input.gitStatus.branch === null && input.threadBranch !== null) { + return null; + } + + if (input.threadBranch === input.gitStatus.branch) { + return null; + } + + return { + branch: input.gitStatus.branch, + }; +} diff --git a/packages/client-runtime/src/index.ts b/packages/client-runtime/src/index.ts index 5dd6b9afa5..8b32ce43f8 100644 --- a/packages/client-runtime/src/index.ts +++ b/packages/client-runtime/src/index.ts @@ -1,2 +1,3 @@ export * from "./knownEnvironment"; export * from "./scoped"; +export * from "./gitActions";