The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 497 lines 18 KB
Raw
1 import { NativeScrollView } from "../../native/NativeScrollViewMarker";
2 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3 import { Button } from "../../components/ui/Button";
4 import * as Dialog from "../../components/ui/Dialog";
5 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
6 import { SelectionRow } from "../../components/ui/SelectionRow";
7 import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
8 import { shouldCheckoutNewTaskBranch } from "./new-task-context-presentation";
9 import type { VcsRef } from "@t3tools/client-runtime/state/vcs";
10 import {
11 AuthSourceControlWriteScope,
12 resolveEnvironmentMachineKind,
13 type EnvironmentId,
14 } from "@t3tools/contracts";
15 import { LegendList } from "@legendapp/list/react-native";
16 import {
17 isAtomCommandInterrupted,
18 squashAtomCommandFailure,
19 } from "@t3tools/client-runtime/state/runtime";
20 import * as Haptics from "expo-haptics";
21 import { useNavigation } from "@react-navigation/native";
22 import { T, useGT, useMessages, Var } from "gt-react-native";
23 import { m } from "../../i18n/messages";
24 import { useRef, useState, type ReactNode } from "react";
25 import { sanitizeNewRefName } from "@t3tools/shared/git";
26 import { Platform, Pressable, ScrollView, View } from "react-native";
27 import { useSafeAreaInsets } from "react-native-safe-area-context";
28
29 import { AppBar } from "../../components/ui/AppBar";
30 import { ScreenContent } from "../../components/ui/ScreenContent";
31 import { SymbolView } from "../../components/ui/AppSymbol";
32 import { AppText as Text } from "../../components/ui/AppText";
33 import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
34 import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
35 import { cn } from "../../lib/cn";
36 import { useEnvironmentScope } from "../../state/session";
37 import { useAtomCommand } from "../../state/use-atom-command";
38 import { vcsEnvironment } from "../../state/vcs";
39 import { useSearchToolbarInset } from "../../components/ui/useBarInset";
40 import type { AppBarSearch } from "../../components/ui/AppBar";
41 import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
42 import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
43 import { filterNewTaskBranches } from "./new-task-context-presentation";
44 import { useDebouncedValue, usePaginatedBranches } from "../../state/queries";
45 import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
46
47 import { useEnvironmentPresentation } from "../../state/presentation";
48 import { useRemoteConnections } from "../../state/use-remote-environment-registry";
49 import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
50 import {
51 ConnectionDiagnosisDetails,
52 useConnectionDiagnosis,
53 } from "../connection/ConnectionDiagnosisDetails";
54 import { environmentStatusText } from "../connection/environmentStatusText";
55
56 const BRANCH_SEARCH_DEBOUNCE_MS = 150;
57
58 function EnvironmentPickerRow(props: {
59 environmentId: EnvironmentId;
60 title: string;
61 selected: boolean;
62 disabled: boolean;
63 isLast: boolean;
64 onPress: () => void;
65 }) {
66 const gt = useGT();
67 const messages = useMessages();
68 const [expanded, setExpanded] = useState(false);
69 const { presentation } = useEnvironmentPresentation(props.environmentId);
70 const { diagnosis, state } = useConnectionDiagnosis(props.environmentId, presentation);
71 const { onReconnectEnvironment } = useRemoteConnections();
72 const connection = presentation?.connection;
73 const status =
74 diagnosis?.headline ??
75 (connection ? environmentStatusText({ ...connection, error: null }, messages) : gt("Offline"));
76 return (
77 <View className={cn("bg-grouped-card", !props.isLast && "border-b border-border-subtle")}>
78 <View className="flex-row items-center">
79 <Pressable
80 accessibilityRole="radio"
81 accessibilityLabel={`${props.title}, ${status}`}
82 accessibilityState={{ checked: props.selected }}
83 disabled={props.disabled}
84 onPress={props.onPress}
85 className="min-h-16 flex-1 flex-row items-center gap-3 px-4 py-3 active:bg-subtle"
86 >
87 <EnvironmentMachineSymbol
88 kind={resolveEnvironmentMachineKind(presentation?.serverConfig ?? null)}
89 size={20}
90 tintColorClassName="accent-icon-muted"
91 />
92 <View className="min-w-0 flex-1 gap-1">
93 <Text className="text-base font-t3-medium text-foreground" numberOfLines={1}>
94 {props.title}
95 </Text>
96 <View className="flex-row items-center gap-1.5">
97 <ConnectionStatusDot state={connection?.phase ?? "offline"} pulse={false} size={6} />
98 <Text className="shrink text-xs text-foreground-muted" numberOfLines={2}>
99 {status}
100 </Text>
101 </View>
102 </View>
103 {props.selected ? (
104 <SymbolView name="checkmark" size={16} tintColorClassName="accent-icon" />
105 ) : null}
106 </Pressable>
107 <Pressable
108 accessibilityRole="button"
109 accessibilityLabel={
110 expanded
111 ? gt("Hide connection details for {title}", { title: props.title })
112 : gt("Show connection details for {title}", { title: props.title })
113 }
114 accessibilityState={{ expanded }}
115 onPress={() => setExpanded(!expanded)}
116 className="min-h-11 min-w-11 items-center justify-center active:opacity-65"
117 >
118 <SymbolView
119 name={expanded ? "chevron.up" : "chevron.down"}
120 size={13}
121 tintColorClassName="accent-icon-muted"
122 />
123 </Pressable>
124 </View>
125 {expanded ? (
126 <View className="gap-3 px-4 pb-4">
127 {diagnosis ? (
128 <ConnectionDiagnosisDetails hostLabel={props.title} diagnosis={diagnosis} />
129 ) : (
130 <Text className="text-sm text-foreground-muted">{status}</Text>
131 )}
132 {state.retryAt ? (
133 <Text className="text-sm text-foreground-muted">
134 <T>
135 Next reconnect at <Var>{new Date(state.retryAt).toLocaleTimeString()}</Var>
136 </T>
137 </Text>
138 ) : null}
139 {connection?.phase !== "connected" ? (
140 <Button
141 label={gt("Reconnect now")}
142 onPress={() => onReconnectEnvironment(props.environmentId)}
143 />
144 ) : null}
145 </View>
146 ) : null}
147 </View>
148 );
149 }
150
151 function ToggleRow(props: {
152 readonly title: string;
153 readonly value: boolean;
154 readonly onValueChange: (value: boolean) => void;
155 }) {
156 return (
157 <View className="min-h-14 flex-row items-center gap-3 bg-grouped-card px-4 py-3">
158 <Text
159 className={cn(
160 "min-w-0 flex-1 text-base text-foreground",
161 Platform.OS !== "android" && "font-t3-medium",
162 )}
163 numberOfLines={1}
164 >
165 {props.title}
166 </Text>
167 <ThemedSwitch
168 accessibilityLabel={props.title}
169 onValueChange={props.onValueChange}
170 value={props.value}
171 />
172 </View>
173 );
174 }
175
176 function PickerSurface(props: { readonly children: ReactNode }) {
177 return (
178 <View
179 className={
180 Platform.OS === "android"
181 ? "overflow-hidden rounded-[28px] bg-grouped-card"
182 : "overflow-hidden rounded-2xl bg-grouped-card"
183 }
184 >
185 {props.children}
186 </View>
187 );
188 }
189
190 export function NewTaskEnvironmentPickerRouteScreen() {
191 const gt = useGT();
192 const flow = useNewTaskFlow();
193 const navigation = useNavigation();
194 const insets = useSafeAreaInsets();
195 return (
196 <View className="flex-1 bg-sheet" collapsable={false}>
197 <AppBar title={gt("Environment")} hideBottomBorder onBack={() => navigation.goBack()} />
198 <ScreenContent>
199 <ScrollView
200 contentInsetAdjustmentBehavior="automatic"
201 contentContainerStyle={{
202 paddingBottom: Math.max(insets.bottom, 16) + 16,
203 paddingHorizontal: 16,
204 paddingTop: 16,
205 }}
206 showsVerticalScrollIndicator={false}
207 >
208 <PickerSurface>
209 {flow.environments.map((environment, index) => (
210 <EnvironmentPickerRow
211 key={String(environment.environmentId)}
212 environmentId={environment.environmentId}
213 isLast={index === flow.environments.length - 1}
214 disabled={flow.switchingToEnvironmentId !== null}
215 onPress={() => {
216 void Haptics.selectionAsync();
217 void flow.switchEnvironment(environment.environmentId).then((switched) => {
218 if (switched) navigation.goBack();
219 });
220 }}
221 selected={flow.selectedEnvironmentId === environment.environmentId}
222 title={environment.environmentLabel}
223 />
224 ))}
225 </PickerSurface>
226 </ScrollView>
227 </ScreenContent>
228 </View>
229 );
230 }
231
232 export function NewTaskBranchPickerRouteScreen() {
233 const gt = useGT();
234 const flow = useNewTaskFlow();
235 const canWriteSourceControl = useEnvironmentScope(
236 flow.selectedProject?.environmentId ?? null,
237 AuthSourceControlWriteScope,
238 );
239 const navigation = useNavigation();
240 const readRefs = useAtomCommand(vcsEnvironment.readRefs, { reportFailure: false });
241 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
242 const [switchingBranchName, setSwitchingBranchName] = useState<string | null>(null);
243 const selectingBranchNameRef = useRef<string | null>(null);
244 const [branchQuery, setBranchQuery] = useState("");
245 const branchSearchQuery = sanitizeNewRefName(branchQuery);
246 const debouncedBranchQuery = useDebouncedValue(branchSearchQuery, BRANCH_SEARCH_DEBOUNCE_MS);
247 const branchState = usePaginatedBranches({
248 environmentId: flow.selectedProject?.environmentId ?? null,
249 cwd: flow.selectedProject?.workspaceRoot || null,
250 query: debouncedBranchQuery,
251 });
252 const branchesLoading =
253 branchSearchQuery !== debouncedBranchQuery ||
254 (branchState.isPending && branchState.data === null);
255 const refreshBranches = () => {
256 if (!flow.selectedProject) return;
257 setPendingConnectionError(null);
258 branchState.refresh();
259 };
260
261 const selectBranch = async (branch: VcsRef) => {
262 const needsCheckout = shouldCheckoutNewTaskBranch({
263 branchIsCurrent: branch.current,
264 branchWorktreePath: branch.worktreePath,
265 workspaceMode: flow.workspaceMode,
266 });
267 if (selectingBranchNameRef.current !== null || (needsCheckout && !canWriteSourceControl)) {
268 return;
269 }
270 selectingBranchNameRef.current = branch.name;
271 void Haptics.selectionAsync();
272
273 const project = flow.selectedProject;
274 if (!project) {
275 selectingBranchNameRef.current = null;
276 return;
277 }
278 setSwitchingBranchName(branch.name);
279 // The guard belongs to this checkout: back actions are refused while it is
280 // in flight, and our own goBack runs after it is lifted.
281 const releaseRemovalGuard = navigation.addListener("beforeRemove", (event) => {
282 event.preventDefault();
283 });
284 const result = await checkoutNewTaskBranch({
285 branch,
286 project,
287 workspaceMode: flow.workspaceMode,
288 readRefs,
289 switchRef,
290 }).finally(releaseRemovalGuard);
291 setSwitchingBranchName(null);
292 if (result._tag === "Failure") {
293 selectingBranchNameRef.current = null;
294 if (navigation.isFocused() && !isAtomCommandInterrupted(result)) {
295 const error = squashAtomCommandFailure(result);
296 Dialog.alert(
297 gt("Could not switch branch"),
298 errorDisplayMessage(error, m) ?? gt("The branch could not be checked out."),
299 );
300 }
301 return;
302 }
303
304 // Checkout already changed Git; persist the draft selection even if the sheet dismissed mid-command.
305 flow.selectBranch(result.value);
306 if (!navigation.isFocused()) {
307 selectingBranchNameRef.current = null;
308 return;
309 }
310 navigation.goBack();
311 selectingBranchNameRef.current = null;
312 };
313
314 return (
315 <BranchPickerScreen
316 title={flow.workspaceMode === "worktree" ? gt("Base branch") : gt("Branch")}
317 project={flow.selectedProject}
318 branches={filterNewTaskBranches(branchState.refs, branchQuery)}
319 selectedBranchName={
320 flow.selectedBranchName ??
321 flow.availableBranches.find((branch) => branch.current)?.name ??
322 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
323 null
324 }
325 query={branchQuery}
326 onQueryChange={setBranchQuery}
327 loading={branchesLoading}
328 error={branchState.error}
329 refreshing={branchState.isFetchingNextPage}
330 hasMore={branchState.data?.nextCursor !== null && branchState.data?.nextCursor !== undefined}
331 onRefresh={refreshBranches}
332 onLoadMore={branchState.loadNext}
333 selectionDisabled={switchingBranchName !== null}
334 onSelect={selectBranch}
335 worktree={
336 flow.workspaceMode === "worktree"
337 ? {
338 startFromOrigin: flow.startFromOrigin,
339 onChangeStartFromOrigin: flow.setStartFromOrigin,
340 }
341 : undefined
342 }
343 />
344 );
345 }
346
347 export function BranchPickerScreen(props: {
348 readonly title: string;
349 readonly project: EnvironmentProject | null;
350 readonly branches: readonly VcsRef[];
351 readonly selectedBranchName: string | null;
352 readonly query: string;
353 readonly onQueryChange: (query: string) => void;
354 readonly loading: boolean;
355 readonly error: string | null;
356 readonly refreshing: boolean;
357 readonly hasMore: boolean;
358 readonly onRefresh: () => void;
359 readonly onLoadMore: () => void;
360 readonly selectionDisabled?: boolean;
361 readonly onSelect: (branch: VcsRef) => void;
362 readonly worktree?: {
363 readonly startFromOrigin: boolean;
364 readonly onChangeStartFromOrigin: (value: boolean) => void;
365 };
366 }) {
367 const gt = useGT();
368 const m = useMessages();
369 const navigation = useNavigation();
370 const insets = useSafeAreaInsets();
371 const search: AppBarSearch = {
372 value: props.query,
373 onChangeText: props.onQueryChange,
374 placeholder: gt("Find a branch"),
375 clearAccessibilityLabel: gt("Clear branch search"),
376 mode: "inline",
377 compactToolbar: true,
378 };
379 const searchToolbarInset = useSearchToolbarInset(search);
380 const selectedBranchName =
381 props.selectedBranchName ??
382 props.branches.find((branch) => branch.current)?.name ??
383 props.branches.find((branch) => branch.isDefault)?.name ??
384 null;
385 const branchListContentStyle = {
386 paddingBottom: searchToolbarInset
387 ? searchToolbarInset + 16
388 : Platform.OS === "ios"
389 ? 16
390 : Math.max(insets.bottom, 16) + 16,
391 paddingHorizontal: 16,
392 paddingTop: 16,
393 };
394
395 const renderBranch = ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
396 <SelectionRow
397 icon="arrow.triangle.branch"
398 disabled={props.selectionDisabled ?? false}
399 isFirst={index === 0}
400 isLast={index === props.branches.length - 1}
401 onPress={() => props.onSelect(item)}
402 selected={selectedBranchName === item.name}
403 subtitle={branchBadgeLabel({ branch: item, project: props.project }, m)?.toUpperCase()}
404 title={item.name}
405 />
406 );
407
408 const branchListHeader = props.worktree ? (
409 <View
410 className={cn(
411 "mb-3 overflow-hidden",
412 Platform.OS === "android" ? "rounded-[28px]" : "rounded-2xl",
413 )}
414 >
415 <ToggleRow
416 onValueChange={props.worktree.onChangeStartFromOrigin}
417 title={gt("Start from remote")}
418 value={props.worktree.startFromOrigin}
419 />
420 </View>
421 ) : null;
422
423 const branchContent =
424 props.branches.length === 0 ? (
425 <ScrollView
426 className="flex-1 bg-sheet android:bg-sheet-solid"
427 contentInsetAdjustmentBehavior="automatic"
428 contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 16, paddingTop: 16 }}
429 scrollEnabled={false}
430 showsVerticalScrollIndicator={false}
431 >
432 {branchListHeader}
433 <View
434 className="flex-1 items-center justify-center gap-3 px-4"
435 style={{
436 marginBottom: searchToolbarInset,
437 }}
438 >
439 {props.loading ? <AppActivityIndicator /> : null}
440 <Text className="text-center text-sm text-foreground-muted">
441 {props.loading
442 ? gt("Loading branches…")
443 : props.error
444 ? props.error
445 : props.query
446 ? gt("No matching branches")
447 : gt("No branches available")}
448 </Text>
449 {!props.loading && props.error ? (
450 <View className="self-center">
451 <Button label={gt("Try again")} tone="secondary" onPress={props.onRefresh} />
452 </View>
453 ) : null}
454 </View>
455 </ScrollView>
456 ) : (
457 <LegendList
458 renderScrollComponent={NativeScrollView}
459 alwaysBounceVertical={false}
460 automaticallyAdjustsScrollIndicatorInsets
461 automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
462 className="flex-1 bg-sheet android:bg-sheet-solid"
463 contentInsetAdjustmentBehavior="automatic"
464 contentContainerStyle={branchListContentStyle}
465 data={props.branches}
466 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
467 keyboardShouldPersistTaps="handled"
468 keyExtractor={(branch) =>
469 `${branch.remoteName ?? "local"}:${branch.name}:${branch.worktreePath ?? ""}`
470 }
471 ListHeaderComponent={branchListHeader}
472 ListFooterComponent={
473 props.refreshing ? (
474 <View className="items-center py-4">
475 <AppActivityIndicator />
476 </View>
477 ) : null
478 }
479 onEndReached={props.hasMore ? props.onLoadMore : undefined}
480 onEndReachedThreshold={0.35}
481 renderItem={renderBranch}
482 showsVerticalScrollIndicator={false}
483 />
484 );
485
486 return (
487 <View className="flex-1 bg-sheet" collapsable={false}>
488 <AppBar
489 title={props.title}
490 hideBottomBorder
491 onBack={() => navigation.goBack()}
492 search={search}
493 />
494 <ScreenContent>{branchContent}</ScreenContent>
495 </View>
496 );
497 }