Open History to see the last commit
1import {
2 type GitActionRequestInput,
3 buildMenuItems,
4 getGitActionDisabledReason,
5 requiresDefaultBranchConfirmation,
6} from "@t3tools/client-runtime/state/vcs";
7import {
8 resolveThreadPullRequestChains,
9 threadPullRequestKeyOf,
10} from "@t3tools/shared/threadPullRequests";
11import { EnvironmentId, ThreadId } from "@t3tools/contracts";
12import {
13 CommonActions,
14 StackActions,
15 useNavigation,
16 type StaticScreenProps,
17} from "@react-navigation/native";
18import { SymbolView } from "../../../components/AppSymbol";
19import { useCallback, useEffect, useMemo, useState } from "react";
20import { Alert, Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
21
22import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
23import { useSafeAreaInsets } from "react-native-safe-area-context";
24import { useUniwindTheme } from "../../../lib/useUniwindTheme";
25import {
26 AndroidHeaderIconButton,
27 AndroidSheetHeader,
28} from "../../../components/AndroidScreenHeader";
29import { AndroidAnchoredMenu } from "../../../components/AndroidAnchoredMenu";
30import { MaterialScreenContent } from "../../../components/MaterialScreenContent";
31import { useAdaptiveWorkspaceLayout } from "../../layout/AdaptiveWorkspaceLayout";
32import { AppText as Text } from "../../../components/AppText";
33import {
34 NativeStackScreenOptions,
35 nativeHeaderScrollEdgeEffects,
36} from "../../../native/StackHeader";
37import { tryOpenExternalUrl } from "../../../lib/openExternalUrl";
38import { useEnvironmentQuery } from "../../../state/query";
39import { useThreadSelection } from "../../../state/use-thread-selection";
40import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
41import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
42import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
43import { vcsEnvironment } from "../../../state/vcs";
44import { resolveGitOverviewReviewNavigationAction } from "./git-overview-navigation";
45import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents";
46
47const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
48
49type GitOverviewSheetProps = StaticScreenProps<{
50 readonly environmentId: string;
51 readonly threadId: string;
52}> & {
53 readonly headerInset?: number;
54 readonly presentation?: "sheet" | "inspector";
55};
56
57export function GitOverviewSheet(props: GitOverviewSheetProps) {
58 const { layout } = useAdaptiveWorkspaceLayout();
59 const navigation = useNavigation();
60 const insets = useSafeAreaInsets();
61 const presentation = props.presentation ?? "sheet";
62 const isInspector = presentation === "inspector";
63 const environmentId = EnvironmentId.make(props.route.params.environmentId);
64 const threadId = ThreadId.make(props.route.params.threadId);
65 const { selectedThread, selectedEnvironmentRuntime } = useThreadSelection();
66 const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree();
67 const supportsLinkedPrSnapshots =
68 selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.threadPullRequests === true;
69 const linkedPrChains = useMemo(
70 () =>
71 resolveThreadPullRequestChains(
72 supportsLinkedPrSnapshots ? (selectedThread?.pullRequests ?? []) : [],
73 ),
74 [selectedThread?.pullRequests, supportsLinkedPrSnapshots],
75 );
76 const gitState = useSelectedThreadGitState();
77 const gitActions = useSelectedThreadGitActions();
78 const theme = useUniwindTheme();
79 const foregroundColor = theme["--color-foreground"];
80 const sheetColor = theme["--color-sheet"];
81
82 const gitStatus = useEnvironmentQuery(
83 selectedThread !== null && selectedThreadCwd !== null
84 ? vcsEnvironment.status({
85 environmentId: selectedThread.environmentId,
86 input: { cwd: selectedThreadCwd },
87 })
88 : null,
89 );
90
91 const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD";
92 const currentStatusSummary = statusSummary(gitStatus.data);
93 const currentWorktreePath = selectedThreadWorktreePath;
94 const gitOperationLabel = gitState.gitOperationLabel;
95 const busy = gitOperationLabel !== null;
96 const isRepo = gitStatus.data?.isRepo ?? true;
97 const hasPrimaryRemote = gitStatus.data?.hasPrimaryRemote ?? false;
98 const isDefaultRef = gitStatus.data?.isDefaultRef ?? false;
99
100 const menuItems = useMemo(
101 () => (isRepo ? buildMenuItems(gitStatus.data, busy, hasPrimaryRemote) : []),
102 [busy, gitStatus.data, hasPrimaryRemote, isRepo],
103 );
104
105 const sheetMenuItems = useMemo(
106 () =>
107 menuItems.map((item) => ({
108 item,
109 disabledReason: getGitActionDisabledReason({
110 item,
111 gitStatus: gitStatus.data,
112 isBusy: busy,
113 hasOriginRemote: hasPrimaryRemote,
114 }),
115 })),
116 [busy, gitStatus.data, hasPrimaryRemote, menuItems],
117 );
118
119 useEffect(() => {
120 void gitActions.refreshSelectedThreadGitStatus({ quiet: true });
121 }, [gitActions]);
122
123 const openExistingPr = useCallback(async () => {
124 const prUrl = gitStatus.data?.pr?.state === "open" ? gitStatus.data.pr.url : null;
125 if (!prUrl) {
126 Alert.alert("No open PR", "This branch does not have an open pull request.");
127 return;
128 }
129 if (!(await tryOpenExternalUrl(prUrl, "pull-request"))) {
130 Alert.alert("Unable to open PR", "The pull request could not be opened.");
131 }
132 }, [gitStatus.data]);
133
134 const runActionWithPrompt = useCallback(
135 async (input: GitActionRequestInput) => {
136 const confirmableAction =
137 input.action === "push" ||
138 input.action === "create_pr" ||
139 input.action === "commit_push" ||
140 input.action === "commit_push_pr"
141 ? input.action
142 : null;
143 const branchName = gitStatus.data?.refName;
144 if (
145 branchName &&
146 confirmableAction &&
147 !input.featureBranch &&
148 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
149 ) {
150 navigation.navigate("GitConfirm", {
151 environmentId: String(environmentId),
152 threadId: String(threadId),
153 confirmAction: confirmableAction,
154 branchName,
155 includesCommit: String(
156 input.action === "commit_push" || input.action === "commit_push_pr",
157 ),
158 });
159 return;
160 }
161
162 if (!isInspector) {
163 navigation.goBack();
164 }
165 await gitActions.onRunSelectedThreadGitAction(input);
166 },
167 [environmentId, gitActions, gitStatus.data, isDefaultRef, isInspector, navigation, threadId],
168 );
169
170 const onPressMenuItem = useCallback(
171 async (item: (typeof menuItems)[number]) => {
172 if (item.disabled) return;
173 if (item.kind === "open_pr") {
174 await openExistingPr();
175 return;
176 }
177 if (item.dialogAction === "commit") {
178 navigation.navigate("GitCommit", {
179 environmentId: String(environmentId),
180 threadId: String(threadId),
181 });
182 return;
183 }
184 if (item.dialogAction === "push") {
185 await runActionWithPrompt({ action: "push" });
186 return;
187 }
188 if (item.dialogAction === "create_pr") {
189 await runActionWithPrompt({ action: "create_pr" });
190 }
191 },
192 [environmentId, openExistingPr, navigation, runActionWithPrompt, threadId],
193 );
194
195 // Status facts live on the relevant rows instead of crowding the header
196 // subtitle: files changed → Commit, ahead → Push, PR → View PR, behind → Pull.
197 const rowStatusDetail = useCallback(
198 (item: (typeof menuItems)[number]): string | undefined => {
199 const status = gitStatus.data;
200 if (status == null) {
201 return undefined;
202 }
203 if (item.dialogAction === "commit" && status.hasWorkingTreeChanges) {
204 const fileCount = status.workingTree?.files.length ?? 0;
205 return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`;
206 }
207 if (item.dialogAction === "push" && (status.aheadCount ?? 0) > 0) {
208 const ahead = status.aheadCount ?? 0;
209 return `${ahead} commit${ahead === 1 ? "" : "s"} ahead`;
210 }
211 if (item.kind === "open_pr" && status.pr?.number != null) {
212 return `PR #${status.pr.number} ${status.pr.state ?? "open"}`;
213 }
214 return undefined;
215 },
216 [gitStatus.data, menuItems],
217 );
218
219 const behindCount = gitStatus.data?.behindCount ?? 0;
220
221 // Deterministic pull-to-refresh state. Tying RefreshControl to the query's
222 // isPending flag left the spinner stuck (the status query reports pending
223 // during quiet background refreshes too).
224 const [isPullRefreshing, setIsPullRefreshing] = useState(false);
225 const handlePullRefresh = useCallback(async () => {
226 setIsPullRefreshing(true);
227 try {
228 await gitActions.refreshSelectedThreadGitStatus();
229 } finally {
230 setIsPullRefreshing(false);
231 }
232 }, [gitActions]);
233
234 const content = (
235 <ScrollView
236 alwaysBounceVertical
237 className="flex-1 android:bg-sheet-solid ios:bg-screen"
238 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
239 showsVerticalScrollIndicator={false}
240 contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
241 contentContainerStyle={{
242 paddingHorizontal: Platform.OS === "android" ? 8 : isInspector ? 12 : 20,
243 paddingTop: 8,
244 gap: Platform.OS === "android" ? 8 : 14,
245 }}
246 refreshControl={
247 <RefreshControl refreshing={isPullRefreshing} onRefresh={() => void handlePullRefresh()} />
248 }
249 >
250 <View
251 className={`overflow-hidden bg-card android:rounded-[20px] ios:border ios:border-border ${
252 isInspector ? "ios:rounded-2xl ios:px-3 ios:py-1" : "ios:rounded-[22px] ios:px-4 ios:py-1"
253 }`}
254 >
255 {sheetMenuItems.map(({ item, disabledReason }, index) => (
256 <View key={`${item.id}-${item.label}`}>
257 {index > 0 && Platform.OS !== "android" ? (
258 <View className="ml-12 h-px bg-border" />
259 ) : null}
260 <SheetListRow
261 icon={menuItemIconName(item.icon)}
262 title={item.label}
263 subtitle={disabledReason ?? rowStatusDetail(item)}
264 disabled={item.disabled}
265 onPress={() => void onPressMenuItem(item)}
266 />
267 </View>
268 ))}
269 {behindCount > 0 ? (
270 <>
271 {Platform.OS !== "android" ? <View className="ml-12 h-px bg-border" /> : null}
272 <SheetListRow
273 icon="arrow.down.circle"
274 title="Pull latest"
275 subtitle={`${behindCount} commit${behindCount === 1 ? "" : "s"} behind upstream`}
276 disabled={busy || !isRepo}
277 onPress={() => void gitActions.onPullSelectedThreadBranch()}
278 />
279 </>
280 ) : null}
281 {Platform.OS !== "android" ? <View className="ml-12 h-px bg-border" /> : null}
282 <SheetListRow
283 icon="text.bubble"
284 title="Review changes"
285 subtitle="Inspect turn diffs, worktree changes, and base branch diff"
286 disabled={busy || !isRepo}
287 onPress={() => {
288 const params = { environmentId, threadId };
289 navigation.dispatch(
290 resolveGitOverviewReviewNavigationAction(presentation) === "replace"
291 ? StackActions.replace("ThreadReview", params)
292 : CommonActions.navigate("ThreadReview", params),
293 );
294 }}
295 />
296 {Platform.OS !== "android" ? <View className="ml-12 h-px bg-border" /> : null}
297 <SheetListRow
298 icon="point.topleft.down.curvedto.point.bottomright.up"
299 title="Branches & worktrees"
300 subtitle="Switch branch, create branch, or move to a worktree"
301 disabled={busy || !isRepo}
302 onPress={() =>
303 navigation.navigate("GitBranches", {
304 environmentId: String(environmentId),
305 threadId: String(threadId),
306 })
307 }
308 />
309 </View>
310
311 {linkedPrChains.length > 0 ? (
312 <View className="gap-2">
313 <Text className="px-1 text-xs font-t3-bold text-foreground-muted">
314 Linked pull requests
315 </Text>
316 {linkedPrChains.map((chain) => (
317 <View
318 key={threadPullRequestKeyOf(chain.layers[0]!)}
319 className="overflow-hidden bg-card android:rounded-[20px] ios:rounded-2xl ios:border ios:border-border ios:px-3 ios:py-1"
320 >
321 {chain.layers.length > 1 ? (
322 <View className="flex-row items-center gap-2 px-1 pt-2 pb-1">
323 <SymbolView
324 name="square.3.layers.3d"
325 size={14}
326 tintColorClassName="accent-foreground-muted"
327 />
328 <Text className="text-xs text-foreground-muted">
329 {chain.kind === "native" ? "Stack" : "Branch stack"} · {chain.layers.length} PRs
330 · bottom to top
331 </Text>
332 </View>
333 ) : null}
334 {chain.layers.map((link, index) => (
335 <View key={threadPullRequestKeyOf(link)}>
336 {index > 0 && Platform.OS !== "android" ? (
337 <View className="ml-12 h-px bg-border" />
338 ) : null}
339 <SheetListRow
340 icon="arrow.triangle.pull"
341 title={`#${link.number} ${link.snapshot?.title ?? "Pull request"}`}
342 subtitle={`${link.repository} · ${link.snapshot === null ? "Status pending" : link.snapshot.isDraft && link.snapshot.state === "open" ? "Draft" : link.snapshot.state}`}
343 onPress={() => {
344 void tryOpenExternalUrl(link.url, "pull-request").then((opened) => {
345 if (!opened)
346 Alert.alert("Unable to open PR", "The pull request could not be opened.");
347 });
348 }}
349 />
350 </View>
351 ))}
352 </View>
353 ))}
354 </View>
355 ) : null}
356
357 {currentWorktreePath ? <MetaCard label="Worktree" value={currentWorktreePath} /> : null}
358 </ScrollView>
359 );
360
361 if (isInspector && Platform.OS === "ios") {
362 return (
363 <View collapsable={false} className="flex-1 border-l border-border bg-sheet">
364 <ScreenStack style={{ flex: 1 }}>
365 <Screen
366 activityState={2}
367 enabled
368 isNativeStack
369 screenId="thread-git-inspector-native"
370 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
371 style={{ backgroundColor: sheetColor, flex: 1 }}
372 >
373 {content}
374 <ScreenStackHeaderConfig
375 backgroundColor="rgba(0,0,0,0)"
376 color={foregroundColor}
377 hideBackButton
378 hideShadow={false}
379 navigationItemStyle="editor"
380 title={currentBranchLabel}
381 titleColor={foregroundColor}
382 titleFontSize={17}
383 titleFontWeight="700"
384 translucent
385 />
386 </Screen>
387 </ScreenStack>
388 </View>
389 );
390 }
391
392 if (Platform.OS === "ios") {
393 // Compact form sheet: a plain screen presented as formSheet never renders a
394 // stack header, so — like the Settings sheet — the header must come from a
395 // nested native stack INSIDE the sheet. This reuses the exact structure of the
396 // inspector branch below: branch as the title, status summary as the native
397 // subtitle, and content that owns pull-to-refresh.
398 return (
399 <View collapsable={false} className="flex-1 bg-sheet">
400 <ScreenStack style={{ flex: 1 }}>
401 <Screen
402 activityState={2}
403 enabled
404 isNativeStack
405 screenId="thread-git-sheet-native"
406 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
407 style={{ backgroundColor: sheetColor, flex: 1 }}
408 >
409 {content}
410 <ScreenStackHeaderConfig
411 backgroundColor="rgba(0,0,0,0)"
412 color={foregroundColor}
413 hideBackButton
414 hideShadow={false}
415 navigationItemStyle="editor"
416 title={currentBranchLabel}
417 titleColor={foregroundColor}
418 titleFontSize={18}
419 titleFontWeight="800"
420 translucent
421 />
422 </Screen>
423 </ScreenStack>
424 </View>
425 );
426 }
427
428 const refreshMenu = (
429 <AndroidAnchoredMenu
430 title="Repository options"
431 actions={[
432 {
433 id: "refresh",
434 title: "Refresh repository status",
435 attributes: { disabled: busy || isPullRefreshing },
436 },
437 ]}
438 onPressAction={({ nativeEvent }) => {
439 if (nativeEvent.event === "refresh") void handlePullRefresh();
440 }}
441 >
442 {(open) => (
443 <AndroidHeaderIconButton
444 accessibilityLabel="Repository options"
445 icon="ellipsis"
446 onPress={open}
447 />
448 )}
449 </AndroidAnchoredMenu>
450 );
451
452 return (
453 <View
454 collapsable={false}
455 className={
456 Platform.OS === "android"
457 ? "flex-1 bg-header"
458 : isInspector
459 ? "flex-1 border-l border-border bg-sheet"
460 : "flex-1 bg-sheet"
461 }
462 >
463 {!isInspector ? (
464 <NativeStackScreenOptions
465 options={{ sheetCornerRadius: Platform.OS === "android" ? 28 : undefined }}
466 />
467 ) : null}
468 {isInspector ? (
469 <View
470 style={{
471 minHeight: props.headerInset ?? 0,
472 paddingTop: props.headerInset ?? 0,
473 }}
474 />
475 ) : null}
476
477 {isInspector ? (
478 <View className="gap-1 px-4 pb-4 pt-3 android:bg-header ios:border-b ios:border-border">
479 {Platform.OS === "android" ? (
480 <View className="absolute right-3 top-4 z-[1]">{refreshMenu}</View>
481 ) : (
482 <Pressable
483 className={
484 busy
485 ? "absolute right-3 top-4 z-[1] h-9 w-9 items-center justify-center rounded-full bg-subtle opacity-[0.45]"
486 : "absolute right-3 top-4 z-[1] h-9 w-9 items-center justify-center rounded-full bg-subtle"
487 }
488 disabled={busy}
489 onPress={() => void gitActions.refreshSelectedThreadGitStatus()}
490 >
491 <SymbolView
492 name="arrow.clockwise"
493 size={16}
494 tintColorClassName="accent-icon"
495 type="monochrome"
496 weight="medium"
497 />
498 </Pressable>
499 )}
500 <Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
501 Repository
502 </Text>
503 <Text className="pr-10 text-xl font-t3-bold">{currentBranchLabel}</Text>
504 <Text className="text-foreground-secondary text-sm font-medium leading-normal">
505 {currentStatusSummary}
506 </Text>
507 </View>
508 ) : (
509 <AndroidSheetHeader
510 title={currentBranchLabel}
511 hideBottomBorder={Platform.OS === "android"}
512 subtitle={currentStatusSummary}
513 onBack={() => navigation.goBack()}
514 trailing={Platform.OS === "android" ? refreshMenu : undefined}
515 actions={
516 Platform.OS === "android"
517 ? undefined
518 : [
519 {
520 accessibilityLabel: "Refresh repository status",
521 disabled: busy,
522 icon: "arrow.clockwise",
523 onPress: () => void gitActions.refreshSelectedThreadGitStatus(),
524 },
525 ]
526 }
527 />
528 )}
529
530 <MaterialScreenContent insetHorizontal={layout.usesSplitView}>
531 {content}
532 </MaterialScreenContent>
533 </View>
534 );
535}