Open History to see the last commit
1import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2import { AsyncResult } from "effect/reactivity";
3import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
4import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
5import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
6import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
7import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
8import { AppBar } from "../../components/ui/AppBar";
9import type { AppBarMenuItem } from "../../components/ui/AppBar.types";
10import type { ReviewSectionItem } from "./reviewModel";
11import { useReviewHeaderPresentation } from "./useReviewHeaderPresentation";
12import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
13import {
14 type Ref,
15 type ReactElement,
16 useEffect,
17 useImperativeHandle,
18 useRef,
19 useState,
20} from "react";
21import {
22 FlatList,
23 Platform,
24 Pressable,
25 RefreshControl,
26 ScrollView,
27 type NativeSyntheticEvent,
28 StyleSheet,
29 View,
30} from "react-native";
31import { useSafeAreaInsets } from "react-native-safe-area-context";
32import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
33import { NativeInspectorContent } from "../../native/NativeInspectorContent";
34
35import { AppText as Text } from "../../components/ui/AppText";
36import { SymbolView } from "../../components/ui/AppSymbol";
37import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";
38import { ScreenContent } from "../../components/ui/ScreenContent";
39import { cn } from "../../lib/cn";
40import { environmentCatalog } from "../../connection/catalog";
41import { useEnvironmentPresentation } from "../../state/presentation";
42import { useAtomCommand } from "../../state/use-atom-command";
43import { useUniwindTheme } from "../../lib/useUniwindTheme";
44import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
45import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
46import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
47import {
48 useAdaptiveWorkspaceLayout,
49 useAdaptiveWorkspacePaneRole,
50 useRegisterWorkspaceInspector,
51} from "../layout/AdaptiveWorkspaceLayout";
52import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
53import { useReviewCacheForThread } from "./reviewState";
54import {
55 isNativeReviewDiffDrawEvent,
56 type NativeReviewDiffViewHandle,
57 resolveNativeReviewDiffView,
58} from "../diffs/nativeReviewDiffSurface";
59import { NATIVE_REVIEW_DIFF_CONTENT_WIDTH } from "./nativeReviewDiffAdapter";
60import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
61import { useReviewDiffData } from "./useReviewDiffData";
62import { useReviewDiffPrewarming } from "./useReviewDiffPrewarming";
63import { useReviewFileVisibility } from "./reviewFileVisibility";
64import { useReviewSections } from "./useReviewSections";
65import { useNativeReviewDiffBridge } from "./useNativeReviewDiffBridge";
66import { useReviewCommentSelectionController } from "./useReviewCommentSelectionController";
67import { resolveReviewAvailability } from "./reviewAvailability";
68import { resolveSelectedReviewFileId } from "./reviewPaneSelection";
69import { buildReviewSectionMenu } from "./review-section-menu";
70import { reportShowcaseSceneRendered } from "../showcase/showcaseRenderSignal";
71
72function ReviewHeader(
73 props: Parameters<typeof useReviewHeaderPresentation>[0] & {
74 readonly iconColor: string;
75 readonly sectionMenu: ReturnType<typeof buildReviewSectionMenu>;
76 readonly showSectionToolbar: boolean;
77 readonly showChangedFilesToggle: boolean;
78 readonly onSelectSection: (sectionId: string) => void;
79 readonly onReturnToThread: () => void;
80 },
81) {
82 const { panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
83 const presentation = useReviewHeaderPresentation(props);
84 const sectionAction = (section: ReviewSectionItem | null, title: string): AppBarMenuItem => ({
85 id: section ? `section:${section.id}` : `unavailable:${title}`,
86 title,
87 disabled: section === null,
88 selected: section !== null && section.id === props.selectedSection?.id,
89 onPress: () => {
90 if (section) props.onSelectSection(section.id);
91 },
92 });
93 return (
94 <AppBar
95 title={presentation.title}
96 subtitle={presentation.subtitle}
97 onBack={props.onReturnToThread}
98 hideBottomBorder
99 options={{ headerTintColor: props.iconColor, headerTitle: props.title }}
100 backInSplitView={{ accessibilityLabel: "Back to chat", icon: "chevron.left" }}
101 actions={
102 props.showChangedFilesToggle
103 ? [
104 {
105 accessibilityLabel: panes.auxiliaryPaneVisible
106 ? "Hide changed files"
107 : "Show changed files",
108 icon: "sidebar.right",
109 selected: panes.auxiliaryPaneVisible,
110 onPress: toggleAuxiliaryPane,
111 },
112 ]
113 : undefined
114 }
115 menus={[
116 ...(presentation.gitMenu ? [presentation.gitMenu] : []),
117 ...(props.showSectionToolbar
118 ? [
119 {
120 title: "Select diff",
121 icon: presentation.menuIcon,
122 items: [
123 {
124 id: "sections",
125 inline: true,
126 items: [
127 sectionAction(props.sectionMenu.branchChanges, "Changes"),
128 sectionAction(props.sectionMenu.workingTree, "Uncommitted"),
129 sectionAction(props.sectionMenu.latestTurn, "Latest turn"),
130 ],
131 },
132 ...(props.sectionMenu.turns.length > 0
133 ? [
134 {
135 id: "turns",
136 title: "Turn",
137 items: props.sectionMenu.turns.map((section) => ({
138 id: `section:${section.id}`,
139 title: section.title,
140 subtitle: section.subtitle ?? undefined,
141 selected: section.id === props.selectedSection?.id,
142 onPress: () => props.onSelectSection(section.id),
143 })),
144 },
145 ]
146 : []),
147 ...(presentation.refreshAction ? [presentation.refreshAction] : []),
148 ],
149 },
150 ]
151 : []),
152 ]}
153 />
154 );
155}
156
157const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
158
159const ReviewNotice = function ReviewNotice(props: { readonly notice: string }) {
160 return (
161 <View
162 className={cn(
163 "bg-warning px-4 py-3",
164 Platform.OS === "android" ? "m-2 rounded-[20px]" : "border-b border-warning-border",
165 )}
166 >
167 <Text className="text-xs font-t3-bold uppercase text-warning-foreground">Partial diff</Text>
168 <Text className="text-xs leading-normal text-warning-foreground">{props.notice}</Text>
169 </View>
170 );
171};
172
173function ReviewSelectionActionBar(props: {
174 readonly bottomInset: number;
175 readonly title: string | null;
176 readonly onOpenComment: (() => void) | null;
177 readonly onClear: () => void;
178}) {
179 if (!props.title) {
180 return null;
181 }
182
183 const content = (
184 <>
185 <SymbolView
186 name={props.onOpenComment ? "text.bubble" : "line.3.horizontal.decrease.circle"}
187 size={16}
188 tintColorClassName="accent-primary-foreground"
189 type="monochrome"
190 />
191 <Text className="text-base font-t3-bold text-primary-foreground">{props.title}</Text>
192 </>
193 );
194
195 return (
196 <View
197 pointerEvents="box-none"
198 style={{
199 position: "absolute",
200 left: 18,
201 right: 18,
202 bottom: Math.max(props.bottomInset, 10) + 18,
203 flexDirection: "row",
204 justifyContent: "center",
205 gap: 10,
206 }}
207 >
208 {props.onOpenComment ? (
209 <Pressable
210 className="h-12 flex-1 flex-row items-center justify-center gap-2 rounded-full bg-primary px-5"
211 onPress={props.onOpenComment}
212 >
213 {content}
214 </Pressable>
215 ) : (
216 <View className="h-12 flex-1 flex-row items-center justify-center gap-2 rounded-full bg-primary px-5">
217 {content}
218 </View>
219 )}
220
221 <Pressable
222 className="h-12 w-12 items-center justify-center rounded-full bg-primary"
223 onPress={props.onClear}
224 >
225 <SymbolView
226 name="xmark"
227 size={16}
228 tintColorClassName="accent-primary-foreground"
229 type="monochrome"
230 />
231 </Pressable>
232 </View>
233 );
234}
235
236interface ReviewNavigatorFile {
237 readonly id: string;
238 readonly path: string;
239 readonly additions: number;
240 readonly deletions: number;
241}
242
243const ReviewFileNavigatorRow = function ReviewFileNavigatorRow(props: {
244 readonly file: ReviewNavigatorFile;
245 readonly selected: boolean;
246 readonly onSelectFile: (fileId: string | null) => void;
247}) {
248 const { file, selected, onSelectFile } = props;
249 const handlePress = () => {
250 onSelectFile(selected ? null : file.id);
251 };
252
253 return (
254 <Pressable
255 accessibilityRole="button"
256 accessibilityState={{ selected }}
257 className={
258 Platform.OS === "android"
259 ? cn(
260 "mt-1 min-h-12 justify-center rounded-[20px] px-3 py-2 active:bg-subtle",
261 selected && "bg-subtle-strong",
262 )
263 : selected
264 ? "mt-1 min-h-12 justify-center rounded-xl bg-subtle-strong px-3 py-2"
265 : "mt-1 min-h-12 justify-center rounded-xl px-3 py-2 active:bg-subtle"
266 }
267 onPress={handlePress}
268 >
269 <Text
270 className={
271 selected
272 ? "text-xs font-t3-bold text-foreground"
273 : "text-xs font-t3-medium text-foreground-secondary"
274 }
275 numberOfLines={2}
276 >
277 {file.path}
278 </Text>
279 <View className="mt-1 flex-row gap-2">
280 <Text className="text-2xs font-t3-bold text-adaptive-emerald-700-300">
281 +{formatDiffCount(file.additions)}
282 </Text>
283 <Text className="text-2xs font-t3-bold text-adaptive-rose-700-300">
284 -{formatDiffCount(file.deletions)}
285 </Text>
286 </View>
287 </Pressable>
288 );
289};
290
291interface ReviewFileNavigatorHandle {
292 readonly setVisibleFile: (fileId: string | null) => void;
293}
294
295interface ReviewFileNavigatorProps {
296 readonly files: ReadonlyArray<ReviewNavigatorFile>;
297 readonly headerInset: number;
298 readonly sectionId: string | null;
299 readonly onSelectFile: (fileId: string | null) => void;
300 readonly ref?: Ref<ReviewFileNavigatorHandle>;
301}
302
303function ReviewFileNavigator({
304 files,
305 headerInset,
306 sectionId,
307 onSelectFile,
308 ref,
309}: ReviewFileNavigatorProps) {
310 const theme = useUniwindTheme();
311 const sheetColor = theme["--color-sheet"];
312 const foregroundColor = theme["--color-foreground"];
313 const headerScrollEdgeEffects = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
314 const [fileSelection, setFileSelection] = useState<{
315 readonly sectionId: string | null;
316 readonly fileId: string | null;
317 }>({ sectionId: null, fileId: null });
318 const availableFileIds = files.map((file) => file.id);
319 const selectedFileId = resolveSelectedReviewFileId({
320 selection: fileSelection,
321 sectionId,
322 availableFileIds,
323 });
324
325 useImperativeHandle(
326 ref,
327 () => ({
328 setVisibleFile: (fileId) => {
329 if (fileId !== null && !availableFileIds.includes(fileId)) {
330 return;
331 }
332 setFileSelection((current) => {
333 if (current.sectionId === sectionId && current.fileId === fileId) {
334 return current;
335 }
336 return { sectionId, fileId };
337 });
338 },
339 }),
340 [availableFileIds, sectionId],
341 );
342
343 const handleSelectFile = (fileId: string | null) => {
344 setFileSelection({ sectionId, fileId });
345 onSelectFile(fileId);
346 };
347
348 const renderFile = ({ item }: { readonly item: ReviewNavigatorFile }) => (
349 <ReviewFileNavigatorRow
350 file={item}
351 selected={selectedFileId === item.id}
352 onSelectFile={handleSelectFile}
353 />
354 );
355
356 const fileList = (
357 <FlatList
358 data={files}
359 extraData={selectedFileId}
360 keyExtractor={(file) => file.id}
361 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
362 contentContainerStyle={{ paddingHorizontal: 8, paddingVertical: 8 }}
363 renderItem={renderFile}
364 />
365 );
366
367 if (Platform.OS === "ios") {
368 return (
369 <View className="flex-1 border-l border-border bg-sheet">
370 <ScreenStack style={{ flex: 1 }}>
371 <Screen
372 activityState={2}
373 enabled
374 isNativeStack
375 screenId="review-file-navigator-native"
376 scrollEdgeEffects={headerScrollEdgeEffects}
377 style={{ backgroundColor: sheetColor, flex: 1 }}
378 >
379 <NativeInspectorContent>{fileList}</NativeInspectorContent>
380 <ScreenStackHeaderConfig
381 backgroundColor="rgba(0,0,0,0)"
382 color={foregroundColor}
383 hideBackButton
384 hideShadow={false}
385 navigationItemStyle="editor"
386 subtitle={`${files.length} ${files.length === 1 ? "file" : "files"}`}
387 title="Changed files"
388 titleColor={foregroundColor}
389 titleFontSize={17}
390 titleFontWeight="700"
391 translucent
392 />
393 </Screen>
394 </ScreenStack>
395 </View>
396 );
397 }
398
399 return (
400 <View
401 className={
402 Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 border-l border-border bg-sheet"
403 }
404 >
405 {Platform.OS === "android" ? (
406 <AndroidScreenHeader
407 title="Changed files"
408 subtitle={`${files.length} ${files.length === 1 ? "file" : "files"}`}
409 hideBottomBorder
410 />
411 ) : (
412 <View className="border-b border-border" style={{ paddingTop: headerInset }}>
413 <View className="px-4 py-3">
414 <Text className="text-sm font-t3-bold text-foreground">Changed files</Text>
415 <Text className="text-xs text-foreground-muted">
416 {files.length} {files.length === 1 ? "file" : "files"}
417 </Text>
418 </View>
419 </View>
420 )}
421 <ScreenContent insetHorizontal>{fileList}</ScreenContent>
422 </View>
423 );
424}
425
426type ReviewSheetProps = StaticScreenProps<{
427 readonly environmentId: EnvironmentId;
428 readonly threadId: ThreadId;
429}>;
430
431export function ReviewSheet(props: ReviewSheetProps) {
432 const { nativeReviewDiffStyle } = useAppearanceCodeSurface();
433 useAdaptiveWorkspacePaneRole("inspector");
434 const { panes, showAuxiliaryPane } = useAdaptiveWorkspaceLayout();
435 const navigation = useNavigation();
436 const insets = useSafeAreaInsets();
437 const { themeAppearance: selectedTheme } = useAppearancePreferences();
438 const headerIcon = String(useUniwindTheme()["--color-icon"]);
439 const { environmentId, threadId } = props.route.params;
440 const environment = useEnvironmentPresentation(environmentId);
441 const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
442 const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
443 const { draftMessage } = useThreadDraftForThread({ environmentId, threadId });
444 const reviewCache = useReviewCacheForThread({ environmentId, threadId });
445 const { selectedThreadCwd } = useSelectedThreadWorktree();
446 const columnMetrics = useNativeColumnLayoutMetrics();
447 const safeArea = columnMetrics?.safeArea ?? insets;
448 const topContentInset = Platform.OS === "ios" ? safeArea.top : 0;
449 const bottomContentInset =
450 Platform.OS === "ios" ? safeArea.bottom + 8 : Math.max(insets.bottom, 18) + 18;
451
452 useEffect(() => {
453 showAuxiliaryPane("inspector");
454 }, [environmentId, showAuxiliaryPane, threadId]);
455 const {
456 error,
457 reviewSections,
458 selectedSection,
459 refreshSelectedSection,
460 selectSection,
461 isSelectedSectionPending,
462 diffPreviewRevision,
463 } = useReviewSections({
464 enabled: isEnvironmentReady,
465 environmentId,
466 threadId,
467 reviewCache,
468 });
469 useReviewDiffPrewarming({
470 threadKey: reviewCache.threadKey,
471 sections: reviewSections,
472 selectedSectionId: selectedSection?.id ?? null,
473 });
474 const {
475 headerDiffSummary,
476 nativeReviewDiffData,
477 parsedDiff,
478 pendingReviewCommentCount,
479 loadVisibleFile,
480 isPending: areFilePatchesPending,
481 } = useReviewDiffData({
482 threadKey: reviewCache.threadKey,
483 environmentId,
484 cwd: selectedThreadCwd,
485 selectedSection,
486 revision: diffPreviewRevision,
487 draftMessage,
488 });
489 // Resolution returns null while Expo registers the native view (or forever
490 // when the binary lacks it). Rendering a null component type crashes the
491 // app, so callers must fall back — ThreadFeed's ReviewCommentCard does the
492 // same check.
493 const NativeReviewDiffView = resolveNativeReviewDiffView();
494 const nativeReviewDiffViewRef = useRef<NativeReviewDiffViewHandle>(null);
495 const showcasedReviewDrawRef = useRef<string | null>(null);
496 const [isPullRefreshing, setIsPullRefreshing] = useState(false);
497 const handlePullToRefresh = async () => {
498 setIsPullRefreshing(true);
499 await refreshSelectedSection();
500 setIsPullRefreshing(false);
501 };
502 const reviewFileNavigatorRef = useRef<ReviewFileNavigatorHandle>(null);
503 const reviewFiles = parsedDiff.kind === "files" ? parsedDiff.files : [];
504 const fileVisibility = useReviewFileVisibility({
505 threadKey: reviewCache.threadKey,
506 sectionId: selectedSection?.id ?? null,
507 files: reviewFiles,
508 cachedExpandedFileIds: selectedSection?.id
509 ? reviewCache.expandedFileIdsBySection[selectedSection.id]
510 : undefined,
511 cachedViewedFileIds: selectedSection?.id
512 ? reviewCache.viewedFileIdsBySection[selectedSection.id]
513 : undefined,
514 });
515 const { collapsedFileIds, toggleExpandedFile, toggleViewedFile, viewedFileIds } = fileVisibility;
516 const commentSelection = useReviewCommentSelectionController({
517 environmentId,
518 threadId,
519 selectedSection,
520 nativeReviewDiffData,
521 });
522 const nativeBridge = useNativeReviewDiffBridge({
523 threadKey: reviewCache.threadKey,
524 sectionId: selectedSection?.id ?? null,
525 diff: selectedSection?.diff,
526 data: nativeReviewDiffData,
527 collapsedFileIds,
528 viewedFileIds,
529 selectedRowIds: commentSelection.selectedRowIds,
530 canHighlight: parsedDiff.kind === "files",
531 });
532 const showcaseReviewKey =
533 SHOWCASE_ENABLED && parsedDiff.kind === "files" && selectedSection
534 ? `${reviewCache.threadKey}:${selectedSection.id}:${nativeBridge.tokensResetKey}:${nativeBridge.themeId}`
535 : null;
536 const handleNativeDebug = (event: NativeSyntheticEvent<Record<string, unknown>>) => {
537 nativeBridge.onDebug(event);
538 if (
539 showcaseReviewKey === null ||
540 showcasedReviewDrawRef.current === showcaseReviewKey ||
541 !isNativeReviewDiffDrawEvent(event.nativeEvent)
542 ) {
543 return;
544 }
545 showcasedReviewDrawRef.current = showcaseReviewKey;
546 reportShowcaseSceneRendered({ scene: "review", themeId: nativeBridge.themeId });
547 };
548
549 const handleSelectFile = async (fileId: string | null) => {
550 loadVisibleFile(fileId, true);
551 commentSelection.clearSelection();
552 if (fileId !== null && collapsedFileIds.includes(fileId)) {
553 toggleExpandedFile(fileId);
554 }
555 const nativeView = nativeReviewDiffViewRef.current;
556 if (!nativeView) return;
557 const result = await settlePromise(() =>
558 fileId === null ? nativeView.scrollToTop(true) : nativeView.scrollToFile(fileId, true),
559 );
560 if (AsyncResult.isFailure(result)) {
561 console.error("[review] Failed to navigate to diff file", squashAtomCommandFailure(result));
562 }
563 };
564 const handleVisibleFileChange = (
565 event: NativeSyntheticEvent<{ readonly fileId?: string | null }>,
566 ) => {
567 loadVisibleFile(event.nativeEvent.fileId ?? null);
568 reviewFileNavigatorRef.current?.setVisibleFile(event.nativeEvent.fileId ?? null);
569 };
570 const renderInspector = () => (
571 <ReviewFileNavigator
572 ref={reviewFileNavigatorRef}
573 files={nativeReviewDiffData.files}
574 headerInset={insets.top}
575 sectionId={selectedSection?.id ?? null}
576 onSelectFile={(fileId) => void handleSelectFile(fileId)}
577 />
578 );
579
580 const handleNativeToggleFile = (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
581 const { fileId } = event.nativeEvent;
582 if (fileId) {
583 loadVisibleFile(fileId, true);
584 toggleExpandedFile(fileId);
585 }
586 };
587
588 const handleNativeToggleViewedFile = (
589 event: NativeSyntheticEvent<{ readonly fileId?: string }>,
590 ) => {
591 const { fileId } = event.nativeEvent;
592 if (fileId) {
593 toggleViewedFile(fileId);
594 }
595 };
596
597 const parsedDiffNotice =
598 parsedDiff.kind === "files" || parsedDiff.kind === "raw" ? parsedDiff.notice : null;
599 const hasCachedSelectedDiff = selectedSection?.diff != null;
600 const hasAnyCachedDiff = reviewSections.some((section) => section.diff != null);
601 const sectionMenu = buildReviewSectionMenu(reviewSections);
602 const { showConnectionNotice, showSectionToolbar } = resolveReviewAvailability({
603 hasEnvironmentPresentation: environment.isReady,
604 isEnvironmentConnected: isEnvironmentReady,
605 hasCachedSelectedDiff,
606 hasAnyCachedDiff,
607 });
608 const handleRetryEnvironment = () => {
609 void retryEnvironment(environmentId);
610 };
611 const handleReturnToThread = () => {
612 if (navigation.canGoBack()) {
613 navigation.goBack();
614 return;
615 }
616 navigation.navigate("Thread", {
617 environmentId: String(environmentId),
618 threadId: String(threadId),
619 });
620 };
621 const androidHeaderSubtitle = [
622 selectedSection?.title,
623 headerDiffSummary.additions,
624 headerDiffSummary.deletions,
625 ]
626 .filter((part): part is string => Boolean(part))
627 .join(" · ");
628
629 const showChangedFilesPane =
630 !showConnectionNotice &&
631 selectedSection !== null &&
632 parsedDiff.kind === "files" &&
633 NativeReviewDiffView !== null;
634 useRegisterWorkspaceInspector(showChangedFilesPane ? renderInspector : undefined);
635 const showChangedFilesToggle = panes.supportsAuxiliaryPane && showChangedFilesPane;
636
637 const listHeader = (() => {
638 const children: ReactElement[] = [];
639
640 if (error) {
641 children.push(
642 <View
643 key="review-error"
644 className={cn(
645 "bg-card px-4 py-3",
646 Platform.OS === "android" ? "m-2 rounded-[20px]" : "border-b border-border",
647 )}
648 >
649 <Text className="text-sm font-t3-bold text-foreground">Review unavailable</Text>
650 <Text className="text-xs leading-normal text-foreground-muted">{error}</Text>
651 </View>,
652 );
653 }
654
655 if (parsedDiffNotice) {
656 children.push(<ReviewNotice key="review-notice" notice={parsedDiffNotice} />);
657 }
658
659 if (children.length === 0) {
660 return null;
661 }
662
663 return <>{children}</>;
664 })();
665 const headerSubtitle = [
666 headerDiffSummary.additions,
667 headerDiffSummary.deletions,
668 pendingReviewCommentCount > 0
669 ? `${pendingReviewCommentCount} comment${pendingReviewCommentCount === 1 ? "" : "s"}`
670 : null,
671 ]
672 .filter(Boolean)
673 .join(" · ");
674 const headerTitleText = selectedSection?.title ?? "Review changes";
675
676 return (
677 <>
678 <ReviewHeader
679 environmentId={environmentId}
680 threadId={threadId}
681 title={headerTitleText}
682 subtitle={headerSubtitle}
683 androidSubtitle={androidHeaderSubtitle}
684 iconColor={headerIcon}
685 selectedThreadCwd={selectedThreadCwd}
686 sectionMenu={sectionMenu}
687 selectedSection={selectedSection}
688 showSectionToolbar={showSectionToolbar}
689 showChangedFilesToggle={showChangedFilesToggle}
690 onRefresh={handlePullToRefresh}
691 onSelectSection={selectSection}
692 onReturnToThread={handleReturnToThread}
693 />
694
695 <ScreenContent>
696 <View className="flex-1 bg-sheet android:bg-sheet-solid">
697 {showConnectionNotice ? (
698 <View className="flex-1" style={{ paddingTop: topContentInset }}>
699 <EnvironmentConnectionNotice
700 environmentLabel={environment.presentation?.entry.target.label ?? "Environment"}
701 connection={
702 environment.presentation?.connection ?? {
703 phase: "available",
704 error: null,
705 traceId: null,
706 }
707 }
708 resourceName="review"
709 onRetry={handleRetryEnvironment}
710 />
711 </View>
712 ) : selectedSection && parsedDiff.kind === "files" && NativeReviewDiffView ? (
713 <View
714 className="flex-1"
715 style={{
716 backgroundColor: nativeBridge.theme.background,
717 }}
718 >
719 <View
720 className="min-w-0 flex-1"
721 style={listHeader ? { paddingTop: topContentInset } : undefined}
722 >
723 {listHeader}
724 <View className="min-w-0 flex-1" collapsable={false}>
725 <NativeReviewDiffView
726 collapsable={false}
727 testID="review-native-diff-view"
728 refreshing={
729 isPullRefreshing || isSelectedSectionPending || areFilePatchesPending
730 }
731 onPullToRefresh={() => void handlePullToRefresh()}
732 style={StyleSheet.absoluteFill}
733 appearanceScheme={selectedTheme}
734 collapsedFileIdsJson={nativeBridge.collapsedFileIdsJson}
735 collapsedCommentIdsJson={nativeBridge.collapsedCommentIdsJson}
736 contentResetKey={`${reviewCache.threadKey}:${selectedSection.id}`}
737 contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
738 contentInsetTop={listHeader ? 0 : topContentInset}
739 contentInsetBottom={bottomContentInset}
740 nativeViewRef={nativeReviewDiffViewRef}
741 rowHeight={nativeReviewDiffStyle.rowHeight}
742 rowsJson={nativeBridge.rowsJson}
743 selectedRowIdsJson={nativeBridge.selectedRowIdsJson}
744 styleJson={nativeBridge.styleJson}
745 themeJson={nativeBridge.themeJson}
746 tokensPatchJson={nativeBridge.tokensPatchJson}
747 tokensResetKey={nativeBridge.tokensResetKey}
748 viewedFileIdsJson={nativeBridge.viewedFileIdsJson}
749 onDebug={handleNativeDebug}
750 onPressLine={commentSelection.onPressLine}
751 onVisibleFileChange={handleVisibleFileChange}
752 onToggleComment={nativeBridge.onToggleComment}
753 onToggleFile={handleNativeToggleFile}
754 onToggleViewedFile={handleNativeToggleViewedFile}
755 />
756 </View>
757 </View>
758 </View>
759 ) : (
760 <ScrollView
761 contentContainerStyle={
762 Platform.OS === "android" && (parsedDiff.kind === "empty" || !selectedSection)
763 ? { flexGrow: 1, justifyContent: "center" }
764 : undefined
765 }
766 contentInsetAdjustmentBehavior="never"
767 contentInset={{ top: topContentInset, bottom: bottomContentInset }}
768 contentOffset={{ x: 0, y: -topContentInset }}
769 automaticallyAdjustsScrollIndicatorInsets={false}
770 scrollIndicatorInsets={{ top: topContentInset, bottom: bottomContentInset }}
771 showsVerticalScrollIndicator={false}
772 className="flex-1"
773 refreshControl={
774 // The native diff surface owns pull-to-refresh via onPullToRefresh;
775 // the raw fallback (and empty states) need an explicit control —
776 // iOS has no other refresh affordance here (the explicit
777 // "Refresh current diff" menu is Android-only).
778 <RefreshControl
779 refreshing={isPullRefreshing || isSelectedSectionPending || areFilePatchesPending}
780 onRefresh={() => void handlePullToRefresh()}
781 />
782 }
783 >
784 {listHeader}
785 {!selectedSection ? (
786 error ? null : (
787 <View
788 className={
789 Platform.OS === "android"
790 ? "items-center px-6 py-5"
791 : "border-b border-border bg-card px-4 py-5"
792 }
793 >
794 <Text className="text-sm font-t3-bold text-foreground">No review diffs</Text>
795 <Text
796 className={cn(
797 "text-xs leading-normal text-foreground-muted",
798 Platform.OS === "android" && "mt-2 text-center",
799 )}
800 >
801 This thread has no ready turn diffs and the worktree diff is empty.
802 </Text>
803 </View>
804 )
805 ) : selectedSection.isLoading && selectedSection.diff === null ? (
806 <View
807 className={cn(
808 "items-center gap-3 px-4 py-6",
809 Platform.OS !== "android" && "border-b border-border bg-card",
810 )}
811 >
812 <AppActivityIndicator size="small" />
813 <Text className="text-xs text-foreground-muted">Loading diff…</Text>
814 </View>
815 ) : parsedDiff.kind === "empty" ? (
816 <View
817 className={
818 Platform.OS === "android"
819 ? "items-center px-6 py-5"
820 : "border-b border-border bg-card px-4 py-5"
821 }
822 >
823 <Text className="text-sm font-t3-bold text-foreground">No changes</Text>
824 <Text
825 className={cn(
826 "text-xs leading-normal text-foreground-muted",
827 Platform.OS === "android" && "mt-2 text-center",
828 )}
829 >
830 {selectedSection.subtitle ?? "This diff is empty."}
831 </Text>
832 </View>
833 ) : parsedDiff.kind === "raw" ? (
834 <View
835 className={cn(
836 "gap-3 bg-card px-4 py-4",
837 Platform.OS === "android" ? "m-2 rounded-[20px]" : "border-b border-border",
838 )}
839 >
840 <Text className="text-xs leading-normal text-foreground-muted">
841 {parsedDiff.reason}
842 </Text>
843 <ScrollView horizontal showsHorizontalScrollIndicator={false} bounces={false}>
844 <Text selectable className="font-mono text-xs leading-relaxed text-foreground">
845 {parsedDiff.text}
846 </Text>
847 </ScrollView>
848 </View>
849 ) : parsedDiff.kind === "files" ? (
850 <View
851 className={cn(
852 "gap-3 bg-card px-4 py-4",
853 Platform.OS === "android" ? "m-2 rounded-[20px]" : "border-b border-border",
854 )}
855 >
856 <Text className="text-xs leading-normal text-foreground-muted">
857 Native diff view unavailable. Showing the raw patch.
858 </Text>
859 <ScrollView horizontal showsHorizontalScrollIndicator={false} bounces={false}>
860 <Text selectable className="font-mono text-xs leading-relaxed text-foreground">
861 {selectedSection?.diff ?? ""}
862 </Text>
863 </ScrollView>
864 </View>
865 ) : null}
866 </ScrollView>
867 )}
868 <ReviewSelectionActionBar
869 bottomInset={insets.bottom}
870 title={commentSelection.selectionAction?.title ?? null}
871 onOpenComment={commentSelection.selectionAction?.onOpenComment ?? null}
872 onClear={commentSelection.clearSelection}
873 />
874 </View>
875 </ScreenContent>
876 </>
877 );
878}