From d950f45672ed71fac5cddd0d9d6ec5616ba0c38e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 7 May 2026 00:11:43 -0700 Subject: [PATCH] Refactor review sheet into focused native review hooks - Split file visibility, diff data, and comment selection logic out of `ReviewSheet` - Add tests for review file visibility and native diff bridge behavior - Wire review selection and mobile remote connect state through shared hooks --- .../src/features/review/ReviewSheet.tsx | 1556 ++--------------- .../review/reviewFileVisibility.test.ts | 50 + .../features/review/reviewFileVisibility.ts | 116 ++ .../mobile/src/features/review/reviewState.ts | 14 +- .../review/useNativeReviewDiffBridge.test.ts | 27 + .../review/useNativeReviewDiffBridge.ts | 152 ++ .../review/useNativeReviewDiffHighlighting.ts | 136 ++ .../useReviewCommentSelectionController.ts | 193 ++ .../src/features/review/useReviewDiffData.ts | 109 ++ .../src/features/review/useReviewSections.ts | 242 +++ .../features/threads/ThreadRouteScreen.tsx | 24 +- .../src/state/use-selected-thread-commands.ts | 74 +- .../src/state/use-selected-thread-requests.ts | 176 ++ .../src/state/use-thread-composer-state.ts | 109 +- apps/server/src/server.test.ts | 3 + apps/web/vitest.config.ts | 16 + 16 files changed, 1391 insertions(+), 1606 deletions(-) create mode 100644 apps/mobile/src/features/review/reviewFileVisibility.test.ts create mode 100644 apps/mobile/src/features/review/reviewFileVisibility.ts create mode 100644 apps/mobile/src/features/review/useNativeReviewDiffBridge.test.ts create mode 100644 apps/mobile/src/features/review/useNativeReviewDiffBridge.ts create mode 100644 apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts create mode 100644 apps/mobile/src/features/review/useReviewCommentSelectionController.ts create mode 100644 apps/mobile/src/features/review/useReviewDiffData.ts create mode 100644 apps/mobile/src/features/review/useReviewSections.ts create mode 100644 apps/mobile/src/state/use-selected-thread-requests.ts create mode 100644 apps/web/vitest.config.ts diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx index 849cd42263..74238bfe4e 100644 --- a/apps/mobile/src/features/review/ReviewSheet.tsx +++ b/apps/mobile/src/features/review/ReviewSheet.tsx @@ -1,552 +1,37 @@ -import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts"; -import { Gesture, GestureDetector } from "react-native-gesture-handler"; -import Animated, { - makeMutable, - type SharedValue, - useAnimatedStyle, - useSharedValue, -} from "react-native-reanimated"; -import { useLocalSearchParams, useRouter } from "expo-router"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { useLocalSearchParams } from "expo-router"; import Stack from "expo-router/stack"; import { SymbolView } from "expo-symbols"; -import { - memo, - type ReactElement, - useCallback, - useDeferredValue, - useEffect, - useMemo, - useRef, - useState, -} from "react"; +import { memo, type ReactElement, useCallback, useMemo } from "react"; import { ActivityIndicator, - FlatList, - type ListRenderItemInfo, Pressable, ScrollView, + type NativeSyntheticEvent, Text as NativeText, + StyleSheet, useColorScheme, - useWindowDimensions, View, } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/AppText"; -import { cn } from "../../lib/cn"; import { useThemeColor } from "../../lib/useThemeColor"; -import { getEnvironmentClient } from "../../state/environment-session-registry"; -import { useSelectedThreadDetail } from "../../state/use-thread-detail"; import { useThreadDraftForThread } from "../../state/use-thread-composer-state"; -import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree"; +import { useReviewCacheForThread } from "./reviewState"; +import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface"; import { - getCachedReviewParsedDiff, - setReviewGitSections, - setReviewSelectedSectionId, - setReviewTurnDiff, - updateReviewExpandedFileIds, - updateReviewRevealedLargeFileIds, - updateReviewViewedFileIds, - useReviewCacheForThread, -} from "./reviewState"; -import { - buildReviewListItems, - getReadyReviewCheckpoints, - buildReviewSectionItems, - getDefaultReviewSectionId, - getReviewFilePreviewState, - getReviewSectionIdForCheckpoint, - type ReviewListItem, - type ReviewParsedDiff, - type ReviewRenderableFile, - type ReviewRenderableLineRow, - type ReviewRenderableRow, -} from "./reviewModel"; -import { - clearReviewHighlightFileCache, - getCachedHighlightedReviewFile, - streamHighlightReviewFile, - type ReviewDiffTheme, - type ReviewHighlightedFile, - type ReviewHighlightedToken, -} from "./shikiReviewHighlighter"; -import { - buildReviewCommentTarget, - clearReviewCommentTarget, - countReviewCommentContexts, - formatReviewSelectedRangeLabel, - getReviewUnifiedLineNumber, - setReviewCommentTarget, - type ReviewCommentTarget, - useReviewCommentTarget, -} from "./reviewCommentSelection"; -import { - changeTone, - DiffTokenText, - REVIEW_DIFF_LINE_HEIGHT, - REVIEW_MONO_FONT_FAMILY, - ReviewChangeBar, -} from "./reviewDiffRendering"; -import { markReviewEvent, measureReviewWork } from "./reviewPerf"; -import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider"; - -interface PendingCommentSelection { - readonly sectionTitle: string; - readonly filePath: string; - readonly lines: ReadonlyArray; - readonly anchorIndex: number; -} - -interface ReviewLineActionInput { - readonly sectionTitle: string; - readonly filePath: string; - readonly lines: ReadonlyArray; - readonly lineIndex: number; -} + NATIVE_REVIEW_DIFF_CONTENT_WIDTH, + NATIVE_REVIEW_DIFF_ROW_HEIGHT, +} from "./nativeReviewDiffAdapter"; +import { useReviewDiffData } from "./useReviewDiffData"; +import { useReviewFileVisibility } from "./reviewFileVisibility"; +import { useReviewSections } from "./useReviewSections"; +import { useNativeReviewDiffBridge } from "./useNativeReviewDiffBridge"; +import { useReviewCommentSelectionController } from "./useReviewCommentSelectionController"; const IOS_NAV_BAR_HEIGHT = 44; const REVIEW_HEADER_SPACING = 0; -const REVIEW_CHANGE_BAR_WIDTH = 5; -const REVIEW_MIN_LINE_NUMBER_WIDTH = 27; -const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8; -const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6; -const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4; -const REVIEW_MAX_CONTENT_WIDTH = 4_800; -const REVIEW_HUNK_ROW_HEIGHT = 35; -const REVIEW_FILE_HEADER_HEIGHT = 43; -const REVIEW_SUPPRESSED_ROW_HEIGHT = 92; -const loggedMissingReviewTokenKeys = new Set(); - -function waitForReviewDelay(durationMs: number): Promise { - return new Promise((resolve) => setTimeout(resolve, durationMs)); -} - -function isReviewDiffDebugLoggingEnabled(): boolean { - return typeof __DEV__ !== "undefined" ? __DEV__ : false; -} - -function logReviewDiffDiagnostic(message: string, details?: Record): void { - if (!isReviewDiffDebugLoggingEnabled()) { - return; - } - - if (details) { - console.log(`[review-sheet] ${message}`, details); - return; - } - - console.log(`[review-sheet] ${message}`); -} - -function getFileHeaderChrome(changeType: ReviewRenderableFile["changeType"]): { - readonly dot: string; -} { - switch (changeType) { - case "new": - return { - dot: "bg-emerald-400", - }; - case "deleted": - return { - dot: "bg-rose-400", - }; - case "rename-pure": - return { - dot: "bg-amber-400", - }; - case "rename-changed": - return { - dot: "bg-sky-400", - }; - default: - return { - dot: "bg-sky-400", - }; - } -} - -function formatHeaderDiffSummary(parsedDiff: ReviewParsedDiff): { - readonly additions: string | null; - readonly deletions: string | null; -} { - if (parsedDiff.kind !== "files") { - return { additions: null, deletions: null }; - } - - return { - additions: `+${parsedDiff.additions}`, - deletions: `-${parsedDiff.deletions}`, - }; -} - -function computeReviewFileContentWidth( - rows: ReadonlyArray, - viewportWidth: number, - gutterWidth: number, -): number { - let maxTextLength = 0; - - rows.forEach((row) => { - if (row.kind === "hunk") { - maxTextLength = Math.max( - maxTextLength, - row.header.length + (row.context ? row.context.length + 1 : 0), - ); - return; - } - - maxTextLength = Math.max(maxTextLength, row.content.length); - }); - - return Math.max( - Math.max(0, viewportWidth - gutterWidth), - Math.min( - REVIEW_MAX_CONTENT_WIDTH, - Math.ceil(48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE), - ), - ); -} - -function computeReviewFileGutterWidth(rows: ReadonlyArray): number { - let maxLineNumber = 0; - - rows.forEach((row) => { - if (row.kind !== "line") { - return; - } - - maxLineNumber = Math.max(maxLineNumber, row.oldLineNumber ?? 0, row.newLineNumber ?? 0); - }); - - const digitCount = Math.max(1, String(maxLineNumber).length); - const lineNumberWidth = Math.max( - REVIEW_MIN_LINE_NUMBER_WIDTH, - digitCount * REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE + REVIEW_LINE_NUMBER_HORIZONTAL_PADDING, - ); - - return REVIEW_CHANGE_BAR_WIDTH + lineNumberWidth; -} - -function getDefaultExpandedFileIds( - files: ReadonlyArray, -): ReadonlyArray { - return files.map((file) => file.id); -} - -function getValidReviewExpandedFileIds( - files: ReadonlyArray, - cachedExpandedFileIds: ReadonlyArray | undefined, -): ReadonlyArray { - if (cachedExpandedFileIds === undefined) { - return getDefaultExpandedFileIds(files); - } - - const fileIdSet = new Set(files.map((file) => file.id)); - return cachedExpandedFileIds.filter((id) => fileIdSet.has(id)); -} - -function getHighlightedTokensForLine( - line: ReviewRenderableLineRow, - highlightedFile: ReviewHighlightedFile | null, -): ReadonlyArray | null { - if (!highlightedFile) { - return null; - } - - if (line.additionTokenIndex !== null) { - return highlightedFile.additionLines[line.additionTokenIndex] ?? null; - } - - if (line.deletionTokenIndex !== null) { - return highlightedFile.deletionLines[line.deletionTokenIndex] ?? null; - } - - return null; -} - -const ReviewLineRow = memo(function ReviewLineRow(props: { - readonly line: ReviewRenderableLineRow; - readonly tokens: ReadonlyArray | null; - readonly viewportWidth: number; - readonly selectionState: "anchor" | "selected" | null; - readonly onComment: () => void; - readonly onStartRangeSelection: () => void; -}) { - const lineNumber = getReviewUnifiedLineNumber(props.line); - - return ( - - - - - - ); -}); - -const ReviewLineGutter = memo(function ReviewLineGutter(props: { - readonly change: ReviewRenderableLineRow["change"]; - readonly gutterWidth: number; - readonly lineNumber: number | null; -}) { - const lineNumberWidth = Math.max(0, props.gutterWidth - REVIEW_CHANGE_BAR_WIDTH); - - return ( - - - - {props.lineNumber ?? ""} - - - ); -}); - -const ReviewHunkGutter = memo(function ReviewHunkGutter(props: { readonly gutterWidth: number }) { - return ( - - ); -}); - -const ReviewFileCard = memo(function ReviewFileCard(props: { - readonly file: ReviewRenderableFile; - readonly fileId: string; - readonly expanded: boolean; - readonly viewed: boolean; - readonly viewportWidth: number; - readonly onToggleFile: (fileId: string) => void; - readonly onToggleViewed: (fileId: string) => void; -}) { - const { expanded, file, fileId, onToggleFile, onToggleViewed, viewed, viewportWidth } = props; - const chrome = getFileHeaderChrome(file.changeType); - const iconColor = String(useThemeColor("--color-icon-muted")); - const handleToggleFile = useCallback(() => { - onToggleFile(fileId); - }, [fileId, onToggleFile]); - const handleToggleViewed = useCallback(() => { - onToggleViewed(fileId); - }, [fileId, onToggleViewed]); - - return ( - - - - - - - - - - {file.path} - - {file.previousPath && file.previousPath !== file.path ? ( - - {file.previousPath} - - ) : null} - - - - - -{file.deletions} - - - +{file.additions} - - - - {viewed ? ( - - ) : null} - - - Viewed - - - - - - ); -}); - -const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: { - readonly message: string; - readonly actionLabel?: string | null; - readonly fileId: string; - readonly viewportWidth: number; - readonly onLoadDiffFile?: (fileId: string) => void; -}) { - return ( - - {props.message} - {props.actionLabel && props.onLoadDiffFile ? ( - props.onLoadDiffFile?.(props.fileId)} - > - {props.actionLabel} - - ) : null} - - ); -}); - -const ReviewHunkRow = memo(function ReviewHunkRow(props: { - readonly header: string; - readonly context: string | null; - readonly viewportWidth: number; -}) { - return ( - - - {props.header} - {props.context ? ` ${props.context}` : ""} - - - ); -}); - -const ReviewCodePanRow = memo(function ReviewCodePanRow(props: { - readonly contentWidth: number; - readonly horizontalOffset: SharedValue; - readonly gutterWidth?: number; - readonly viewportWidth: number; - readonly leftGutter?: ReactElement; - readonly children: ReactElement; -}) { - const { - children, - contentWidth, - gutterWidth = 0, - horizontalOffset, - leftGutter, - viewportWidth, - } = props; - const dragStartOffset = useSharedValue(0); - const visibleContentWidth = leftGutter ? viewportWidth - gutterWidth : viewportWidth; - const maxOffset = Math.max(0, contentWidth - visibleContentWidth); - - const panGesture = useMemo( - () => - Gesture.Pan() - .activeOffsetX([-8, 8]) - .failOffsetY([-10, 10]) - .onBegin(() => { - dragStartOffset.value = horizontalOffset.value; - }) - .onUpdate((event) => { - "worklet"; - const nextOffset = dragStartOffset.value - event.translationX; - horizontalOffset.value = Math.min(maxOffset, Math.max(0, nextOffset)); - }), - [dragStartOffset, horizontalOffset, maxOffset], - ); - - const contentStyle = useAnimatedStyle( - () => ({ - transform: [{ translateX: -horizontalOffset.value }], - }), - [horizontalOffset], - ); - - return ( - - - {leftGutter ?? null} - - {children} - - - - ); -}); const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) { return ( @@ -562,15 +47,27 @@ const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }); function ReviewSelectionActionBar(props: { - readonly target: ReviewCommentTarget | null; readonly bottomInset: number; - readonly onOpenComment: () => void; + readonly title: string | null; + readonly onOpenComment: (() => void) | null; readonly onClear: () => void; }) { - if (!props.target || props.target.startIndex === props.target.endIndex) { + if (!props.title) { return null; } + const content = ( + <> + + {props.title} + + ); + return ( - - - - Comment on {formatReviewSelectedRangeLabel(props.target)} - - + {props.onOpenComment ? ( + + {content} + + ) : ( + + {content} + + )} (); const { draftMessage } = useThreadDraftForThread({ environmentId, threadId }); const reviewCache = useReviewCacheForThread({ environmentId, threadId }); - const selectedThread = useSelectedThreadDetail(); - const [loadingTurnIds, setLoadingTurnIds] = useState>({}); - const [loadingGitDiffs, setLoadingGitDiffs] = useState(false); - const [error, setError] = useState(null); - const [pendingCommentSelection, setPendingCommentSelection] = - useState(null); - const [highlightedFilesById, setHighlightedFilesById] = useState< - Record - >({}); - const deferredHighlightedFilesById = useDeferredValue(highlightedFilesById); - const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState< - Record> - >({}); - const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState< - Record> - >({}); - const activeCommentTarget = useReviewCommentTarget(); - const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme; - const reviewHighlighter = useReviewHighlighterStatus(); - const highlightRunIdRef = useRef(0); - const highlightableFilesRef = useRef>([]); - const horizontalOffsetByFileIdRef = useRef>>(new Map()); - const { selectedThreadCwd } = useSelectedThreadWorktree(); - - const cwd = selectedThreadCwd; - const readyCheckpoints = useMemo( - () => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []), - [selectedThread?.checkpoints], - ); - - const checkpointBySectionId = useMemo(() => { - return Object.fromEntries( - readyCheckpoints.map((checkpoint) => [ - getReviewSectionIdForCheckpoint(checkpoint), - checkpoint, - ]), - ) as Record; - }, [readyCheckpoints]); - - const reviewSections = useMemo( - () => - buildReviewSectionItems({ - checkpoints: readyCheckpoints, - gitSections: reviewCache.gitSections, - turnDiffById: reviewCache.turnDiffById, - loadingTurnIds, - }), - [loadingTurnIds, readyCheckpoints, reviewCache.gitSections, reviewCache.turnDiffById], - ); - - const selectedSection = - reviewSections.find((section) => section.id === reviewCache.selectedSectionId) ?? - reviewSections[0] ?? - null; + const selectedTheme = colorScheme === "dark" ? "dark" : "light"; const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT; - const parsedDiff = useMemo( - () => - measureReviewWork("parse-diff", () => - getCachedReviewParsedDiff({ - threadKey: reviewCache.threadKey, - sectionId: selectedSection?.id ?? null, - diff: selectedSection?.diff, - }), - ), - [reviewCache.threadKey, selectedSection?.diff, selectedSection?.id], - ); - const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]); - const pendingReviewCommentCount = useMemo( - () => countReviewCommentContexts(draftMessage), - [draftMessage], - ); - const viewportWidth = Math.max(width, 280); - - useEffect(() => { - if (!selectedSection?.id || parsedDiff.kind !== "files") { - return; - } - - setLocalExpandedFileIdsBySection((current) => { - if (current[selectedSection.id] !== undefined) { - return current; - } - - return { - ...current, - [selectedSection.id]: getValidReviewExpandedFileIds( - parsedDiff.files, - reviewCache.expandedFileIdsBySection[selectedSection.id], - ), - }; + const { + error, + loadingGitDiffs, + loadingTurnIds, + reviewSections, + selectedSection, + refreshSelectedSection, + selectSection, + } = useReviewSections({ environmentId, threadId, reviewCache }); + const { headerDiffSummary, nativeReviewDiffData, parsedDiff, pendingReviewCommentCount } = + useReviewDiffData({ + threadKey: reviewCache.threadKey, + selectedSection, + draftMessage, }); + const NativeReviewDiffView = resolveNativeReviewDiffView()!; + const reviewFiles = parsedDiff.kind === "files" ? parsedDiff.files : []; + const fileVisibility = useReviewFileVisibility({ + threadKey: reviewCache.threadKey, + sectionId: selectedSection?.id ?? null, + files: reviewFiles, + cachedExpandedFileIds: selectedSection?.id + ? reviewCache.expandedFileIdsBySection[selectedSection.id] + : undefined, + cachedViewedFileIds: selectedSection?.id + ? reviewCache.viewedFileIdsBySection[selectedSection.id] + : undefined, + }); + const { collapsedFileIds, toggleExpandedFile, toggleViewedFile, viewedFileIds } = fileVisibility; + const commentSelection = useReviewCommentSelectionController({ + environmentId, + threadId, + selectedSection, + nativeReviewDiffData, + }); + const nativeBridge = useNativeReviewDiffBridge({ + threadKey: reviewCache.threadKey, + sectionId: selectedSection?.id ?? null, + diff: selectedSection?.diff, + data: nativeReviewDiffData, + scheme: selectedTheme, + collapsedFileIds, + viewedFileIds, + selectedRowIds: commentSelection.selectedRowIds, + canHighlight: parsedDiff.kind === "files", + }); - setLocalViewedFileIdsBySection((current) => { - if (current[selectedSection.id] !== undefined) { - return current; - } - - return { - ...current, - [selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [], - }; - }); - }, [ - parsedDiff, - reviewCache.expandedFileIdsBySection, - reviewCache.viewedFileIdsBySection, - selectedSection?.id, - ]); - - const expandedFileIds = useMemo( - () => - selectedSection?.id && parsedDiff.kind === "files" - ? getValidReviewExpandedFileIds( - parsedDiff.files, - localExpandedFileIdsBySection[selectedSection.id], - ) - : [], - [localExpandedFileIdsBySection, parsedDiff, selectedSection?.id], - ); - const revealedLargeFileIds = useMemo( - () => - selectedSection?.id - ? (reviewCache.revealedLargeFileIdsBySection[selectedSection.id] ?? []) - : [], - [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id], - ); - const viewedFileIds = useMemo( - () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []), - [localViewedFileIdsBySection, selectedSection?.id], - ); - const viewedFileIdSet = useMemo(() => new Set(viewedFileIds), [viewedFileIds]); - const reviewListItems = useMemo( - () => - selectedSection && parsedDiff.kind === "files" - ? measureReviewWork("build-list-items", () => - buildReviewListItems({ - files: parsedDiff.files, - expandedFileIds, - revealedLargeFileIds, - }), - ) - : [], - [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection], - ); - const reviewLineRowsByFileId = useMemo(() => { - if (parsedDiff.kind !== "files") { - return new Map>(); - } - - return measureReviewWork( - "index-line-rows", - () => - new Map( - parsedDiff.files.map((file) => [ - file.id, - file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"), - ]), - ), - ); - }, [parsedDiff]); - const reviewContentWidthByFileId = useMemo(() => { - if (parsedDiff.kind !== "files") { - return new Map(); - } - - return measureReviewWork( - "measure-file-widths", - () => - new Map( - parsedDiff.files.map((file) => [ - file.id, - computeReviewFileContentWidth( - file.rows, - viewportWidth, - computeReviewFileGutterWidth(file.rows), - ), - ]), - ), - ); - }, [parsedDiff, viewportWidth]); - const reviewGutterWidthByFileId = useMemo(() => { - if (parsedDiff.kind !== "files") { - return new Map(); - } - - return new Map( - parsedDiff.files.map((file) => [file.id, computeReviewFileGutterWidth(file.rows)]), - ); - }, [parsedDiff]); - const getReviewFileHorizontalOffset = useCallback((fileId: string) => { - let offset = horizontalOffsetByFileIdRef.current.get(fileId); - if (!offset) { - offset = makeMutable(0); - horizontalOffsetByFileIdRef.current.set(fileId, offset); - } - - return offset; - }, []); - useEffect(() => { - const knownFileIds = - parsedDiff.kind === "files" ? new Set(parsedDiff.files.map((file) => file.id)) : new Set(); - - horizontalOffsetByFileIdRef.current.forEach((offset, fileId) => { - if (!knownFileIds.has(fileId)) { - horizontalOffsetByFileIdRef.current.delete(fileId); - return; - } - - const contentWidth = reviewContentWidthByFileId.get(fileId) ?? viewportWidth; - const gutterWidth = reviewGutterWidthByFileId.get(fileId) ?? 0; - offset.value = Math.min( - offset.value, - Math.max(0, contentWidth - (viewportWidth - gutterWidth)), - ); - }); - }, [parsedDiff, reviewContentWidthByFileId, reviewGutterWidthByFileId, viewportWidth]); - const highlightableFiles = useMemo(() => { - if (parsedDiff.kind !== "files") { - return [] as ReadonlyArray; - } - - const expandedFileIdSet = new Set(expandedFileIds); - const revealedLargeFileIdSet = new Set(revealedLargeFileIds); - - return parsedDiff.files.filter((file) => { - if (!expandedFileIdSet.has(file.id)) { - return false; - } - - const previewState = getReviewFilePreviewState(file); - return ( - previewState.kind === "render" || - (previewState.reason === "large" && revealedLargeFileIdSet.has(file.id)) - ); - }); - }, [expandedFileIds, parsedDiff, revealedLargeFileIds]); - const highlightableFilesKey = useMemo( - () => highlightableFiles.map((file) => `${file.id}:${file.cacheKey}`).join("\n"), - [highlightableFiles], - ); - useEffect(() => { - highlightableFilesRef.current = highlightableFiles; - }, [highlightableFiles]); - const loadGitDiffs = useCallback(async () => { - if (!cwd) { - return; - } - - const client = getEnvironmentClient(environmentId); - if (!client) { - setError("Remote connection is not ready."); - return; - } - - setLoadingGitDiffs(true); - setError(null); - try { - const result = await client.review.getDiffPreview({ cwd }); - if (reviewCache.threadKey) { - setReviewGitSections(reviewCache.threadKey, result.sources); - } - } catch (cause) { - setError(cause instanceof Error ? cause.message : "Failed to load review diffs."); - } finally { - setLoadingGitDiffs(false); - } - }, [cwd, environmentId, reviewCache.threadKey]); - - const loadTurnDiff = useCallback( - async (checkpoint: OrchestrationCheckpointSummary, force = false) => { - if (!threadId) { - return; - } - - const sectionId = getReviewSectionIdForCheckpoint(checkpoint); - if (reviewCache.threadKey) { - setReviewSelectedSectionId(reviewCache.threadKey, sectionId); - } - - if (!force && reviewCache.turnDiffById[sectionId] !== undefined) { - return; - } - - const client = getEnvironmentClient(environmentId); - if (!client) { - setError("Remote connection is not ready."); - return; - } - - setLoadingTurnIds((current) => ({ ...current, [sectionId]: true })); - setError(null); - try { - const result = await client.orchestration.getTurnDiff({ - threadId, - fromTurnCount: Math.max(0, checkpoint.checkpointTurnCount - 1), - toTurnCount: checkpoint.checkpointTurnCount, - }); - if (reviewCache.threadKey) { - setReviewTurnDiff(reviewCache.threadKey, sectionId, result.diff); - } - } catch (cause) { - setError(cause instanceof Error ? cause.message : "Failed to load turn diff."); - } finally { - setLoadingTurnIds((current) => { - const next = { ...current }; - delete next[sectionId]; - return next; - }); + const handleNativeToggleFile = useCallback( + (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => { + const { fileId } = event.nativeEvent; + if (fileId) { + toggleExpandedFile(fileId); } }, - [environmentId, reviewCache.threadKey, reviewCache.turnDiffById, threadId], + [toggleExpandedFile], ); - useEffect(() => { - void loadGitDiffs(); - }, [loadGitDiffs]); - - useEffect(() => { - if (reviewSections.length === 0) { - return; - } - - const fallbackId = getDefaultReviewSectionId(reviewSections); - if ( - reviewCache.threadKey && - (!reviewCache.selectedSectionId || - !reviewSections.some((section) => section.id === reviewCache.selectedSectionId)) - ) { - setReviewSelectedSectionId(reviewCache.threadKey, fallbackId); - } - }, [reviewCache.selectedSectionId, reviewCache.threadKey, reviewSections]); - - useEffect(() => { - const latest = readyCheckpoints[0]; - if (!latest) { - return; - } - - const latestId = getReviewSectionIdForCheckpoint(latest); - if (reviewCache.turnDiffById[latestId] !== undefined || loadingTurnIds[latestId]) { - return; - } - - void loadTurnDiff(latest); - }, [loadTurnDiff, loadingTurnIds, readyCheckpoints, reviewCache.turnDiffById]); - - useEffect(() => { - if (!selectedSection || selectedSection.kind !== "turn" || selectedSection.diff !== null) { - return; - } - - const checkpoint = checkpointBySectionId[selectedSection.id]; - if (checkpoint && !loadingTurnIds[selectedSection.id]) { - void loadTurnDiff(checkpoint); - } - }, [checkpointBySectionId, loadTurnDiff, loadingTurnIds, selectedSection]); - - useEffect(() => { - if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") { - return; - } - - updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => { - const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing); - if ( - existing !== undefined && - validIds.length === existing.length && - validIds.every((id, index) => id === existing[index]) - ) { - return existing; - } - return validIds; - }); - }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]); - - useEffect(() => { - if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") { - return; - } - - updateReviewRevealedLargeFileIds(reviewCache.threadKey, selectedSection.id, (existing) => { - if (existing === undefined) { - return undefined; - } - - const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id)); - if (validIds.length === existing.length) { - return existing; - } - - return validIds; - }); - }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]); - - useEffect(() => { - setHighlightedFilesById({}); - highlightRunIdRef.current += 1; - clearReviewHighlightFileCache(); - loggedMissingReviewTokenKeys.clear(); - logReviewDiffDiagnostic("reset highlighted files", { - selectedSectionId: selectedSection?.id ?? null, - selectedTheme, - }); - }, [selectedSection?.id, selectedTheme]); - - useEffect(() => { - if (parsedDiff.kind !== "files") { - return; - } - - markReviewEvent("parsed-diff-ready", { - sectionId: selectedSection?.id ?? null, - fileCount: parsedDiff.fileCount, - additions: parsedDiff.additions, - deletions: parsedDiff.deletions, - renderedItems: reviewListItems.length, - }); - logReviewDiffDiagnostic("parsed diff files", { - selectedSectionId: selectedSection?.id ?? null, - fileCount: parsedDiff.fileCount, - renderableFileCount: parsedDiff.files.length, - }); - }, [parsedDiff, reviewListItems.length, selectedSection?.id]); - - useEffect(() => { - const files = highlightableFilesRef.current; - if (files.length === 0) { - logReviewDiffDiagnostic("no highlightable files", { - selectedSectionId: selectedSection?.id ?? null, - parsedDiffKind: parsedDiff.kind, - requestedFileCount: 0, - }); - return; - } - - if (reviewHighlighter.status !== "ready") { - logReviewDiffDiagnostic("waiting for highlighter provider", { - selectedSectionId: selectedSection?.id ?? null, - status: reviewHighlighter.status, - error: reviewHighlighter.error, - }); - return; - } - - const runId = highlightRunIdRef.current; - let cancelled = false; - - logReviewDiffDiagnostic("streaming file highlights", { - selectedSectionId: selectedSection?.id ?? null, - fileCount: files.length, - }); - - void (async () => { - for (const file of files) { - if (cancelled || runId !== highlightRunIdRef.current) { - return; - } - - const cached = getCachedHighlightedReviewFile(file, selectedTheme); - if (cached) { - setHighlightedFilesById((current) => - current[file.id] === cached ? current : { ...current, [file.id]: cached }, - ); - continue; - } - - logReviewDiffDiagnostic("requesting highlighted file", { - fileId: file.id, - filePath: file.path, - theme: selectedTheme, - }); - - try { - const highlightStartedAt = performance.now(); - const result = await streamHighlightReviewFile(file, selectedTheme, (progress) => { - if (cancelled || runId !== highlightRunIdRef.current) { - return; - } - - if (!progress.complete) { - return; - } - - logReviewDiffDiagnostic("received streamed highlighted file", { - fileId: file.id, - filePath: file.path, - highlightedLineCount: progress.highlightedLineCount, - durationMs: Math.round(performance.now() - highlightStartedAt), - }); - }); - - if (cancelled || runId !== highlightRunIdRef.current) { - return; - } - - logReviewDiffDiagnostic("received highlighted file", { - fileId: file.id, - filePath: file.path, - additionLines: result.additionLines.length, - deletionLines: result.deletionLines.length, - }); - setHighlightedFilesById((current) => - current[file.id] === result ? current : { ...current, [file.id]: result }, - ); - } catch (error) { - logReviewDiffDiagnostic("highlight request failed", { - fileId: file.id, - filePath: file.path, - error: error instanceof Error ? error.message : String(error), - }); - } - - await waitForReviewDelay(0); - } - })(); - - return () => { - cancelled = true; - }; - }, [ - highlightableFilesKey, - parsedDiff.kind, - reviewHighlighter.error, - reviewHighlighter.status, - selectedSection?.id, - selectedTheme, - ]); - - const refreshSelectedSection = useCallback(async () => { - if (!selectedSection) { - return; - } - - if (selectedSection.kind === "turn") { - const checkpoint = checkpointBySectionId[selectedSection.id]; - if (checkpoint) { - await loadTurnDiff(checkpoint, true); - } - return; - } - - await loadGitDiffs(); - }, [checkpointBySectionId, loadGitDiffs, loadTurnDiff, selectedSection]); - - const handleToggleExpandedFile = useCallback( - (fileId: string) => { - if (!selectedSection?.id || parsedDiff.kind !== "files") { - return; - } - - const sectionId = selectedSection.id; - - setLocalExpandedFileIdsBySection((current) => { - const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]); - const nextIds = currentIds.includes(fileId) - ? currentIds.filter((id) => id !== fileId) - : [...currentIds, fileId]; - - return { - ...current, - [sectionId]: nextIds, - }; - }); - - if (reviewCache.threadKey) { - updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => { - const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing); - return currentIds.includes(fileId) - ? currentIds.filter((id) => id !== fileId) - : [...currentIds, fileId]; - }); + const handleNativeToggleViewedFile = useCallback( + (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => { + const { fileId } = event.nativeEvent; + if (fileId) { + toggleViewedFile(fileId); } }, - [parsedDiff, reviewCache.threadKey, selectedSection?.id], + [toggleViewedFile], ); - const handleToggleViewedFile = useCallback( - (fileId: string) => { - if (!selectedSection?.id) { - return; - } - - const sectionId = selectedSection.id; - - setLocalViewedFileIdsBySection((current) => { - const currentIds = current[sectionId] ?? []; - const nextIds = currentIds.includes(fileId) - ? currentIds.filter((id) => id !== fileId) - : [...currentIds, fileId]; - - return { - ...current, - [sectionId]: nextIds, - }; - }); - - if (reviewCache.threadKey) { - updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => { - const currentIds = existing ?? []; - return currentIds.includes(fileId) - ? currentIds.filter((id) => id !== fileId) - : [...currentIds, fileId]; - }); - } - }, - [reviewCache.threadKey, selectedSection?.id], - ); - - const handleRevealLargeDiff = useCallback( - (fileId: string) => { - if (!reviewCache.threadKey || !selectedSection?.id) { - return; - } - - updateReviewRevealedLargeFileIds(reviewCache.threadKey, selectedSection.id, (existing) => { - const currentIds = existing ?? []; - return currentIds.includes(fileId) ? currentIds : [...currentIds, fileId]; - }); - }, - [reviewCache.threadKey, selectedSection?.id], - ); - - const handlePressLine = useCallback( - (input: ReviewLineActionInput) => { - if (pendingCommentSelection) { - if ( - pendingCommentSelection.sectionTitle === input.sectionTitle && - pendingCommentSelection.filePath === input.filePath - ) { - setReviewCommentTarget( - buildReviewCommentTarget( - { - sectionTitle: pendingCommentSelection.sectionTitle, - filePath: pendingCommentSelection.filePath, - lines: pendingCommentSelection.lines, - }, - pendingCommentSelection.anchorIndex, - input.lineIndex, - ), - ); - setPendingCommentSelection(null); - return; - } - - clearReviewCommentTarget(); - setPendingCommentSelection({ - sectionTitle: input.sectionTitle, - filePath: input.filePath, - lines: input.lines, - anchorIndex: input.lineIndex, - }); - return; - } - - setReviewCommentTarget({ - sectionTitle: input.sectionTitle, - filePath: input.filePath, - lines: input.lines, - startIndex: input.lineIndex, - endIndex: input.lineIndex, - }); - if (environmentId && threadId) { - router.push({ - pathname: "/threads/[environmentId]/[threadId]/review-comment", - params: { environmentId, threadId }, - }); - } - }, - [environmentId, pendingCommentSelection, router, threadId], - ); - - const handleStartRangeSelection = useCallback((input: ReviewLineActionInput) => { - clearReviewCommentTarget(); - setPendingCommentSelection({ - sectionTitle: input.sectionTitle, - filePath: input.filePath, - lines: input.lines, - anchorIndex: input.lineIndex, - }); - }, []); - const parsedDiffNotice = parsedDiff.kind === "files" || parsedDiff.kind === "raw" ? parsedDiff.notice : null; @@ -1325,169 +211,6 @@ export function ReviewSheet() { return <>{children}; }, [error, parsedDiffNotice]); - const renderReviewListItem = useCallback( - ({ item }: ListRenderItemInfo) => { - if (!selectedSection) { - return null; - } - - let renderedItem: ReactElement | null = null; - switch (item.kind) { - case "file-header": - renderedItem = ( - - ); - break; - case "file-suppressed": - renderedItem = ( - - ); - break; - case "hunk": { - const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth; - const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0; - - renderedItem = ( - } - viewportWidth={viewportWidth} - > - - - ); - break; - } - case "line": { - const fileLineRows = reviewLineRowsByFileId.get(item.file.id) ?? []; - const pendingSelectionForFile = - pendingCommentSelection && - pendingCommentSelection.sectionTitle === selectedSection.title && - pendingCommentSelection.filePath === item.file.path - ? pendingCommentSelection - : null; - const selectedTargetForFile = - activeCommentTarget && - activeCommentTarget.sectionTitle === selectedSection.title && - activeCommentTarget.filePath === item.file.path - ? activeCommentTarget - : null; - const highlightedFile = - deferredHighlightedFilesById[item.file.id] ?? - getCachedHighlightedReviewFile(item.file, selectedTheme) ?? - null; - const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth; - const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0; - - if (highlightedFile === null) { - const missingTokenKey = `${selectedSection.id}:${item.file.id}`; - if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) { - loggedMissingReviewTokenKeys.add(missingTokenKey); - logReviewDiffDiagnostic("rendering file without tokens", { - sectionId: selectedSection.id, - fileId: item.file.id, - filePath: item.file.path, - highlightedFileKnownInState: - deferredHighlightedFilesById[item.file.id] !== undefined, - }); - } - } - - const selectionState = - pendingSelectionForFile?.anchorIndex === item.lineIndex - ? ("anchor" as const) - : selectedTargetForFile && - item.lineIndex >= selectedTargetForFile.startIndex && - item.lineIndex <= selectedTargetForFile.endIndex - ? ("selected" as const) - : null; - - renderedItem = ( - - } - viewportWidth={viewportWidth} - > - - handlePressLine({ - sectionTitle: selectedSection.title, - filePath: item.file.path, - lines: fileLineRows, - lineIndex: item.lineIndex, - }) - } - onStartRangeSelection={() => - handleStartRangeSelection({ - sectionTitle: selectedSection.title, - filePath: item.file.path, - lines: fileLineRows, - lineIndex: item.lineIndex, - }) - } - /> - - ); - break; - } - } - - return renderedItem; - }, - [ - activeCommentTarget, - handlePressLine, - handleRevealLargeDiff, - handleStartRangeSelection, - handleToggleExpandedFile, - handleToggleViewedFile, - getReviewFileHorizontalOffset, - deferredHighlightedFilesById, - pendingCommentSelection, - reviewContentWidthByFileId, - reviewGutterWidthByFileId, - reviewLineRowsByFileId, - selectedSection, - selectedTheme, - viewedFileIdSet, - viewportWidth, - ], - ); - return ( <> { - if (reviewCache.threadKey) { - setReviewSelectedSectionId(reviewCache.threadKey, section.id); - } - }} + onPress={() => selectSection(section.id)} subtitle={section.subtitle ?? undefined} > {section.title} @@ -1621,35 +340,53 @@ export function ReviewSheet() { {selectedSection && parsedDiff.kind === "files" ? ( - item.id} - initialNumToRender={20} - maxToRenderPerBatch={20} - updateCellsBatchingPeriod={16} - windowSize={5} - removeClippedSubviews={false} - keyboardShouldPersistTaps="handled" - ListHeaderComponent={listHeader} - contentContainerStyle={{ + + > + {listHeader} + + + + ) : ( {listHeader} @@ -1686,22 +423,11 @@ export function ReviewSheet() { ) : null} )} - { - if (activeCommentTarget && environmentId && threadId) { - router.push({ - pathname: "/threads/[environmentId]/[threadId]/review-comment", - params: { environmentId, threadId }, - }); - } - }} - onClear={() => { - clearReviewCommentTarget(); - setPendingCommentSelection(null); - }} + title={commentSelection.selectionAction?.title ?? null} + onOpenComment={commentSelection.selectionAction?.onOpenComment ?? null} + onClear={commentSelection.clearSelection} /> diff --git a/apps/mobile/src/features/review/reviewFileVisibility.test.ts b/apps/mobile/src/features/review/reviewFileVisibility.test.ts new file mode 100644 index 0000000000..4e7cb1c200 --- /dev/null +++ b/apps/mobile/src/features/review/reviewFileVisibility.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vitest"; + +import { + getDefaultReviewExpandedFileIds, + getValidExplicitReviewFileIds, + getValidReviewFileIds, + removeReviewFileId, + toggleReviewFileId, +} from "./reviewFileVisibility"; +import type { ReviewRenderableFile } from "./reviewModel"; + +function makeFile(id: string): ReviewRenderableFile { + return { + id, + cacheKey: id, + path: id, + previousPath: null, + changeType: "change", + additions: 0, + deletions: 0, + languageHint: null, + additionLines: [], + deletionLines: [], + rows: [], + }; +} + +describe("review file visibility", () => { + const files = [makeFile("a.ts"), makeFile("b.ts")]; + + it("defaults expanded files to every renderable file", () => { + expect(getDefaultReviewExpandedFileIds(files)).toEqual(["a.ts", "b.ts"]); + expect(getValidReviewFileIds(files, undefined)).toEqual(["a.ts", "b.ts"]); + }); + + it("filters stale cached file ids", () => { + expect(getValidReviewFileIds(files, ["missing.ts", "b.ts"])).toEqual(["b.ts"]); + expect(getValidExplicitReviewFileIds(files, undefined)).toEqual([]); + expect(getValidExplicitReviewFileIds(files, ["a.ts", "missing.ts"])).toEqual(["a.ts"]); + }); + + it("toggles and removes ids without mutating the original array", () => { + const original = ["a.ts"]; + + expect(toggleReviewFileId(original, "b.ts")).toEqual(["a.ts", "b.ts"]); + expect(toggleReviewFileId(original, "a.ts")).toEqual([]); + expect(removeReviewFileId(original, "a.ts")).toEqual([]); + expect(original).toEqual(["a.ts"]); + }); +}); diff --git a/apps/mobile/src/features/review/reviewFileVisibility.ts b/apps/mobile/src/features/review/reviewFileVisibility.ts new file mode 100644 index 0000000000..53f2d7f5f9 --- /dev/null +++ b/apps/mobile/src/features/review/reviewFileVisibility.ts @@ -0,0 +1,116 @@ +import { useCallback, useMemo } from "react"; + +import { updateReviewExpandedFileIds, updateReviewViewedFileIds } from "./reviewState"; +import type { ReviewRenderableFile } from "./reviewModel"; + +export function getDefaultReviewExpandedFileIds( + files: ReadonlyArray, +): ReadonlyArray { + return files.map((file) => file.id); +} + +export function getValidReviewFileIds( + files: ReadonlyArray, + fileIds: ReadonlyArray | undefined, +): ReadonlyArray { + if (fileIds === undefined) { + return getDefaultReviewExpandedFileIds(files); + } + + const fileIdSet = new Set(files.map((file) => file.id)); + return fileIds.filter((id) => fileIdSet.has(id)); +} + +export function getValidExplicitReviewFileIds( + files: ReadonlyArray, + fileIds: ReadonlyArray | undefined, +): ReadonlyArray { + if (fileIds === undefined) { + return []; + } + + return getValidReviewFileIds(files, fileIds); +} + +export function toggleReviewFileId( + fileIds: ReadonlyArray, + fileId: string, +): ReadonlyArray { + return fileIds.includes(fileId) ? fileIds.filter((id) => id !== fileId) : [...fileIds, fileId]; +} + +export function removeReviewFileId( + fileIds: ReadonlyArray, + fileId: string, +): ReadonlyArray { + return fileIds.includes(fileId) ? fileIds.filter((id) => id !== fileId) : fileIds; +} + +export function useReviewFileVisibility(input: { + readonly threadKey: string | null; + readonly sectionId: string | null; + readonly files: ReadonlyArray; + readonly cachedExpandedFileIds: ReadonlyArray | undefined; + readonly cachedViewedFileIds: ReadonlyArray | undefined; +}) { + const { cachedExpandedFileIds, cachedViewedFileIds, files, sectionId, threadKey } = input; + + const expandedFileIds = useMemo( + () => getValidReviewFileIds(files, cachedExpandedFileIds), + [cachedExpandedFileIds, files], + ); + const viewedFileIds = useMemo( + () => getValidExplicitReviewFileIds(files, cachedViewedFileIds), + [cachedViewedFileIds, files], + ); + const collapsedFileIds = useMemo(() => { + const expandedFileIdSet = new Set(expandedFileIds); + return files.reduce((fileIds, file) => { + if (!expandedFileIdSet.has(file.id)) { + fileIds.push(file.id); + } + return fileIds; + }, []); + }, [expandedFileIds, files]); + + const toggleExpandedFile = useCallback( + (fileId: string) => { + if (!threadKey || !sectionId) { + return; + } + + updateReviewExpandedFileIds(threadKey, sectionId, (existing) => + toggleReviewFileId(getValidReviewFileIds(files, existing), fileId), + ); + }, + [files, sectionId, threadKey], + ); + + const toggleViewedFile = useCallback( + (fileId: string) => { + if (!threadKey || !sectionId) { + return; + } + + const shouldCollapse = !viewedFileIds.includes(fileId); + updateReviewViewedFileIds(threadKey, sectionId, (existing) => + toggleReviewFileId(getValidExplicitReviewFileIds(files, existing), fileId), + ); + + if (shouldCollapse) { + updateReviewExpandedFileIds(threadKey, sectionId, (existing) => + removeReviewFileId(getValidReviewFileIds(files, existing), fileId), + ); + } + }, + [files, sectionId, threadKey, viewedFileIds], + ); + + return { + expandedFileIds, + viewedFileIds, + collapsedFileIds, + toggleExpandedFile, + toggleViewedFile, + }; +} diff --git a/apps/mobile/src/features/review/reviewState.ts b/apps/mobile/src/features/review/reviewState.ts index bd5fc69703..7d30813813 100644 --- a/apps/mobile/src/features/review/reviewState.ts +++ b/apps/mobile/src/features/review/reviewState.ts @@ -78,6 +78,18 @@ const reviewParsedDiffBySectionCacheKeyAtom = Atom.family((cacheKey: string) => ), ); +export interface ReviewCacheForThread { + readonly threadKey: string | null; + readonly gitSections: ReadonlyArray; + readonly turnDiffById: Readonly>; + readonly selectedSectionId: string | null; + readonly expandedFileIdsBySection: Readonly | undefined>>; + readonly revealedLargeFileIdsBySection: Readonly< + Record | undefined> + >; + readonly viewedFileIdsBySection: Readonly | undefined>>; +} + function buildThreadKey(input: { readonly environmentId?: EnvironmentId; readonly threadId?: ThreadId; @@ -94,7 +106,7 @@ function buildSectionCacheKey(threadKey: string, sectionId: string): string { export function useReviewCacheForThread(input: { readonly environmentId?: EnvironmentId; readonly threadId?: ThreadId; -}) { +}): ReviewCacheForThread { const threadKey = buildThreadKey(input); const gitSections = useAtomValue( threadKey ? reviewGitSectionsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_GIT_SECTIONS_ATOM, diff --git a/apps/mobile/src/features/review/useNativeReviewDiffBridge.test.ts b/apps/mobile/src/features/review/useNativeReviewDiffBridge.test.ts new file mode 100644 index 0000000000..479e34cc8f --- /dev/null +++ b/apps/mobile/src/features/review/useNativeReviewDiffBridge.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vitest"; + +import { buildNativeReviewTokensResetKey, hashReviewDiffKey } from "./useNativeReviewDiffBridge"; + +describe("native review diff bridge", () => { + it("builds stable reset keys from the rendered diff identity", () => { + const input = { + threadKey: "env:thread", + sectionId: "turn:2", + scheme: "dark" as const, + diff: "diff --git a/a.ts b/a.ts", + fileCount: 1, + rowCount: 4, + }; + + expect(buildNativeReviewTokensResetKey(input)).toBe(buildNativeReviewTokensResetKey(input)); + expect(buildNativeReviewTokensResetKey({ ...input, rowCount: 5 })).not.toBe( + buildNativeReviewTokensResetKey(input), + ); + expect(buildNativeReviewTokensResetKey({ ...input, diff: null })).toContain(":empty:"); + }); + + it("includes diff length in the hash key to reduce accidental collisions", () => { + expect(hashReviewDiffKey("abc")).toMatch(/^3:/); + expect(hashReviewDiffKey("abcd")).toMatch(/^4:/); + }); +}); diff --git a/apps/mobile/src/features/review/useNativeReviewDiffBridge.ts b/apps/mobile/src/features/review/useNativeReviewDiffBridge.ts new file mode 100644 index 0000000000..d0030e51a4 --- /dev/null +++ b/apps/mobile/src/features/review/useNativeReviewDiffBridge.ts @@ -0,0 +1,152 @@ +import { useCallback, useMemo, useState } from "react"; +import type { NativeSyntheticEvent } from "react-native"; + +import { type NativeReviewDiffHighlightScheme } from "../diffs/nativeReviewDiffHighlighter"; +import { + createNativeReviewDiffTheme, + NATIVE_REVIEW_DIFF_STYLE, + type NativeReviewDiffData, +} from "./nativeReviewDiffAdapter"; +import { useNativeReviewDiffHighlighting } from "./useNativeReviewDiffHighlighting"; + +export function hashReviewDiffKey(diff: string | null | undefined): string { + if (!diff) { + return "empty"; + } + + let hash = 5381; + for (let index = 0; index < diff.length; index += 1) { + hash = (hash * 33) ^ diff.charCodeAt(index); + } + + return `${diff.length}:${(hash >>> 0).toString(36)}`; +} + +export function buildNativeReviewTokensResetKey(input: { + readonly threadKey: string | null; + readonly sectionId: string | null; + readonly scheme: NativeReviewDiffHighlightScheme; + readonly diff: string | null | undefined; + readonly fileCount: number; + readonly rowCount: number; +}): string { + return [ + input.threadKey ?? "none", + input.sectionId ?? "none", + input.scheme, + hashReviewDiffKey(input.diff), + input.fileCount, + input.rowCount, + ].join(":"); +} + +export function useNativeReviewDiffBridge(input: { + readonly threadKey: string | null; + readonly sectionId: string | null; + readonly diff: string | null | undefined; + readonly data: NativeReviewDiffData; + readonly scheme: NativeReviewDiffHighlightScheme; + readonly collapsedFileIds: ReadonlyArray; + readonly viewedFileIds: ReadonlyArray; + readonly selectedRowIds: ReadonlyArray; + readonly canHighlight: boolean; +}) { + const { + canHighlight, + collapsedFileIds, + data, + diff, + scheme, + sectionId, + selectedRowIds, + threadKey, + viewedFileIds, + } = input; + const [collapsedCommentIds, setCollapsedCommentIds] = useState>( + () => new Set(), + ); + + const theme = useMemo(() => createNativeReviewDiffTheme(scheme), [scheme]); + const rowsJson = useMemo(() => JSON.stringify(data.rows), [data.rows]); + const collapsedFileIdsJson = useMemo(() => JSON.stringify(collapsedFileIds), [collapsedFileIds]); + const viewedFileIdsJson = useMemo(() => JSON.stringify(viewedFileIds), [viewedFileIds]); + const selectedRowIdsJson = useMemo(() => JSON.stringify(selectedRowIds), [selectedRowIds]); + const collapsedCommentIdsJson = useMemo( + () => JSON.stringify(Array.from(collapsedCommentIds)), + [collapsedCommentIds], + ); + const themeJson = useMemo(() => JSON.stringify(theme), [theme]); + const styleJson = useMemo(() => JSON.stringify(NATIVE_REVIEW_DIFF_STYLE), []); + const tokensResetKey = useMemo( + () => + buildNativeReviewTokensResetKey({ + threadKey, + sectionId, + scheme, + diff, + fileCount: data.files.length, + rowCount: data.rows.length, + }), + [data.files.length, data.rows.length, diff, scheme, sectionId, threadKey], + ); + const { tokensPatchJson, updateVisibleRange } = useNativeReviewDiffHighlighting({ + files: data.files, + rows: data.rows, + scheme, + resetKey: tokensResetKey, + enabled: canHighlight, + }); + + const onDebug = useCallback( + (event: NativeSyntheticEvent>) => { + const payload = event.nativeEvent; + const message = payload.message; + if ( + (message === "draw-metrics" || message === "visible-range") && + typeof payload.firstRowIndex === "number" && + typeof payload.lastRowIndex === "number" + ) { + updateVisibleRange({ + firstRowIndex: payload.firstRowIndex, + lastRowIndex: payload.lastRowIndex, + }); + } + }, + [updateVisibleRange], + ); + + const onToggleComment = useCallback( + (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => { + const { commentId } = event.nativeEvent; + if (!commentId) { + return; + } + + setCollapsedCommentIds((current) => { + const next = new Set(current); + if (next.has(commentId)) { + next.delete(commentId); + } else { + next.add(commentId); + } + return next; + }); + }, + [], + ); + + return { + theme, + rowsJson, + collapsedFileIdsJson, + collapsedCommentIdsJson, + viewedFileIdsJson, + selectedRowIdsJson, + themeJson, + styleJson, + tokensPatchJson, + tokensResetKey, + onDebug, + onToggleComment, + }; +} diff --git a/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts b/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts new file mode 100644 index 0000000000..98df26641a --- /dev/null +++ b/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts @@ -0,0 +1,136 @@ +import { useCallback, useEffect, useRef, useState } from "react"; + +import { + highlightNativeReviewDiffVisibleRows, + type NativeReviewDiffHighlightEngine, + type NativeReviewDiffHighlightScheme, +} from "../diffs/nativeReviewDiffHighlighter"; +import type { NativeReviewDiffRow } from "../diffs/nativeReviewDiffSurface"; +import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes"; + +interface NativeReviewVisibleRange { + readonly firstRowIndex: number; + readonly lastRowIndex: number; +} + +function createEmptyTokenPatch(resetKey: string): string { + return JSON.stringify({ resetKey, tokensByRowId: {} }); +} + +function isReviewDiffDebugLoggingEnabled(): boolean { + return typeof __DEV__ !== "undefined" ? __DEV__ : false; +} + +function logReviewDiffDiagnostic(message: string, details?: Record): void { + if (!isReviewDiffDebugLoggingEnabled()) { + return; + } + + if (details) { + console.log(`[review-sheet] ${message}`, details); + return; + } + + console.log(`[review-sheet] ${message}`); +} + +export function useNativeReviewDiffHighlighting(input: { + readonly files: ReadonlyArray; + readonly rows: ReadonlyArray; + readonly scheme: NativeReviewDiffHighlightScheme; + readonly resetKey: string; + readonly enabled: boolean; +}) { + const { enabled, files, resetKey, rows, scheme } = input; + const highlightedRowIdsRef = useRef>(new Set()); + const visibleRangeRef = useRef({ + firstRowIndex: 0, + lastRowIndex: 80, + }); + const visibleChunkIndexRef = useRef(0); + const [tokensPatchJson, setTokensPatchJson] = useState(() => createEmptyTokenPatch(resetKey)); + const [visibleHighlightRequest, setVisibleHighlightRequest] = useState(0); + + useEffect(() => { + highlightedRowIdsRef.current = new Set(); + visibleChunkIndexRef.current = 0; + visibleRangeRef.current = { firstRowIndex: 0, lastRowIndex: 80 }; + setTokensPatchJson(createEmptyTokenPatch(resetKey)); + if (enabled && rows.length > 0) { + setVisibleHighlightRequest((request) => request + 1); + } + }, [enabled, resetKey, rows.length]); + + useEffect(() => { + if (!enabled || rows.length === 0) { + return; + } + + const abortController = new AbortController(); + const requestRange = visibleRangeRef.current; + const engine: NativeReviewDiffHighlightEngine = "native"; + + void (async () => { + try { + const result = await highlightNativeReviewDiffVisibleRows({ + files, + rows, + scheme, + engine, + firstRowIndex: requestRange.firstRowIndex, + lastRowIndex: requestRange.lastRowIndex, + alreadyHighlightedRowIds: highlightedRowIdsRef.current, + signal: abortController.signal, + }); + + if (abortController.signal.aborted || result.rowCount === 0) { + return; + } + + for (const rowId of Object.keys(result.tokensByRowId)) { + highlightedRowIdsRef.current.add(rowId); + } + + const chunkIndex = visibleChunkIndexRef.current; + visibleChunkIndexRef.current += 1; + setTokensPatchJson( + JSON.stringify({ + resetKey, + chunkIndex, + fileId: "visible", + filePath: "visible rows", + language: "diff", + lineCount: result.rowCount, + durationMs: result.durationMs, + tokensByRowId: result.tokensByRowId, + }), + ); + } catch (error) { + if (!abortController.signal.aborted) { + logReviewDiffDiagnostic("native visible highlight failed", { + error: error instanceof Error ? error.message : String(error), + }); + } + } + })(); + + return () => abortController.abort(); + }, [enabled, files, resetKey, rows, scheme, visibleHighlightRequest]); + + const updateVisibleRange = useCallback((nextRange: NativeReviewVisibleRange) => { + const previousRange = visibleRangeRef.current; + const movedRows = + Math.abs(nextRange.firstRowIndex - previousRange.firstRowIndex) + + Math.abs(nextRange.lastRowIndex - previousRange.lastRowIndex); + + visibleRangeRef.current = nextRange; + if (movedRows >= 20) { + setVisibleHighlightRequest((request) => request + 1); + } + }, []); + + return { + tokensPatchJson, + updateVisibleRange, + }; +} diff --git a/apps/mobile/src/features/review/useReviewCommentSelectionController.ts b/apps/mobile/src/features/review/useReviewCommentSelectionController.ts new file mode 100644 index 0000000000..683508b2b1 --- /dev/null +++ b/apps/mobile/src/features/review/useReviewCommentSelectionController.ts @@ -0,0 +1,193 @@ +import { useCallback, useEffect, useMemo, useState } from "react"; +import type { NativeSyntheticEvent } from "react-native"; +import { useRouter } from "expo-router"; + +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; + +import { + buildReviewCommentTarget, + clearReviewCommentTarget, + formatReviewSelectedRangeLabel, + getSelectedReviewCommentLines, + setReviewCommentTarget, + useReviewCommentTarget, +} from "./reviewCommentSelection"; +import type { + NativeReviewDiffData, + NativeReviewDiffCommentTarget, +} from "./nativeReviewDiffAdapter"; +import type { ReviewSectionItem } from "./reviewModel"; + +interface PendingNativeCommentSelection extends NativeReviewDiffCommentTarget { + readonly sectionId: string; + readonly sectionTitle: string; + readonly rowId: string; +} + +export function useReviewCommentSelectionController(input: { + readonly environmentId?: EnvironmentId; + readonly threadId?: ThreadId; + readonly selectedSection: ReviewSectionItem | null; + readonly nativeReviewDiffData: NativeReviewDiffData; +}) { + const { environmentId, nativeReviewDiffData, selectedSection, threadId } = input; + const { push } = useRouter(); + const activeCommentTarget = useReviewCommentTarget(); + const [pendingNativeCommentSelection, setPendingNativeCommentSelection] = + useState(null); + + const openReviewCommentSheet = useCallback(() => { + if (!environmentId || !threadId) { + return; + } + + push({ + pathname: "/threads/[environmentId]/[threadId]/review-comment", + params: { environmentId, threadId }, + }); + }, [environmentId, push, threadId]); + + const selectedRowIds = useMemo(() => { + if ( + activeCommentTarget && + activeCommentTarget.sectionTitle === selectedSection?.title && + activeCommentTarget.startIndex !== activeCommentTarget.endIndex + ) { + return getSelectedReviewCommentLines(activeCommentTarget).flatMap((line) => { + const rowId = nativeReviewDiffData.rowIdByCommentLineId.get(line.id); + return rowId ? [rowId] : []; + }); + } + + return pendingNativeCommentSelection ? [pendingNativeCommentSelection.rowId] : []; + }, [ + activeCommentTarget, + nativeReviewDiffData.rowIdByCommentLineId, + pendingNativeCommentSelection, + selectedSection?.title, + ]); + + const selectionAction = useMemo(() => { + if ( + activeCommentTarget && + activeCommentTarget.sectionTitle === selectedSection?.title && + activeCommentTarget.startIndex !== activeCommentTarget.endIndex + ) { + return { + title: `Comment on ${formatReviewSelectedRangeLabel(activeCommentTarget)}`, + onOpenComment: openReviewCommentSheet, + }; + } + + if ( + pendingNativeCommentSelection && + pendingNativeCommentSelection.sectionTitle === selectedSection?.title + ) { + return { + title: "Select range end", + onOpenComment: null, + }; + } + + return null; + }, [ + activeCommentTarget, + openReviewCommentSheet, + pendingNativeCommentSelection, + selectedSection?.title, + ]); + + useEffect(() => { + clearReviewCommentTarget(); + setPendingNativeCommentSelection(null); + }, [selectedSection?.id]); + + useEffect(() => { + if (activeCommentTarget === null) { + setPendingNativeCommentSelection(null); + } + }, [activeCommentTarget]); + + const onPressLine = useCallback( + ( + event: NativeSyntheticEvent<{ + readonly rowId?: string; + readonly gesture?: "tap" | "longPress"; + }>, + ) => { + if (!selectedSection) { + return; + } + + const { rowId, gesture } = event.nativeEvent; + if (!rowId) { + return; + } + + const target = nativeReviewDiffData.commentTargetsByRowId.get(rowId); + if (!target) { + return; + } + + if (gesture === "longPress") { + clearReviewCommentTarget(); + setPendingNativeCommentSelection({ + ...target, + sectionId: selectedSection.id, + sectionTitle: selectedSection.title, + rowId, + }); + return; + } + + if ( + pendingNativeCommentSelection && + pendingNativeCommentSelection.sectionTitle === selectedSection.title && + pendingNativeCommentSelection.filePath === target.filePath + ) { + setReviewCommentTarget( + buildReviewCommentTarget( + { + sectionTitle: pendingNativeCommentSelection.sectionTitle, + sectionId: pendingNativeCommentSelection.sectionId, + filePath: pendingNativeCommentSelection.filePath, + lines: pendingNativeCommentSelection.lines, + }, + pendingNativeCommentSelection.lineIndex, + target.lineIndex, + ), + ); + return; + } + + setPendingNativeCommentSelection(null); + setReviewCommentTarget({ + sectionTitle: selectedSection.title, + sectionId: selectedSection.id, + filePath: target.filePath, + lines: target.lines, + startIndex: target.lineIndex, + endIndex: target.lineIndex, + }); + openReviewCommentSheet(); + }, + [ + nativeReviewDiffData.commentTargetsByRowId, + openReviewCommentSheet, + pendingNativeCommentSelection, + selectedSection, + ], + ); + + const clearSelection = useCallback(() => { + clearReviewCommentTarget(); + setPendingNativeCommentSelection(null); + }, []); + + return { + selectedRowIds, + selectionAction, + onPressLine, + clearSelection, + }; +} diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts new file mode 100644 index 0000000000..ee04673dfc --- /dev/null +++ b/apps/mobile/src/features/review/useReviewDiffData.ts @@ -0,0 +1,109 @@ +import { useEffect, useMemo } from "react"; + +import { countReviewCommentContexts, parseReviewInlineComments } from "./reviewCommentSelection"; +import { buildNativeReviewDiffData } from "./nativeReviewDiffAdapter"; +import { markReviewEvent, measureReviewWork } from "./reviewPerf"; +import { getCachedReviewParsedDiff } from "./reviewState"; +import type { ReviewParsedDiff, ReviewSectionItem } from "./reviewModel"; + +function isReviewDiffDebugLoggingEnabled(): boolean { + return typeof __DEV__ !== "undefined" ? __DEV__ : false; +} + +function logReviewDiffDiagnostic(message: string, details?: Record): void { + if (!isReviewDiffDebugLoggingEnabled()) { + return; + } + + if (details) { + console.log(`[review-sheet] ${message}`, details); + return; + } + + console.log(`[review-sheet] ${message}`); +} + +export function formatHeaderDiffSummary(parsedDiff: ReviewParsedDiff): { + readonly additions: string | null; + readonly deletions: string | null; +} { + if (parsedDiff.kind !== "files") { + return { additions: null, deletions: null }; + } + + return { + additions: `+${parsedDiff.additions}`, + deletions: `-${parsedDiff.deletions}`, + }; +} + +export function useReviewDiffData(input: { + readonly threadKey: string | null; + readonly selectedSection: ReviewSectionItem | null; + readonly draftMessage: string; +}) { + const { draftMessage, selectedSection, threadKey } = input; + const parsedDiff = useMemo( + () => + measureReviewWork("parse-diff", () => + getCachedReviewParsedDiff({ + threadKey, + sectionId: selectedSection?.id ?? null, + diff: selectedSection?.diff, + }), + ), + [selectedSection?.diff, selectedSection?.id, threadKey], + ); + const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]); + const inlineReviewComments = useMemo( + () => parseReviewInlineComments(draftMessage), + [draftMessage], + ); + const selectedSectionInlineComments = useMemo( + () => + selectedSection + ? inlineReviewComments.filter((comment) => comment.sectionId === selectedSection.id) + : [], + [inlineReviewComments, selectedSection], + ); + const nativeReviewDiffData = useMemo( + () => + measureReviewWork("build-native-diff-data", () => + buildNativeReviewDiffData({ + parsedDiff, + comments: selectedSectionInlineComments, + }), + ), + [parsedDiff, selectedSectionInlineComments], + ); + const pendingReviewCommentCount = useMemo( + () => countReviewCommentContexts(draftMessage), + [draftMessage], + ); + + useEffect(() => { + if (parsedDiff.kind !== "files") { + return; + } + + markReviewEvent("parsed-diff-ready", { + sectionId: selectedSection?.id ?? null, + fileCount: parsedDiff.fileCount, + additions: parsedDiff.additions, + deletions: parsedDiff.deletions, + renderedItems: nativeReviewDiffData.rows.length, + }); + logReviewDiffDiagnostic("parsed diff files", { + selectedSectionId: selectedSection?.id ?? null, + fileCount: parsedDiff.fileCount, + renderableFileCount: parsedDiff.files.length, + }); + }, [nativeReviewDiffData.rows.length, parsedDiff, selectedSection?.id]); + + return { + parsedDiff, + headerDiffSummary, + nativeReviewDiffData, + pendingReviewCommentCount, + }; +} diff --git a/apps/mobile/src/features/review/useReviewSections.ts b/apps/mobile/src/features/review/useReviewSections.ts new file mode 100644 index 0000000000..248a6cb139 --- /dev/null +++ b/apps/mobile/src/features/review/useReviewSections.ts @@ -0,0 +1,242 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; + +import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts"; + +import { getEnvironmentClient } from "../../state/environment-session-registry"; +import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree"; +import { useSelectedThreadDetail } from "../../state/use-thread-detail"; +import { + buildReviewSectionItems, + getDefaultReviewSectionId, + getReadyReviewCheckpoints, + getReviewSectionIdForCheckpoint, +} from "./reviewModel"; +import { + setReviewGitSections, + setReviewSelectedSectionId, + setReviewTurnDiff, + type ReviewCacheForThread, +} from "./reviewState"; + +export function useReviewSections(input: { + readonly environmentId?: EnvironmentId; + readonly threadId?: ThreadId; + readonly reviewCache: ReviewCacheForThread; +}) { + const { environmentId, reviewCache, threadId } = input; + const selectedThread = useSelectedThreadDetail(); + const { selectedThreadCwd } = useSelectedThreadWorktree(); + const [loadingTurnIds, setLoadingTurnIds] = useState>({}); + const [loadingGitDiffs, setLoadingGitDiffs] = useState(false); + const [error, setError] = useState(null); + const turnDiffByIdRef = useRef(reviewCache.turnDiffById); + + useEffect(() => { + turnDiffByIdRef.current = reviewCache.turnDiffById; + }, [reviewCache.turnDiffById]); + + const readyCheckpoints = useMemo( + () => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []), + [selectedThread?.checkpoints], + ); + const checkpointBySectionId = useMemo(() => { + return Object.fromEntries( + readyCheckpoints.map((checkpoint) => [ + getReviewSectionIdForCheckpoint(checkpoint), + checkpoint, + ]), + ) as Record; + }, [readyCheckpoints]); + const reviewSections = useMemo( + () => + buildReviewSectionItems({ + checkpoints: readyCheckpoints, + gitSections: reviewCache.gitSections, + turnDiffById: reviewCache.turnDiffById, + loadingTurnIds, + }), + [loadingTurnIds, readyCheckpoints, reviewCache.gitSections, reviewCache.turnDiffById], + ); + const selectedSection = useMemo( + () => + reviewSections.find((section) => section.id === reviewCache.selectedSectionId) ?? + reviewSections[0] ?? + null, + [reviewCache.selectedSectionId, reviewSections], + ); + const fallbackSectionId = useMemo( + () => getDefaultReviewSectionId(reviewSections), + [reviewSections], + ); + const hasReviewSections = reviewSections.length > 0; + const selectedSectionIdExists = useMemo( + () => + reviewCache.selectedSectionId + ? reviewSections.some((section) => section.id === reviewCache.selectedSectionId) + : false, + [reviewCache.selectedSectionId, reviewSections], + ); + + const loadGitDiffs = useCallback(async () => { + if (!environmentId || !selectedThreadCwd) { + return; + } + + const client = getEnvironmentClient(environmentId); + if (!client) { + setError("Remote connection is not ready."); + return; + } + + setLoadingGitDiffs(true); + setError(null); + try { + const result = await client.review.getDiffPreview({ cwd: selectedThreadCwd }); + if (reviewCache.threadKey) { + setReviewGitSections(reviewCache.threadKey, result.sources); + } + } catch (cause) { + setError(cause instanceof Error ? cause.message : "Failed to load review diffs."); + } finally { + setLoadingGitDiffs(false); + } + }, [environmentId, reviewCache.threadKey, selectedThreadCwd]); + + const loadTurnDiff = useCallback( + async (checkpoint: OrchestrationCheckpointSummary, force = false) => { + if (!environmentId || !threadId) { + return; + } + + const sectionId = getReviewSectionIdForCheckpoint(checkpoint); + if (reviewCache.threadKey) { + setReviewSelectedSectionId(reviewCache.threadKey, sectionId); + } + + if (!force && turnDiffByIdRef.current[sectionId] !== undefined) { + return; + } + + const client = getEnvironmentClient(environmentId); + if (!client) { + setError("Remote connection is not ready."); + return; + } + + setLoadingTurnIds((current) => ({ ...current, [sectionId]: true })); + setError(null); + try { + const result = await client.orchestration.getTurnDiff({ + threadId, + fromTurnCount: Math.max(0, checkpoint.checkpointTurnCount - 1), + toTurnCount: checkpoint.checkpointTurnCount, + }); + if (reviewCache.threadKey) { + setReviewTurnDiff(reviewCache.threadKey, sectionId, result.diff); + } + } catch (cause) { + setError(cause instanceof Error ? cause.message : "Failed to load turn diff."); + } finally { + setLoadingTurnIds((current) => { + const next = { ...current }; + delete next[sectionId]; + return next; + }); + } + }, + [environmentId, reviewCache.threadKey, threadId], + ); + + useEffect(() => { + void loadGitDiffs(); + }, [loadGitDiffs]); + + useEffect(() => { + if (!hasReviewSections) { + return; + } + + if (reviewCache.threadKey && (!reviewCache.selectedSectionId || !selectedSectionIdExists)) { + setReviewSelectedSectionId(reviewCache.threadKey, fallbackSectionId); + } + }, [ + fallbackSectionId, + hasReviewSections, + reviewCache.selectedSectionId, + reviewCache.threadKey, + selectedSectionIdExists, + ]); + + const latestCheckpoint = readyCheckpoints[0] ?? null; + const latestSectionId = latestCheckpoint + ? getReviewSectionIdForCheckpoint(latestCheckpoint) + : null; + const latestTurnDiffLoaded = latestSectionId + ? reviewCache.turnDiffById[latestSectionId] !== undefined + : true; + const latestTurnDiffLoading = latestSectionId ? loadingTurnIds[latestSectionId] === true : false; + + useEffect(() => { + if (!latestCheckpoint || !latestSectionId || latestTurnDiffLoaded || latestTurnDiffLoading) { + return; + } + + void loadTurnDiff(latestCheckpoint); + }, [ + latestCheckpoint, + latestSectionId, + latestTurnDiffLoaded, + latestTurnDiffLoading, + loadTurnDiff, + ]); + + const selectedTurnCheckpoint = + selectedSection?.kind === "turn" ? (checkpointBySectionId[selectedSection.id] ?? null) : null; + const selectedTurnDiffMissing = + selectedSection?.kind === "turn" && selectedSection.diff === null && selectedTurnCheckpoint; + const selectedTurnDiffLoading = + selectedSection?.kind === "turn" ? loadingTurnIds[selectedSection.id] === true : false; + + useEffect(() => { + if (!selectedTurnDiffMissing || selectedTurnDiffLoading) { + return; + } + + void loadTurnDiff(selectedTurnDiffMissing); + }, [loadTurnDiff, selectedTurnDiffLoading, selectedTurnDiffMissing]); + + const refreshSelectedSection = useCallback(async () => { + if (!selectedSection) { + return; + } + + if (selectedSection.kind === "turn") { + const checkpoint = checkpointBySectionId[selectedSection.id]; + if (checkpoint) { + await loadTurnDiff(checkpoint, true); + } + return; + } + + await loadGitDiffs(); + }, [checkpointBySectionId, loadGitDiffs, loadTurnDiff, selectedSection]); + + const selectSection = useCallback( + (sectionId: string) => { + if (reviewCache.threadKey) { + setReviewSelectedSectionId(reviewCache.threadKey, sectionId); + } + }, + [reviewCache.threadKey], + ); + + return { + error, + loadingGitDiffs, + loadingTurnIds, + reviewSections, + selectedSection, + refreshSelectedSection, + selectSection, + }; +} diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 655d39229d..78622fb1d8 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -41,6 +41,7 @@ import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer"; import { useSelectedThreadCommands } from "../../state/use-selected-thread-commands"; import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions"; import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state"; +import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests"; import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree"; import { useThreadComposerState } from "../../state/use-thread-composer-state"; @@ -65,9 +66,8 @@ export function ThreadRouteScreen() { const composer = useThreadComposerState(); const gitState = useSelectedThreadGitState(); const gitActions = useSelectedThreadGitActions(); + const requests = useSelectedThreadRequests(); const commands = useSelectedThreadCommands({ - activePendingUserInput: composer.activePendingUserInput, - activePendingUserInputAnswers: composer.activePendingUserInputAnswers, refreshSelectedThreadGitStatus: gitActions.refreshSelectedThreadGitStatus, }); const refreshSelectedThread = commands.onRefresh; @@ -369,12 +369,12 @@ export function ThreadRouteScreen() { bearerToken={selectedEnvironmentConnection?.bearerToken ?? null} selectedThreadFeed={composer.selectedThreadFeed} activeWorkStartedAt={composer.activeWorkStartedAt} - activePendingApproval={composer.activePendingApproval} - respondingApprovalId={commands.respondingApprovalId} - activePendingUserInput={composer.activePendingUserInput} - activePendingUserInputDrafts={composer.activePendingUserInputDrafts} - activePendingUserInputAnswers={composer.activePendingUserInputAnswers} - respondingUserInputId={commands.respondingUserInputId} + activePendingApproval={requests.activePendingApproval} + respondingApprovalId={requests.respondingApprovalId} + activePendingUserInput={requests.activePendingUserInput} + activePendingUserInputDrafts={requests.activePendingUserInputDrafts} + activePendingUserInputAnswers={requests.activePendingUserInputAnswers} + respondingUserInputId={requests.respondingUserInputId} draftMessage={composer.draftMessage} draftAttachments={composer.draftAttachments} connectionStateLabel={routeConnectionState} @@ -395,10 +395,10 @@ export function ThreadRouteScreen() { onUpdateThreadModelSelection={commands.onUpdateThreadModelSelection} onUpdateThreadRuntimeMode={commands.onUpdateThreadRuntimeMode} onUpdateThreadInteractionMode={commands.onUpdateThreadInteractionMode} - onRespondToApproval={commands.onRespondToApproval} - onSelectUserInputOption={composer.onSelectUserInputOption} - onChangeUserInputCustomAnswer={composer.onChangeUserInputCustomAnswer} - onSubmitUserInput={commands.onSubmitUserInput} + onRespondToApproval={requests.onRespondToApproval} + onSelectUserInputOption={requests.onSelectUserInputOption} + onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer} + onSubmitUserInput={requests.onSubmitUserInput} /> | null; readonly refreshSelectedThreadGitStatus: (options?: { readonly quiet?: boolean; readonly cwd?: string | null; }) => Promise; }) { - const { activePendingUserInput, activePendingUserInputAnswers, refreshSelectedThreadGitStatus } = - input; + const { refreshSelectedThreadGitStatus } = input; const { selectedThread } = useThreadSelection(); const { savedConnectionsById } = useRemoteEnvironmentState(); - const [respondingApprovalId, setRespondingApprovalId] = useState(null); - const [respondingUserInputId, setRespondingUserInputId] = useState( - null, - ); const onRefresh = useCallback(async () => { const targets = selectedThread @@ -187,71 +176,12 @@ export function useSelectedThreadCommands(input: { [selectedThread], ); - const onRespondToApproval = useCallback( - async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => { - if (!selectedThread) { - return; - } - - const client = getEnvironmentClient(selectedThread.environmentId); - if (!client) { - return; - } - - setRespondingApprovalId(requestId); - try { - await client.orchestration.dispatchCommand({ - type: "thread.approval.respond", - commandId: CommandId.make(uuidv4()), - threadId: selectedThread.id, - requestId, - decision, - createdAt: new Date().toISOString(), - }); - } finally { - setRespondingApprovalId((current) => (current === requestId ? null : current)); - } - }, - [selectedThread], - ); - - const onSubmitUserInput = useCallback(async () => { - if (!selectedThread || !activePendingUserInput || !activePendingUserInputAnswers) { - return; - } - - const client = getEnvironmentClient(selectedThread.environmentId); - if (!client) { - return; - } - - setRespondingUserInputId(activePendingUserInput.requestId); - try { - await client.orchestration.dispatchCommand({ - type: "thread.user-input.respond", - commandId: CommandId.make(uuidv4()), - threadId: selectedThread.id, - requestId: activePendingUserInput.requestId, - answers: activePendingUserInputAnswers, - createdAt: new Date().toISOString(), - }); - } finally { - setRespondingUserInputId((current) => - current === activePendingUserInput.requestId ? null : current, - ); - } - }, [activePendingUserInput, activePendingUserInputAnswers, selectedThread]); - return { - respondingApprovalId, - respondingUserInputId, onRefresh, onUpdateThreadModelSelection, onUpdateThreadRuntimeMode, onUpdateThreadInteractionMode, onRenameThread, onStopThread, - onRespondToApproval, - onSubmitUserInput, }; } diff --git a/apps/mobile/src/state/use-selected-thread-requests.ts b/apps/mobile/src/state/use-selected-thread-requests.ts new file mode 100644 index 0000000000..232135b6a7 --- /dev/null +++ b/apps/mobile/src/state/use-selected-thread-requests.ts @@ -0,0 +1,176 @@ +import { useAtomValue } from "@effect/atom-react"; +import { useCallback, useMemo, useState } from "react"; + +import { ApprovalRequestId, CommandId, type ProviderApprovalDecision } from "@t3tools/contracts"; +import { Atom } from "effect/unstable/reactivity"; + +import { scopedRequestKey } from "../lib/scopedEntities"; +import { + buildPendingUserInputAnswers, + derivePendingApprovals, + derivePendingUserInputs, + setPendingUserInputCustomAnswer, + type PendingUserInputDraftAnswer, +} from "../lib/threadActivity"; +import { uuidv4 } from "../lib/uuid"; +import { appAtomRegistry } from "./atom-registry"; +import { getEnvironmentClient } from "./environment-session-registry"; +import { useSelectedThreadDetail } from "./use-thread-detail"; +import { useThreadSelection } from "./use-thread-selection"; + +const userInputDraftsByRequestKeyAtom = Atom.make< + Record> +>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts")); + +function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void { + const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom); + appAtomRegistry.set(userInputDraftsByRequestKeyAtom, { + ...current, + [requestKey]: { + ...current[requestKey], + [questionId]: { + selectedOptionLabel: label, + }, + }, + }); +} + +function setUserInputDraftCustomAnswer( + requestKey: string, + questionId: string, + customAnswer: string, +): void { + const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom); + appAtomRegistry.set(userInputDraftsByRequestKeyAtom, { + ...current, + [requestKey]: { + ...current[requestKey], + [questionId]: setPendingUserInputCustomAnswer( + current[requestKey]?.[questionId], + customAnswer, + ), + }, + }); +} + +export function useSelectedThreadRequests() { + const { selectedThread: selectedThreadShell } = useThreadSelection(); + const selectedThread = useSelectedThreadDetail(); + const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom); + const [respondingApprovalId, setRespondingApprovalId] = useState(null); + const [respondingUserInputId, setRespondingUserInputId] = useState( + null, + ); + + const activePendingApprovals = useMemo( + () => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []), + [selectedThread], + ); + const activePendingApproval = activePendingApprovals[0] ?? null; + const activePendingUserInputs = useMemo( + () => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []), + [selectedThread], + ); + const activePendingUserInput = activePendingUserInputs[0] ?? null; + const activePendingUserInputDrafts = + activePendingUserInput && selectedThreadShell + ? (userInputDraftsByRequestKey[ + scopedRequestKey(selectedThreadShell.environmentId, activePendingUserInput.requestId) + ] ?? {}) + : {}; + const activePendingUserInputAnswers = activePendingUserInput + ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingUserInputDrafts) + : null; + + const onSelectUserInputOption = useCallback( + (requestId: ApprovalRequestId, questionId: string, label: string) => { + if (!selectedThreadShell) { + return; + } + + const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId); + setUserInputDraftOption(requestKey, questionId, label); + }, + [selectedThreadShell], + ); + + const onChangeUserInputCustomAnswer = useCallback( + (requestId: ApprovalRequestId, questionId: string, customAnswer: string) => { + if (!selectedThreadShell) { + return; + } + + const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId); + setUserInputDraftCustomAnswer(requestKey, questionId, customAnswer); + }, + [selectedThreadShell], + ); + + const onRespondToApproval = useCallback( + async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => { + if (!selectedThreadShell) { + return; + } + + const client = getEnvironmentClient(selectedThreadShell.environmentId); + if (!client) { + return; + } + + setRespondingApprovalId(requestId); + try { + await client.orchestration.dispatchCommand({ + type: "thread.approval.respond", + commandId: CommandId.make(uuidv4()), + threadId: selectedThreadShell.id, + requestId, + decision, + createdAt: new Date().toISOString(), + }); + } finally { + setRespondingApprovalId((current) => (current === requestId ? null : current)); + } + }, + [selectedThreadShell], + ); + + const onSubmitUserInput = useCallback(async () => { + if (!selectedThreadShell || !activePendingUserInput || !activePendingUserInputAnswers) { + return; + } + + const client = getEnvironmentClient(selectedThreadShell.environmentId); + if (!client) { + return; + } + + setRespondingUserInputId(activePendingUserInput.requestId); + try { + await client.orchestration.dispatchCommand({ + type: "thread.user-input.respond", + commandId: CommandId.make(uuidv4()), + threadId: selectedThreadShell.id, + requestId: activePendingUserInput.requestId, + answers: activePendingUserInputAnswers, + createdAt: new Date().toISOString(), + }); + } finally { + setRespondingUserInputId((current) => + current === activePendingUserInput.requestId ? null : current, + ); + } + }, [activePendingUserInput, activePendingUserInputAnswers, selectedThreadShell]); + + return { + activePendingApproval, + activePendingUserInput, + activePendingUserInputDrafts, + activePendingUserInputAnswers, + respondingApprovalId, + respondingUserInputId, + onRespondToApproval, + onSelectUserInputOption, + onChangeUserInputCustomAnswer, + onSubmitUserInput, + }; +} diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index d24ddcd85a..4f1d4ce965 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -2,13 +2,7 @@ import { useAtomValue } from "@effect/atom-react"; import { useCallback, useEffect, useMemo } from "react"; import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime"; -import { - CommandId, - MessageId, - type ApprovalRequestId, - type EnvironmentId, - type ThreadId, -} from "@t3tools/contracts"; +import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tools/contracts"; import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming"; import { Atom } from "effect/unstable/reactivity"; @@ -18,16 +12,8 @@ import { pickComposerImages, } from "../lib/composerImages"; import type { DraftComposerImageAttachment } from "../lib/composerImages"; -import { scopedRequestKey, scopedThreadKey } from "../lib/scopedEntities"; -import { - buildPendingUserInputAnswers, - buildThreadFeed, - derivePendingApprovals, - derivePendingUserInputs, - setPendingUserInputCustomAnswer, - type PendingUserInputDraftAnswer, - type QueuedThreadMessage, -} from "../lib/threadActivity"; +import { scopedThreadKey } from "../lib/scopedEntities"; +import { buildThreadFeed, type QueuedThreadMessage } from "../lib/threadActivity"; import { uuidv4 } from "../lib/uuid"; import { appAtomRegistry } from "../state/atom-registry"; import { getEnvironmentClient } from "./environment-session-registry"; @@ -58,10 +44,6 @@ const queuedMessagesByThreadKeyAtom = Atom.make> ->({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts")); - function setDraftMessage(threadKey: string, value: string): void { const current = appAtomRegistry.get(draftMessageByThreadKeyAtom); appAtomRegistry.set(draftMessageByThreadKeyAtom, { @@ -187,37 +169,6 @@ function removeQueuedMessage( appAtomRegistry.set(queuedMessagesByThreadKeyAtom, next); } -function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void { - const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom); - appAtomRegistry.set(userInputDraftsByRequestKeyAtom, { - ...current, - [requestKey]: { - ...current[requestKey], - [questionId]: { - selectedOptionLabel: label, - }, - }, - }); -} - -function setUserInputDraftCustomAnswer( - requestKey: string, - questionId: string, - customAnswer: string, -): void { - const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom); - appAtomRegistry.set(userInputDraftsByRequestKeyAtom, { - ...current, - [requestKey]: { - ...current[requestKey], - [questionId]: setPendingUserInputCustomAnswer( - current[requestKey]?.[questionId], - customAnswer, - ), - }, - }); -} - function useQueueDrain(input: { readonly dispatchingQueuedMessageId: MessageId | null; readonly queuedMessagesByThreadKey: Record>; @@ -284,15 +235,10 @@ export function useThreadComposerState() { const draftAttachmentsByThreadKey = useAtomValue(draftAttachmentsByThreadKeyAtom); const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom); const queuedMessagesByThreadKey = useAtomValue(queuedMessagesByThreadKeyAtom); - const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom); const selectedThreadKey = selectedThreadShell ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id) : null; - const selectedRequestKey = selectedThreadShell - ? (requestId: ApprovalRequestId) => - scopedRequestKey(selectedThreadShell.environmentId, requestId) - : null; const selectedThreadQueuedMessages = useMemo( () => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []), [queuedMessagesByThreadKey, selectedThreadKey], @@ -336,25 +282,6 @@ export function useThreadComposerState() { ); }, [queuedSendStartedAt, selectedThread, selectedThreadSessionActivity]); - const activePendingApprovals = useMemo( - () => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []), - [selectedThread], - ); - const activePendingApproval = activePendingApprovals[0] ?? null; - - const activePendingUserInputs = useMemo( - () => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []), - [selectedThread], - ); - const activePendingUserInput = activePendingUserInputs[0] ?? null; - const activePendingUserInputDrafts = - activePendingUserInput && selectedRequestKey - ? (userInputDraftsByRequestKey[selectedRequestKey(activePendingUserInput.requestId)] ?? {}) - : {}; - const activePendingUserInputAnswers = activePendingUserInput - ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingUserInputDrafts) - : null; - const activeThreadBusy = !!selectedThread && (selectedThread.session?.status === "running" || selectedThread.session?.status === "starting"); @@ -442,30 +369,6 @@ export function useThreadComposerState() { clearDraft(threadKey); }, [draftAttachmentsByThreadKey, draftMessageByThreadKey, selectedThreadShell]); - const onSelectUserInputOption = useCallback( - (requestId: ApprovalRequestId, questionId: string, label: string) => { - if (!selectedThreadShell) { - return; - } - - const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId); - setUserInputDraftOption(requestKey, questionId, label); - }, - [selectedThreadShell], - ); - - const onChangeUserInputCustomAnswer = useCallback( - (requestId: ApprovalRequestId, questionId: string, customAnswer: string) => { - if (!selectedThreadShell) { - return; - } - - const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId); - setUserInputDraftCustomAnswer(requestKey, questionId, customAnswer); - }, - [selectedThreadShell], - ); - const onChangeDraftMessage = useCallback( (value: string) => { if (!selectedThreadShell) { @@ -553,10 +456,6 @@ export function useThreadComposerState() { selectedThreadFeed, selectedThreadQueueCount, activeWorkStartedAt, - activePendingApproval, - activePendingUserInput, - activePendingUserInputDrafts, - activePendingUserInputAnswers, draftMessage, draftAttachments, activeThreadBusy, @@ -566,7 +465,5 @@ export function useThreadComposerState() { onNativePasteImages, onRemoveDraftImage, onSendMessage, - onSelectUserInputOption, - onChangeUserInputCustomAnswer, }; } diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 3b4de0d1ba..64bba3d638 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -2598,6 +2598,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => { it.effect("routes websocket rpc git methods", () => Effect.gen(function* () { yield* buildAppUnderTest({ + config: { + cwd: "/tmp/repo", + }, layers: { gitManager: { invalidateLocalStatus: () => Effect.void, diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts new file mode 100644 index 0000000000..18834d8a44 --- /dev/null +++ b/apps/web/vitest.config.ts @@ -0,0 +1,16 @@ +import { defineConfig, mergeConfig } from "vitest/config"; + +import viteConfig from "./vite.config"; + +export default mergeConfig( + viteConfig, + defineConfig({ + test: { + // The web runtime suite exercises auth bootstrap, saved environments, + // and websocket subscription lifecycles. Under the full monorepo test + // run, those async tests can exceed Vitest's default 5s budget. + testTimeout: 15_000, + hookTimeout: 15_000, + }, + }), +);