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