From 87f74346b254933d3b7beef3c899109a89b74c04 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 | 929 ++---------------- .../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, 1325 insertions(+), 1045 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 7ee51ee5d0..74238bfe4e 100644 --- a/apps/mobile/src/features/review/ReviewSheet.tsx +++ b/apps/mobile/src/features/review/ReviewSheet.tsx @@ -1,8 +1,8 @@ -import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts"; -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, useEffect, useMemo, useRef, useState } from "react"; +import { memo, type ReactElement, useCallback, useMemo } from "react"; import { ActivityIndicator, Pressable, @@ -17,137 +17,22 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/AppText"; 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 { - getCachedReviewParsedDiff, - setReviewGitSections, - setReviewSelectedSectionId, - setReviewTurnDiff, - updateReviewExpandedFileIds, - updateReviewViewedFileIds, - useReviewCacheForThread, -} from "./reviewState"; -import { - getReadyReviewCheckpoints, - buildReviewSectionItems, - getDefaultReviewSectionId, - getReviewSectionIdForCheckpoint, - type ReviewParsedDiff, - type ReviewRenderableFile, -} from "./reviewModel"; -import { - buildReviewCommentTarget, - clearReviewCommentTarget, - countReviewCommentContexts, - formatReviewSelectedRangeLabel, - getSelectedReviewCommentLines, - parseReviewInlineComments, - setReviewCommentTarget, - useReviewCommentTarget, -} from "./reviewCommentSelection"; -import { markReviewEvent, measureReviewWork } from "./reviewPerf"; -import { - highlightNativeReviewDiffVisibleRows, - type NativeReviewDiffHighlightEngine, -} from "../diffs/nativeReviewDiffHighlighter"; +import { useReviewCacheForThread } from "./reviewState"; import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface"; import { - buildNativeReviewDiffData, - createNativeReviewDiffTheme, NATIVE_REVIEW_DIFF_CONTENT_WIDTH, NATIVE_REVIEW_DIFF_ROW_HEIGHT, - NATIVE_REVIEW_DIFF_STYLE, - type NativeReviewDiffCommentTarget, } 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; -interface PendingNativeCommentSelection extends NativeReviewDiffCommentTarget { - readonly sectionId: string; - readonly sectionTitle: string; - readonly rowId: string; -} - -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 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 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)}`; -} - -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 areStringArraysEqual(left: ReadonlyArray, right: ReadonlyArray): boolean { - if (left.length !== right.length) { - return false; - } - - for (let index = 0; index < left.length; index += 1) { - if (left[index] !== right[index]) { - return false; - } - } - - return true; -} - const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) { return ( @@ -220,7 +105,6 @@ function ReviewSelectionActionBar(props: { } export function ReviewSheet() { - const { push } = useRouter(); const insets = useSafeAreaInsets(); const colorScheme = useColorScheme(); const headerForeground = String(useThemeColor("--color-foreground")); @@ -232,729 +116,73 @@ export function ReviewSheet() { }>(); 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 [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState< - Record> - >({}); - const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState< - Record> - >({}); - const [pendingNativeCommentSelection, setPendingNativeCommentSelection] = - useState(null); - const [collapsedCommentIds, setCollapsedCommentIds] = useState>( - () => new Set(), - ); - const [nativeTokensPatchJson, setNativeTokensPatchJson] = useState(() => - JSON.stringify({ resetKey: "", tokensByRowId: {} }), - ); const selectedTheme = colorScheme === "dark" ? "dark" : "light"; - const nativeHighlightedRowIdsRef = useRef>(new Set()); - const nativeVisibleRangeRef = useRef({ firstRowIndex: 0, lastRowIndex: 80 }); - const nativeVisibleChunkIndexRef = useRef(0); - const [nativeVisibleHighlightRequest, setNativeVisibleHighlightRequest] = useState(0); - const activeCommentTarget = useReviewCommentTarget(); - 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 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 { + 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 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 nativeReviewDiffTheme = useMemo( - () => createNativeReviewDiffTheme(selectedTheme), - [selectedTheme], - ); - const nativeRowsJson = useMemo( - () => JSON.stringify(nativeReviewDiffData.rows), - [nativeReviewDiffData.rows], - ); - const collapsedCommentIdsJson = useMemo( - () => JSON.stringify(Array.from(collapsedCommentIds)), - [collapsedCommentIds], - ); - const nativeThemeJson = useMemo( - () => JSON.stringify(nativeReviewDiffTheme), - [nativeReviewDiffTheme], - ); - const nativeStyleJson = useMemo(() => JSON.stringify(NATIVE_REVIEW_DIFF_STYLE), []); - const nativeTokensResetKey = useMemo( - () => - [ - reviewCache.threadKey, - selectedSection?.id ?? "none", - selectedTheme, - hashReviewDiffKey(selectedSection?.diff), - nativeReviewDiffData.files.length, - nativeReviewDiffData.rows.length, - ].join(":"), - [ - nativeReviewDiffData.files.length, - nativeReviewDiffData.rows.length, - reviewCache.threadKey, - selectedSection?.diff, - selectedSection?.id, - selectedTheme, - ], - ); - const pendingReviewCommentCount = useMemo( - () => countReviewCommentContexts(draftMessage), - [draftMessage], - ); - 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], - ), - }; - }); - - 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 viewedFileIds = useMemo( - () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []), - [localViewedFileIdsBySection, selectedSection?.id], - ); - const nativeCollapsedFileIds = useMemo(() => { - if (parsedDiff.kind !== "files") { - return []; - } - - const expandedFileIdSet = new Set(expandedFileIds); - return parsedDiff.files.reduce((fileIds, file) => { - if (!expandedFileIdSet.has(file.id)) { - fileIds.push(file.id); - } - return fileIds; - }, []); - }, [expandedFileIds, parsedDiff]); - const nativeCollapsedFileIdsJson = useMemo( - () => JSON.stringify(nativeCollapsedFileIds), - [nativeCollapsedFileIds], - ); - const nativeViewedFileIdsJson = useMemo(() => JSON.stringify(viewedFileIds), [viewedFileIds]); - const openReviewCommentSheet = useCallback(() => { - if (!environmentId || !threadId) { - return; - } - - push({ - pathname: "/threads/[environmentId]/[threadId]/review-comment", - params: { environmentId, threadId }, - }); - }, [environmentId, push, threadId]); - const selectedNativeRowIds = 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 selectedNativeRowIdsJson = useMemo( - () => JSON.stringify(selectedNativeRowIds), - [selectedNativeRowIds], - ); - 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, - ]); - 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; - }); - } - }, - [environmentId, reviewCache.threadKey, reviewCache.turnDiffById, threadId], - ); - - 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 && areStringArraysEqual(validIds, existing)) { - return existing; - } - return validIds; - }); - }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]); - - useEffect(() => { - nativeHighlightedRowIdsRef.current = new Set(); - nativeVisibleChunkIndexRef.current = 0; - nativeVisibleRangeRef.current = { firstRowIndex: 0, lastRowIndex: 80 }; - setNativeTokensPatchJson(JSON.stringify({ resetKey: nativeTokensResetKey, tokensByRowId: {} })); - if (nativeReviewDiffData.rows.length > 0) { - setNativeVisibleHighlightRequest((request) => request + 1); - } - }, [nativeReviewDiffData.rows.length, nativeTokensResetKey]); - - useEffect(() => { - clearReviewCommentTarget(); - setPendingNativeCommentSelection(null); - }, [selectedSection?.id]); - - useEffect(() => { - if (activeCommentTarget === null) { - setPendingNativeCommentSelection(null); - } - }, [activeCommentTarget]); - - useEffect(() => { - if (parsedDiff.kind !== "files" || nativeReviewDiffData.rows.length === 0) { - return; - } - - const abortController = new AbortController(); - const requestRange = nativeVisibleRangeRef.current; - const engine: NativeReviewDiffHighlightEngine = "native"; - - void (async () => { - try { - const result = await highlightNativeReviewDiffVisibleRows({ - files: nativeReviewDiffData.files, - rows: nativeReviewDiffData.rows, - scheme: selectedTheme, - engine, - firstRowIndex: requestRange.firstRowIndex, - lastRowIndex: requestRange.lastRowIndex, - alreadyHighlightedRowIds: nativeHighlightedRowIdsRef.current, - signal: abortController.signal, - }); - - if (abortController.signal.aborted || result.rowCount === 0) { - return; - } - - for (const rowId of Object.keys(result.tokensByRowId)) { - nativeHighlightedRowIdsRef.current.add(rowId); - } - - const chunkIndex = nativeVisibleChunkIndexRef.current; - nativeVisibleChunkIndexRef.current += 1; - setNativeTokensPatchJson( - JSON.stringify({ - resetKey: nativeTokensResetKey, - 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(); - }, [ - nativeReviewDiffData.files, - nativeReviewDiffData.rows, - nativeTokensResetKey, - nativeVisibleHighlightRequest, - parsedDiff.kind, - 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: nativeReviewDiffData.rows.length, - }); - logReviewDiffDiagnostic("parsed diff files", { - selectedSectionId: selectedSection?.id ?? null, - fileCount: parsedDiff.fileCount, - renderableFileCount: parsedDiff.files.length, - }); - }, [nativeReviewDiffData.rows.length, parsedDiff, selectedSection?.id]); - - 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]; - }); - } - }, - [parsedDiff, reviewCache.threadKey, selectedSection?.id], - ); - - const handleToggleViewedFile = useCallback( - (fileId: string) => { - if (!selectedSection?.id || parsedDiff.kind !== "files") { - return; - } - - const sectionId = selectedSection.id; - const shouldCollapse = !viewedFileIds.includes(fileId); - - setLocalViewedFileIdsBySection((current) => { - const currentIds = current[sectionId] ?? []; - const nextIds = currentIds.includes(fileId) - ? currentIds.filter((id) => id !== fileId) - : [...currentIds, fileId]; - - return { - ...current, - [sectionId]: nextIds, - }; - }); - - if (shouldCollapse) { - setLocalExpandedFileIdsBySection((current) => { - const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]); - return { - ...current, - [sectionId]: currentIds.filter((id) => id !== fileId), - }; - }); - } - - if (reviewCache.threadKey) { - updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => { - const currentIds = existing ?? []; - return currentIds.includes(fileId) - ? currentIds.filter((id) => id !== fileId) - : [...currentIds, fileId]; - }); - - if (shouldCollapse) { - updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => { - const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing); - return currentIds.filter((id) => id !== fileId); - }); - } - } - }, - [parsedDiff, reviewCache.threadKey, selectedSection?.id, viewedFileIds], - ); - - const handleNativeDebug = 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" - ) { - const previousRange = nativeVisibleRangeRef.current; - const nextRange = { - firstRowIndex: payload.firstRowIndex, - lastRowIndex: payload.lastRowIndex, - }; - const movedRows = - Math.abs(nextRange.firstRowIndex - previousRange.firstRowIndex) + - Math.abs(nextRange.lastRowIndex - previousRange.lastRowIndex); - - nativeVisibleRangeRef.current = nextRange; - if (movedRows >= 20) { - setNativeVisibleHighlightRequest((request) => request + 1); - } - } - }, []); + 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", + }); const handleNativeToggleFile = useCallback( (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => { const { fileId } = event.nativeEvent; if (fileId) { - handleToggleExpandedFile(fileId); + toggleExpandedFile(fileId); } }, - [handleToggleExpandedFile], + [toggleExpandedFile], ); const handleNativeToggleViewedFile = useCallback( (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => { const { fileId } = event.nativeEvent; if (fileId) { - handleToggleViewedFile(fileId); + toggleViewedFile(fileId); } }, - [handleToggleViewedFile], - ); - - const handleNativePressLine = 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 handleNativeToggleComment = 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; - }); - }, - [], + [toggleViewedFile], ); const parsedDiffNotice = @@ -1090,11 +318,7 @@ export function ReviewSheet() { { - if (reviewCache.threadKey) { - setReviewSelectedSectionId(reviewCache.threadKey, section.id); - } - }} + onPress={() => selectSection(section.id)} subtitle={section.subtitle ?? undefined} > {section.title} @@ -1119,7 +343,7 @@ export function ReviewSheet() { @@ -1131,20 +355,20 @@ export function ReviewSheet() { testID="review-native-diff-view" style={StyleSheet.absoluteFillObject} appearanceScheme={selectedTheme} - collapsedFileIdsJson={nativeCollapsedFileIdsJson} - collapsedCommentIdsJson={collapsedCommentIdsJson} + collapsedFileIdsJson={nativeBridge.collapsedFileIdsJson} + collapsedCommentIdsJson={nativeBridge.collapsedCommentIdsJson} contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH} rowHeight={NATIVE_REVIEW_DIFF_ROW_HEIGHT} - rowsJson={nativeRowsJson} - selectedRowIdsJson={selectedNativeRowIdsJson} - styleJson={nativeStyleJson} - themeJson={nativeThemeJson} - tokensPatchJson={nativeTokensPatchJson} - tokensResetKey={nativeTokensResetKey} - viewedFileIdsJson={nativeViewedFileIdsJson} - onDebug={handleNativeDebug} - onPressLine={handleNativePressLine} - onToggleComment={handleNativeToggleComment} + rowsJson={nativeBridge.rowsJson} + selectedRowIdsJson={nativeBridge.selectedRowIdsJson} + styleJson={nativeBridge.styleJson} + themeJson={nativeBridge.themeJson} + tokensPatchJson={nativeBridge.tokensPatchJson} + tokensResetKey={nativeBridge.tokensResetKey} + viewedFileIdsJson={nativeBridge.viewedFileIdsJson} + onDebug={nativeBridge.onDebug} + onPressLine={commentSelection.onPressLine} + onToggleComment={nativeBridge.onToggleComment} onToggleFile={handleNativeToggleFile} onToggleViewedFile={handleNativeToggleViewedFile} /> @@ -1201,12 +425,9 @@ export function ReviewSheet() { )} { - clearReviewCommentTarget(); - setPendingNativeCommentSelection(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 44564e1f68..ba4f9702e1 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -2475,6 +2475,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, + }, + }), +);