Add mobile remote connection and git workflows

- Rework the mobile shell around home, thread, and task sheets
- Add pairing, connection editing, and git branch/worktree actions
- Share client-runtime git helpers across mobile and web
This commit is contained in:
Julius Marminge committed 2026-04-13 14:44:00 -07:00
1 parent 93cf431303
commit ac0173589a
50 files changed
+6888 -1763

No files matched your search

+15
View File
@@ -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
+16 -8
View File
@@ -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"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 178 KiB

After

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 2.0 MiB

+1
View File
@@ -1,3 +1,4 @@
import "react-native-gesture-handler";
import { registerRootComponent } from "expo";
import App from "./App";
+4
View File
@@ -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",
+2
View File
@@ -1,3 +1,5 @@
/// <reference types="react-native-css/types" />
// NOTE: This file is generated by react-native-css / NativeWind integration.
declare module "*.css";
+5
View File
@@ -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",
+21 -2
View File
@@ -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 = <LoadingScreen isDarkMode={isDarkMode} message="Loading remote workspace…" />;
} else if (app.reconnectingScreenVisible) {
content = <LoadingScreen isDarkMode={isDarkMode} message="Reconnecting…" />;
@@ -21,5 +34,11 @@ export default function App() {
content = <MobileAppShell app={app} isDarkMode={isDarkMode} />;
}
return <SafeAreaProvider>{content}</SafeAreaProvider>;
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<BottomSheetModalProvider>
<SafeAreaProvider>{content}</SafeAreaProvider>
</BottomSheetModalProvider>
</GestureHandlerRootView>
);
}
+56 -222
View File
@@ -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<TransitionSourceFrame | null>(null);
const [transitionPhase, setTransitionPhase] = useState<"idle" | "opening" | "closing">("idle");
const revealProgress = useSharedValue(1);
const openingAnimationFrameRef = useRef<number | null>(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
/>
<View style={{ flex: 1 }} pointerEvents={app.selectedThread ? "none" : "auto"}>
<ThreadListScreen
heroTitle={app.heroTitle}
showBrandWordmark={app.showBrandWordmark}
screenTone={app.screenTone}
connectionState={app.connectionState}
connectionPulse={app.hasRemoteActivity}
{app.selectedThread && selectedThreadDetailProps ? (
<ThreadDetailScreen {...selectedThreadDetailProps} />
) : (
<HomeScreen
projects={app.projects}
threads={app.threads}
connectedEnvironmentCount={app.connectedEnvironmentCount}
hasClient={app.hasClient}
hasServerConfig={app.serverConfig !== null}
hiddenThreadKey={
app.selectedThread
? `${app.selectedThread.environmentId}:${app.selectedThread.id}`
: null
}
connectionError={app.connectionError}
connectionState={app.connectionState}
connectionPulse={app.hasRemoteActivity}
onOpenConnectionEditor={app.onOpenConnectionEditor}
onRefresh={app.onRefresh}
onCreateThread={app.onCreateThread}
onSelectThread={handleSelectThread}
onOpenNewTask={() => setNewTaskVisible(true)}
onSelectThread={app.onSelectThread}
/>
</View>
{app.selectedThread && sharedDetailProps ? (
<View className="absolute inset-0">
<ThreadDetailScreen {...sharedDetailProps} showContent={transitionPhase === "idle"} />
{transitionPhase !== "idle" ? (
<Animated.View
className="absolute inset-0"
pointerEvents="none"
style={revealMaskStyle}
>
<Animated.View style={revealContentStyle}>
<ThreadDetailScreen {...sharedDetailProps} showHeader={false} />
</Animated.View>
</Animated.View>
) : null}
</View>
) : null}
)}
<ConnectionSheet
visible={app.connectionSheetRequired}
@@ -288,9 +100,31 @@ export function MobileAppShell(props: {
onRequestClose={app.onRequestCloseConnectionEditor}
onChangePairingUrl={app.onChangeConnectionPairingUrl}
onConnect={app.onConnectPress}
onClose={app.onCloseConnectionEditor}
onUpdateEnvironment={app.onUpdateEnvironment}
onRemoveEnvironment={app.onRemoveEnvironmentPress}
/>
<ThreadNavigationDrawer
visible={threadsSheetVisible}
projects={app.projects}
threads={app.threads}
selectedThreadKey={selectedThreadKey}
onClose={() => setThreadsSheetVisible(false)}
onSelectThread={app.onSelectThread}
onStartNewTask={() => setNewTaskVisible(true)}
/>
{newTaskVisible ? (
<NewTaskSheet
visible={newTaskVisible}
projects={app.projects}
threads={app.threads}
serverConfigByEnvironmentId={app.serverConfigByEnvironmentId}
onRequestClose={() => setNewTaskVisible(false)}
onCreateThreadWithOptions={app.onCreateThreadWithOptions}
onListProjectBranches={app.onListProjectBranches}
/>
) : null}
</View>
);
}
+561 -21
View File
@@ -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<ConnectedEnvironmentSummary>;
readonly connectedEnvironmentCount: number;
readonly serverConfig: T3ServerConfig | null;
readonly serverConfigByEnvironmentId: Readonly<Record<string, T3ServerConfig | null>>;
readonly projects: ReadonlyArray<ScopedMobileProject>;
readonly threads: ReadonlyArray<ScopedMobileThread>;
readonly selectedThread: ScopedMobileThread | null;
@@ -81,6 +94,8 @@ export interface RemoteAppModel {
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly screenTone: ReturnType<typeof connectionTone>;
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<void>;
readonly onRemoveEnvironmentPress: (environmentId: string) => void;
readonly onRefresh: () => Promise<void>;
readonly onCreateThread: (project: ScopedMobileProject) => Promise<void>;
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<DraftComposerImageAttachment>;
}) => Promise<void>;
readonly onSelectThread: (thread: ScopedMobileThread) => void;
readonly onBackFromThread: () => void;
readonly onChangeDraftMessage: (value: string) => void;
readonly onPickDraftImages: () => Promise<void>;
readonly onPasteIntoDraft: () => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onRefreshSelectedThreadGitStatus: (options?: {
readonly quiet?: boolean;
}) => Promise<void>;
readonly onListProjectBranches: (
project: ScopedMobileProject,
) => Promise<ReadonlyArray<GitBranch>>;
readonly onCreateProjectWorktree: (
project: ScopedMobileProject,
input: {
readonly baseBranch: string;
readonly newBranch: string;
},
) => Promise<{
readonly branch: string;
readonly worktreePath: string;
} | null>;
readonly onListSelectedThreadBranches: () => Promise<ReadonlyArray<GitBranch>>;
readonly onCheckoutSelectedThreadBranch: (branch: string) => Promise<void>;
readonly onCreateSelectedThreadBranch: (branch: string) => Promise<void>;
readonly onCreateSelectedThreadWorktree: (input: {
readonly baseBranch: string;
readonly newBranch: string;
}) => Promise<void>;
readonly onPullSelectedThreadBranch: () => Promise<void>;
readonly onRunSelectedThreadGitAction: (
input: GitActionRequestInput,
) => Promise<GitRunStackedActionResult | null>;
readonly onSendMessage: () => void;
readonly onRenameThread: (title: string) => Promise<void>;
readonly onStopThread: () => Promise<void>;
@@ -147,6 +204,16 @@ function firstNonNull<T>(values: ReadonlyArray<T | null | undefined>): 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<ConnectedEnvironmentSummary>,
): RemoteClientConnectionState {
@@ -268,6 +335,10 @@ export function useRemoteAppState(): RemoteAppModel {
null,
);
const [dispatchingQueuedMessageId, setDispatchingQueuedMessageId] = useState<string | null>(null);
const [selectedThreadGitStatus, setSelectedThreadGitStatus] = useState<GitStatusResult | null>(
null,
);
const [gitOperationLabel, setGitOperationLabel] = useState<string | null>(null);
const [queuedMessagesByThreadKey, setQueuedMessagesByThreadKey] = useState<
Record<string, ReadonlyArray<QueuedThreadMessage>>
>({});
@@ -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 <T>(
label: string,
operation: (input: {
readonly client: RemoteClient;
readonly thread: ScopedMobileThread;
readonly project: ScopedMobileProject;
}) => Promise<T>,
): Promise<T | null> => {
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<ReadonlyArray<GitBranch>> => {
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<ReadonlyArray<GitBranch>> => {
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<GitRunStackedActionResult | null> => {
const [firstStage] = buildGitActionProgressStages({
action: input.action,
hasCustomCommitMessage: Boolean(input.commitMessage?.trim()),
hasWorkingTreeChanges: selectedThreadGitStatus?.hasWorkingTreeChanges ?? false,
featureBranch: input.featureBranch ?? false,
shouldPushBeforePr:
input.action === "create_pr" &&
((selectedThreadGitStatus?.aheadCount ?? 0) > 0 ||
!(selectedThreadGitStatus?.hasUpstream ?? false)),
});
return await runSelectedThreadGitMutation(
firstStage ?? "Running git action",
async ({ client, thread, project }) => {
const cwd = thread.worktreePath ?? project.workspaceRoot;
const result = await client.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<DraftComposerImageAttachment>;
}) => {
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,
+10 -8
View File
@@ -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;
}
+60
View File
@@ -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 (
<View className="flex-row items-center gap-3">
<Image
source={BRAND_MARK_SOURCE}
accessibilityIgnoresInvertColors
style={{
width: iconSize,
height: iconSize,
borderRadius: compact ? 10 : 14,
}}
/>
<View className="gap-1">
<View className="flex-row items-center gap-2">
<Text
className="text-[17px] font-t3-bold"
style={{ color: textColor, letterSpacing: -0.4 }}
>
T3 Code
</Text>
<View
className="rounded-full px-2 py-1"
style={{
backgroundColor: stageBackground,
}}
>
<Text
className="text-[10px] font-t3-bold uppercase"
style={{ color: mutedColor, letterSpacing: 1.1 }}
>
{stageLabel}
</Text>
</View>
</View>
{!compact ? (
<Text className="text-[12px] font-medium" style={{ color: mutedColor }}>
Mobile control surface for your live coding environments
</Text>
) : null}
</View>
</View>
);
}
+3 -1
View File
@@ -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
/>
<View className="flex-1 items-center justify-center gap-3.5">
<View className="flex-1 items-center justify-center gap-5 px-6">
<BrandMark compact dark={props.isDarkMode} />
<ActivityIndicator size="large" />
<Text className="font-t3-bold text-lg text-slate-950 dark:text-slate-50">
{props.message}
+22 -3
View File
@@ -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 (
<View className={cx("rounded-full px-3 py-1.5", props.pillClassName)}>
<Text className={cx("font-t3-bold text-xs", props.textClassName)}>{props.label}</Text>
<View
className={cx(
"rounded-full",
size === "compact" ? "px-2.5 py-1" : "px-3 py-1.5",
props.pillClassName,
)}
>
<Text
className={cx(
"font-t3-bold",
size === "compact" ? "text-[11px]" : "text-xs",
props.textClassName,
)}
>
{props.label}
</Text>
</View>
);
}
File diff suppressed because it is too large. Load diff
@@ -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<ScopedMobileProject>;
readonly threads: ReadonlyArray<ScopedMobileThread>;
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 (
<View style={{ flex: 1, backgroundColor: "#f6f4ef" }}>
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={{
paddingBottom: Math.max(insets.bottom, 24) + 92,
paddingHorizontal: 20,
paddingTop: insets.top + 6,
gap: 16,
}}
>
<View className="flex-row items-center justify-between">
<Text className="text-[34px] font-t3-bold" style={{ color: "#171717" }}>
Recents
</Text>
<Pressable
onPress={props.onOpenConnectionEditor}
className="h-14 min-w-[56px] items-center justify-center rounded-full px-4"
style={{ backgroundColor: "rgba(255,255,255,0.9)" }}
>
<ConnectionStatusDot state={props.connectionState} pulse={props.connectionPulse} />
</Pressable>
</View>
{props.threads.length === 0 ? (
<EmptyState
title="No threads yet"
detail="Create a task to start a new coding session in one of your connected projects."
/>
) : (
<View className="overflow-hidden rounded-[24px]" style={{ backgroundColor: "#ffffff" }}>
{props.threads.map((thread, index) => {
const projectKey = scopedProjectKey(thread.environmentId, thread.projectId);
const projectLabel = projectLabelsByKey.get(projectKey);
return (
<Pressable
key={`${thread.environmentId}:${thread.id}`}
onPress={() => props.onSelectThread(thread)}
style={{
paddingHorizontal: 16,
paddingVertical: 13,
borderTopWidth: index === 0 ? 0 : 1,
borderTopColor: "rgba(23,23,23,0.06)",
}}
>
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-1.5">
<Text
className="text-[17px] font-t3-bold leading-[24px]"
numberOfLines={2}
style={{ color: "#171717" }}
>
{thread.title}
</Text>
</View>
<StatusPill {...threadStatusTone(thread)} size="compact" />
</View>
<View className="mt-2 flex-row items-center justify-between gap-3">
<View className="flex-1 flex-row items-center gap-2">
<Text
className="text-[13px] font-medium leading-[18px]"
numberOfLines={1}
style={{ color: "#57534e", flexShrink: 1 }}
>
{projectLabel?.projectTitle ?? thread.title}
</Text>
<View
className="h-1 w-1 rounded-full"
style={{ backgroundColor: "rgba(120,113,108,0.45)" }}
/>
<Text
className="text-[12px] font-t3-bold uppercase tracking-[0.4px]"
numberOfLines={1}
style={{ color: "#78716c", flexShrink: 1 }}
>
{projectLabel?.environmentLabel ?? "Local"}
</Text>
</View>
<Text
className="text-[12px] font-t3-bold"
style={{ color: "#78716c", fontVariant: ["tabular-nums"] }}
>
{relativeTime(thread.updatedAt ?? thread.createdAt)}
</Text>
</View>
</Pressable>
);
})}
</View>
)}
</ScrollView>
<View
pointerEvents="box-none"
style={{
position: "absolute",
right: 20,
bottom: Math.max(insets.bottom, 18),
}}
>
<Pressable
onPress={props.onOpenNewTask}
className="flex-row items-center gap-3 rounded-full px-6 py-4"
style={{
backgroundColor: "#171717",
boxShadow: "0 20px 36px rgba(23,23,23,0.18)",
}}
>
<SymbolView name="square.and.pencil" size={20} tintColor="#fafaf9" type="monochrome" />
<Text className="text-[18px] font-t3-bold" style={{ color: "#fafaf9" }}>
New task
</Text>
</Pressable>
</View>
</View>
);
}
File diff suppressed because it is too large. Load diff
@@ -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<ScopedMobileProject>;
readonly threads: ReadonlyArray<ScopedMobileThread>;
readonly onClose: () => void;
readonly onSelectProject: (project: ScopedMobileProject) => void;
}) {
const insets = useSafeAreaInsets();
const sheetRef = useRef<BottomSheetModal>(null);
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects: props.projects, threads: props.threads }),
[props.projects, props.threads],
);
const logicalProjects = useMemo(
() =>
repositoryGroups
.map((group) => {
const primaryProject = group.projects[0]?.project;
if (!primaryProject) {
return null;
}
return {
key: group.key,
project: primaryProject,
};
})
.filter((entry) => entry !== null),
[repositoryGroups],
);
const renderBackdrop = useCallback(
(backdropProps: React.ComponentProps<typeof BottomSheetBackdrop>) => (
<BottomSheetBackdrop
{...backdropProps}
appearsOnIndex={0}
disappearsOnIndex={-1}
opacity={0.18}
pressBehavior="close"
/>
),
[],
);
useEffect(() => {
const sheet = sheetRef.current;
if (!sheet) {
return;
}
if (props.visible) {
sheet.present();
return;
}
sheet.dismiss();
}, [props.visible]);
return (
<BottomSheetModal
ref={sheetRef}
index={0}
snapPoints={["88%"]}
enableDynamicSizing={false}
enablePanDownToClose
backdropComponent={renderBackdrop}
onDismiss={props.onClose}
backgroundStyle={{ backgroundColor: "rgba(250,248,242,0.98)" }}
handleIndicatorStyle={{ backgroundColor: "rgba(120,113,108,0.35)" }}
>
<BottomSheetView className="px-4 pt-1">
<View className="mb-4 items-center gap-1">
<Text
className="text-[12px] font-t3-bold uppercase"
style={{ color: "#78716c", letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold" style={{ color: "#171717" }}>
Choose project
</Text>
</View>
<BottomSheetScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={{
paddingBottom: Math.max(insets.bottom, 18) + 18,
}}
>
<View className="overflow-hidden rounded-[24px]" style={{ backgroundColor: "#ffffff" }}>
{logicalProjects.map((entry, index) => (
<Pressable
key={entry.key}
onPress={() => props.onSelectProject(entry.project)}
style={{
paddingHorizontal: 16,
paddingVertical: 18,
borderTopWidth: index === 0 ? 0 : 1,
borderTopColor: "rgba(23,23,23,0.06)",
}}
>
<View className="flex-row items-center justify-between gap-3">
<View className="flex-1">
<Text className="text-[18px] font-t3-bold" style={{ color: "#171717" }}>
{entry.project.title}
</Text>
</View>
</View>
</Pressable>
))}
</View>
</BottomSheetScrollView>
</BottomSheetView>
</BottomSheetModal>
);
}
@@ -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<void>;
readonly onPasteIntoDraft: () => Promise<void>;
@@ -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 (
<View
className="gap-3 border-t border-slate-200 bg-white/92 px-4 pt-3.5 dark:border-white/6 dark:bg-slate-950/92"
className="gap-3 border-t border-slate-200 bg-stone-50/96 px-4 pt-3.5 dark:border-white/6 dark:bg-slate-950/92"
style={{ paddingBottom: (props.bottomInset ?? 0) + 16 }}
>
<View className="rounded-[24px] border border-slate-200 bg-white px-3.5 py-3 dark:border-white/8 dark:bg-slate-900">
<View
className="w-full self-center rounded-[24px] border border-slate-200 bg-white px-3.5 py-3 dark:border-white/8 dark:bg-slate-900"
style={{ maxWidth: isSplitLayout ? 960 : undefined }}
>
<TextInput
multiline
value={props.draftMessage}
@@ -84,19 +90,19 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
<View className="flex-row flex-wrap gap-2.5">
<ComposerAction
icon="photo.on.rectangle"
backgroundClassName="bg-slate-200 dark:bg-slate-800"
backgroundClassName="bg-stone-200 dark:bg-slate-800"
iconTintColor="#0f172a"
onPress={() => void props.onPickDraftImages()}
/>
<ComposerAction
icon="doc.on.clipboard"
backgroundClassName="bg-slate-200 dark:bg-slate-800"
backgroundClassName="bg-stone-200 dark:bg-slate-800"
iconTintColor="#0f172a"
onPress={() => void props.onPasteIntoDraft()}
/>
<ComposerAction
icon="arrow.clockwise"
backgroundClassName="bg-slate-200 dark:bg-slate-800"
backgroundClassName="bg-stone-200 dark:bg-slate-800"
iconTintColor="#0f172a"
onPress={() => 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
</View>
</View>
{props.draftAttachments.length > 0 ? (
<ScrollView horizontal showsHorizontalScrollIndicator={false}>
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
style={isSplitLayout ? { alignSelf: "center", width: "100%", maxWidth: 960 } : undefined}
>
<View className="flex-row gap-2">
{props.draftAttachments.map((image) => (
<View key={image.id} className="gap-2">
@@ -150,7 +160,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
</ScrollView>
) : null}
{props.queueCount > 0 ? (
<Text className="font-t3-medium text-xs leading-[18px] text-slate-500 dark:text-slate-400">
<Text
className="self-center font-t3-medium text-xs leading-[18px] text-slate-500 dark:text-slate-400"
style={{ maxWidth: 960, width: "100%" }}
>
{props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
automatically.
</Text>
@@ -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<DraftComposerImageAttachment>;
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<void>;
readonly onPasteIntoDraft: () => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onRefresh: () => Promise<void>;
readonly onRefreshSelectedThreadGitStatus: (options?: {
readonly quiet?: boolean;
}) => Promise<void>;
readonly onListSelectedThreadBranches: () => Promise<ReadonlyArray<GitBranch>>;
readonly onCheckoutSelectedThreadBranch: (branch: string) => Promise<void>;
readonly onCreateSelectedThreadBranch: (branch: string) => Promise<void>;
readonly onCreateSelectedThreadWorktree: (input: {
readonly baseBranch: string;
readonly newBranch: string;
}) => Promise<void>;
readonly onPullSelectedThreadBranch: () => Promise<void>;
readonly onRunSelectedThreadGitAction: (
input: GitActionRequestInput,
) => Promise<GitRunStackedActionResult | null>;
readonly onRenameThread: (title: string) => Promise<void>;
readonly onStopThread: () => Promise<void>;
readonly onSendMessage: () => void;
@@ -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<ThreadFeedEntry>) {
const lastStreamingAssistantRef = useRef<{
readonly id: string;
@@ -155,28 +180,117 @@ function useStreamingHaptics(threadId: string, feed: ReadonlyArray<ThreadFeedEnt
}
export function ThreadDetailScreen(props: ThreadDetailScreenProps) {
const { onBack, onOpenDrawer, onRefresh, onRefreshSelectedThreadGitStatus } = props;
const isDarkMode = useColorScheme() === "dark";
const insets = useSafeAreaInsets();
const { width } = useWindowDimensions();
const agentLabel = `${props.selectedThread.modelSelection.provider} agent`;
const headerOverlayHeight = insets.top + 70;
const headerOverlayHeight = insets.top + 118;
const composerBottomInset = Math.max(insets.bottom, 12);
const screenBackgroundColor = isDarkMode ? "#020617" : "#f8fafc";
const screenBackgroundColor = isDarkMode ? "#0c1118" : "#f7f7f5";
const modalBackdropColor = isDarkMode ? "rgba(2,6,23,0.68)" : "rgba(15,23,42,0.22)";
const modalPanelColor = isDarkMode ? "#111827" : "#ffffff";
const modalBorderColor = isDarkMode ? "rgba(255,255,255,0.08)" : "#e2e8f0";
const modalMutedColor = isDarkMode ? "#94a3b8" : "#64748b";
const modalPrimaryColor = isDarkMode ? "#f8fafc" : "#020617";
const connectionPulse = props.activeThreadBusy;
const [renameVisible, setRenameVisible] = useState(false);
const [renameDraft, setRenameDraft] = useRenameDraftSync(
props.selectedThread.id,
props.selectedThread.title,
);
const [refreshing, setRefreshing] = useState(false);
const [renameDraft, setRenameDraft] = useState(props.selectedThread.title);
const showHeader = props.showHeader ?? true;
const showContent = props.showContent ?? true;
const layoutVariant = props.layoutVariant ?? "compact";
const isSplitLayout = layoutVariant === "split";
const edgeSwipeTranslation = useSharedValue(0);
useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
const completeDrawerGesture = useCallback(() => {
void Haptics.selectionAsync();
onOpenDrawer();
}, [onOpenDrawer]);
const completeBackGesture = useCallback(() => {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
onBack();
}, [onBack]);
const handleRefresh = useCallback(async (): Promise<void> => {
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<void> {
const trimmed = renameDraft.trim();
if (trimmed.length === 0) {
@@ -188,216 +302,243 @@ export function ThreadDetailScreen(props: ThreadDetailScreenProps) {
}
return (
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : undefined}
style={{ flex: 1, backgroundColor: screenBackgroundColor }}
>
{showHeader ? (
<View className="absolute inset-x-0 top-0 z-20">
<GlassSafeAreaView
leftSlot={
<Pressable
className="min-w-[76px] items-center rounded-[14px] bg-slate-200 px-2.5 py-2.5 dark:bg-slate-800"
onPress={props.onBack}
>
<Text className="font-t3-bold text-[13px] text-slate-950 dark:text-slate-50">
Back
</Text>
</Pressable>
}
centerSlot={
<View className="items-center gap-1">
<Pressable onLongPress={() => setRenameVisible(true)}>
<Animated.Text
numberOfLines={1}
style={{
color: isDarkMode ? "#f8fafc" : "#020617",
fontSize: 18,
fontWeight: "800",
lineHeight: 22,
}}
>
{props.selectedThread.title}
</Animated.Text>
</Pressable>
<Text
className="text-[11px] font-bold uppercase"
style={{ color: modalMutedColor, letterSpacing: 1.05 }}
>
{props.activeWorkDurationLabel ? props.activeWorkDurationLabel : ""}
</Text>
</View>
}
rightSlot={
<Pressable className="rounded-full px-3 py-2" onPress={props.onOpenConnectionEditor}>
<ConnectionStatusDot state={props.connectionStateLabel} pulse={connectionPulse} />
</Pressable>
}
/>
</View>
) : null}
{showContent && props.connectionError ? (
<View
className="mx-4 mt-3"
style={{
paddingTop: props.activeWorkDurationLabel
? headerOverlayHeight + 12
: headerOverlayHeight + 6,
}}
<GestureDetector gesture={edgeSwipeGesture}>
<Animated.View style={edgeSwipeStyle}>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : undefined}
style={{ flex: 1, backgroundColor: screenBackgroundColor }}
>
<ErrorBanner message={props.connectionError} />
</View>
) : null}
{showContent ? (
<>
<View style={{ flex: 1, minHeight: 0 }}>
<ThreadFeed
threadId={props.selectedThread.id}
feed={props.selectedThreadFeed}
httpBaseUrl={props.httpBaseUrl}
bearerToken={props.bearerToken}
agentLabel={agentLabel}
contentTopInset={headerOverlayHeight + 20}
contentBottomInset={composerBottomInset + 20}
/>
</View>
{props.activePendingApproval || props.activePendingUserInput ? (
<View className="gap-3 px-4 pb-3" style={{ flexShrink: 0 }}>
{props.activePendingApproval ? (
<PendingApprovalCard
approval={props.activePendingApproval}
respondingApprovalId={props.respondingApprovalId}
onRespond={props.onRespondToApproval}
{showHeader ? (
<View className="absolute inset-x-0 top-0 z-20">
<View
style={{
backgroundColor: isDarkMode ? "rgba(12,17,24,0.94)" : "rgba(247,247,245,0.94)",
borderBottomWidth: 1,
borderBottomColor: isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(23,23,23,0.06)",
}}
>
<GlassSafeAreaView
leftSlot={
isSplitLayout ? null : (
<Pressable
className="h-11 w-11 items-center justify-center rounded-full"
style={{
backgroundColor: isDarkMode
? "rgba(255,255,255,0.06)"
: "rgba(23,23,23,0.05)",
}}
onPress={props.onBack}
>
<SymbolView
name="chevron.left"
size={18}
tintColor={isDarkMode ? "#fafaf9" : "#171717"}
type="monochrome"
/>
</Pressable>
)
}
centerSlot={
<View className="items-center gap-1">
<Pressable
onLongPress={() => {
setRenameDraft(props.selectedThread.title);
setRenameVisible(true);
}}
>
<Animated.Text
numberOfLines={1}
style={{
color: isDarkMode ? "#f8fafc" : "#020617",
fontSize: 18,
fontWeight: "800",
lineHeight: 22,
}}
>
{props.selectedThread.title}
</Animated.Text>
</Pressable>
<Text
className="text-[11px] font-bold uppercase"
style={{ color: modalMutedColor, letterSpacing: 1.05 }}
>
{props.activeWorkDurationLabel ? props.activeWorkDurationLabel : ""}
</Text>
</View>
}
rightSlot={
<ThreadGitControls
currentBranch={props.selectedThread.branch}
currentWorktreePath={props.selectedThread.worktreePath}
gitStatus={props.selectedThreadGitStatus}
gitOperationLabel={props.gitOperationLabel}
onRefreshStatus={props.onRefreshSelectedThreadGitStatus}
onListBranches={props.onListSelectedThreadBranches}
onCheckoutBranch={props.onCheckoutSelectedThreadBranch}
onCreateBranch={props.onCreateSelectedThreadBranch}
onCreateWorktree={props.onCreateSelectedThreadWorktree}
onPull={props.onPullSelectedThreadBranch}
onRunAction={props.onRunSelectedThreadGitAction}
/>
}
/>
) : null}
{props.activePendingUserInput ? (
<PendingUserInputCard
pendingUserInput={props.activePendingUserInput}
drafts={props.activePendingUserInputDrafts}
answers={props.activePendingUserInputAnswers}
respondingUserInputId={props.respondingUserInputId}
onSelectOption={props.onSelectUserInputOption}
onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
onSubmit={props.onSubmitUserInput}
/>
) : null}
</View>
</View>
) : null}
<ThreadComposer
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
connectionState={props.connectionStateLabel}
selectedThread={props.selectedThread}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
onPickDraftImages={props.onPickDraftImages}
onPasteIntoDraft={props.onPasteIntoDraft}
onRemoveDraftImage={props.onRemoveDraftImage}
onRefresh={props.onRefresh}
onStopThread={props.onStopThread}
onSendMessage={props.onSendMessage}
/>
</>
) : (
<View style={{ flex: 1 }} />
)}
{showContent ? (
<>
<View style={{ flex: 1, minHeight: 0 }}>
<ThreadFeed
threadId={props.selectedThread.id}
feed={props.selectedThreadFeed}
httpBaseUrl={props.httpBaseUrl}
bearerToken={props.bearerToken}
agentLabel={agentLabel}
contentTopInset={headerOverlayHeight + 20}
contentBottomInset={composerBottomInset + 20}
layoutVariant={layoutVariant}
refreshing={refreshing}
onRefresh={() => void handleRefresh()}
/>
</View>
<Modal
transparent
animationType="fade"
visible={renameVisible}
onRequestClose={() => setRenameVisible(false)}
>
<View
className="flex-1 items-center justify-center px-5"
style={{ backgroundColor: modalBackdropColor }}
>
<View
className="w-full gap-4 px-4 py-4"
style={{
maxWidth: 420,
borderWidth: 1,
borderColor: modalBorderColor,
backgroundColor: modalPanelColor,
}}
{props.activePendingApproval || props.activePendingUserInput ? (
<View className="gap-3 px-4 pb-3" style={{ flexShrink: 0 }}>
{props.activePendingApproval ? (
<PendingApprovalCard
approval={props.activePendingApproval}
respondingApprovalId={props.respondingApprovalId}
onRespond={props.onRespondToApproval}
/>
) : null}
{props.activePendingUserInput ? (
<PendingUserInputCard
pendingUserInput={props.activePendingUserInput}
drafts={props.activePendingUserInputDrafts}
answers={props.activePendingUserInputAnswers}
respondingUserInputId={props.respondingUserInputId}
onSelectOption={props.onSelectUserInputOption}
onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
onSubmit={props.onSubmitUserInput}
/>
) : null}
</View>
) : null}
<ThreadComposer
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
connectionState={props.connectionStateLabel}
selectedThread={props.selectedThread}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
layoutVariant={layoutVariant}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
onPickDraftImages={props.onPickDraftImages}
onPasteIntoDraft={props.onPasteIntoDraft}
onRemoveDraftImage={props.onRemoveDraftImage}
onRefresh={props.onRefresh}
onStopThread={props.onStopThread}
onSendMessage={props.onSendMessage}
/>
</>
) : (
<View style={{ flex: 1 }} />
)}
<Modal
transparent
animationType="fade"
visible={renameVisible}
onRequestClose={() => setRenameVisible(false)}
>
<View className="gap-2">
<Text
className="text-[11px] font-bold uppercase"
style={{ color: modalMutedColor, letterSpacing: 1.2 }}
>
Thread name
</Text>
<Text
className="text-[20px] font-extrabold leading-[24px]"
style={{ color: modalPrimaryColor }}
>
Rename thread
</Text>
</View>
<TextInput
autoFocus
value={renameDraft}
onChangeText={setRenameDraft}
placeholder="Thread title"
className="min-h-[56px] px-4 py-3 text-[15px]"
style={{
borderWidth: 1,
borderColor: modalBorderColor,
backgroundColor: isDarkMode ? "#0f172a" : "#ffffff",
color: modalPrimaryColor,
}}
onSubmitEditing={() => {
void handleSubmitRename();
}}
/>
<View className="flex-row gap-3">
<Pressable
className="min-h-[48px] flex-1 items-center justify-center px-4 py-3"
<View
className="flex-1 items-center justify-center px-5"
style={{ backgroundColor: modalBackdropColor }}
>
<View
className="w-full gap-4 px-4 py-4"
style={{
maxWidth: 420,
borderWidth: 1,
borderColor: modalBorderColor,
backgroundColor: isDarkMode ? "#1f2937" : "#f8fafc",
}}
onPress={() => {
setRenameDraft(props.selectedThread.title);
setRenameVisible(false);
backgroundColor: modalPanelColor,
}}
>
<Text
className="text-sm font-extrabold uppercase"
style={{ color: modalPrimaryColor, letterSpacing: 1 }}
>
Cancel
</Text>
</Pressable>
<Pressable
className="min-h-[48px] flex-1 items-center justify-center px-4 py-3"
style={{ backgroundColor: modalPrimaryColor }}
onPress={() => {
void handleSubmitRename();
}}
>
<Text
className="text-sm font-extrabold uppercase"
style={{ color: isDarkMode ? "#020617" : "#f8fafc", letterSpacing: 1 }}
>
Save
</Text>
</Pressable>
<View className="gap-2">
<Text
className="text-[11px] font-bold uppercase"
style={{ color: modalMutedColor, letterSpacing: 1.2 }}
>
Thread name
</Text>
<Text
className="text-[20px] font-extrabold leading-[24px]"
style={{ color: modalPrimaryColor }}
>
Rename thread
</Text>
</View>
<TextInput
value={renameDraft}
onChangeText={setRenameDraft}
placeholder="Thread title"
className="min-h-[56px] px-4 py-3 text-[15px]"
style={{
borderWidth: 1,
borderColor: modalBorderColor,
backgroundColor: isDarkMode ? "#0f172a" : "#ffffff",
color: modalPrimaryColor,
}}
onSubmitEditing={() => {
void handleSubmitRename();
}}
/>
<View className="flex-row gap-3">
<Pressable
className="min-h-[48px] flex-1 items-center justify-center px-4 py-3"
style={{
borderWidth: 1,
borderColor: modalBorderColor,
backgroundColor: isDarkMode ? "#1f2937" : "#f8fafc",
}}
onPress={() => {
setRenameDraft(props.selectedThread.title);
setRenameVisible(false);
}}
>
<Text
className="text-sm font-extrabold uppercase"
style={{ color: modalPrimaryColor, letterSpacing: 1 }}
>
Cancel
</Text>
</Pressable>
<Pressable
className="min-h-[48px] flex-1 items-center justify-center px-4 py-3"
style={{ backgroundColor: modalPrimaryColor }}
onPress={() => {
void handleSubmitRename();
}}
>
<Text
className="text-sm font-extrabold uppercase"
style={{ color: isDarkMode ? "#020617" : "#f8fafc", letterSpacing: 1 }}
>
Save
</Text>
</Pressable>
</View>
</View>
</View>
</View>
</View>
</Modal>
</KeyboardAvoidingView>
</Modal>
</KeyboardAvoidingView>
</Animated.View>
</GestureDetector>
);
}
+209 -64
View File
@@ -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<ThreadFeedEntry>,
props: Pick<ThreadFeedProps, "agentLabel" | "bearerToken" | "httpBaseUrl">,
props: Pick<ThreadFeedProps, "bearerToken" | "httpBaseUrl"> & {
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
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 (
<View
className={cx(
"mb-3.5 gap-2.5 rounded-[22px] border px-4 py-4",
isUser
? "border-orange-300/60 bg-orange-100/70 dark:border-orange-300/22 dark:bg-orange-300/14"
: "border-slate-200 bg-slate-100/80 dark:border-white/6 dark:bg-slate-900/80",
)}
>
<View className="flex-row justify-between gap-3">
<Text className="font-t3-bold text-[13px] text-slate-950 dark:text-slate-50">
{isUser ? "You" : props.agentLabel}
</Text>
<Text className="font-t3-medium text-xs text-slate-500 dark:text-slate-500">
{relativeTime(message.createdAt)}
{message.streaming ? " • live" : ""}
if (isUser) {
return (
<View className="mb-3.5 items-end gap-1.5">
<View className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[10px] border border-orange-300/60 bg-orange-100/70 px-4 py-4 dark:border-orange-300/22 dark:bg-orange-300/14">
{message.text.trim().length > 0 ? (
<Markdown style={markdownStyles}>{message.text}</Markdown>
) : null}
{attachments.map((attachment) => {
const uri = messageImageUrl(props.httpBaseUrl, attachment.id);
if (!uri) {
return null;
}
return (
<Image
key={attachment.id}
source={{
uri,
...(props.bearerToken
? {
headers: {
Authorization: `Bearer ${props.bearerToken}`,
},
}
: {}),
}}
className="aspect-[1.3] w-full rounded-[18px] bg-slate-200 dark:bg-slate-800"
resizeMode="cover"
/>
);
})}
</View>
<Text className="px-1 text-right font-t3-medium text-xs text-slate-500 dark:text-slate-500">
{timestampLabel}
</Text>
</View>
);
}
return (
<View className="mb-3.5 gap-1.5 px-1">
{message.text.trim().length > 0 ? (
<Markdown style={markdownStyles}>{message.text}</Markdown>
) : 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(
/>
);
})}
<Text className="font-t3-medium text-xs text-slate-500 dark:text-slate-500">
{timestampLabel}
</Text>
</View>
);
}
if (entry.type === "queued-message") {
return (
<View className="mb-3.5 gap-2.5 rounded-[22px] border border-sky-300/60 bg-sky-100/75 px-4 py-4 dark:border-sky-300/20 dark:bg-sky-400/10">
<View className="flex-row justify-between gap-3">
<Text className="font-t3-bold text-[13px] text-slate-950 dark:text-slate-50">
{entry.sending ? "Sending next" : "Queued"}
</Text>
<Text className="font-t3-medium text-xs text-slate-500 dark:text-slate-500">
{entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
<View className="mb-3.5 gap-1.5 items-end">
<View className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[10px] border border-sky-300/60 bg-sky-100/75 px-4 py-4 dark:border-sky-300/20 dark:bg-sky-400/10">
<Text className="font-sans text-[15px] leading-[22px] text-slate-950 dark:text-slate-50">
{entry.queuedMessage.text}
</Text>
{entry.queuedMessage.attachments.length > 0 ? (
<Text className="font-t3-medium text-xs text-slate-500 dark:text-slate-500">
{entry.queuedMessage.attachments.length} image
{entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached
</Text>
) : null}
</View>
<Text className="font-sans text-[15px] leading-[22px] text-slate-950 dark:text-slate-50">
{entry.queuedMessage.text}
<Text className="px-1 text-right font-t3-medium text-xs text-slate-500 dark:text-slate-500">
{entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
</Text>
{entry.queuedMessage.attachments.length > 0 ? (
<Text className="font-t3-medium text-xs text-slate-500 dark:text-slate-500">
{entry.queuedMessage.attachments.length} image
{entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached
</Text>
) : null}
</View>
);
}
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 (
<View className="mb-3.5 gap-3 rounded-[22px] border border-slate-200/80 bg-slate-50/85 px-4 py-4 dark:border-white/4 dark:bg-white/[0.025]">
<View className="flex-row items-center justify-between gap-3 pb-0.5">
<Text className="font-t3-bold text-[11px] uppercase tracking-[0.8px] text-slate-500 dark:text-slate-500">
Command center
</Text>
<Text className="font-t3-medium text-[11px] text-slate-500 dark:text-slate-500">
{relativeTime(entry.createdAt)}
</Text>
</View>
{rows.map((row, index) => (
<View className="mb-3 rounded-[20px] border border-slate-200/80 bg-slate-50/85 px-3 py-2 dark:border-white/4 dark:bg-white/[0.025]">
{showHeader ? (
<View className="mb-1.5 flex-row items-center justify-between gap-3 px-0.5">
<Text className="font-t3-bold text-[10px] uppercase tracking-[0.8px] text-slate-500 dark:text-slate-500">
Tool calls ({rows.length})
</Text>
<Pressable onPress={() => props.onToggleWorkGroup(entry.id)}>
<Text className="font-t3-medium text-[10px] uppercase tracking-[0.8px] text-slate-500 dark:text-slate-500">
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
</Text>
</Pressable>
</View>
) : null}
{visibleRows.map((row, index) => (
<View
key={row.id}
className={cx(
"gap-1.5 py-2",
"flex-row items-center gap-2 rounded-lg px-1 py-1",
index > 0 && "border-t border-slate-200/80 dark:border-white/4",
)}
>
<View className="flex-row items-start justify-between gap-3">
<Text className="flex-1 font-t3-medium text-[14px] text-slate-700 dark:text-slate-200">
{row.label}
</Text>
<Text className="font-t3-medium text-[11px] capitalize text-slate-500 dark:text-slate-500">
{row.status ? row.status.replaceAll("_", " ") : "done"}
</Text>
<View className="items-center justify-center pt-0.5">
<SymbolView name="terminal" size={13} tintColor="#64748b" type="monochrome" />
</View>
{row.detail && row.detail !== row.label ? (
<Text className="font-sans text-xs leading-[18px] text-slate-500 dark:text-slate-500">
{row.detail}
<ScrollView
horizontal
nestedScrollEnabled
directionalLockEnabled
showsHorizontalScrollIndicator={false}
bounces={false}
className="flex-1"
contentContainerStyle={{ paddingRight: 12 }}
style={{ flex: 1 }}
>
<Text
className="text-[11px] leading-[18px] text-slate-500 dark:text-slate-500"
onLongPress={() => {
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)}
</Text>
</ScrollView>
{props.copiedRowId === row.id ? (
<Text className="shrink-0 font-t3-medium text-[10px] uppercase tracking-[0.8px] text-emerald-600 dark:text-emerald-400">
Copied
</Text>
) : null}
</View>
@@ -307,14 +390,71 @@ function useAutoScrollToLatest(
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const listRef = useRef<FlashListRef<ThreadFeedEntry>>(null);
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [copiedRowId, setCopiedRowId] = useState<string | null>(null);
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
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<ThreadFeedEntry>) =>
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 (
<View
className="flex-1 px-4"
className="flex-1"
style={{
minHeight: 0,
paddingHorizontal: horizontalPadding,
paddingTop: props.contentTopInset ?? 18,
paddingBottom: props.contentBottomInset ?? 18,
}}
@@ -334,18 +474,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
key={props.threadId}
style={{ flex: 1 }}
data={props.feed}
renderItem={(info) => renderFeedEntry(info, props)}
renderItem={renderItem}
keyExtractor={(entry) => `${entry.type}:${entry.id}`}
keyboardShouldPersistTaps="handled"
onScroll={updateFollowLatest}
scrollEventThrottle={16}
refreshControl={
props.onRefresh ? (
<RefreshControl refreshing={props.refreshing ?? false} onRefresh={props.onRefresh} />
) : undefined
}
maintainVisibleContentPosition={{
autoscrollToBottomThreshold: 0.2,
animateAutoScrollToBottom: true,
startRenderingFromBottom: true,
}}
contentContainerStyle={{
paddingHorizontal: 16,
paddingHorizontal: horizontalPadding,
paddingTop: props.contentTopInset ?? 18,
paddingBottom: props.contentBottomInset ?? 18,
}}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -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<ScopedMobileProject>;
readonly threads: ReadonlyArray<ScopedMobileThread>;
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 (
<Modal transparent visible={mounted} onRequestClose={props.onClose} statusBarTranslucent>
<View style={{ flex: 1 }}>
<Animated.View
pointerEvents="none"
style={[
{
position: "absolute",
left: 0,
right: 0,
top: 0,
bottom: 0,
backgroundColor: "rgba(15,23,42,0.22)",
},
backdropStyle,
]}
/>
<Pressable
style={{ position: "absolute", left: 0, right: 0, top: 0, bottom: 0 }}
onPress={props.onClose}
/>
<GestureDetector gesture={panGesture}>
<Animated.View
style={[
{
position: "absolute",
left: 0,
top: 0,
bottom: 0,
width: drawerWidth,
backgroundColor: "rgba(250,248,242,0.99)",
paddingTop: insets.top + 10,
paddingBottom: Math.max(insets.bottom, 18),
boxShadow: "20px 0 36px rgba(15,23,42,0.12)",
},
drawerStyle,
]}
>
<View className="flex-row items-center justify-between px-4 pb-5">
<Text className="text-[26px] font-t3-bold" style={{ color: "#171717" }}>
Threads
</Text>
<Pressable
onPress={() => {
props.onClose();
props.onStartNewTask();
}}
className="h-11 w-11 items-center justify-center rounded-full"
style={{ backgroundColor: "#171717" }}
>
<SymbolView
name="square.and.pencil"
size={17}
tintColor="#fafaf9"
type="monochrome"
/>
</Pressable>
</View>
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={{
gap: 20,
paddingHorizontal: 14,
paddingBottom: Math.max(insets.bottom, 18) + 12,
}}
>
{groupedThreads.map((group) => (
<View key={group.key} className="gap-3">
<Text
className="px-1 text-[15px] font-t3-bold"
style={{ color: "#78716c", letterSpacing: -0.2 }}
>
{group.title}
</Text>
<View
className="overflow-hidden rounded-[22px]"
style={{ backgroundColor: "#ffffff" }}
>
{group.threads.length === 0 ? (
<View className="px-4 py-4">
<Text className="text-[14px] font-medium" style={{ color: "#a8a29e" }}>
No threads yet
</Text>
</View>
) : (
group.threads.map((thread, index) => {
const threadKey = scopedThreadKey(thread.environmentId, thread.id);
const selected = props.selectedThreadKey === threadKey;
return (
<Pressable
key={threadKey}
onPress={() => {
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",
}}
>
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-1">
<Text
className="text-[16px] font-t3-bold"
numberOfLines={1}
style={{ color: "#171717" }}
>
{thread.title}
</Text>
<Text
className="text-[13px] font-medium"
numberOfLines={1}
style={{ color: "#78716c" }}
>
{relativeTime(thread.updatedAt ?? thread.createdAt)}
</Text>
</View>
<StatusPill {...threadStatusTone(thread)} />
</View>
</Pressable>
);
})
)}
</View>
</View>
))}
</ScrollView>
</Animated.View>
</GestureDetector>
</View>
</Modal>
);
}
@@ -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";
}
+36
View File
@@ -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,
});
});
});
+37
View File
@@ -0,0 +1,37 @@
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
export type MobileLayoutVariant = "compact" | "split";
export interface MobileLayout {
readonly variant: MobileLayoutVariant;
readonly usesSplitView: boolean;
readonly listPaneWidth: number | null;
readonly shellPadding: number;
}
export function deriveMobileLayout(input: {
readonly width: number;
readonly height: number;
}): MobileLayout {
const { width, height } = input;
const shortestEdge = Math.min(width, height);
const wideEnoughForSplit = width >= 900 || (width >= 700 && shortestEdge >= 700);
if (!wideEnoughForSplit) {
return {
variant: "compact",
usesSplitView: false,
listPaneWidth: null,
shellPadding: 0,
};
}
return {
variant: "split",
usesSplitView: true,
listPaneWidth: clamp(Math.round(width * 0.34), 320, 420),
shellPadding: width >= 1180 ? 20 : 14,
};
}
+104
View File
@@ -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: "[email protected]: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: "[email protected]: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");
});
});
+4
View File
@@ -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 }
: {}),
+25
View File
@@ -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.",
);
});
});
+22
View File
@@ -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;
}
+62
View File
@@ -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<GitStatusResult> {
return await this.request(
WS_METHODS.gitRefreshStatus,
input,
"Request timed out: git.refreshStatus",
);
}
async gitListBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
return await this.request(
WS_METHODS.gitListBranches,
input,
"Request timed out: git.listBranches",
);
}
async gitCreateBranch(input: GitCreateBranchInput): Promise<GitCreateBranchResult> {
return await this.request(
WS_METHODS.gitCreateBranch,
input,
"Request timed out: git.createBranch",
);
}
async gitCheckout(input: GitCheckoutInput): Promise<GitCheckoutResult> {
return await this.request(WS_METHODS.gitCheckout, input, "Request timed out: git.checkout");
}
async gitCreateWorktree(input: GitCreateWorktreeInput): Promise<GitCreateWorktreeResult> {
return await this.request(
WS_METHODS.gitCreateWorktree,
input,
"Request timed out: git.createWorktree",
);
}
async gitPull(input: GitPullInput): Promise<GitPullResult> {
return await this.request(WS_METHODS.gitPull, input, "Request timed out: git.pull");
}
async gitRunStackedAction(input: GitRunStackedActionInput): Promise<GitRunStackedActionResult> {
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 {
@@ -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<ScopedMobileProject> &
Pick<ScopedMobileProject, "environmentId" | "environmentLabel" | "id" | "title">,
): 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<ScopedMobileThread> &
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: "[email protected]: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();
});
});
+135
View File
@@ -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<ScopedMobileThread>;
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<MobileRepositoryProjectGroup>;
}
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<ScopedMobileThread>,
): string {
const latestThread = threads[0];
return latestThread?.updatedAt ?? latestThread?.createdAt ?? project.updatedAt;
}
export function groupProjectsByRepository(input: {
readonly projects: ReadonlyArray<ScopedMobileProject>;
readonly threads: ReadonlyArray<ScopedMobileThread>;
}): ReadonlyArray<MobileRepositoryGroup> {
const threadsByProjectKey = new Map<string, ScopedMobileThread[]>();
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<string, MobileRepositoryGroup>();
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),
);
}
+2 -2
View File
@@ -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<string, string>();
type AsyncStorageModule = typeof import("@react-native-async-storage/async-storage");
@@ -89,7 +89,7 @@ async function removeStorageItem(key: string): Promise<void> {
}
function connectionTokenKey(environmentId: string): string {
return `t3remote:bearer-token:${environmentId}`;
return `t3code:bearer-token:${environmentId}`;
}
async function loadSecureToken(environmentId: string): Promise<string> {
+14
View File
@@ -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()}`;
}
@@ -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";
+2 -69
View File
@@ -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({
</MenuTrigger>
<MenuPopup align="end" className="w-full">
{gitActionMenuItems.map((item) => {
const disabledReason = getMenuActionDisabledReason({
const disabledReason = getGitActionDisabledReason({
item,
gitStatus: gitStatusForActions,
isBusy: isGitActionRunning,
+1 -1
View File
@@ -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(
+13 -18
View File
@@ -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}
<span className={threadMetaClassName}>
<span className="inline-flex items-center gap-1">
{isRemoteThread && (
<Tooltip>
<TooltipTrigger
render={
<span
aria-label={threadEnvironmentLabel ?? "Remote"}
className="inline-flex items-center justify-center"
/>
}
>
<CloudIcon className="size-3 text-muted-foreground/40" />
</TooltipTrigger>
<TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
</Tooltip>
)}
<span
title={threadEnvironmentLabel}
className={`inline-flex max-w-18 items-center truncate rounded-full border border-border/70 bg-background/85 px-1.5 py-0.5 text-[9px] font-medium tracking-[0.08em] ${
isHighlighted
? "text-foreground/72 dark:text-foreground/82"
: "text-muted-foreground/60"
}`}
>
{threadEnvironmentLabel}
</span>
{jumpLabel ? (
<span
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
@@ -848,7 +843,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
return (
<SidebarMenuSub
ref={attachThreadListAutoAnimateRef}
className="mx-1 my-0 w-full translate-x-0 gap-0.5 overflow-hidden px-1.5 py-0"
className="mx-0.5 my-0 w-full translate-x-0 gap-0.5 overflow-hidden px-1 py-0 sm:mx-1 sm:px-1.5"
>
{shouldShowThreadPanel && showEmptyThreadState ? (
<SidebarMenuSubItem className="w-full" data-thread-selection-safe>
@@ -1685,7 +1680,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
<SidebarMenuButton
ref={isManualProjectSorting ? dragHandleProps?.setActivatorNodeRef : undefined}
size="sm"
className={`gap-2 px-2 py-1.5 text-left hover:bg-accent group-hover/project-header:bg-accent group-hover/project-header:text-sidebar-accent-foreground ${
className={`gap-2 px-2 py-1 text-left hover:bg-accent group-hover/project-header:bg-accent group-hover/project-header:text-sidebar-accent-foreground sm:py-1.5 ${
isManualProjectSorting ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"
}`}
{...(isManualProjectSorting && dragHandleProps ? dragHandleProps.attributes : {})}
+8 -5
View File
@@ -69,17 +69,20 @@ export const ChatHeader = memo(function ChatHeader({
onToggleDiff,
}: ChatHeaderProps) {
return (
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2">
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
<div className="@container/header-actions flex min-w-0 flex-1 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 flex-wrap items-center gap-2 overflow-hidden sm:flex-1 sm:flex-nowrap sm:gap-3">
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
<h2
className="min-w-0 shrink truncate text-sm font-medium text-foreground"
className="min-w-0 flex-1 basis-40 truncate text-sm font-medium text-foreground"
title={activeThreadTitle}
>
{activeThreadTitle}
</h2>
{activeProjectName && (
<Badge variant="outline" className="min-w-0 shrink overflow-hidden">
<Badge
variant="outline"
className="min-w-0 max-w-full shrink overflow-hidden sm:max-w-56"
>
<span className="min-w-0 truncate">{activeProjectName}</span>
</Badge>
)}
@@ -89,7 +92,7 @@ export const ChatHeader = memo(function ChatHeader({
</Badge>
)}
</div>
<div className="flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3">
<div className="flex min-w-0 flex-wrap items-center justify-start gap-2 sm:shrink-0 sm:justify-end @3xl/header-actions:gap-3">
{activeProjectScripts && (
<ProjectScriptsControl
scripts={activeProjectScripts}
+31
View File
@@ -45,14 +45,18 @@
"version": "0.0.0",
"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",
@@ -68,6 +72,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",
@@ -499,6 +504,8 @@
"@effect/vitest": ["@effect/[email protected]", "", { "peerDependencies": { "effect": "^4.0.0-beta.45", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-38JA5Z6c2FoEhpVKbl7rjTrMU8Al5T30Kwtb6N3B9kOkyr2SsmvNsP9T65bh03IBh3ak9U//acrkmjS3hLQwKA=="],
"@egjs/hammerjs": ["@egjs/[email protected]", "", { "dependencies": { "@types/hammerjs": "^2.0.36" } }, "sha512-XQsZgjm2EcVUiZQf11UBJQfmZeEmOW8DpI1gsFeln6w0ae0ii4dMQEQ0kjl6DspdWX1aGY1/loyXnP0JS06e/A=="],
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
"@emmetio/abbreviation": ["@emmetio/[email protected]", "", { "dependencies": { "@emmetio/scanner": "^1.0.4" } }, "sha512-mgv58UrU3rh4YgbE/TzgLQwJ3pFsHHhCLqY20aJq+9comytTXUDNGG/SMtSeMJdkpxgXSXunBGLD8Boka3JyVA=="],
@@ -647,6 +654,10 @@
"@formkit/auto-animate": ["@formkit/[email protected]", "", {}, "sha512-VhP4zEAacXS3dfTpJpJ88QdLqMTcabMg0jwpOSxZ/VzfQVfl3GkZSCZThhGC5uhq/TxPHPzW0dzr4H9Bb1OgKA=="],
"@gorhom/bottom-sheet": ["@gorhom/[email protected]", "", { "dependencies": { "@gorhom/portal": "1.0.14", "invariant": "^2.2.4" }, "peerDependencies": { "@types/react": "*", "@types/react-native": "*", "react": "*", "react-native": "*", "react-native-gesture-handler": ">=2.16.1", "react-native-reanimated": ">=3.16.0 || >=4.0.0-" }, "optionalPeers": ["@types/react", "@types/react-native"] }, "sha512-YwieCsEnTQnN2QW4VBKfCGszzxaw2ID7FydusEgqo7qB817fZ45N88kptcuNwZFnnauCjdyzKdrVBWmLmpl9oQ=="],
"@gorhom/portal": ["@gorhom/[email protected]", "", { "dependencies": { "nanoid": "^3.3.1" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-MXyL4xvCjmgaORr/rtryDNFy3kU4qUbKlwtQqqsygd0xX3mhKjOLn6mQK8wfu0RkoE0pBE0nAasRoHua+/QZ7A=="],
"@hono/node-server": ["@hono/[email protected]", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="],
"@img/colour": ["@img/[email protected]", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
@@ -907,6 +918,8 @@
"@react-native-masked-view/masked-view": ["@react-native-masked-view/[email protected]", "", { "peerDependencies": { "react": ">=16", "react-native": ">=0.57" } }, "sha512-XwuQoW7/GEgWRMovOQtX3A4PrXhyaZm0lVUiY8qJDvdngjLms9Cpdck6SmGAUNqQwcj2EadHC1HwL0bEyoa/SQ=="],
"@react-native-menu/menu": ["@react-native-menu/[email protected]", "", { "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-hb8Mirw6aKPGONhgo52IiNpwHtISVrgCT3rMdFX1qS7eOFNzOcQh8d2UDnaH5zVpxN+QuvWtaaiRMGFpIjzdtA=="],
"@react-native/assets-registry": ["@react-native/[email protected]", "", {}, "sha512-aqKtpbJDSQeSX/Dwv0yMe1/Rd2QfXi12lnyZDXNn/OEKz59u6+LuPBVgO/9CRyclHmdlvwg8c7PJ9eX2ZMnjWg=="],
"@react-native/babel-plugin-codegen": ["@react-native/[email protected]", "", { "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/[email protected]", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="],
"@types/emscripten": ["@types/[email protected]", "", {}, "sha512-cMQm7pxu6BxtHyqJ7mQZ2kXWV5SLmugybFdHCBbJ5eHzOo6VhBckEgAT3//rP5FwPHNPeEiq4SmQ5ucBwsOo4Q=="],
"@types/estree": ["@types/[email protected]", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],
"@types/estree-jsx": ["@types/[email protected]", "", { "dependencies": { "@types/estree": "*" } }, "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg=="],
"@types/graceful-fs": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ=="],
"@types/hammerjs": ["@types/[email protected]", "", {}, "sha512-ynRvcq6wvqexJ9brDMS4BnBLzmr0e14d6ZJTEShTBWKymQiHwlAyGu0ZPEFI2Fh1U53F7tN9ufClWM5KvqkKOw=="],
"@types/hast": ["@types/[email protected]", "", { "dependencies": { "@types/unist": "*" } }, "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ=="],
"@types/http-cache-semantics": ["@types/[email protected]", "", {}, "sha512-L3LgimLHXtGkWikKnsPg0/VFx9OGZaC+eN1u4r+OB1XRqH3meBIAVC2zr1WdMH+RHmnRkqliQAOHNJ/E0j/e0Q=="],
@@ -1141,6 +1158,8 @@
"@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="],
"@types/react-test-renderer": ["@types/[email protected]", "", { "dependencies": { "@types/react": "*" } }, "sha512-XD0WZrHqjNrxA/MaR9O22w/RNidWR9YZmBdRGI7wcnWGrv/3dA8wKCJ8m63Sn+tLJhcjmuhOi629N66W6kgWzQ=="],
"@types/responselike": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw=="],
"@types/stack-utils": ["@types/[email protected]", "", {}, "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw=="],
@@ -1279,6 +1298,8 @@
"balanced-match": ["[email protected]", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
"barcode-detector": ["[email protected]", "", { "dependencies": { "zxing-wasm": "3.0.2" } }, "sha512-Q5kjXpVH5I3ItykNzbWmfWnNryFN1ZTWp10k9/PKJuS0RnoKR7jTrHEJODR4fn04bRomq7TJwie/Dr9fj/GoGQ=="],
"base64-js": ["[email protected]", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-VSnGQAOLtP5mib/DPyg2/t+Tlv65NTBz83BJBJvmLVHHuKJVaDOBvJJykiT5TR++em5nfAySPccDZDa4oSrn8A=="],
@@ -1567,6 +1588,8 @@
"expo-asset": ["[email protected]", "", { "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": ["[email protected]", "", { "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": ["[email protected]", "", { "peerDependencies": { "expo": "*", "react": "*", "react-native": "*" } }, "sha512-PrOmmuVsGW4bAkNQmGKtxMXj3invsfN+jfIKmQxHwE/dn7ODqwFWviUTa+PMUjP3XZmYCDLyu/i0GLeu7HF9Ew=="],
"expo-constants": ["[email protected]", "", { "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": ["[email protected]", "", { "dependencies": { "hermes-estree": "0.32.1" } }, "sha512-175dz634X/W5AiwrpLdoMl/MOb17poLHyIqgyExlE8D9zQ1OPnoORnGMB5ltRKnpvQzBjMYvT2rN/sHeIfZW5Q=="],
"hoist-non-react-statics": ["[email protected]", "", { "dependencies": { "react-is": "^16.7.0" } }, "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw=="],
"hono": ["[email protected]", "", {}, "sha512-p1JfQMKaceuCbpJKAPKVqyqviZdS0eUxH9v82oWo1kb9xjQ5wA6iP3FNVAPDFlz5/p7d45lO+BpSk1tuSZMF4Q=="],
"hookable": ["[email protected]", "", {}, "sha512-ZoKZSJgu8voGK2geJS+6YtYjvIzu9AOM/KZXsBxr83uhLL++e9pEv/dlgwgy3dvHg06kTz6JOh1hk3C8Ceiymw=="],
@@ -2333,6 +2358,8 @@
"react-native-fit-image": ["[email protected]", "", { "dependencies": { "prop-types": "^15.5.10" } }, "sha512-Wl3Vq2DQzxgsWKuW4USfck9zS7YzhvLNPpkwUUCF90bL32e1a0zOVQ3WsJILJOwzmPdHfzZmWasiiAUNBkhNkg=="],
"react-native-gesture-handler": ["[email protected]", "", { "dependencies": { "@egjs/hammerjs": "^2.0.17", "@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": ["[email protected]", "", { "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-FLbPWl/MyYQWz+KwqOZsSyj2JmLKglHatd3xLZWskXOpRaio4LfEDEz8E/A6uD8QoTHW6Aobw1jbEwK7KMgR7Q=="],
"react-native-markdown-display": ["[email protected]", "", { "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": ["[email protected]", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],
"zxing-wasm": ["[email protected]", "", { "dependencies": { "@types/emscripten": "^1.41.5", "type-fest": "^5.5.0" } }, "sha512-2YMAriaYHX9wrBY2k7H0epSo+dyCaCZg/vOtt+nEDXM9ul480gkXz/9SkwpOeHcD2H5qqDG8lWDSBwpTcZpa6w=="],
"@astrojs/language-server/@astrojs/compiler": ["@astrojs/[email protected]", "", {}, "sha512-f3FN83d2G/v32ipNClRKgYv30onQlMZX1vCeZMjPsMMPl1mDpmbl0+N5BYo4S/ofzqJyS5hvwacEo0CCVDn/Qg=="],
"@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="],
@@ -2971,6 +3000,8 @@
"h3/cookie-es": ["[email protected]", "", {}, "sha512-lXVyvUvrNXblMqzIRrxHb57UUVmqsSWlxqt3XIjCkUP0wDAf6uicO6KMbEgYrMNtEvWgWHwe42CKxPu9MYAnWw=="],
"hoist-non-react-statics/react-is": ["[email protected]", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],
"hosted-git-info/lru-cache": ["[email protected]", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],
"istanbul-lib-instrument/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+6 -1
View File
@@ -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": {
+430
View File
@@ -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,
};
}
+1
View File
@@ -1,2 +1,3 @@
export * from "./knownEnvironment";
export * from "./scoped";
export * from "./gitActions";