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