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";
32
33import { AppText as Text } from "../../components/AppText";
34import { SymbolView } from "../../components/AppSymbol";
35import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
36import { MaterialScreenContent } from "../../components/MaterialScreenContent";
37import { cn } from "../../lib/cn";
38import { environmentCatalog } from "../../connection/catalog";
39import { useEnvironmentPresentation } from "../../state/presentation";
40import { useAtomCommand } from "../../state/use-atom-command";
41import { useUniwindTheme } from "../../lib/useUniwindTheme";
42import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
43import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
44import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
45import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
46import {
47 useAdaptiveWorkspaceLayout,
48 useAdaptiveWorkspacePaneRole,
49 useRegisterWorkspaceInspector,
50} from "../layout/AdaptiveWorkspaceLayout";
51import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
52import { useReviewCacheForThread } from "./reviewState";
53import {
54 isNativeReviewDiffDrawEvent,
55 type NativeReviewDiffViewHandle,
56 resolveNativeReviewDiffView,
57} from "../diffs/nativeReviewDiffSurface";
58import { NATIVE_REVIEW_DIFF_CONTENT_WIDTH } from "./nativeReviewDiffAdapter";
59import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
60import { useReviewDiffData } from "./useReviewDiffData";
61import { useReviewDiffPrewarming } from "./useReviewDiffPrewarming";
62import { useReviewFileVisibility } from "./reviewFileVisibility";
63import { useReviewSections } from "./useReviewSections";
64import { useNativeReviewDiffBridge } from "./useNativeReviewDiffBridge";
65import { useReviewCommentSelectionController } from "./useReviewCommentSelectionController";
66import { resolveReviewAvailability } from "./reviewAvailability";
67import { resolveSelectedReviewFileId } from "./reviewPaneSelection";
68import { buildReviewSectionMenu } from "./review-section-menu";
69import { reportShowcaseSceneRendered } from "../showcase/showcaseRenderSignal";
70
71function ReviewHeader(
72 props: Parameters<typeof useReviewHeaderPresentation>[0] & {
73 readonly iconColor: string;
74 readonly sectionMenu: ReturnType<typeof buildReviewSectionMenu>;
75 readonly showSectionToolbar: boolean;
76 readonly showChangedFilesToggle: boolean;
77 readonly onSelectSection: (sectionId: string) => void;
78 readonly onReturnToThread: () => void;
79 },
80) {
81 const { panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
82 const presentation = useReviewHeaderPresentation(props);
83 const sectionAction = (
84 section: ReviewSectionItem | null,
85 title: string,
86 ): ScreenHeaderMenuItem => ({
87 id: section ? `section:${section.id}` : `unavailable:${title}`,
88 title,
89 disabled: section === null,
90 selected: section !== null && section.id === props.selectedSection?.id,
91 onPress: () => {
92 if (section) props.onSelectSection(section.id);
93 },
94 });
95 return (
96 <ScreenHeader
97 title={presentation.title}
98 subtitle={presentation.subtitle}
99 onBack={props.onReturnToThread}
100 hideBottomBorder
101 options={{ headerTintColor: props.iconColor, headerTitle: props.title }}
102 backInSplitView={{ accessibilityLabel: "Back to chat", icon: "chevron.left" }}
103 actions={
104 props.showChangedFilesToggle
105 ? [
106 {
107 accessibilityLabel: panes.auxiliaryPaneVisible
108 ? "Hide changed files"
109 : "Show changed files",
110 icon: "sidebar.right",
111 selected: panes.auxiliaryPaneVisible,
112 onPress: toggleAuxiliaryPane,
113 },
114 ]
115 : undefined
116 }
117 menus={[
118 ...(presentation.gitMenu ? [presentation.gitMenu] : []),
119 ...(props.showSectionToolbar
120 ? [
121 {
122 title: "Select diff",
123 icon: presentation.menuIcon,
124 items: [
125 {
126 id: "sections",
127 inline: true,
128 items: [
129 sectionAction(props.sectionMenu.workingTree, "Working tree"),
130 sectionAction(props.sectionMenu.branchChanges, "Branch changes"),
131 sectionAction(props.sectionMenu.latestTurn, "Latest turn"),
132 ],
133 },
134 ...(props.sectionMenu.turns.length > 0
135 ? [
136 {
137 id: "turns",
138 title: "Turn",
139 items: props.sectionMenu.turns.map((section) => ({
140 id: `section:${section.id}`,
141 title: section.title,
142 subtitle: section.subtitle ?? undefined,
143 selected: section.id === props.selectedSection?.id,
144 onPress: () => props.onSelectSection(section.id),
145 })),
146 },
147 ]
148 : []),
149 ...(presentation.refreshAction ? [presentation.refreshAction] : []),
150 ],
151 },
152 ]
153 : []),
154 ]}
155 />
156 );
157}
158
159const REVIEW_HEADER_SPACING = 0;
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 // With a solid (non-overlay) header the content lays out below the header
465 // natively, so no manual top inset is needed. (Android renders its own
466 // in-flow AndroidScreenHeader, so it needs no inset either.)
467 const topContentInset = 0;
468
469 useEffect(() => {
470 showAuxiliaryPane("inspector");
471 }, [environmentId, showAuxiliaryPane, threadId]);
472 const {
473 error,
474 reviewSections,
475 selectedSection,
476 refreshSelectedSection,
477 selectSection,
478 isSelectedSectionPending,
479 diffPreviewRevision,
480 } = useReviewSections({
481 enabled: isEnvironmentReady,
482 environmentId,
483 threadId,
484 reviewCache,
485 });
486 useReviewDiffPrewarming({
487 threadKey: reviewCache.threadKey,
488 sections: reviewSections,
489 selectedSectionId: selectedSection?.id ?? null,
490 });
491 const {
492 headerDiffSummary,
493 nativeReviewDiffData,
494 parsedDiff,
495 pendingReviewCommentCount,
496 loadVisibleFile,
497 isPending: areFilePatchesPending,
498 } = useReviewDiffData({
499 threadKey: reviewCache.threadKey,
500 environmentId,
501 cwd: selectedThreadCwd,
502 selectedSection,
503 revision: diffPreviewRevision,
504 draftMessage,
505 });
506 // Resolution returns null while Expo registers the native view (or forever
507 // when the binary lacks it). Rendering a null component type crashes the
508 // app, so callers must fall back — ThreadFeed's ReviewCommentCard does the
509 // same check.
510 const NativeReviewDiffView = resolveNativeReviewDiffView();
511 const nativeReviewDiffViewRef = useRef<NativeReviewDiffViewHandle>(null);
512 const showcasedReviewDrawRef = useRef<string | null>(null);
513 // Native pull-to-refresh on the diff surface (replaces the old Refresh menu item).
514 const [isPullRefreshing, setIsPullRefreshing] = useState(false);
515 const handlePullToRefresh = useCallback(async () => {
516 setIsPullRefreshing(true);
517 try {
518 await refreshSelectedSection();
519 } finally {
520 setIsPullRefreshing(false);
521 }
522 }, [refreshSelectedSection]);
523 const reviewFileNavigatorRef = useRef<ReviewFileNavigatorHandle>(null);
524 const reviewFiles = parsedDiff.kind === "files" ? parsedDiff.files : [];
525 const fileVisibility = useReviewFileVisibility({
526 threadKey: reviewCache.threadKey,
527 sectionId: selectedSection?.id ?? null,
528 files: reviewFiles,
529 cachedExpandedFileIds: selectedSection?.id
530 ? reviewCache.expandedFileIdsBySection[selectedSection.id]
531 : undefined,
532 cachedViewedFileIds: selectedSection?.id
533 ? reviewCache.viewedFileIdsBySection[selectedSection.id]
534 : undefined,
535 });
536 const { collapsedFileIds, toggleExpandedFile, toggleViewedFile, viewedFileIds } = fileVisibility;
537 const commentSelection = useReviewCommentSelectionController({
538 environmentId,
539 threadId,
540 selectedSection,
541 nativeReviewDiffData,
542 });
543 const nativeBridge = useNativeReviewDiffBridge({
544 threadKey: reviewCache.threadKey,
545 sectionId: selectedSection?.id ?? null,
546 diff: selectedSection?.diff,
547 data: nativeReviewDiffData,
548 collapsedFileIds,
549 viewedFileIds,
550 selectedRowIds: commentSelection.selectedRowIds,
551 canHighlight: parsedDiff.kind === "files",
552 });
553 const showcaseReviewKey =
554 SHOWCASE_ENABLED && parsedDiff.kind === "files" && selectedSection
555 ? `${reviewCache.threadKey}:${selectedSection.id}:${nativeBridge.tokensResetKey}:${nativeBridge.themeId}`
556 : null;
557 const handleNativeDebug = useCallback(
558 (event: NativeSyntheticEvent<Record<string, unknown>>) => {
559 nativeBridge.onDebug(event);
560 if (
561 showcaseReviewKey === null ||
562 showcasedReviewDrawRef.current === showcaseReviewKey ||
563 !isNativeReviewDiffDrawEvent(event.nativeEvent)
564 ) {
565 return;
566 }
567 showcasedReviewDrawRef.current = showcaseReviewKey;
568 reportShowcaseSceneRendered({ scene: "review", themeId: nativeBridge.themeId });
569 },
570 [nativeBridge.onDebug, nativeBridge.themeId, showcaseReviewKey],
571 );
572
573 const handleSelectFile = useCallback(
574 (fileId: string | null) => {
575 loadVisibleFile(fileId, true);
576 commentSelection.clearSelection();
577 if (fileId !== null && collapsedFileIds.includes(fileId)) {
578 toggleExpandedFile(fileId);
579 }
580 const navigation =
581 fileId === null
582 ? nativeReviewDiffViewRef.current?.scrollToTop(true)
583 : nativeReviewDiffViewRef.current?.scrollToFile(fileId, true);
584 void navigation?.catch((error: unknown) => {
585 console.error("[review] Failed to navigate to diff file", error);
586 });
587 },
588 [collapsedFileIds, commentSelection, toggleExpandedFile, loadVisibleFile],
589 );
590 const handleVisibleFileChange = useCallback(
591 (event: NativeSyntheticEvent<{ readonly fileId?: string | null }>) => {
592 loadVisibleFile(event.nativeEvent.fileId ?? null);
593 reviewFileNavigatorRef.current?.setVisibleFile(event.nativeEvent.fileId ?? null);
594 },
595 [loadVisibleFile],
596 );
597 const renderInspector = useCallback(
598 () => (
599 <ReviewFileNavigator
600 ref={reviewFileNavigatorRef}
601 files={nativeReviewDiffData.files}
602 // The workspace inspector column spans the full window height, so the
603 // pane clears the status bar itself.
604 headerInset={insets.top}
605 sectionId={selectedSection?.id ?? null}
606 onSelectFile={handleSelectFile}
607 />
608 ),
609 [handleSelectFile, insets.top, nativeReviewDiffData.files, selectedSection?.id],
610 );
611
612 const handleNativeToggleFile = useCallback(
613 (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
614 const { fileId } = event.nativeEvent;
615 if (fileId) {
616 loadVisibleFile(fileId, true);
617 toggleExpandedFile(fileId);
618 }
619 },
620 [toggleExpandedFile, loadVisibleFile],
621 );
622
623 const handleNativeToggleViewedFile = useCallback(
624 (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
625 const { fileId } = event.nativeEvent;
626 if (fileId) {
627 toggleViewedFile(fileId);
628 }
629 },
630 [toggleViewedFile],
631 );
632
633 const parsedDiffNotice =
634 parsedDiff.kind === "files" || parsedDiff.kind === "raw" ? parsedDiff.notice : null;
635 const hasCachedSelectedDiff = selectedSection?.diff != null;
636 const hasAnyCachedDiff = reviewSections.some((section) => section.diff != null);
637 const sectionMenu = useMemo(() => buildReviewSectionMenu(reviewSections), [reviewSections]);
638 const { showConnectionNotice, showSectionToolbar } = resolveReviewAvailability({
639 hasEnvironmentPresentation: environment.isReady,
640 isEnvironmentConnected: isEnvironmentReady,
641 hasCachedSelectedDiff,
642 hasAnyCachedDiff,
643 });
644 const handleRetryEnvironment = useCallback(() => {
645 void retryEnvironment(environmentId);
646 }, [environmentId, retryEnvironment]);
647 const handleReturnToThread = useCallback(() => {
648 if (navigation.canGoBack()) {
649 navigation.goBack();
650 return;
651 }
652 navigation.navigate("Thread", {
653 environmentId: String(environmentId),
654 threadId: String(threadId),
655 });
656 }, [environmentId, navigation, threadId]);
657 const androidHeaderSubtitle = [
658 selectedSection?.title,
659 headerDiffSummary.additions,
660 headerDiffSummary.deletions,
661 ]
662 .filter((part): part is string => Boolean(part))
663 .join(" · ");
664
665 // The changed-files navigator drives the native diff surface via
666 // scrollToFile, so it is only useful when that surface resolved. In raw
667 // fallback mode the ref is necessarily null and the raw patch neither
668 // scrolls nor filters — registering the navigator would present working
669 // controls that cannot navigate.
670 const showChangedFilesPane =
671 !showConnectionNotice &&
672 selectedSection !== null &&
673 parsedDiff.kind === "files" &&
674 NativeReviewDiffView !== null;
675 useRegisterWorkspaceInspector(showChangedFilesPane ? renderInspector : undefined);
676 // A toggle needs registered content; loading, errors and raw patches have no navigator pane.
677 const showChangedFilesToggle = panes.supportsAuxiliaryPane && showChangedFilesPane;
678
679 const listHeader = useMemo(() => {
680 const children: ReactElement[] = [];
681
682 if (error) {
683 children.push(
684 <View
685 key="review-error"
686 className={cn(
687 "bg-card px-4 py-3",
688 Platform.OS === "android" ? "m-2 rounded-[20px]" : "border-b border-border",
689 )}
690 >
691 <Text className="text-sm font-t3-bold text-foreground">Review unavailable</Text>
692 <Text className="text-xs leading-normal text-foreground-muted">{error}</Text>
693 </View>,
694 );
695 }
696
697 if (parsedDiffNotice) {
698 children.push(<ReviewNotice key="review-notice" notice={parsedDiffNotice} />);
699 }
700
701 if (children.length === 0) {
702 return null;
703 }
704
705 return <>{children}</>;
706 }, [error, parsedDiffNotice]);
707 const headerSubtitle = [
708 headerDiffSummary.additions,
709 headerDiffSummary.deletions,
710 pendingReviewCommentCount > 0
711 ? `${pendingReviewCommentCount} comment${pendingReviewCommentCount === 1 ? "" : "s"}`
712 : null,
713 ]
714 .filter(Boolean)
715 .join(" · ");
716 const headerTitleText = selectedSection?.title ?? "Review changes";
717
718 return (
719 <>
720 <ReviewHeader
721 environmentId={environmentId}
722 threadId={threadId}
723 title={headerTitleText}
724 subtitle={headerSubtitle}
725 androidSubtitle={androidHeaderSubtitle}
726 iconColor={headerIcon}
727 selectedThreadCwd={selectedThreadCwd}
728 sectionMenu={sectionMenu}
729 selectedSection={selectedSection}
730 showSectionToolbar={showSectionToolbar}
731 showChangedFilesToggle={showChangedFilesToggle}
732 onRefresh={handlePullToRefresh}
733 onSelectSection={selectSection}
734 onReturnToThread={handleReturnToThread}
735 />
736
737 <MaterialScreenContent>
738 <View className="flex-1 bg-sheet android:bg-sheet-solid">
739 {showConnectionNotice ? (
740 <View className="flex-1" style={{ paddingTop: topContentInset }}>
741 <EnvironmentConnectionNotice
742 environmentLabel={environment.presentation?.entry.target.label ?? "Environment"}
743 connection={
744 environment.presentation?.connection ?? {
745 phase: "available",
746 error: null,
747 traceId: null,
748 }
749 }
750 resourceName="review"
751 onRetry={handleRetryEnvironment}
752 />
753 </View>
754 ) : selectedSection && parsedDiff.kind === "files" && NativeReviewDiffView ? (
755 <View
756 className="flex-1"
757 style={{
758 backgroundColor: nativeBridge.theme.background,
759 }}
760 >
761 <View
762 className="min-w-0 flex-1"
763 style={{ paddingTop: topContentInset + REVIEW_HEADER_SPACING }}
764 >
765 {listHeader}
766 <View className="min-w-0 flex-1" collapsable={false}>
767 <NativeReviewDiffView
768 collapsable={false}
769 testID="review-native-diff-view"
770 refreshing={
771 isPullRefreshing || isSelectedSectionPending || areFilePatchesPending
772 }
773 onPullToRefresh={() => void handlePullToRefresh()}
774 style={StyleSheet.absoluteFill}
775 appearanceScheme={selectedTheme}
776 collapsedFileIdsJson={nativeBridge.collapsedFileIdsJson}
777 collapsedCommentIdsJson={nativeBridge.collapsedCommentIdsJson}
778 contentResetKey={`${reviewCache.threadKey}:${selectedSection.id}`}
779 contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
780 nativeViewRef={nativeReviewDiffViewRef}
781 rowHeight={nativeReviewDiffStyle.rowHeight}
782 rowsJson={nativeBridge.rowsJson}
783 selectedRowIdsJson={nativeBridge.selectedRowIdsJson}
784 styleJson={nativeBridge.styleJson}
785 themeJson={nativeBridge.themeJson}
786 tokensPatchJson={nativeBridge.tokensPatchJson}
787 tokensResetKey={nativeBridge.tokensResetKey}
788 viewedFileIdsJson={nativeBridge.viewedFileIdsJson}
789 onDebug={handleNativeDebug}
790 onPressLine={commentSelection.onPressLine}
791 onVisibleFileChange={handleVisibleFileChange}
792 onToggleComment={nativeBridge.onToggleComment}
793 onToggleFile={handleNativeToggleFile}
794 onToggleViewedFile={handleNativeToggleViewedFile}
795 />
796 </View>
797 </View>
798 </View>
799 ) : (
800 <ScrollView
801 contentContainerStyle={
802 Platform.OS === "android" && (parsedDiff.kind === "empty" || !selectedSection)
803 ? { flexGrow: 1, justifyContent: "center" }
804 : undefined
805 }
806 contentInsetAdjustmentBehavior="never"
807 contentInset={{ top: topContentInset, bottom: Math.max(insets.bottom, 18) + 18 }}
808 contentOffset={{ x: 0, y: -topContentInset }}
809 scrollIndicatorInsets={{
810 top: topContentInset,
811 bottom: Math.max(insets.bottom, 18) + 18,
812 }}
813 showsVerticalScrollIndicator={false}
814 className="flex-1"
815 refreshControl={
816 // The native diff surface owns pull-to-refresh via onPullToRefresh;
817 // the raw fallback (and empty states) need an explicit control —
818 // iOS has no other refresh affordance here (the explicit
819 // "Refresh current diff" menu is Android-only).
820 <RefreshControl
821 refreshing={isPullRefreshing || isSelectedSectionPending || areFilePatchesPending}
822 onRefresh={() => void handlePullToRefresh()}
823 />
824 }
825 >
826 {listHeader}
827 {!selectedSection ? (
828 <View
829 className={
830 Platform.OS === "android"
831 ? "items-center px-6 py-5"
832 : "border-b border-border bg-card px-4 py-5"
833 }
834 >
835 <Text className="text-sm font-t3-bold text-foreground">No review diffs</Text>
836 <Text
837 className={cn(
838 "text-xs leading-normal text-foreground-muted",
839 Platform.OS === "android" && "mt-2 text-center",
840 )}
841 >
842 This thread has no ready turn diffs and the worktree diff is empty.
843 </Text>
844 </View>
845 ) : selectedSection.isLoading && selectedSection.diff === null ? (
846 <View
847 className={cn(
848 "items-center gap-3 px-4 py-6",
849 Platform.OS !== "android" && "border-b border-border bg-card",
850 )}
851 >
852 <ActivityIndicator size="small" />
853 <Text className="text-xs text-foreground-muted">Loading diff…</Text>
854 </View>
855 ) : parsedDiff.kind === "empty" ? (
856 <View
857 className={
858 Platform.OS === "android"
859 ? "items-center px-6 py-5"
860 : "border-b border-border bg-card px-4 py-5"
861 }
862 >
863 <Text className="text-sm font-t3-bold text-foreground">No changes</Text>
864 <Text
865 className={cn(
866 "text-xs leading-normal text-foreground-muted",
867 Platform.OS === "android" && "mt-2 text-center",
868 )}
869 >
870 {selectedSection.subtitle ?? "This diff is empty."}
871 </Text>
872 </View>
873 ) : parsedDiff.kind === "raw" ? (
874 <View
875 className={cn(
876 "gap-3 bg-card px-4 py-4",
877 Platform.OS === "android" ? "m-2 rounded-[20px]" : "border-b border-border",
878 )}
879 >
880 <Text className="text-xs leading-normal text-foreground-muted">
881 {parsedDiff.reason}
882 </Text>
883 <ScrollView horizontal showsHorizontalScrollIndicator={false} bounces={false}>
884 <Text selectable className="font-mono text-xs leading-relaxed text-foreground">
885 {parsedDiff.text}
886 </Text>
887 </ScrollView>
888 </View>
889 ) : parsedDiff.kind === "files" ? (
890 // The native diff surface could not be resolved on this binary;
891 // degrade to the raw patch instead of crashing the app.
892 <View
893 className={cn(
894 "gap-3 bg-card px-4 py-4",
895 Platform.OS === "android" ? "m-2 rounded-[20px]" : "border-b border-border",
896 )}
897 >
898 <Text className="text-xs leading-normal text-foreground-muted">
899 Native diff view unavailable. Showing the raw patch.
900 </Text>
901 <ScrollView horizontal showsHorizontalScrollIndicator={false} bounces={false}>
902 <Text selectable className="font-mono text-xs leading-relaxed text-foreground">
903 {selectedSection?.diff ?? ""}
904 </Text>
905 </ScrollView>
906 </View>
907 ) : null}
908 </ScrollView>
909 )}
910 <ReviewSelectionActionBar
911 bottomInset={insets.bottom}
912 title={commentSelection.selectionAction?.title ?? null}
913 onOpenComment={commentSelection.selectionAction?.onOpenComment ?? null}
914 onClear={commentSelection.clearSelection}
915 />
916 </View>
917 </MaterialScreenContent>
918 </>
919 );
920}