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