diff --git a/T3 Code blueprint.icon/Assets/T3.svg b/T3 Code blueprint.icon/Assets/T3.svg new file mode 100644 index 0000000000..b12706fdfc --- /dev/null +++ b/T3 Code blueprint.icon/Assets/T3.svg @@ -0,0 +1,3 @@ + + + diff --git a/T3 Code blueprint.icon/Assets/Texturelabs_Paper_381XL.jpg b/T3 Code blueprint.icon/Assets/Texturelabs_Paper_381XL.jpg new file mode 100644 index 0000000000..d98c41a4e3 Binary files /dev/null and b/T3 Code blueprint.icon/Assets/Texturelabs_Paper_381XL.jpg differ diff --git a/T3 Code blueprint.icon/Assets/seedream-v4.5-kn732b3mfqe78y3dga2h92wbk984vnh7.png b/T3 Code blueprint.icon/Assets/seedream-v4.5-kn732b3mfqe78y3dga2h92wbk984vnh7.png new file mode 100644 index 0000000000..b98c8fa4d8 Binary files /dev/null and b/T3 Code blueprint.icon/Assets/seedream-v4.5-kn732b3mfqe78y3dga2h92wbk984vnh7.png differ diff --git a/T3 Code blueprint.icon/icon.json b/T3 Code blueprint.icon/icon.json new file mode 100644 index 0000000000..868b2f0ec8 --- /dev/null +++ b/T3 Code blueprint.icon/icon.json @@ -0,0 +1,46 @@ +{ + "fill": { + "solid": "display-p3:0.00000,0.00000,0.00000,1.00000" + }, + "groups": [ + { + "layers": [ + { + "blend-mode": "normal", + "fill": "automatic", + "hidden": false, + "image-name": "seedream-v4.5-kn732b3mfqe78y3dga2h92wbk984vnh7.png", + "name": "seedream-v4.5-kn732b3mfqe78y3dga2h92wbk984vnh7", + "position": { + "scale": 0.25, + "translation-in-points": [0, 0] + } + }, + { + "image-name": "T3.svg", + "name": "T3", + "position": { + "scale": 10, + "translation-in-points": [0, 0] + } + }, + { + "hidden": false, + "image-name": "Texturelabs_Paper_381XL.jpg", + "name": "Texturelabs_Paper_381XL" + } + ], + "shadow": { + "kind": "neutral", + "opacity": 0.5 + }, + "translucency": { + "enabled": true, + "value": 0.5 + } + } + ], + "supported-platforms": { + "squares": ["iOS", "macOS"] + } +} diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 6904143b67..6d4395f06c 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -37,6 +37,7 @@ "@effect/atom-react": "catalog:", "@expo-google-fonts/dm-sans": "^0.4.2", "@legendapp/list": "3.0.0-beta.44", + "@pierre/diffs": "^1.1.0-beta.16", "@react-native-menu/menu": "^2.0.0", "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", @@ -74,6 +75,7 @@ "react-native-screens": "~4.23.0", "react-native-svg": "15.15.3", "react-native-worklets": "0.7.2", + "shiki": "^4.0.2", "tailwind-merge": "^3.5.0", "uniwind": "^1.6.2" }, diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx index b5e83cbad4..898bebae63 100644 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx @@ -4,6 +4,9 @@ import { useResolveClassNames } from "uniwind"; export default function ThreadLayout() { const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet")); + const headerBg = { + backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor, + }; return ( @@ -38,6 +41,29 @@ export default function ThreadLayout() { sheetGrabberVisible: true, }} /> + + ); } diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx index c2d725188d..15b10c295f 100644 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx @@ -42,6 +42,17 @@ export default function GitSheetLayout() { headerStyle: headerBg, }} /> + ); } diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/review.tsx new file mode 100644 index 0000000000..dd28795c12 --- /dev/null +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/review.tsx @@ -0,0 +1,17 @@ +import { Redirect, useLocalSearchParams } from "expo-router"; + +export default function ReviewRoute() { + const { environmentId, threadId } = useLocalSearchParams<{ + environmentId: string; + threadId: string; + }>(); + + return ( + + ); +} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review-comment.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review-comment.tsx new file mode 100644 index 0000000000..1e77810270 --- /dev/null +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review-comment.tsx @@ -0,0 +1,5 @@ +import { ReviewCommentComposerSheet } from "../../../../features/threads/review/ReviewCommentComposerSheet"; + +export default function ReviewCommentRoute() { + return ; +} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx new file mode 100644 index 0000000000..193d0e8f47 --- /dev/null +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx @@ -0,0 +1,5 @@ +import { ReviewSheet } from "../../../../features/threads/review/ReviewSheet"; + +export default function ReviewRoute() { + return ; +} diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx index 88ebe59128..77262e8248 100644 --- a/apps/mobile/src/features/threads/ThreadGitControls.tsx +++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx @@ -8,6 +8,7 @@ import { useLocalSearchParams, useRouter } from "expo-router"; import Stack from "expo-router/stack"; import { useCallback, useMemo } from "react"; import { Alert, Linking } from "react-native"; +import { buildThreadReviewRoutePath } from "../../lib/routes"; function truncateMiddle(value: string, maxLength: number): string { if (value.length <= maxLength) { @@ -183,6 +184,14 @@ export function ThreadGitControls(props: { > {quickAction.label} + router.push(buildThreadReviewRoutePath({ environmentId, threadId }))} + subtitle="Turn diffs and worktree changes" + > + Review changes + diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx index 57296b9026..765d603a4d 100644 --- a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx @@ -12,6 +12,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useThemeColor } from "../../../lib/useThemeColor"; import { AppText as Text } from "../../../components/AppText"; +import { buildThreadReviewRoutePath } from "../../../lib/routes"; import { useGitStatus } from "../../../state/use-git-status"; import { useThreadSelection } from "../../../state/use-thread-selection"; import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions"; @@ -215,6 +216,14 @@ export function GitOverviewSheet() { ) : null} + router.push(buildThreadReviewRoutePath({ environmentId, threadId }))} + /> + leading.replaceAll(" ", "\u00A0")); +} + +function changeTone(change: "context" | "add" | "delete"): string { + if (change === "add") return "bg-emerald-500/12"; + if (change === "delete") return "bg-rose-500/12"; + return "bg-card"; +} + +export function ReviewCommentComposerSheet() { + const router = useRouter(); + const insets = useSafeAreaInsets(); + const iconTint = String(useThemeColor("--color-icon")); + const target = useReviewCommentTarget(); + const { environmentId, threadId } = useLocalSearchParams<{ + environmentId: string; + threadId: string; + }>(); + const [commentText, setCommentText] = useState(""); + + const selectedLines = useMemo( + () => (target ? getSelectedReviewCommentLines(target) : []), + [target], + ); + const firstLine = selectedLines[0] ?? null; + const lastLine = selectedLines[selectedLines.length - 1] ?? null; + const firstNumber = firstLine ? getReviewUnifiedLineNumber(firstLine) : null; + const lastNumber = lastLine ? getReviewUnifiedLineNumber(lastLine) : null; + const canSubmit = + commentText.trim().length > 0 && target !== null && !!environmentId && !!threadId; + + return ( + + + { + clearReviewCommentTarget(); + router.dismiss(); + }} + > + + + + Add Comment + + { + if (!target || !environmentId || !threadId || commentText.trim().length === 0) { + return; + } + + appendReviewCommentToDraft({ + environmentId, + threadId, + text: formatReviewCommentContext(target, commentText), + }); + clearReviewCommentTarget(); + router.dismiss(); + }} + style={{ opacity: canSubmit ? 1 : 0.55 }} + > + + Comment + + + + + {!target ? ( + + No selection + + Select a diff line or range first. + + + ) : ( + <> + + + {target.filePath} + + + {selectedLines.length === 1 + ? firstNumber !== null + ? `Line ${firstNumber}` + : "File comment" + : firstNumber !== null && lastNumber !== null + ? `Lines ${firstNumber}-${lastNumber}` + : `${selectedLines.length} lines selected`} + + + + + {selectedLines.map((line) => { + const lineNumber = getReviewUnifiedLineNumber(line); + + return ( + + + {lineNumber ?? ""} + + + {getReviewChangeMarker(line.change)} + + + {renderVisibleWhitespace(line.content || " ")} + + + ); + })} + + + + Comment + + + + )} + + ); +} diff --git a/apps/mobile/src/features/threads/review/ReviewSheet.tsx b/apps/mobile/src/features/threads/review/ReviewSheet.tsx new file mode 100644 index 0000000000..5745669147 --- /dev/null +++ b/apps/mobile/src/features/threads/review/ReviewSheet.tsx @@ -0,0 +1,1000 @@ +import { + ThreadId, + type GitReviewDiffSection, + type OrchestrationCheckpointSummary, +} from "@t3tools/contracts"; +import { useLocalSearchParams, useRouter } from "expo-router"; +import Stack from "expo-router/stack"; +import { SymbolView } from "expo-symbols"; +import { type ReactElement, useCallback, useEffect, useMemo, useState } from "react"; +import { + ActivityIndicator, + Platform, + Pressable, + ScrollView, + Text as NativeText, + 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/use-remote-environment-registry"; +import { useSelectedThreadDetail } from "../../../state/use-thread-detail"; +import { useThreadSelection } from "../../../state/use-thread-selection"; +import { + buildReviewParsedDiff, + getReadyReviewCheckpoints, + buildReviewSectionItems, + getDefaultReviewSectionId, + getReviewSectionIdForCheckpoint, + type ReviewRenderableFile, + type ReviewRenderableLineRow, +} from "./reviewModel"; +import { + highlightReviewFile, + type ReviewDiffTheme, + type ReviewHighlightedFile, + type ReviewHighlightedToken, +} from "./shikiReviewHighlighter"; +import { + buildReviewCommentTarget, + clearReviewCommentTarget, + formatReviewSelectedRangeLabel, + getReviewChangeMarker, + getReviewUnifiedLineNumber, + getSelectedReviewCommentLines, + setReviewCommentTarget, + type ReviewCommentTarget, + useReviewCommentTarget, +} from "./reviewCommentSelection"; + +interface PendingCommentSelection { + readonly sectionTitle: string; + readonly filePath: string; + readonly lines: ReadonlyArray; + readonly anchorIndex: number; +} + +const REVIEW_MONO_FONT_FAMILY = Platform.select({ + ios: "ui-monospace", + android: "monospace", + default: "monospace", +}); +const IOS_NAV_BAR_HEIGHT = 44; +const REVIEW_HEADER_SPACING = 32; + +function changeTone(change: ReviewRenderableLineRow["change"]): string { + if (change === "add") return "bg-emerald-500/12"; + if (change === "delete") return "bg-rose-500/12"; + return "bg-card"; +} + +function changeTypeLabel(type: ReviewRenderableFile["changeType"]): string { + switch (type) { + case "new": + return "Added"; + case "deleted": + return "Deleted"; + case "rename-pure": + return "Renamed"; + case "rename-changed": + return "Renamed + edited"; + default: + return "Edited"; + } +} + +function formatHeaderDiffSummary(parsedDiff: ReturnType): { + 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 shouldAutoExpandFile(file: ReviewRenderableFile): boolean { + return file.additions + file.deletions <= 20 && file.rows.length <= 40; +} + +function getDefaultExpandedFileIds( + files: ReadonlyArray, +): ReadonlyArray { + const autoExpanded = files.filter(shouldAutoExpandFile).map((file) => file.id); + if (autoExpanded.length > 0) { + return autoExpanded; + } + return files.length === 1 ? [files[0]!.id] : []; +} + +function renderVisibleWhitespace(value: string): string { + const expandedTabs = value.replace(/\t/g, " "); + return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0")); +} + +function DiffTokenText(props: { + readonly tokens: ReadonlyArray | null; + readonly fallback: string; +}) { + if (!props.tokens || props.tokens.length === 0) { + return ( + + {renderVisibleWhitespace(props.fallback || " ")} + + ); + } + + return ( + + {(() => { + let offset = 0; + + return props.tokens.map((token) => { + const start = offset; + offset += token.content.length; + + const fontWeight = + token.fontStyle !== null && (token.fontStyle & 2) === 2 + ? ("700" as const) + : ("400" as const); + const fontStyle = + token.fontStyle !== null && (token.fontStyle & 1) === 1 + ? ("italic" as const) + : ("normal" as const); + + return ( + + {token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "} + + ); + }); + })()} + + ); +} + +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 ( + + + {lineNumber ?? ""} + + + {getReviewChangeMarker(props.line.change)} + + + + + + ); +} + +function ReviewFileCard(props: { + readonly file: ReviewRenderableFile; + readonly expanded: boolean; + readonly onToggle: () => void; +}) { + return ( + + + + + + + + {props.file.path} + + {props.file.previousPath && props.file.previousPath !== props.file.path ? ( + + {props.file.previousPath} + + ) : null} + + + + {changeTypeLabel(props.file.changeType)} + + + + +{props.file.additions} + + -{props.file.deletions} + + + + + ); +} + +function ReviewFileBody(props: { + readonly file: ReviewRenderableFile; + readonly sectionTitle: string; + readonly highlightedFile: ReviewHighlightedFile | null; + readonly viewportWidth: number; + readonly pendingSelection: PendingCommentSelection | null; + readonly selectedTarget: ReviewCommentTarget | null; + readonly onPressLine: ( + line: ReviewRenderableLineRow, + availableLines: ReadonlyArray, + lineIndex: number, + ) => void; + readonly onStartRangeSelection: ( + line: ReviewRenderableLineRow, + availableLines: ReadonlyArray, + lineIndex: number, + ) => void; +}) { + const commentableLines = props.file.rows.filter( + (row): row is ReviewRenderableLineRow => row.kind === "line", + ); + const anchorLineId = + props.pendingSelection && + props.pendingSelection.sectionTitle === props.sectionTitle && + props.pendingSelection.filePath === props.file.path + ? (props.pendingSelection.lines[props.pendingSelection.anchorIndex]?.id ?? null) + : null; + const selectedLineIds = + props.selectedTarget && + props.selectedTarget.sectionTitle === props.sectionTitle && + props.selectedTarget.filePath === props.file.path + ? new Set(getSelectedReviewCommentLines(props.selectedTarget).map((line) => line.id)) + : null; + + return ( + + + {props.file.rows.map((row) => { + if (row.kind === "hunk") { + return ( + + + {row.header} + {row.context ? ` ${row.context}` : ""} + + + ); + } + + const tokens = + row.change === "delete" + ? (props.highlightedFile?.deletionLines[row.deletionTokenIndex ?? -1] ?? null) + : (props.highlightedFile?.additionLines[row.additionTokenIndex ?? -1] ?? null); + + return ( + { + const lineIndex = commentableLines.findIndex( + (candidate) => candidate.id === row.id, + ); + props.onPressLine(row, commentableLines, lineIndex >= 0 ? lineIndex : 0); + }} + onStartRangeSelection={() => { + const lineIndex = commentableLines.findIndex( + (candidate) => candidate.id === row.id, + ); + props.onStartRangeSelection(row, commentableLines, lineIndex >= 0 ? lineIndex : 0); + }} + /> + ); + })} + + + ); +} + +function ReviewSelectionActionBar(props: { + readonly target: ReviewCommentTarget | null; + readonly bottomInset: number; + readonly onOpenComment: () => void; + readonly onClear: () => void; +}) { + if (!props.target || props.target.startIndex === props.target.endIndex) { + return null; + } + + return ( + + + + + Comment on {formatReviewSelectedRangeLabel(props.target)} + + + + + + + + ); +} + +export function ReviewSheet() { + const router = useRouter(); + const insets = useSafeAreaInsets(); + const { width } = useWindowDimensions(); + const colorScheme = useColorScheme(); + const headerForeground = String(useThemeColor("--color-foreground")); + const headerMuted = String(useThemeColor("--color-foreground-muted")); + const headerIcon = String(useThemeColor("--color-icon")); + const { environmentId, threadId } = useLocalSearchParams<{ + environmentId: string; + threadId: string; + }>(); + const { selectedThreadProject } = useThreadSelection(); + const selectedThread = useSelectedThreadDetail(); + const [gitSections, setGitSections] = useState>([]); + const [turnDiffById, setTurnDiffById] = useState>({}); + const [loadingTurnIds, setLoadingTurnIds] = useState>({}); + const [selectedSectionId, setSelectedSectionId] = useState(null); + const [loadingGitDiffs, setLoadingGitDiffs] = useState(false); + const [error, setError] = useState(null); + const [expandedFileIdsBySection, setExpandedFileIdsBySection] = useState< + Record | undefined> + >({}); + const [highlightedFileByKey, setHighlightedFileByKey] = useState< + Record + >({}); + const [pendingCommentSelection, setPendingCommentSelection] = + useState(null); + const activeCommentTarget = useReviewCommentTarget(); + + const cwd = selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null; + 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, + turnDiffById, + loadingTurnIds, + }), + [gitSections, loadingTurnIds, readyCheckpoints, turnDiffById], + ); + + const selectedSection = + reviewSections.find((section) => section.id === selectedSectionId) ?? reviewSections[0] ?? null; + const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT; + const parsedDiff = useMemo( + () => buildReviewParsedDiff(selectedSection?.diff, selectedSection?.id ?? "mobile-review"), + [selectedSection?.diff, selectedSection?.id], + ); + const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]); + + const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme; + const expandedFileIds = useMemo( + () => + selectedSection?.id && parsedDiff.kind === "files" + ? (expandedFileIdsBySection[selectedSection.id] ?? + getDefaultExpandedFileIds(parsedDiff.files)) + : [], + [expandedFileIdsBySection, parsedDiff, selectedSection?.id], + ); + const expandedFiles = useMemo( + () => + parsedDiff.kind === "files" + ? parsedDiff.files.filter((file) => expandedFileIds.includes(file.id)) + : [], + [expandedFileIds, parsedDiff], + ); + + const loadGitDiffs = useCallback(async () => { + if (!environmentId || !cwd) { + return; + } + + const client = getEnvironmentClient(environmentId); + if (!client) { + setError("Remote connection is not ready."); + return; + } + + setLoadingGitDiffs(true); + setError(null); + try { + const result = await client.git.getReviewDiffs({ cwd }); + setGitSections(result.sections); + } catch (cause) { + setError(cause instanceof Error ? cause.message : "Failed to load review diffs."); + } finally { + setLoadingGitDiffs(false); + } + }, [cwd, environmentId]); + + const loadTurnDiff = useCallback( + async (checkpoint: OrchestrationCheckpointSummary, force = false) => { + if (!environmentId || !threadId) { + return; + } + + const sectionId = getReviewSectionIdForCheckpoint(checkpoint); + setSelectedSectionId(sectionId); + + if (!force && 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: ThreadId.make(threadId), + fromTurnCount: Math.max(0, checkpoint.checkpointTurnCount - 1), + toTurnCount: checkpoint.checkpointTurnCount, + }); + setTurnDiffById((current) => ({ ...current, [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, threadId, turnDiffById], + ); + + useEffect(() => { + void loadGitDiffs(); + }, [loadGitDiffs]); + + useEffect(() => { + if (reviewSections.length === 0) { + return; + } + + const fallbackId = getDefaultReviewSectionId(reviewSections); + if (!selectedSectionId || !reviewSections.some((section) => section.id === selectedSectionId)) { + setSelectedSectionId(fallbackId); + } + }, [reviewSections, selectedSectionId]); + + useEffect(() => { + const latest = readyCheckpoints[0]; + if (!latest) { + return; + } + + const latestId = getReviewSectionIdForCheckpoint(latest); + if (turnDiffById[latestId] !== undefined || loadingTurnIds[latestId]) { + return; + } + + void loadTurnDiff(latest); + }, [loadTurnDiff, loadingTurnIds, readyCheckpoints, 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 (!selectedSectionId || parsedDiff.kind !== "files") { + return; + } + + setExpandedFileIdsBySection((current) => { + const existing = current[selectedSectionId]; + if (existing !== undefined) { + const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id)); + if (validIds.length === existing.length) { + return current; + } + return { ...current, [selectedSectionId]: validIds }; + } + + return { + ...current, + [selectedSectionId]: getDefaultExpandedFileIds(parsedDiff.files), + }; + }); + }, [parsedDiff, selectedSectionId]); + + useEffect(() => { + if (!selectedSection || expandedFiles.length === 0) { + return; + } + + const filesToHighlight = expandedFiles.filter((file) => { + const key = `${selectedSection.id}:${selectedTheme}:${file.cacheKey}`; + return highlightedFileByKey[key] === undefined; + }); + if (filesToHighlight.length === 0) { + return; + } + + let cancelled = false; + void Promise.all( + filesToHighlight.map( + async (file) => + [ + `${selectedSection.id}:${selectedTheme}:${file.cacheKey}`, + await highlightReviewFile(file, selectedTheme), + ] as const, + ), + ) + .then((entries) => { + if (!cancelled) { + setHighlightedFileByKey((current) => ({ + ...current, + ...Object.fromEntries(entries), + })); + } + }) + .catch(() => { + if (cancelled) { + return; + } + }); + + return () => { + cancelled = true; + }; + }, [expandedFiles, highlightedFileByKey, selectedSection, 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 reviewContent = useMemo(() => { + const children: ReactElement[] = []; + const stickyHeaderIndices: number[] = []; + + if (error) { + children.push( + + Review unavailable + {error} + , + ); + } + + if (parsedDiff.kind !== "empty" && parsedDiff.notice) { + children.push( + + + Partial diff + + + {parsedDiff.notice} + + , + ); + } + + if (!selectedSection) { + children.push( + + No review diffs + + This thread has no ready turn diffs and the worktree diff is empty. + + , + ); + return { children, stickyHeaderIndices }; + } + + if (selectedSection.isLoading && selectedSection.diff === null) { + children.push( + + + Loading diff… + , + ); + return { children, stickyHeaderIndices }; + } + + if (parsedDiff.kind === "empty") { + children.push( + + No changes + + {selectedSection.subtitle ?? "This diff is empty."} + + , + ); + return { children, stickyHeaderIndices }; + } + + if (parsedDiff.kind === "raw") { + children.push( + + + {parsedDiff.reason} + + + + {parsedDiff.text} + + + , + ); + return { children, stickyHeaderIndices }; + } + + parsedDiff.files.forEach((file) => { + const isExpanded = expandedFileIds.includes(file.id); + const fileHighlightKey = `${selectedSection.id}:${selectedTheme}:${file.cacheKey}`; + const fileHighlights = highlightedFileByKey[fileHighlightKey] ?? null; + + stickyHeaderIndices.push(children.length); + children.push( + + setExpandedFileIdsBySection((current) => { + const existing = + current[selectedSection.id] ?? getDefaultExpandedFileIds(parsedDiff.files); + const next = existing.includes(file.id) + ? existing.filter((id) => id !== file.id) + : [...existing, file.id]; + return { + ...current, + [selectedSection.id]: next, + }; + }) + } + />, + ); + + if (isExpanded) { + children.push( + { + if (pendingCommentSelection) { + if ( + pendingCommentSelection.sectionTitle === selectedSection.title && + pendingCommentSelection.filePath === file.path + ) { + setReviewCommentTarget( + buildReviewCommentTarget( + { + sectionTitle: pendingCommentSelection.sectionTitle, + filePath: pendingCommentSelection.filePath, + lines: pendingCommentSelection.lines, + }, + pendingCommentSelection.anchorIndex, + lineIndex, + ), + ); + setPendingCommentSelection(null); + return; + } + + clearReviewCommentTarget(); + setPendingCommentSelection({ + sectionTitle: selectedSection.title, + filePath: file.path, + lines: availableLines, + anchorIndex: lineIndex, + }); + return; + } + + setReviewCommentTarget({ + sectionTitle: selectedSection.title, + filePath: file.path, + lines: availableLines, + startIndex: lineIndex, + endIndex: lineIndex, + }); + if (environmentId && threadId) { + router.push({ + pathname: "/threads/[environmentId]/[threadId]/review-comment", + params: { environmentId, threadId }, + }); + } + }} + onStartRangeSelection={(_line, availableLines, lineIndex) => { + clearReviewCommentTarget(); + setPendingCommentSelection({ + sectionTitle: selectedSection.title, + filePath: file.path, + lines: availableLines, + anchorIndex: lineIndex, + }); + }} + />, + ); + } + }); + + return { children, stickyHeaderIndices }; + }, [ + activeCommentTarget, + error, + expandedFileIds, + highlightedFileByKey, + pendingCommentSelection, + parsedDiff, + router, + selectedSection, + selectedTheme, + threadId, + width, + environmentId, + ]); + + return ( + <> + ( + + + Files Changed + + + {headerDiffSummary.additions && headerDiffSummary.deletions ? ( + <> + + {headerDiffSummary.additions} + + + {headerDiffSummary.deletions} + + + ) : ( + + {selectedSection?.title ?? "Review changes"} + + )} + + + ), + }} + /> + + + + {reviewSections.map((section) => ( + setSelectedSectionId(section.id)} + subtitle={section.subtitle ?? undefined} + > + {section.title} + + ))} + void refreshSelectedSection()} + subtitle="Reload current diff" + > + Refresh + + + + + + + {reviewContent.children} + + + { + if (activeCommentTarget && environmentId && threadId) { + router.push({ + pathname: "/threads/[environmentId]/[threadId]/review-comment", + params: { environmentId, threadId }, + }); + } + }} + onClear={() => { + clearReviewCommentTarget(); + setPendingCommentSelection(null); + }} + /> + + + ); +} diff --git a/apps/mobile/src/features/threads/review/diffParser.ts b/apps/mobile/src/features/threads/review/diffParser.ts new file mode 100644 index 0000000000..76e8872f8a --- /dev/null +++ b/apps/mobile/src/features/threads/review/diffParser.ts @@ -0,0 +1,158 @@ +export type ParsedDiffLineType = "context" | "add" | "delete" | "meta" | "hunk"; + +export interface ParsedDiffLine { + readonly id: string; + readonly type: ParsedDiffLineType; + readonly oldLine: number | null; + readonly newLine: number | null; + readonly content: string; +} + +export interface ParsedDiffFile { + readonly id: string; + readonly oldPath: string | null; + readonly newPath: string | null; + readonly lines: ReadonlyArray; +} + +function parseHunkStart( + line: string, +): { readonly oldLine: number; readonly newLine: number } | null { + const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/); + if (!match) { + return null; + } + + return { + oldLine: Number.parseInt(match[1] ?? "0", 10), + newLine: Number.parseInt(match[2] ?? "0", 10), + }; +} + +function parseDiffPath(line: string, prefix: "--- " | "+++ "): string | null { + if (!line.startsWith(prefix)) { + return null; + } + const raw = line.slice(prefix.length).trim(); + if (raw === "/dev/null") { + return null; + } + return raw.replace(/^[ab]\//, ""); +} + +export function parseUnifiedDiff(diff: string): ReadonlyArray { + const files: ParsedDiffFile[] = []; + let current: { + oldPath: string | null; + newPath: string | null; + lines: ParsedDiffLine[]; + } | null = null; + let oldLine: number | null = null; + let newLine: number | null = null; + + const pushCurrent = () => { + if (!current) { + return; + } + files.push({ + id: `${current.oldPath ?? "null"}:${current.newPath ?? "null"}:${files.length}`, + oldPath: current.oldPath, + newPath: current.newPath, + lines: current.lines, + }); + }; + + for (const rawLine of diff.replace(/\r\n/g, "\n").split("\n")) { + if (rawLine.startsWith("diff --git ")) { + pushCurrent(); + const match = rawLine.match(/^diff --git a\/(.+) b\/(.+)$/); + current = { + oldPath: match?.[1] ?? null, + newPath: match?.[2] ?? null, + lines: [], + }; + oldLine = null; + newLine = null; + continue; + } + + if (!current) { + if (rawLine.trim().length === 0) { + continue; + } + current = { oldPath: null, newPath: null, lines: [] }; + } + + const oldPath = parseDiffPath(rawLine, "--- "); + if (oldPath !== null || rawLine === "--- /dev/null") { + current.oldPath = oldPath; + continue; + } + + const newPath = parseDiffPath(rawLine, "+++ "); + if (newPath !== null || rawLine === "+++ /dev/null") { + current.newPath = newPath; + continue; + } + + const hunk = parseHunkStart(rawLine); + if (hunk) { + oldLine = hunk.oldLine; + newLine = hunk.newLine; + current.lines.push({ + id: `${current.lines.length}:hunk`, + type: "hunk", + oldLine: null, + newLine: null, + content: rawLine, + }); + continue; + } + + if (oldLine === null || newLine === null) { + current.lines.push({ + id: `${current.lines.length}:meta`, + type: "meta", + oldLine: null, + newLine: null, + content: rawLine, + }); + continue; + } + + const marker = rawLine[0]; + const content = rawLine.length > 0 ? rawLine.slice(1) : ""; + if (marker === "+") { + current.lines.push({ + id: `${current.lines.length}:add:${newLine}`, + type: "add", + oldLine: null, + newLine, + content, + }); + newLine += 1; + } else if (marker === "-") { + current.lines.push({ + id: `${current.lines.length}:delete:${oldLine}`, + type: "delete", + oldLine, + newLine: null, + content, + }); + oldLine += 1; + } else { + current.lines.push({ + id: `${current.lines.length}:context:${oldLine}:${newLine}`, + type: "context", + oldLine, + newLine, + content: marker === " " ? content : rawLine, + }); + oldLine += 1; + newLine += 1; + } + } + + pushCurrent(); + return files.filter((file) => file.lines.length > 0 || file.oldPath || file.newPath); +} diff --git a/apps/mobile/src/features/threads/review/reviewCommentSelection.ts b/apps/mobile/src/features/threads/review/reviewCommentSelection.ts new file mode 100644 index 0000000000..0ffff8d186 --- /dev/null +++ b/apps/mobile/src/features/threads/review/reviewCommentSelection.ts @@ -0,0 +1,154 @@ +import { useSyncExternalStore } from "react"; + +import type { ReviewRenderableLineRow } from "./reviewModel"; + +export interface ReviewCommentTarget { + readonly sectionTitle: string; + readonly filePath: string; + readonly lines: ReadonlyArray; + readonly startIndex: number; + readonly endIndex: number; +} + +let currentTarget: ReviewCommentTarget | null = null; +const listeners = new Set<() => void>(); + +function emitChange() { + listeners.forEach((listener) => listener()); +} + +export function subscribeReviewCommentTarget(listener: () => void): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +export function getReviewCommentTarget(): ReviewCommentTarget | null { + return currentTarget; +} + +export function setReviewCommentTarget(target: ReviewCommentTarget | null) { + currentTarget = target; + emitChange(); +} + +export function clearReviewCommentTarget() { + currentTarget = null; + emitChange(); +} + +export function useReviewCommentTarget(): ReviewCommentTarget | null { + return useSyncExternalStore( + subscribeReviewCommentTarget, + getReviewCommentTarget, + getReviewCommentTarget, + ); +} + +export function getSelectedReviewCommentLines( + target: ReviewCommentTarget, +): ReadonlyArray { + return target.lines.slice(target.startIndex, target.endIndex + 1); +} + +export function getReviewUnifiedLineNumber(line: ReviewRenderableLineRow): number | null { + return line.newLineNumber ?? line.oldLineNumber; +} + +export function formatReviewLineLabel(line: ReviewRenderableLineRow): string { + if (line.newLineNumber !== null) { + return `new line ${line.newLineNumber}`; + } + if (line.oldLineNumber !== null) { + return `old line ${line.oldLineNumber}`; + } + return "file"; +} + +export function getReviewChangeMarker(change: ReviewRenderableLineRow["change"]): string { + if (change === "add") return "+"; + if (change === "delete") return "-"; + return " "; +} + +export function buildReviewCommentTarget( + target: Pick, + anchorIndex: number, + lineIndex: number, +): ReviewCommentTarget { + return { + sectionTitle: target.sectionTitle, + filePath: target.filePath, + lines: target.lines, + startIndex: Math.min(anchorIndex, lineIndex), + endIndex: Math.max(anchorIndex, lineIndex), + }; +} + +export function formatReviewSelectedRangeLabel(target: ReviewCommentTarget): string { + const lines = getSelectedReviewCommentLines(target); + const firstLine = lines[0]!; + const lastLine = lines[lines.length - 1]!; + const firstNumber = getReviewUnifiedLineNumber(firstLine); + const lastNumber = getReviewUnifiedLineNumber(lastLine); + + if (firstNumber === null || lastNumber === null) { + return lines.length === 1 ? "line" : `${lines.length} lines`; + } + + const firstMarker = getReviewChangeMarker(firstLine.change).trim(); + const consistentMarker = + lines.every((line) => line.change === firstLine.change) && firstMarker.length > 0 + ? getReviewChangeMarker(firstLine.change) + : ""; + + if (firstNumber === lastNumber) { + return `${consistentMarker}${firstNumber}`; + } + + return `${consistentMarker}${firstNumber} to ${consistentMarker}${lastNumber}`; +} + +function getDiffHunkRange( + selectedLines: ReadonlyArray, + key: "oldLineNumber" | "newLineNumber", +): { + readonly start: number; + readonly count: number; +} { + const numberedLines = selectedLines.filter((line) => line[key] !== null); + if (numberedLines.length === 0) { + return { start: 0, count: 0 }; + } + + return { + start: numberedLines[0]![key] ?? 0, + count: numberedLines.length, + }; +} + +function formatReviewSelectedDiff(target: ReviewCommentTarget): string { + const selectedLines = getSelectedReviewCommentLines(target); + const oldRange = getDiffHunkRange(selectedLines, "oldLineNumber"); + const newRange = getDiffHunkRange(selectedLines, "newLineNumber"); + const diffBody = selectedLines + .map((line) => `${getReviewChangeMarker(line.change)}${line.content}`) + .join("\n"); + + return [ + `@@ -${oldRange.start},${oldRange.count} +${newRange.start},${newRange.count} @@`, + diffBody.length > 0 ? diffBody : " ", + ].join("\n"); +} + +export function formatReviewCommentContext(target: ReviewCommentTarget, comment: string): string { + return [ + "", + comment.trim(), + "```diff", + formatReviewSelectedDiff(target), + "```", + "", + ].join("\n"); +} diff --git a/apps/mobile/src/features/threads/review/reviewModel.test.ts b/apps/mobile/src/features/threads/review/reviewModel.test.ts new file mode 100644 index 0000000000..295ba871a2 --- /dev/null +++ b/apps/mobile/src/features/threads/review/reviewModel.test.ts @@ -0,0 +1,174 @@ +import { describe, expect, it } from "vitest"; + +import { + MessageId, + TurnId, + type GitReviewDiffSection, + type OrchestrationCheckpointSummary, +} from "@t3tools/contracts"; + +import { + buildReviewParsedDiff, + buildReviewSectionItems, + getDefaultReviewSectionId, + getReviewSectionIdForCheckpoint, +} from "./reviewModel"; + +function makeCheckpoint( + input: Partial & + Pick, +): OrchestrationCheckpointSummary { + return { + checkpointRef: `refs/t3/checkpoints/thread/${input.checkpointTurnCount}` as any, + status: "ready", + files: [], + assistantMessageId: MessageId.make(`msg-${input.checkpointTurnCount}`), + ...input, + }; +} + +describe("buildReviewSectionItems", () => { + it("keeps one chip per checkpoint and appends git sources", () => { + const checkpoints = [ + makeCheckpoint({ + turnId: TurnId.make("turn-1"), + checkpointTurnCount: 1, + completedAt: "2026-04-01T00:00:00.000Z", + }), + makeCheckpoint({ + turnId: TurnId.make("turn-2"), + checkpointTurnCount: 2, + completedAt: "2026-04-02T00:00:00.000Z", + }), + ]; + const gitSections: GitReviewDiffSection[] = [ + { + kind: "dirty", + title: "Dirty worktree", + baseRef: "HEAD", + headRef: null, + diff: "diff --git a/a.ts b/a.ts", + }, + { + kind: "base", + title: "Against main", + baseRef: "main", + headRef: "feature", + diff: "diff --git a/a.ts b/a.ts", + }, + ]; + + const loadedTurnId = getReviewSectionIdForCheckpoint(checkpoints[0]); + const items = buildReviewSectionItems({ + checkpoints, + gitSections, + turnDiffById: { + [loadedTurnId]: "diff --git a/loaded.ts b/loaded.ts", + }, + loadingTurnIds: { + [getReviewSectionIdForCheckpoint(checkpoints[1])]: true, + }, + }); + + expect(items.map((item) => item.id)).toEqual(["turn:2", "turn:1", "git:dirty", "git:base"]); + expect(items[0]).toMatchObject({ isLoading: true, diff: null }); + expect(items[1]).toMatchObject({ + isLoading: false, + diff: expect.stringContaining("loaded.ts"), + }); + expect(getDefaultReviewSectionId(items)).toBe("turn:2"); + }); +}); + +describe("buildReviewParsedDiff", () => { + it("builds renderable rows from a unified patch", () => { + const parsed = buildReviewParsedDiff( + [ + "diff --git a/apps/mobile/src/a.ts b/apps/mobile/src/a.ts", + "index 1111111..2222222 100644", + "--- a/apps/mobile/src/a.ts", + "+++ b/apps/mobile/src/a.ts", + "@@ -1,2 +1,3 @@", + "-const before = 1;", + "+const after = 2;", + "+console.log(after);", + " return true;", + ].join("\n"), + "unit", + ); + + expect(parsed.kind).toBe("files"); + if (parsed.kind !== "files") { + return; + } + + expect(parsed.fileCount).toBe(1); + expect(parsed.additions).toBe(2); + expect(parsed.deletions).toBe(1); + expect(parsed.files[0]).toMatchObject({ + path: "apps/mobile/src/a.ts", + additions: 2, + deletions: 1, + }); + expect(parsed.files[0]?.rows).toEqual([ + expect.objectContaining({ kind: "hunk", header: "@@ -1,2 +1,3 @@" }), + expect.objectContaining({ + kind: "line", + change: "delete", + oldLineNumber: 1, + newLineNumber: null, + content: "const before = 1;", + }), + expect.objectContaining({ + kind: "line", + change: "add", + oldLineNumber: null, + newLineNumber: 1, + content: "const after = 2;", + }), + expect.objectContaining({ + kind: "line", + change: "add", + oldLineNumber: null, + newLineNumber: 2, + content: "console.log(after);", + }), + expect.objectContaining({ + kind: "line", + change: "context", + oldLineNumber: 2, + newLineNumber: 3, + content: "return true;", + }), + ]); + }); + + it("treats truncated patches as partial diffs instead of failing", () => { + const parsed = buildReviewParsedDiff( + [ + "diff --git a/apps/mobile/src/a.ts b/apps/mobile/src/a.ts", + "index 1111111..2222222 100644", + "--- a/apps/mobile/src/a.ts", + "+++ b/apps/mobile/src/a.ts", + "@@ -1 +1,2 @@", + " const before = 1;", + "+const after = 2;", + "", + "[truncated]", + ].join("\n"), + "unit-truncated", + ); + + expect(parsed.kind).toBe("files"); + if (parsed.kind !== "files") { + return; + } + + expect(parsed.notice).toContain("server size cap"); + expect(parsed.fileCount).toBe(1); + expect(parsed.files[0]?.rows[0]).toMatchObject({ + kind: "hunk", + header: "@@ -1,1 +1,2 @@", + }); + }); +}); diff --git a/apps/mobile/src/features/threads/review/reviewModel.ts b/apps/mobile/src/features/threads/review/reviewModel.ts new file mode 100644 index 0000000000..7b289fbc77 --- /dev/null +++ b/apps/mobile/src/features/threads/review/reviewModel.ts @@ -0,0 +1,380 @@ +import { parsePatchFiles, type ChangeTypes, type FileDiffMetadata } from "@pierre/diffs/utils"; +import type { GitReviewDiffSection, OrchestrationCheckpointSummary } from "@t3tools/contracts"; +import * as Arr from "effect/Array"; +import * as Order from "effect/Order"; + +export type ReviewSectionKind = "turn" | "dirty" | "base"; + +export interface ReviewSectionItem { + readonly id: string; + readonly kind: ReviewSectionKind; + readonly title: string; + readonly subtitle: string | null; + readonly diff: string | null; + readonly isLoading: boolean; +} + +export interface ReviewRenderableHunkRow { + readonly kind: "hunk"; + readonly id: string; + readonly header: string; + readonly context: string | null; +} + +export interface ReviewRenderableLineRow { + readonly kind: "line"; + readonly id: string; + readonly change: "context" | "add" | "delete"; + readonly oldLineNumber: number | null; + readonly newLineNumber: number | null; + readonly content: string; + readonly additionTokenIndex: number | null; + readonly deletionTokenIndex: number | null; +} + +export type ReviewRenderableRow = ReviewRenderableHunkRow | ReviewRenderableLineRow; + +export interface ReviewRenderableFile { + readonly id: string; + readonly cacheKey: string; + readonly path: string; + readonly previousPath: string | null; + readonly changeType: ChangeTypes; + readonly additions: number; + readonly deletions: number; + readonly languageHint: string | null; + readonly additionLines: ReadonlyArray; + readonly deletionLines: ReadonlyArray; + readonly rows: ReadonlyArray; +} + +export type ReviewParsedDiff = + | { + readonly kind: "empty"; + } + | { + readonly kind: "raw"; + readonly text: string; + readonly reason: string; + readonly notice: string | null; + } + | { + readonly kind: "files"; + readonly files: ReadonlyArray; + readonly fileCount: number; + readonly additions: number; + readonly deletions: number; + readonly notice: string | null; + }; + +function checkpointTitle(checkpoint: OrchestrationCheckpointSummary): string { + return `Turn ${checkpoint.checkpointTurnCount}`; +} + +function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string { + const fileCount = checkpoint.files.length; + if (checkpoint.status !== "ready") { + return `Diff ${checkpoint.status}`; + } + return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`; +} + +function compareCheckpointTurnCountDescending( + left: OrchestrationCheckpointSummary, + right: OrchestrationCheckpointSummary, +): -1 | 0 | 1 { + if (left.checkpointTurnCount === right.checkpointTurnCount) { + return 0; + } + + return left.checkpointTurnCount > right.checkpointTurnCount ? -1 : 1; +} + +const readyCheckpointOrder = Order.make( + compareCheckpointTurnCountDescending, +); + +function gitSubtitle(section: GitReviewDiffSection): string | null { + if (section.kind === "dirty") { + return "Tracked, staged, and untracked worktree changes"; + } + if (section.baseRef) { + return `${section.baseRef} ... ${section.headRef ?? "HEAD"}`; + } + return "Base branch unavailable"; +} + +function stripGitPrefix(pathValue: string | undefined): string | null { + if (!pathValue) { + return null; + } + if (pathValue.startsWith("a/") || pathValue.startsWith("b/")) { + return pathValue.slice(2); + } + return pathValue; +} + +function stripTrailingNewline(value: string): string { + return value.endsWith("\n") ? value.slice(0, -1) : value; +} + +function splitTruncationMarker(diff: string): { + readonly text: string; + readonly truncated: boolean; +} { + const trimmed = diff.trimEnd(); + if (!trimmed.endsWith("[truncated]")) { + return { text: trimmed, truncated: false }; + } + + return { + text: trimmed.replace(/\n*\[truncated\]\s*$/, "").trimEnd(), + truncated: true, + }; +} + +function runDiffParserSilently(callback: () => T): T { + const originalConsoleError = console.error; + console.error = () => undefined; + try { + return callback(); + } finally { + console.error = originalConsoleError; + } +} + +const FNV_OFFSET_BASIS_32 = 0x811c9dc5; +const FNV_PRIME_32 = 0x01000193; +const SECONDARY_HASH_SEED = 0x9e3779b9; +const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b; + +function fnv1a32(input: string, seed: number, multiplier: number): number { + let hash = seed >>> 0; + for (let index = 0; index < input.length; index += 1) { + hash ^= input.charCodeAt(index); + hash = Math.imul(hash, multiplier) >>> 0; + } + return hash >>> 0; +} + +function buildPatchCacheKey(patch: string, scope: string): string { + const normalizedPatch = patch.trim(); + const primary = fnv1a32(normalizedPatch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36); + const secondary = fnv1a32( + normalizedPatch, + SECONDARY_HASH_SEED, + SECONDARY_HASH_MULTIPLIER, + ).toString(36); + return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`; +} + +function fallbackHunkHeader(hunk: FileDiffMetadata["hunks"][number]): string { + return `@@ -${hunk.deletionStart},${hunk.deletionCount} +${hunk.additionStart},${hunk.additionCount} @@`; +} + +function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray { + const rows: ReviewRenderableRow[] = []; + let rowIndex = 0; + + file.hunks.forEach((hunk, hunkIndex) => { + rows.push({ + kind: "hunk", + id: `${file.cacheKey ?? file.name}:hunk:${hunkIndex}`, + header: fallbackHunkHeader(hunk), + context: hunk.hunkContext ? stripTrailingNewline(hunk.hunkContext) : null, + }); + + let deletionLineNumber = hunk.deletionStart; + let additionLineNumber = hunk.additionStart; + let deletionTokenIndex = hunk.deletionLineIndex; + let additionTokenIndex = hunk.additionLineIndex; + + hunk.hunkContent.forEach((segment) => { + if (segment.type === "context") { + for (let index = 0; index < segment.lines; index += 1) { + rows.push({ + kind: "line", + id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`, + change: "context", + oldLineNumber: deletionLineNumber, + newLineNumber: additionLineNumber, + content: stripTrailingNewline( + file.additionLines[additionTokenIndex] ?? + file.deletionLines[deletionTokenIndex] ?? + "", + ), + additionTokenIndex, + deletionTokenIndex, + }); + deletionLineNumber += 1; + additionLineNumber += 1; + deletionTokenIndex += 1; + additionTokenIndex += 1; + } + return; + } + + for (let index = 0; index < segment.deletions; index += 1) { + rows.push({ + kind: "line", + id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`, + change: "delete", + oldLineNumber: deletionLineNumber, + newLineNumber: null, + content: stripTrailingNewline(file.deletionLines[deletionTokenIndex] ?? ""), + additionTokenIndex: null, + deletionTokenIndex, + }); + deletionLineNumber += 1; + deletionTokenIndex += 1; + } + + for (let index = 0; index < segment.additions; index += 1) { + rows.push({ + kind: "line", + id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`, + change: "add", + oldLineNumber: null, + newLineNumber: additionLineNumber, + content: stripTrailingNewline(file.additionLines[additionTokenIndex] ?? ""), + additionTokenIndex, + deletionTokenIndex: null, + }); + additionLineNumber += 1; + additionTokenIndex += 1; + } + }); + }); + + return rows; +} + +function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile { + const path = stripGitPrefix(file.name) ?? stripGitPrefix(file.prevName) ?? file.name; + const previousPath = stripGitPrefix(file.prevName); + const additions = file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0); + const deletions = file.hunks.reduce((total, hunk) => total + hunk.deletionLines, 0); + const cacheKey = file.cacheKey ?? `${previousPath ?? "none"}:${path}:${file.type}`; + + return { + id: cacheKey, + cacheKey, + path, + previousPath, + changeType: file.type, + additions, + deletions, + languageHint: file.lang ?? null, + additionLines: file.additionLines, + deletionLines: file.deletionLines, + rows: buildRenderableRows(file), + }; +} + +export function getReviewSectionIdForCheckpoint( + checkpoint: Pick, +): string { + return `turn:${checkpoint.checkpointTurnCount}`; +} + +export function getReadyReviewCheckpoints( + checkpoints: ReadonlyArray, +): ReadonlyArray { + return Arr.sort( + checkpoints.filter((checkpoint) => checkpoint.status === "ready"), + readyCheckpointOrder, + ); +} + +export function buildReviewSectionItems(input: { + readonly checkpoints: ReadonlyArray; + readonly gitSections: ReadonlyArray; + readonly turnDiffById: Readonly>; + readonly loadingTurnIds: Readonly>; +}): ReadonlyArray { + const turnItems = getReadyReviewCheckpoints(input.checkpoints).map( + (checkpoint) => { + const id = getReviewSectionIdForCheckpoint(checkpoint); + return { + id, + kind: "turn", + title: checkpointTitle(checkpoint), + subtitle: checkpointSubtitle(checkpoint), + diff: input.turnDiffById[id] ?? null, + isLoading: input.loadingTurnIds[id] === true, + }; + }, + ); + + const gitItems = input.gitSections.map((section) => ({ + id: `git:${section.kind}`, + kind: section.kind, + title: section.title, + subtitle: gitSubtitle(section), + diff: section.diff, + isLoading: false, + })); + + return [...turnItems, ...gitItems]; +} + +export function getDefaultReviewSectionId( + sections: ReadonlyArray, +): string | null { + return sections[0]?.id ?? null; +} + +export function buildReviewParsedDiff( + diff: string | null | undefined, + cacheScope: string, +): ReviewParsedDiff { + const normalized = diff?.trim(); + if (!normalized) { + return { kind: "empty" }; + } + + const { text, truncated } = splitTruncationMarker(normalized); + if (text.length === 0) { + return { kind: "empty" }; + } + + const notice = truncated + ? "Diff output hit the server size cap. Showing the available excerpt." + : null; + + try { + const parsedPatches = runDiffParserSilently(() => + parsePatchFiles(text, buildPatchCacheKey(text, cacheScope)), + ); + const files = parsedPatches.flatMap((patch) => patch.files).map(mapRenderableFile); + + if (files.length === 0) { + return { + kind: "raw", + text, + reason: truncated + ? "Diff was truncated before it could be parsed completely. Showing the raw excerpt." + : "Unsupported diff format. Showing raw patch.", + notice, + }; + } + + return { + kind: "files", + files, + fileCount: files.length, + additions: files.reduce((total, file) => total + file.additions, 0), + deletions: files.reduce((total, file) => total + file.deletions, 0), + notice, + }; + } catch { + return { + kind: "raw", + text, + reason: truncated + ? "Diff was truncated before it could be parsed completely. Showing the raw excerpt." + : "Failed to parse patch. Showing raw patch.", + notice, + }; + } +} diff --git a/apps/mobile/src/features/threads/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/threads/review/shikiReviewHighlighter.ts new file mode 100644 index 0000000000..722cb4ea7a --- /dev/null +++ b/apps/mobile/src/features/threads/review/shikiReviewHighlighter.ts @@ -0,0 +1,131 @@ +import { getFiletypeFromFileName } from "@pierre/diffs/utils"; + +import type { ReviewRenderableFile } from "./reviewModel"; + +export type ReviewDiffTheme = "light" | "dark"; + +export interface ReviewHighlightedToken { + readonly content: string; + readonly color: string | null; + readonly fontStyle: number | null; +} + +export interface ReviewHighlightedFile { + readonly additionLines: ReadonlyArray>; + readonly deletionLines: ReadonlyArray>; +} + +const SHIKI_THEME_BY_SCHEME = { + light: "github-light-default", + dark: "github-dark-default", +} as const; + +const highlightCache = new Map>(); +const loadedLanguages = new Set(["text"]); +type ShikiHighlighter = { + loadLanguage: (...langs: string[]) => Promise; + codeToTokensBase: ( + code: string, + options: { readonly lang: string; readonly theme: string }, + ) => Promise>>; +}; +let highlighterPromise: Promise | null = null; + +function cleanLastNewline(value: string): string { + return value.endsWith("\n") ? value.slice(0, -1) : value; +} + +function joinPatchLines(lines: ReadonlyArray): string { + if (lines.length === 0) { + return ""; + } + + return cleanLastNewline(lines.join("")); +} + +async function getHighlighter() { + if (!highlighterPromise) { + highlighterPromise = import("shiki").then( + async ({ createHighlighter, createJavaScriptRegexEngine }) => { + const highlighter = await createHighlighter({ + themes: [SHIKI_THEME_BY_SCHEME.light, SHIKI_THEME_BY_SCHEME.dark], + langs: [], + engine: createJavaScriptRegexEngine(), + }); + return highlighter as unknown as ShikiHighlighter; + }, + ); + } + + return highlighterPromise as Promise; +} + +async function resolveLanguage(file: ReviewRenderableFile): Promise { + const candidate = file.languageHint ?? getFiletypeFromFileName(file.path); + if (!candidate || candidate === "text" || candidate === "ansi") { + return "text"; + } + + const highlighter = await getHighlighter(); + if (!loadedLanguages.has(candidate)) { + try { + await highlighter.loadLanguage(candidate); + loadedLanguages.add(candidate); + } catch { + return "text"; + } + } + + return candidate; +} + +function normalizeHighlightedLines( + tokenLines: ReadonlyArray>, +): ReadonlyArray> { + return tokenLines.map((line) => + line.map((token) => ({ + content: token.content, + color: token.color ?? null, + fontStyle: token.fontStyle ?? null, + })), + ); +} + +async function highlightLines( + code: string, + language: string, + theme: string, +): Promise>> { + if (code.length === 0) { + return []; + } + + const highlighter = await getHighlighter(); + const tokenLines = await highlighter.codeToTokensBase(code, { lang: language, theme }); + return normalizeHighlightedLines(tokenLines); +} + +export async function highlightReviewFile( + file: ReviewRenderableFile, + theme: ReviewDiffTheme, +): Promise { + const shikiTheme = SHIKI_THEME_BY_SCHEME[theme]; + const cacheKey = `${shikiTheme}:${file.cacheKey}`; + const cached = highlightCache.get(cacheKey); + if (cached) { + return cached; + } + + const promise = (async () => { + const language = await resolveLanguage(file); + const [additionLines, deletionLines] = await Promise.all([ + highlightLines(joinPatchLines(file.additionLines), language, shikiTheme), + highlightLines(joinPatchLines(file.deletionLines), language, shikiTheme), + ]); + + return { additionLines, deletionLines }; + })(); + + highlightCache.set(cacheKey, promise); + return promise; +} diff --git a/apps/mobile/src/features/threads/use-thread-composer-state.ts b/apps/mobile/src/features/threads/use-thread-composer-state.ts index d0241e7b19..66392c66bf 100644 --- a/apps/mobile/src/features/threads/use-thread-composer-state.ts +++ b/apps/mobile/src/features/threads/use-thread-composer-state.ts @@ -89,6 +89,24 @@ function appendDraftMessage(threadKey: string, value: string): void { }); } +export function appendReviewCommentToDraft(input: { + readonly environmentId: string; + readonly threadId: string; + readonly text: string; +}): void { + const threadKey = scopedThreadKey( + EnvironmentId.make(input.environmentId), + ThreadId.make(input.threadId), + ); + const current = appAtomRegistry.get(draftMessageByThreadKeyAtom); + const existing = current[threadKey] ?? ""; + const separator = existing.trim().length > 0 && !existing.endsWith("\n") ? "\n\n" : ""; + appAtomRegistry.set(draftMessageByThreadKeyAtom, { + ...current, + [threadKey]: `${existing}${separator}${input.text}`, + }); +} + function clearDraft(threadKey: string): void { const draftMessages = appAtomRegistry.get(draftMessageByThreadKeyAtom); const draftAttachments = appAtomRegistry.get(draftAttachmentsByThreadKeyAtom); diff --git a/apps/mobile/src/lib/routes.ts b/apps/mobile/src/lib/routes.ts index 293b3f4da4..b70ab7638e 100644 --- a/apps/mobile/src/lib/routes.ts +++ b/apps/mobile/src/lib/routes.ts @@ -6,14 +6,29 @@ import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime"; type ThreadRouteInput = | Pick | Pick; +type PlainThreadRouteInput = + | { + environmentId: string; + threadId: string; + } + | { + environmentId: string; + id: string; + }; -export function buildThreadRoutePath(input: ThreadRouteInput): string { +export function buildThreadRoutePath(input: ThreadRouteInput | PlainThreadRouteInput): string { const environmentId = input.environmentId; const threadId = "threadId" in input ? input.threadId : input.id; return `/threads/${encodeURIComponent(environmentId)}/${encodeURIComponent(threadId)}`; } +export function buildThreadReviewRoutePath( + input: ThreadRouteInput | PlainThreadRouteInput, +): string { + return `${buildThreadRoutePath(input)}/review`; +} + export function dismissRoute(router: Router) { if (router.canGoBack()) { router.back(); diff --git a/apps/server/src/git/Layers/GitCore.ts b/apps/server/src/git/Layers/GitCore.ts index 3e9df316f1..98763e0318 100644 --- a/apps/server/src/git/Layers/GitCore.ts +++ b/apps/server/src/git/Layers/GitCore.ts @@ -18,7 +18,7 @@ import { } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -import { GitCommandError, type GitBranch } from "@t3tools/contracts"; +import { GitCommandError, type GitBranch, type GitReviewDiffSection } from "@t3tools/contracts"; import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git"; import { compactTraceAttributes } from "../../observability/Attributes.ts"; import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../../observability/Metrics.ts"; @@ -46,6 +46,8 @@ const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000; const RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES = 19_000; const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000; const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000; +const REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES = 180_000; +const REVIEW_UNTRACKED_DIFF_MAX_OUTPUT_BYTES = 40_000; const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024; const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [ @@ -1628,6 +1630,116 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { }, ); + const readUntrackedReviewDiffs = Effect.fn("readUntrackedReviewDiffs")(function* (cwd: string) { + const untrackedOutput = yield* runGitStdoutWithOptions( + "GitCore.readUntrackedReviewDiffs.list", + cwd, + ["ls-files", "--others", "--exclude-standard", "-z"], + { + maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ); + const untrackedPaths = splitNullSeparatedPaths(untrackedOutput, false); + if (untrackedPaths.length === 0) { + return ""; + } + + const diffs = yield* Effect.forEach( + untrackedPaths, + (relativePath) => + executeGit( + "GitCore.readUntrackedReviewDiffs.diff", + cwd, + ["diff", "--no-index", "--patch", "--minimal", "--", "/dev/null", relativePath], + { + allowNonZeroExit: true, + maxOutputBytes: REVIEW_UNTRACKED_DIFF_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ).pipe( + Effect.map((result) => + result.stdoutTruncated ? `${result.stdout}${OUTPUT_TRUNCATED_MARKER}` : result.stdout, + ), + ), + { concurrency: 4 }, + ); + + return diffs.filter((diff) => diff.trim().length > 0).join("\n"); + }); + + const getReviewDiffs: GitCoreShape["getReviewDiffs"] = Effect.fn("getReviewDiffs")( + function* (input) { + const details = yield* statusDetailsLocal(input.cwd); + if (!details.isRepo) { + return { + cwd: input.cwd, + generatedAt: new Date().toISOString(), + sections: [], + }; + } + + const branch = details.branch; + const baseRef = branch + ? yield* resolveBaseBranchForNoUpstream(input.cwd, branch).pipe( + Effect.catch(() => Effect.succeed(null)), + ) + : null; + + const dirtyTrackedDiff = yield* runGitStdoutWithOptions( + "GitCore.getReviewDiffs.dirtyTracked", + input.cwd, + ["diff", "--patch", "--minimal", "HEAD", "--"], + { + maxOutputBytes: REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ).pipe(Effect.catch(() => Effect.succeed(""))); + const dirtyUntrackedDiff = yield* readUntrackedReviewDiffs(input.cwd).pipe( + Effect.catch(() => Effect.succeed("")), + ); + const dirtyDiff = [dirtyTrackedDiff.trimEnd(), dirtyUntrackedDiff.trimEnd()] + .filter((diff) => diff.length > 0) + .join("\n"); + + const baseDiff = + baseRef && branch + ? yield* runGitStdoutWithOptions( + "GitCore.getReviewDiffs.base", + input.cwd, + ["diff", "--patch", "--minimal", `${baseRef}...HEAD`], + { + maxOutputBytes: REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ).pipe(Effect.catch(() => Effect.succeed(""))) + : ""; + + const sections: GitReviewDiffSection[] = [ + { + kind: "dirty", + title: "Dirty worktree", + baseRef: "HEAD", + headRef: null, + diff: dirtyDiff, + }, + { + kind: "base", + title: baseRef ? `Against ${baseRef}` : "Against base branch", + baseRef, + headRef: branch ?? "HEAD", + diff: baseDiff, + }, + ]; + + return { + cwd: input.cwd, + generatedAt: new Date().toISOString(), + sections, + }; + }, + ); + const readConfigValue: GitCoreShape["readConfigValue"] = (cwd, key) => runGitStdout("GitCore.readConfigValue", cwd, ["config", "--get", key], true).pipe( Effect.map((stdout) => stdout.trim()), @@ -2184,6 +2296,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { pushCurrentBranch, pullCurrentBranch, readRangeContext, + getReviewDiffs, readConfigValue, isInsideWorkTree, listWorkspaceFiles, diff --git a/apps/server/src/git/Services/GitCore.ts b/apps/server/src/git/Services/GitCore.ts index 9f3bc0b9b9..2dff62c53e 100644 --- a/apps/server/src/git/Services/GitCore.ts +++ b/apps/server/src/git/Services/GitCore.ts @@ -20,6 +20,8 @@ import type { GitListBranchesResult, GitPullResult, GitRemoveWorktreeInput, + GitReviewDiffsInput, + GitReviewDiffsResult, GitStatusInput, GitStatusResult, } from "@t3tools/contracts"; @@ -197,6 +199,13 @@ export interface GitCoreShape { baseBranch: string, ) => Effect.Effect; + /** + * Read review-oriented diffs for dirty worktree changes and branch changes against base. + */ + readonly getReviewDiffs: ( + input: GitReviewDiffsInput, + ) => Effect.Effect; + /** * Read a Git config value from the local repository. */ diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 276bc1d9b4..ebcefefc83 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -2259,6 +2259,27 @@ it.layer(NodeServices.layer)("server router seam", (it) => { createBranch: (input) => Effect.succeed({ branch: input.branch }), checkoutBranch: (input) => Effect.succeed({ branch: input.branch }), initRepo: () => Effect.void, + getReviewDiffs: (input) => + Effect.succeed({ + cwd: input.cwd, + generatedAt: new Date(0).toISOString(), + sections: [ + { + kind: "dirty", + title: "Dirty worktree", + baseRef: "HEAD", + headRef: null, + diff: "dirty-diff", + }, + { + kind: "base", + title: "Against main", + baseRef: "main", + headRef: "feature/demo", + diff: "base-diff", + }, + ], + }), }, }, }); @@ -2368,6 +2389,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }), ), ); + + const reviewDiffs = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitGetReviewDiffs]({ cwd: "/tmp/repo" }), + ), + ); + assert.equal(reviewDiffs.sections[0]?.diff, "dirty-diff"); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index b41ed77fa3..c1f76a1849 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -866,6 +866,10 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) => git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), { "rpc.aggregate": "git" }, ), + [WS_METHODS.gitGetReviewDiffs]: (input) => + observeRpcEffect(WS_METHODS.gitGetReviewDiffs, git.getReviewDiffs(input), { + "rpc.aggregate": "git", + }), [WS_METHODS.terminalOpen]: (input) => observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), { "rpc.aggregate": "terminal", diff --git a/apps/web/src/environmentApi.ts b/apps/web/src/environmentApi.ts index 06fce4ea61..a77e6528c0 100644 --- a/apps/web/src/environmentApi.ts +++ b/apps/web/src/environmentApi.ts @@ -30,6 +30,7 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi { init: rpcClient.git.init, resolvePullRequest: rpcClient.git.resolvePullRequest, preparePullRequestThread: rpcClient.git.preparePullRequestThread, + getReviewDiffs: rpcClient.git.getReviewDiffs, }, orchestration: { dispatchCommand: rpcClient.orchestration.dispatchCommand, diff --git a/apps/web/src/environments/runtime/connection.test.ts b/apps/web/src/environments/runtime/connection.test.ts index 57f2324145..4bdda57bda 100644 --- a/apps/web/src/environments/runtime/connection.test.ts +++ b/apps/web/src/environments/runtime/connection.test.ts @@ -97,6 +97,7 @@ function createTestClient() { init: vi.fn(async () => undefined), resolvePullRequest: vi.fn(async () => undefined), preparePullRequestThread: vi.fn(async () => undefined), + getReviewDiffs: vi.fn(async () => undefined), }, } as unknown as WsRpcClient; diff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.ts index 0e169efb21..fa82535027 100644 --- a/apps/web/src/localApi.test.ts +++ b/apps/web/src/localApi.test.ts @@ -69,6 +69,7 @@ const rpcClientMock = { init: vi.fn(), resolvePullRequest: vi.fn(), preparePullRequestThread: vi.fn(), + getReviewDiffs: vi.fn(), }, server: { getConfig: vi.fn(), @@ -113,6 +114,7 @@ vi.mock("./environments/runtime", () => ({ resetEnvironmentServiceForTests: vi.fn(), resetSavedEnvironmentRegistryStoreForTests: vi.fn(), resetSavedEnvironmentRuntimeStoreForTests: vi.fn(), + subscribeEnvironmentConnections: vi.fn(() => () => undefined), })); vi.mock("./contextMenuFallback", () => ({ diff --git a/apps/web/src/rpc/wsRpcClient.ts b/apps/web/src/rpc/wsRpcClient.ts index 753d27caba..50eca4eecc 100644 --- a/apps/web/src/rpc/wsRpcClient.ts +++ b/apps/web/src/rpc/wsRpcClient.ts @@ -92,6 +92,8 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient { transport.request((client) => client[WS_METHODS.gitResolvePullRequest](input)), preparePullRequestThread: (input) => transport.request((client) => client[WS_METHODS.gitPreparePullRequestThread](input)), + getReviewDiffs: (input) => + transport.request((client) => client[WS_METHODS.gitGetReviewDiffs](input)), }, server: { getConfig: () => transport.request((client) => client[WS_METHODS.serverGetConfig]({})), diff --git a/bun.lock b/bun.lock index a046fadbf6..e04cf5cd88 100644 --- a/bun.lock +++ b/bun.lock @@ -48,6 +48,7 @@ "@effect/atom-react": "catalog:", "@expo-google-fonts/dm-sans": "^0.4.2", "@legendapp/list": "3.0.0-beta.44", + "@pierre/diffs": "^1.1.0-beta.16", "@react-native-menu/menu": "^2.0.0", "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", @@ -85,6 +86,7 @@ "react-native-screens": "~4.23.0", "react-native-svg": "15.15.3", "react-native-worklets": "0.7.2", + "shiki": "^4.0.2", "tailwind-merge": "^3.5.0", "uniwind": "^1.6.2", }, diff --git a/package.json b/package.json index d6befdc17b..df1e4af64d 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ }, "type": "module", "scripts": { - "postinstall": "node scripts/patch-expo-dev-launcher.mjs", + "postinstall": "node scripts/patch-expo-dev-launcher.mjs && node scripts/patch-react-native-nitro-modules.mjs && node scripts/patch-pierre-diffs-utils.mjs", "dev": "node scripts/dev-runner.ts dev", "dev:server": "node scripts/dev-runner.ts dev:server", "dev:web": "node scripts/dev-runner.ts dev:web", diff --git a/packages/client-runtime/src/wsRpcClient.ts b/packages/client-runtime/src/wsRpcClient.ts index 33745cf934..5e1148d527 100644 --- a/packages/client-runtime/src/wsRpcClient.ts +++ b/packages/client-runtime/src/wsRpcClient.ts @@ -95,6 +95,7 @@ export interface WsRpcClient { readonly preparePullRequestThread: RpcUnaryMethod< typeof WS_METHODS.gitPreparePullRequestThread >; + readonly getReviewDiffs: RpcUnaryMethod; }; readonly server: { readonly getConfig: RpcUnaryNoArgMethod; @@ -193,6 +194,8 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient { transport.request((client) => client[WS_METHODS.gitResolvePullRequest](input)), preparePullRequestThread: (input) => transport.request((client) => client[WS_METHODS.gitPreparePullRequestThread](input)), + getReviewDiffs: (input) => + transport.request((client) => client[WS_METHODS.gitGetReviewDiffs](input)), }, server: { getConfig: () => transport.request((client) => client[WS_METHODS.serverGetConfig]({})), diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts index 345208acf9..ecaa91fc5d 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -189,6 +189,11 @@ export const GitInitInput = Schema.Struct({ }); export type GitInitInput = typeof GitInitInput.Type; +export const GitReviewDiffsInput = Schema.Struct({ + cwd: TrimmedNonEmptyStringSchema, +}); +export type GitReviewDiffsInput = typeof GitReviewDiffsInput.Type; + // RPC Results const GitStatusPr = Schema.Struct({ @@ -284,6 +289,25 @@ export const GitCheckoutResult = Schema.Struct({ }); export type GitCheckoutResult = typeof GitCheckoutResult.Type; +export const GitReviewDiffKind = Schema.Literals(["dirty", "base"]); +export type GitReviewDiffKind = typeof GitReviewDiffKind.Type; + +export const GitReviewDiffSection = Schema.Struct({ + kind: GitReviewDiffKind, + title: TrimmedNonEmptyStringSchema, + baseRef: Schema.NullOr(TrimmedNonEmptyStringSchema), + headRef: Schema.NullOr(TrimmedNonEmptyStringSchema), + diff: Schema.String, +}); +export type GitReviewDiffSection = typeof GitReviewDiffSection.Type; + +export const GitReviewDiffsResult = Schema.Struct({ + cwd: TrimmedNonEmptyStringSchema, + generatedAt: Schema.String, + sections: Schema.Array(GitReviewDiffSection), +}); +export type GitReviewDiffsResult = typeof GitReviewDiffsResult.Type; + export const GitRunStackedActionResult = Schema.Struct({ action: GitStackedAction, branch: Schema.Struct({ diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index a657526d60..f5df23f858 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -13,6 +13,8 @@ import type { GitPullInput, GitPullResult, GitRemoveWorktreeInput, + GitReviewDiffsInput, + GitReviewDiffsResult, GitResolvePullRequestResult, GitStatusInput, GitStatusResult, @@ -239,6 +241,7 @@ export interface EnvironmentApi { preparePullRequestThread: ( input: GitPreparePullRequestThreadInput, ) => Promise; + getReviewDiffs: (input: GitReviewDiffsInput) => Promise; pull: (input: GitPullInput) => Promise; refreshStatus: (input: GitStatusInput) => Promise; onStatus: ( diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index b3809d9658..c20e65d083 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -23,6 +23,8 @@ import { GitPullRequestRefInput, GitPullResult, GitRemoveWorktreeInput, + GitReviewDiffsInput, + GitReviewDiffsResult, GitResolvePullRequestResult, GitRunStackedActionInput, GitStatusInput, @@ -95,6 +97,7 @@ export const WS_METHODS = { gitInit: "git.init", gitResolvePullRequest: "git.resolvePullRequest", gitPreparePullRequestThread: "git.preparePullRequestThread", + gitGetReviewDiffs: "git.getReviewDiffs", // Terminal methods terminalOpen: "terminal.open", @@ -237,6 +240,12 @@ export const WsGitInitRpc = Rpc.make(WS_METHODS.gitInit, { error: GitCommandError, }); +export const WsGitGetReviewDiffsRpc = Rpc.make(WS_METHODS.gitGetReviewDiffs, { + payload: GitReviewDiffsInput, + success: GitReviewDiffsResult, + error: GitCommandError, +}); + export const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, { payload: TerminalOpenInput, success: TerminalSessionSnapshot, @@ -362,6 +371,7 @@ export const WsRpcGroup = RpcGroup.make( WsGitCreateBranchRpc, WsGitCheckoutRpc, WsGitInitRpc, + WsGitGetReviewDiffsRpc, WsTerminalOpenRpc, WsTerminalWriteRpc, WsTerminalResizeRpc, diff --git a/scripts/patch-pierre-diffs-utils.mjs b/scripts/patch-pierre-diffs-utils.mjs new file mode 100644 index 0000000000..11ab526ee3 --- /dev/null +++ b/scripts/patch-pierre-diffs-utils.mjs @@ -0,0 +1,105 @@ +import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +const root = process.cwd(); +const bunStorePath = join(root, "node_modules/.bun"); + +const packageDirs = []; + +if (existsSync(join(root, "node_modules/@pierre/diffs"))) { + packageDirs.push(join(root, "node_modules/@pierre/diffs")); +} + +if (existsSync(bunStorePath)) { + for (const entry of readdirSync(bunStorePath)) { + if (!entry.startsWith("@pierre+diffs@")) { + continue; + } + + packageDirs.push(join(bunStorePath, entry, "node_modules/@pierre/diffs")); + } +} + +const utilsIndexJs = [ + 'export { parsePatchFiles, processFile, processPatch } from "./parsePatchFiles.js";', + "export {", + " EXTENSION_TO_FILE_FORMAT,", + " getCustomExtensionsMap,", + " getCustomExtensionsVersion,", + " getFiletypeFromFileName,", + " replaceCustomExtensions,", + " setCustomExtension,", + '} from "./getFiletypeFromFileName.js";', + "", +].join("\n"); + +const utilsIndexDts = [ + 'export { parsePatchFiles, processFile, processPatch } from "./parsePatchFiles.js";', + "export {", + " EXTENSION_TO_FILE_FORMAT,", + " getCustomExtensionsMap,", + " getCustomExtensionsVersion,", + " getFiletypeFromFileName,", + " replaceCustomExtensions,", + " setCustomExtension,", + '} from "./getFiletypeFromFileName.js";', + 'export type { ChangeTypes, FileDiffMetadata, ParsedPatch, SupportedLanguages } from "../types.js";', + "", +].join("\n"); + +let patchedCount = 0; +let locatedCount = 0; + +for (const packageDir of packageDirs) { + if (!existsSync(packageDir)) { + continue; + } + + locatedCount += 1; + + const packageJsonPath = join(packageDir, "package.json"); + const utilsIndexJsPath = join(packageDir, "dist/utils/index.js"); + const utilsIndexDtsPath = join(packageDir, "dist/utils/index.d.ts"); + + const pkg = JSON.parse(readFileSync(packageJsonPath, "utf8")); + const currentUtilsExport = pkg.exports?.["./utils"]; + + const expectedUtilsExport = { + types: "./dist/utils/index.d.ts", + import: "./dist/utils/index.js", + }; + + const needsExportPatch = + currentUtilsExport?.types !== expectedUtilsExport.types || + currentUtilsExport?.import !== expectedUtilsExport.import; + + if (needsExportPatch) { + pkg.exports = { + ...pkg.exports, + "./utils": expectedUtilsExport, + }; + writeFileSync(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`); + } + + const currentJs = existsSync(utilsIndexJsPath) ? readFileSync(utilsIndexJsPath, "utf8") : null; + if (currentJs !== utilsIndexJs) { + writeFileSync(utilsIndexJsPath, utilsIndexJs); + } + + const currentDts = existsSync(utilsIndexDtsPath) ? readFileSync(utilsIndexDtsPath, "utf8") : null; + if (currentDts !== utilsIndexDts) { + writeFileSync(utilsIndexDtsPath, utilsIndexDts); + } + + if (needsExportPatch || currentJs !== utilsIndexJs || currentDts !== utilsIndexDts) { + patchedCount += 1; + } +} + +if (patchedCount > 0) { + console.log(`[patch-pierre-diffs-utils] patched ${patchedCount} @pierre/diffs installation(s).`); +} else if (locatedCount > 0) { + console.log("[patch-pierre-diffs-utils] @pierre/diffs already patched."); +} else { + console.log("[patch-pierre-diffs-utils] @pierre/diffs not installed; skipping."); +} diff --git a/scripts/patch-react-native-nitro-modules.mjs b/scripts/patch-react-native-nitro-modules.mjs new file mode 100644 index 0000000000..17caedc8b8 --- /dev/null +++ b/scripts/patch-react-native-nitro-modules.mjs @@ -0,0 +1,73 @@ +import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +const root = process.cwd(); + +const candidates = [join(root, "node_modules/react-native-nitro-modules/package.json")]; + +const bunStorePath = join(root, "node_modules/.bun"); + +if (existsSync(bunStorePath)) { + for (const entry of readdirSync(bunStorePath)) { + if (!entry.startsWith("react-native-nitro-modules@")) { + continue; + } + + candidates.push( + join(bunStorePath, entry, "node_modules/react-native-nitro-modules/package.json"), + ); + } +} + +let patchedCount = 0; +let locatedCount = 0; + +for (const filePath of candidates) { + if (!existsSync(filePath)) { + continue; + } + + locatedCount += 1; + + const source = readFileSync(filePath, "utf8"); + const pkg = JSON.parse(source); + + if (pkg.codegenConfig == null || typeof pkg.codegenConfig !== "object") { + throw new Error( + `Found react-native-nitro-modules package at ${filePath}, but codegenConfig was missing.`, + ); + } + + const iosConfig = + pkg.codegenConfig.ios != null && typeof pkg.codegenConfig.ios === "object" + ? pkg.codegenConfig.ios + : {}; + + const modulesProvider = + iosConfig.modulesProvider != null && typeof iosConfig.modulesProvider === "object" + ? iosConfig.modulesProvider + : {}; + + if (modulesProvider.NitroModules === "NativeNitroModules") { + continue; + } + + modulesProvider.NitroModules = "NativeNitroModules"; + iosConfig.modulesProvider = modulesProvider; + pkg.codegenConfig.ios = iosConfig; + + writeFileSync(filePath, `${JSON.stringify(pkg, null, 2)}\n`); + patchedCount += 1; +} + +if (patchedCount > 0) { + console.log( + `[patch-react-native-nitro-modules] patched ${patchedCount} react-native-nitro-modules installation(s).`, + ); +} else if (locatedCount > 0) { + console.log("[patch-react-native-nitro-modules] react-native-nitro-modules already patched."); +} else { + console.log( + "[patch-react-native-nitro-modules] react-native-nitro-modules not installed; skipping.", + ); +}