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";
33
34import { AppText as Text } from "../../components/ui/AppText";
35import { SymbolView } from "../../components/ui/AppSymbol";
36import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";
37import { ScreenContent } from "../../components/ui/ScreenContent";
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 = (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 insets = useSafeAreaInsets();
311 const theme = useUniwindTheme();
312 const sheetColor = theme["--color-sheet"];
313 const foregroundColor = theme["--color-foreground"];
314 const headerScrollEdgeEffects = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
315 const [fileSelection, setFileSelection] = useState<{
316 readonly sectionId: string | null;
317 readonly fileId: string | null;
318 }>({ sectionId: null, fileId: null });
319 const availableFileIds = files.map((file) => file.id);
320 const selectedFileId = resolveSelectedReviewFileId({
321 selection: fileSelection,
322 sectionId,
323 availableFileIds,
324 });
325
326 useImperativeHandle(
327 ref,
328 () => ({
329 setVisibleFile: (fileId) => {
330 if (fileId !== null && !availableFileIds.includes(fileId)) {
331 return;
332 }
333 setFileSelection((current) => {
334 if (current.sectionId === sectionId && current.fileId === fileId) {
335 return current;
336 }
337 return { sectionId, fileId };
338 });
339 },
340 }),
341 [availableFileIds, sectionId],
342 );
343
344 const handleSelectFile = (fileId: string | null) => {
345 setFileSelection({ sectionId, fileId });
346 onSelectFile(fileId);
347 };
348
349 const renderFile = ({ item }: { readonly item: ReviewNavigatorFile }) => (
350 <ReviewFileNavigatorRow
351 file={item}
352 selected={selectedFileId === item.id}
353 onSelectFile={handleSelectFile}
354 />
355 );
356
357 const fileList = (
358 <FlatList
359 data={files}
360 extraData={selectedFileId}
361 keyExtractor={(file) => file.id}
362 contentContainerStyle={{
363 paddingHorizontal: 8,
364 paddingBottom: 8,
365
366 paddingTop: Platform.OS === "ios" ? insets.top + IOS_NAV_BAR_HEIGHT + 8 : 8,
367 }}
368 scrollIndicatorInsets={
369 Platform.OS === "ios" ? { top: insets.top + IOS_NAV_BAR_HEIGHT } : undefined
370 }
371 renderItem={renderFile}
372 />
373 );
374
375 if (Platform.OS === "ios") {
376 return (
377 <View className="flex-1 border-l border-border bg-sheet">
378 <ScreenStack style={{ flex: 1 }}>
379 <Screen
380 activityState={2}
381 enabled
382 isNativeStack
383 screenId="review-file-navigator-native"
384 scrollEdgeEffects={headerScrollEdgeEffects}
385 style={{ backgroundColor: sheetColor, flex: 1 }}
386 >
387 {fileList}
388 <ScreenStackHeaderConfig
389 backgroundColor="rgba(0,0,0,0)"
390 color={foregroundColor}
391 hideBackButton
392 hideShadow={false}
393 navigationItemStyle="editor"
394 subtitle={`${files.length} ${files.length === 1 ? "file" : "files"}`}
395 title="Changed files"
396 titleColor={foregroundColor}
397 titleFontSize={17}
398 titleFontWeight="700"
399 translucent
400 />
401 </Screen>
402 </ScreenStack>
403 </View>
404 );
405 }
406
407 return (
408 <View
409 className={
410 Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 border-l border-border bg-sheet"
411 }
412 >
413 {Platform.OS === "android" ? (
414 <AndroidScreenHeader
415 title="Changed files"
416 subtitle={`${files.length} ${files.length === 1 ? "file" : "files"}`}
417 hideBottomBorder
418 />
419 ) : (
420 <View className="border-b border-border" style={{ paddingTop: headerInset }}>
421 <View className="px-4 py-3">
422 <Text className="text-sm font-t3-bold text-foreground">Changed files</Text>
423 <Text className="text-xs text-foreground-muted">
424 {files.length} {files.length === 1 ? "file" : "files"}
425 </Text>
426 </View>
427 </View>
428 )}
429 <ScreenContent insetHorizontal>{fileList}</ScreenContent>
430 </View>
431 );
432}
433
434type ReviewSheetProps = StaticScreenProps<{
435 readonly environmentId: EnvironmentId;
436 readonly threadId: ThreadId;
437}>;
438
439export function ReviewSheet(props: ReviewSheetProps) {
440 const { nativeReviewDiffStyle } = useAppearanceCodeSurface();
441 useAdaptiveWorkspacePaneRole("inspector");
442 const { panes, showAuxiliaryPane } = useAdaptiveWorkspaceLayout();
443 const navigation = useNavigation();
444 const insets = useSafeAreaInsets();
445 const { themeAppearance: selectedTheme } = useAppearancePreferences();
446 const headerIcon = String(useUniwindTheme()["--color-icon"]);
447 const { environmentId, threadId } = props.route.params;
448 const environment = useEnvironmentPresentation(environmentId);
449 const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
450 const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
451 const { draftMessage } = useThreadDraftForThread({ environmentId, threadId });
452 const reviewCache = useReviewCacheForThread({ environmentId, threadId });
453 const { selectedThreadCwd } = useSelectedThreadWorktree();
454 const columnMetrics = useNativeColumnLayoutMetrics();
455 const safeArea = columnMetrics?.safeArea ?? insets;
456 const topContentInset = Platform.OS === "ios" ? safeArea.top : 0;
457 const bottomContentInset =
458 Platform.OS === "ios" ? safeArea.bottom + 8 : Math.max(insets.bottom, 18) + 18;
459
460 useEffect(() => {
461 showAuxiliaryPane("inspector");
462 }, [environmentId, showAuxiliaryPane, threadId]);
463 const {
464 error,
465 reviewSections,
466 selectedSection,
467 refreshSelectedSection,
468 selectSection,
469 isSelectedSectionPending,
470 diffPreviewRevision,
471 } = useReviewSections({
472 enabled: isEnvironmentReady,
473 environmentId,
474 threadId,
475 reviewCache,
476 });
477 useReviewDiffPrewarming({
478 threadKey: reviewCache.threadKey,
479 sections: reviewSections,
480 selectedSectionId: selectedSection?.id ?? null,
481 });
482 const {
483 headerDiffSummary,
484 nativeReviewDiffData,
485 parsedDiff,
486 pendingReviewCommentCount,
487 loadVisibleFile,
488 isPending: areFilePatchesPending,
489 } = useReviewDiffData({
490 threadKey: reviewCache.threadKey,
491 environmentId,
492 cwd: selectedThreadCwd,
493 selectedSection,
494 revision: diffPreviewRevision,
495 draftMessage,
496 });
497 // Resolution returns null while Expo registers the native view (or forever
498 // when the binary lacks it). Rendering a null component type crashes the
499 // app, so callers must fall back — ThreadFeed's ReviewCommentCard does the
500 // same check.
501 const NativeReviewDiffView = resolveNativeReviewDiffView();
502 const nativeReviewDiffViewRef = useRef<NativeReviewDiffViewHandle>(null);
503 const showcasedReviewDrawRef = useRef<string | null>(null);
504 const [isPullRefreshing, setIsPullRefreshing] = useState(false);
505 const handlePullToRefresh = async () => {
506 setIsPullRefreshing(true);
507 await refreshSelectedSection();
508 setIsPullRefreshing(false);
509 };
510 const reviewFileNavigatorRef = useRef<ReviewFileNavigatorHandle>(null);
511 const reviewFiles = parsedDiff.kind === "files" ? parsedDiff.files : [];
512 const fileVisibility = useReviewFileVisibility({
513 threadKey: reviewCache.threadKey,
514 sectionId: selectedSection?.id ?? null,
515 files: reviewFiles,
516 cachedExpandedFileIds: selectedSection?.id
517 ? reviewCache.expandedFileIdsBySection[selectedSection.id]
518 : undefined,
519 cachedViewedFileIds: selectedSection?.id
520 ? reviewCache.viewedFileIdsBySection[selectedSection.id]
521 : undefined,
522 });
523 const { collapsedFileIds, toggleExpandedFile, toggleViewedFile, viewedFileIds } = fileVisibility;
524 const commentSelection = useReviewCommentSelectionController({
525 environmentId,
526 threadId,
527 selectedSection,
528 nativeReviewDiffData,
529 });
530 const nativeBridge = useNativeReviewDiffBridge({
531 threadKey: reviewCache.threadKey,
532 sectionId: selectedSection?.id ?? null,
533 diff: selectedSection?.diff,
534 data: nativeReviewDiffData,
535 collapsedFileIds,
536 viewedFileIds,
537 selectedRowIds: commentSelection.selectedRowIds,
538 canHighlight: parsedDiff.kind === "files",
539 });
540 const showcaseReviewKey =
541 SHOWCASE_ENABLED && parsedDiff.kind === "files" && selectedSection
542 ? `${reviewCache.threadKey}:${selectedSection.id}:${nativeBridge.tokensResetKey}:${nativeBridge.themeId}`
543 : null;
544 const handleNativeDebug = (event: NativeSyntheticEvent<Record<string, unknown>>) => {
545 nativeBridge.onDebug(event);
546 if (
547 showcaseReviewKey === null ||
548 showcasedReviewDrawRef.current === showcaseReviewKey ||
549 !isNativeReviewDiffDrawEvent(event.nativeEvent)
550 ) {
551 return;
552 }
553 showcasedReviewDrawRef.current = showcaseReviewKey;
554 reportShowcaseSceneRendered({ scene: "review", themeId: nativeBridge.themeId });
555 };
556
557 const handleSelectFile = async (fileId: string | null) => {
558 loadVisibleFile(fileId, true);
559 commentSelection.clearSelection();
560 if (fileId !== null && collapsedFileIds.includes(fileId)) {
561 toggleExpandedFile(fileId);
562 }
563 const nativeView = nativeReviewDiffViewRef.current;
564 if (!nativeView) return;
565 const result = await settlePromise(() =>
566 fileId === null ? nativeView.scrollToTop(true) : nativeView.scrollToFile(fileId, true),
567 );
568 if (AsyncResult.isFailure(result)) {
569 console.error("[review] Failed to navigate to diff file", squashAtomCommandFailure(result));
570 }
571 };
572 const handleVisibleFileChange = (
573 event: NativeSyntheticEvent<{ readonly fileId?: string | null }>,
574 ) => {
575 loadVisibleFile(event.nativeEvent.fileId ?? null);
576 reviewFileNavigatorRef.current?.setVisibleFile(event.nativeEvent.fileId ?? null);
577 };
578 const renderInspector = () => (
579 <ReviewFileNavigator
580 ref={reviewFileNavigatorRef}
581 files={nativeReviewDiffData.files}
582 headerInset={insets.top}
583 sectionId={selectedSection?.id ?? null}
584 onSelectFile={(fileId) => void handleSelectFile(fileId)}
585 />
586 );
587
588 const handleNativeToggleFile = (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
589 const { fileId } = event.nativeEvent;
590 if (fileId) {
591 loadVisibleFile(fileId, true);
592 toggleExpandedFile(fileId);
593 }
594 };
595
596 const handleNativeToggleViewedFile = (
597 event: NativeSyntheticEvent<{ readonly fileId?: string }>,
598 ) => {
599 const { fileId } = event.nativeEvent;
600 if (fileId) {
601 toggleViewedFile(fileId);
602 }
603 };
604
605 const parsedDiffNotice =
606 parsedDiff.kind === "files" || parsedDiff.kind === "raw" ? parsedDiff.notice : null;
607 const hasCachedSelectedDiff = selectedSection?.diff != null;
608 const hasAnyCachedDiff = reviewSections.some((section) => section.diff != null);
609 const sectionMenu = buildReviewSectionMenu(reviewSections);
610 const { showConnectionNotice, showSectionToolbar } = resolveReviewAvailability({
611 hasEnvironmentPresentation: environment.isReady,
612 isEnvironmentConnected: isEnvironmentReady,
613 hasCachedSelectedDiff,
614 hasAnyCachedDiff,
615 });
616 const handleRetryEnvironment = () => {
617 void retryEnvironment(environmentId);
618 };
619 const handleReturnToThread = () => {
620 if (navigation.canGoBack()) {
621 navigation.goBack();
622 return;
623 }
624 navigation.navigate("Thread", {
625 environmentId: String(environmentId),
626 threadId: String(threadId),
627 });
628 };
629 const androidHeaderSubtitle = [
630 selectedSection?.title,
631 headerDiffSummary.additions,
632 headerDiffSummary.deletions,
633 ]
634 .filter((part): part is string => Boolean(part))
635 .join(" · ");
636
637 const showChangedFilesPane =
638 !showConnectionNotice &&
639 selectedSection !== null &&
640 parsedDiff.kind === "files" &&
641 NativeReviewDiffView !== null;
642 useRegisterWorkspaceInspector(showChangedFilesPane ? renderInspector : undefined);
643 const showChangedFilesToggle = panes.supportsAuxiliaryPane && showChangedFilesPane;
644
645 const listHeader = (() => {
646 const children: ReactElement[] = [];
647
648 if (error) {
649 children.push(
650 <View
651 key="review-error"
652 className={cn(
653 "bg-card px-4 py-3",
654 Platform.OS === "android" ? "m-2 rounded-[20px]" : "border-b border-border",
655 )}
656 >
657 <Text className="text-sm font-t3-bold text-foreground">Review unavailable</Text>
658 <Text className="text-xs leading-normal text-foreground-muted">{error}</Text>
659 </View>,
660 );
661 }
662
663 if (parsedDiffNotice) {
664 children.push(<ReviewNotice key="review-notice" notice={parsedDiffNotice} />);
665 }
666
667 if (children.length === 0) {
668 return null;
669 }
670
671 return <>{children}</>;
672 })();
673 const headerSubtitle = [
674 headerDiffSummary.additions,
675 headerDiffSummary.deletions,
676 pendingReviewCommentCount > 0
677 ? `${pendingReviewCommentCount} comment${pendingReviewCommentCount === 1 ? "" : "s"}`
678 : null,
679 ]
680 .filter(Boolean)
681 .join(" · ");
682 const headerTitleText = selectedSection?.title ?? "Review changes";
683
684 return (
685 <>
686 <ReviewHeader
687 environmentId={environmentId}
688 threadId={threadId}
689 title={headerTitleText}
690 subtitle={headerSubtitle}
691 androidSubtitle={androidHeaderSubtitle}
692 iconColor={headerIcon}
693 selectedThreadCwd={selectedThreadCwd}
694 sectionMenu={sectionMenu}
695 selectedSection={selectedSection}
696 showSectionToolbar={showSectionToolbar}
697 showChangedFilesToggle={showChangedFilesToggle}
698 onRefresh={handlePullToRefresh}
699 onSelectSection={selectSection}
700 onReturnToThread={handleReturnToThread}
701 />
702
703 <ScreenContent>
704 <View className="flex-1 bg-sheet android:bg-sheet-solid">
705 {showConnectionNotice ? (
706 <View className="flex-1" style={{ paddingTop: topContentInset }}>
707 <EnvironmentConnectionNotice
708 environmentLabel={environment.presentation?.entry.target.label ?? "Environment"}
709 connection={
710 environment.presentation?.connection ?? {
711 phase: "available",
712 error: null,
713 traceId: null,
714 }
715 }
716 resourceName="review"
717 onRetry={handleRetryEnvironment}
718 />
719 </View>
720 ) : selectedSection && parsedDiff.kind === "files" && NativeReviewDiffView ? (
721 <View
722 className="flex-1"
723 style={{
724 backgroundColor: nativeBridge.theme.background,
725 }}
726 >
727 <View
728 className="min-w-0 flex-1"
729 style={listHeader ? { paddingTop: topContentInset } : undefined}
730 >
731 {listHeader}
732 <View className="min-w-0 flex-1" collapsable={false}>
733 <NativeReviewDiffView
734 collapsable={false}
735 testID="review-native-diff-view"
736 refreshing={
737 isPullRefreshing || isSelectedSectionPending || areFilePatchesPending
738 }
739 onPullToRefresh={() => void handlePullToRefresh()}
740 style={StyleSheet.absoluteFill}
741 appearanceScheme={selectedTheme}
742 collapsedFileIdsJson={nativeBridge.collapsedFileIdsJson}
743 collapsedCommentIdsJson={nativeBridge.collapsedCommentIdsJson}
744 contentResetKey={`${reviewCache.threadKey}:${selectedSection.id}`}
745 contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
746 contentInsetTop={listHeader ? 0 : topContentInset}
747 contentInsetBottom={bottomContentInset}
748 nativeViewRef={nativeReviewDiffViewRef}
749 rowHeight={nativeReviewDiffStyle.rowHeight}
750 rowsJson={nativeBridge.rowsJson}
751 selectedRowIdsJson={nativeBridge.selectedRowIdsJson}
752 styleJson={nativeBridge.styleJson}
753 themeJson={nativeBridge.themeJson}
754 tokensPatchJson={nativeBridge.tokensPatchJson}
755 tokensResetKey={nativeBridge.tokensResetKey}
756 viewedFileIdsJson={nativeBridge.viewedFileIdsJson}
757 onDebug={handleNativeDebug}
758 onPressLine={commentSelection.onPressLine}
759 onVisibleFileChange={handleVisibleFileChange}
760 onToggleComment={nativeBridge.onToggleComment}
761 onToggleFile={handleNativeToggleFile}
762 onToggleViewedFile={handleNativeToggleViewedFile}
763 />
764 </View>
765 </View>
766 </View>
767 ) : (
768 <ScrollView
769 contentContainerStyle={
770 Platform.OS === "android" && (parsedDiff.kind === "empty" || !selectedSection)
771 ? { flexGrow: 1, justifyContent: "center" }
772 : undefined
773 }
774 contentInsetAdjustmentBehavior="never"
775 contentInset={{ top: topContentInset, bottom: bottomContentInset }}
776 contentOffset={{ x: 0, y: -topContentInset }}
777 automaticallyAdjustsScrollIndicatorInsets={false}
778 scrollIndicatorInsets={{ top: topContentInset, bottom: bottomContentInset }}
779 showsVerticalScrollIndicator={false}
780 className="flex-1"
781 refreshControl={
782 // The native diff surface owns pull-to-refresh via onPullToRefresh;
783 // the raw fallback (and empty states) need an explicit control —
784 // iOS has no other refresh affordance here (the explicit
785 // "Refresh current diff" menu is Android-only).
786 <RefreshControl
787 refreshing={isPullRefreshing || isSelectedSectionPending || areFilePatchesPending}
788 onRefresh={() => void handlePullToRefresh()}
789 />
790 }
791 >
792 {listHeader}
793 {!selectedSection ? (
794 error ? null : (
795 <View
796 className={
797 Platform.OS === "android"
798 ? "items-center px-6 py-5"
799 : "border-b border-border bg-card px-4 py-5"
800 }
801 >
802 <Text className="text-sm font-t3-bold text-foreground">No review diffs</Text>
803 <Text
804 className={cn(
805 "text-xs leading-normal text-foreground-muted",
806 Platform.OS === "android" && "mt-2 text-center",
807 )}
808 >
809 This thread has no ready turn diffs and the worktree diff is empty.
810 </Text>
811 </View>
812 )
813 ) : selectedSection.isLoading && selectedSection.diff === null ? (
814 <View
815 className={cn(
816 "items-center gap-3 px-4 py-6",
817 Platform.OS !== "android" && "border-b border-border bg-card",
818 )}
819 >
820 <AppActivityIndicator size="small" />
821 <Text className="text-xs text-foreground-muted">Loading diff…</Text>
822 </View>
823 ) : parsedDiff.kind === "empty" ? (
824 <View
825 className={
826 Platform.OS === "android"
827 ? "items-center px-6 py-5"
828 : "border-b border-border bg-card px-4 py-5"
829 }
830 >
831 <Text className="text-sm font-t3-bold text-foreground">No changes</Text>
832 <Text
833 className={cn(
834 "text-xs leading-normal text-foreground-muted",
835 Platform.OS === "android" && "mt-2 text-center",
836 )}
837 >
838 {selectedSection.subtitle ?? "This diff is empty."}
839 </Text>
840 </View>
841 ) : parsedDiff.kind === "raw" ? (
842 <View
843 className={cn(
844 "gap-3 bg-card px-4 py-4",
845 Platform.OS === "android" ? "m-2 rounded-[20px]" : "border-b border-border",
846 )}
847 >
848 <Text className="text-xs leading-normal text-foreground-muted">
849 {parsedDiff.reason}
850 </Text>
851 <ScrollView horizontal showsHorizontalScrollIndicator={false} bounces={false}>
852 <Text selectable className="font-mono text-xs leading-relaxed text-foreground">
853 {parsedDiff.text}
854 </Text>
855 </ScrollView>
856 </View>
857 ) : parsedDiff.kind === "files" ? (
858 <View
859 className={cn(
860 "gap-3 bg-card px-4 py-4",
861 Platform.OS === "android" ? "m-2 rounded-[20px]" : "border-b border-border",
862 )}
863 >
864 <Text className="text-xs leading-normal text-foreground-muted">
865 Native diff view unavailable. Showing the raw patch.
866 </Text>
867 <ScrollView horizontal showsHorizontalScrollIndicator={false} bounces={false}>
868 <Text selectable className="font-mono text-xs leading-relaxed text-foreground">
869 {selectedSection?.diff ?? ""}
870 </Text>
871 </ScrollView>
872 </View>
873 ) : null}
874 </ScrollView>
875 )}
876 <ReviewSelectionActionBar
877 bottomInset={insets.bottom}
878 title={commentSelection.selectionAction?.title ?? null}
879 onOpenComment={commentSelection.selectionAction?.onOpenComment ?? null}
880 onClear={commentSelection.clearSelection}
881 />
882 </View>
883 </ScreenContent>
884 </>
885 );
886}