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