Add mobile review diff and comment sheets (#2021)
Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
1 parent
a62b2ac173
commit
efc36b41d4
37 files changed
+2734
-3
No files matched your search
@@ -0,0 +1,3 @@
|
||||
<svg width="77" height="47" viewBox="0 0 77 47" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M14.56 45.5V8.58H1.69082e-06V-3.09944e-06H39.65V8.58H25.09V45.5H14.56ZM57.8454 46.28C54.6821 46.28 51.5404 45.8683 48.4204 45.045C45.3004 44.1783 42.6571 42.965 40.4904 41.405L44.5854 33.345C46.3188 34.6017 48.3338 35.5983 50.6304 36.335C52.9271 37.0717 55.2454 37.44 57.5854 37.44C60.2288 37.44 62.3088 36.92 63.8254 35.88C65.3421 34.84 66.1004 33.41 66.1004 31.59C66.1004 29.8567 65.4288 28.4917 64.0854 27.495C62.7421 26.4983 60.5754 26 57.5854 26H52.7754V19.045L65.4504 4.68L66.6204 8.45H42.7654V-3.09944e-06H74.6154V6.825L62.0054 21.19L56.6754 18.135H59.7304C65.3204 18.135 69.5454 19.3917 72.4054 21.905C75.2654 24.4183 76.6954 27.6467 76.6954 31.59C76.6954 34.1467 76.0238 36.5517 74.6804 38.805C73.3371 41.015 71.2788 42.8133 68.5054 44.2C65.7321 45.5867 62.1788 46.28 57.8454 46.28Z" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 920 B |
Binary file not shown.
|
After Width: | Height: | Size: 10 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 14 MiB |
@@ -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"]
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -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 (
|
||||
<Stack screenOptions={{ headerShown: false }}>
|
||||
@@ -38,6 +41,29 @@ export default function ThreadLayout() {
|
||||
sheetGrabberVisible: true,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="review"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: sheetStyle,
|
||||
headerShown: true,
|
||||
headerTitle: "Files changed",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="review-comment"
|
||||
options={{
|
||||
contentStyle: sheetStyle,
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet" as const,
|
||||
sheetAllowedDetents: [0.72, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -42,6 +42,17 @@ export default function GitSheetLayout() {
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="review"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
headerShown: true,
|
||||
headerTitle: "Review changes",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Redirect, useLocalSearchParams } from "expo-router";
|
||||
|
||||
export default function ReviewRoute() {
|
||||
const { environmentId, threadId } = useLocalSearchParams<{
|
||||
environmentId: string;
|
||||
threadId: string;
|
||||
}>();
|
||||
|
||||
return (
|
||||
<Redirect
|
||||
href={{
|
||||
pathname: "/threads/[environmentId]/[threadId]/review",
|
||||
params: { environmentId, threadId },
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { ReviewCommentComposerSheet } from "../../../../features/threads/review/ReviewCommentComposerSheet";
|
||||
|
||||
export default function ReviewCommentRoute() {
|
||||
return <ReviewCommentComposerSheet />;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { ReviewSheet } from "../../../../features/threads/review/ReviewSheet";
|
||||
|
||||
export default function ReviewRoute() {
|
||||
return <ReviewSheet />;
|
||||
}
|
||||
@@ -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: {
|
||||
>
|
||||
<Stack.Toolbar.Label>{quickAction.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="text.bubble"
|
||||
disabled={!isRepo}
|
||||
onPress={() => router.push(buildThreadReviewRoutePath({ environmentId, threadId }))}
|
||||
subtitle="Turn diffs and worktree changes"
|
||||
>
|
||||
<Stack.Toolbar.Label>Review changes</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="ellipsis.circle"
|
||||
onPress={() =>
|
||||
|
||||
@@ -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}
|
||||
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
|
||||
<SheetListRow
|
||||
icon="text.bubble"
|
||||
title="Review changes"
|
||||
subtitle="Inspect turn diffs, worktree changes, and base branch diff"
|
||||
disabled={busy || !isRepo}
|
||||
onPress={() => router.push(buildThreadReviewRoutePath({ environmentId, threadId }))}
|
||||
/>
|
||||
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
|
||||
<SheetListRow
|
||||
icon="point.topleft.down.curvedto.point.bottomright.up"
|
||||
title="Branches & worktrees"
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import { useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Platform, Pressable, ScrollView, Text as NativeText, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
|
||||
import { cn } from "../../../lib/cn";
|
||||
import { useThemeColor } from "../../../lib/useThemeColor";
|
||||
import {
|
||||
clearReviewCommentTarget,
|
||||
formatReviewCommentContext,
|
||||
getReviewChangeMarker,
|
||||
getReviewUnifiedLineNumber,
|
||||
getSelectedReviewCommentLines,
|
||||
useReviewCommentTarget,
|
||||
} from "./reviewCommentSelection";
|
||||
import { appendReviewCommentToDraft } from "../use-thread-composer-state";
|
||||
|
||||
const REVIEW_MONO_FONT_FAMILY = Platform.select({
|
||||
ios: "ui-monospace",
|
||||
android: "monospace",
|
||||
default: "monospace",
|
||||
});
|
||||
|
||||
function renderVisibleWhitespace(value: string): string {
|
||||
const expandedTabs = value.replace(/\t/g, " ");
|
||||
return expandedTabs.replace(/^( +)/, (leading) => 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 (
|
||||
<ScrollView
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentContainerStyle={{
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 8,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
gap: 16,
|
||||
}}
|
||||
>
|
||||
<View className="flex-row items-center justify-between py-2">
|
||||
<Pressable
|
||||
className="bg-subtle h-12 w-12 items-center justify-center rounded-full"
|
||||
onPress={() => {
|
||||
clearReviewCommentTarget();
|
||||
router.dismiss();
|
||||
}}
|
||||
>
|
||||
<SymbolView name="xmark" size={18} tintColor={iconTint} type="monochrome" />
|
||||
</Pressable>
|
||||
|
||||
<Text className="text-[18px] font-t3-bold text-foreground">Add Comment</Text>
|
||||
|
||||
<Pressable
|
||||
className={cn(
|
||||
"min-h-[44px] min-w-[124px] items-center justify-center rounded-full px-5",
|
||||
canSubmit ? "bg-foreground" : "border border-border bg-card",
|
||||
)}
|
||||
disabled={!canSubmit}
|
||||
onPress={() => {
|
||||
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 }}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"text-[14px] font-t3-bold",
|
||||
canSubmit ? "text-background" : "text-foreground-muted",
|
||||
)}
|
||||
>
|
||||
Comment
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
{!target ? (
|
||||
<View className="rounded-[22px] border border-border bg-card px-4 py-5">
|
||||
<Text className="text-[15px] font-t3-bold text-foreground">No selection</Text>
|
||||
<Text className="mt-1 text-[13px] leading-[19px] text-foreground-muted">
|
||||
Select a diff line or range first.
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
<>
|
||||
<View className="gap-1 rounded-[22px] border border-border bg-card px-4 py-4">
|
||||
<Text className="font-mono text-[13px] leading-[18px] text-foreground">
|
||||
{target.filePath}
|
||||
</Text>
|
||||
<Text className="text-[12px] font-t3-medium text-foreground-muted">
|
||||
{selectedLines.length === 1
|
||||
? firstNumber !== null
|
||||
? `Line ${firstNumber}`
|
||||
: "File comment"
|
||||
: firstNumber !== null && lastNumber !== null
|
||||
? `Lines ${firstNumber}-${lastNumber}`
|
||||
: `${selectedLines.length} lines selected`}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View className="overflow-hidden rounded-[22px] border border-border bg-card">
|
||||
{selectedLines.map((line) => {
|
||||
const lineNumber = getReviewUnifiedLineNumber(line);
|
||||
|
||||
return (
|
||||
<View
|
||||
key={line.id}
|
||||
className={cn(
|
||||
"flex-row items-start border-b border-border/60",
|
||||
changeTone(line.change),
|
||||
)}
|
||||
>
|
||||
<Text className="w-9 px-1 py-2 text-right text-[11px] font-t3-medium text-foreground-muted">
|
||||
{lineNumber ?? ""}
|
||||
</Text>
|
||||
<Text
|
||||
className="px-0.5 py-2 text-center font-mono text-[12px] text-foreground-muted"
|
||||
style={{ width: 18 }}
|
||||
>
|
||||
{getReviewChangeMarker(line.change)}
|
||||
</Text>
|
||||
<NativeText
|
||||
selectable
|
||||
className="flex-1 px-1 py-2 text-[12px] leading-[19px] text-foreground"
|
||||
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
|
||||
>
|
||||
{renderVisibleWhitespace(line.content || " ")}
|
||||
</NativeText>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
<View className="gap-2">
|
||||
<Text className="text-[13px] font-t3-bold text-foreground">Comment</Text>
|
||||
<TextInput
|
||||
autoFocus
|
||||
multiline
|
||||
placeholder="Leave a comment..."
|
||||
textAlignVertical="top"
|
||||
value={commentText}
|
||||
onChangeText={setCommentText}
|
||||
className="min-h-[192px] rounded-[20px] px-4 py-3.5 font-sans text-[15px]"
|
||||
/>
|
||||
</View>
|
||||
</>
|
||||
)}
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -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<ReviewRenderableLineRow>;
|
||||
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<typeof buildReviewParsedDiff>): {
|
||||
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<ReviewRenderableFile>,
|
||||
): ReadonlyArray<string> {
|
||||
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<ReviewHighlightedToken> | null;
|
||||
readonly fallback: string;
|
||||
}) {
|
||||
if (!props.tokens || props.tokens.length === 0) {
|
||||
return (
|
||||
<NativeText
|
||||
selectable
|
||||
className="text-[12px] leading-[19px] text-foreground"
|
||||
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
|
||||
>
|
||||
{renderVisibleWhitespace(props.fallback || " ")}
|
||||
</NativeText>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<NativeText
|
||||
selectable
|
||||
className="text-[12px] leading-[19px] text-foreground"
|
||||
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
|
||||
>
|
||||
{(() => {
|
||||
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 (
|
||||
<NativeText
|
||||
key={`${start}:${token.content.length}:${token.color ?? ""}:${token.fontStyle ?? ""}`}
|
||||
selectable
|
||||
style={{
|
||||
color: token.color ?? undefined,
|
||||
fontFamily: REVIEW_MONO_FONT_FAMILY,
|
||||
fontWeight,
|
||||
fontStyle,
|
||||
}}
|
||||
>
|
||||
{token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "}
|
||||
</NativeText>
|
||||
);
|
||||
});
|
||||
})()}
|
||||
</NativeText>
|
||||
);
|
||||
}
|
||||
|
||||
function ReviewLineRow(props: {
|
||||
readonly line: ReviewRenderableLineRow;
|
||||
readonly tokens: ReadonlyArray<ReviewHighlightedToken> | null;
|
||||
readonly viewportWidth: number;
|
||||
readonly selectionState: "anchor" | "selected" | null;
|
||||
readonly onComment: () => void;
|
||||
readonly onStartRangeSelection: () => void;
|
||||
}) {
|
||||
const lineNumber = getReviewUnifiedLineNumber(props.line);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
className={cn(
|
||||
"flex-row items-start border-b border-border/60",
|
||||
changeTone(props.line.change),
|
||||
props.selectionState === "anchor" && "bg-sky-500/16",
|
||||
props.selectionState === "selected" && "bg-amber-300/28",
|
||||
)}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={
|
||||
lineNumber !== null
|
||||
? props.selectionState === "anchor"
|
||||
? `Range starts on line ${lineNumber}`
|
||||
: `Add comment on line ${lineNumber}`
|
||||
: "Add comment on line"
|
||||
}
|
||||
delayLongPress={220}
|
||||
onLongPress={props.onStartRangeSelection}
|
||||
onPress={props.onComment}
|
||||
style={{ minWidth: props.viewportWidth }}
|
||||
>
|
||||
<Text className="w-9 px-1 py-2 text-right text-[11px] font-t3-medium text-foreground-muted">
|
||||
{lineNumber ?? ""}
|
||||
</Text>
|
||||
<Text
|
||||
className="px-0.5 py-2 text-center font-mono text-[12px] text-foreground-muted"
|
||||
style={{ width: 18 }}
|
||||
>
|
||||
{getReviewChangeMarker(props.line.change)}
|
||||
</Text>
|
||||
<View className="min-w-0 flex-1 flex-shrink-0 px-1 py-2">
|
||||
<DiffTokenText tokens={props.tokens} fallback={props.line.content} />
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function ReviewFileCard(props: {
|
||||
readonly file: ReviewRenderableFile;
|
||||
readonly expanded: boolean;
|
||||
readonly onToggle: () => void;
|
||||
}) {
|
||||
return (
|
||||
<View className="border-b border-border bg-card" style={{ zIndex: 1 }}>
|
||||
<Pressable className="flex-row items-start gap-2 px-3 py-3" onPress={props.onToggle}>
|
||||
<View className="pt-0.5">
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.down" : "chevron.right"}
|
||||
size={14}
|
||||
tintColor="#8a8a8a"
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<View className="min-w-0 flex-1 gap-1">
|
||||
<Text className="font-mono text-[13px] leading-[18px] text-foreground">
|
||||
{props.file.path}
|
||||
</Text>
|
||||
{props.file.previousPath && props.file.previousPath !== props.file.path ? (
|
||||
<Text className="font-mono text-[11px] leading-[16px] text-foreground-muted">
|
||||
{props.file.previousPath}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<View className="items-end gap-1 pl-2">
|
||||
<Text className="text-[11px] font-t3-bold uppercase text-foreground-muted">
|
||||
{changeTypeLabel(props.file.changeType)}
|
||||
</Text>
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text className="text-[12px] font-t3-bold text-emerald-600">
|
||||
+{props.file.additions}
|
||||
</Text>
|
||||
<Text className="text-[12px] font-t3-bold text-rose-600">-{props.file.deletions}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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<ReviewRenderableLineRow>,
|
||||
lineIndex: number,
|
||||
) => void;
|
||||
readonly onStartRangeSelection: (
|
||||
line: ReviewRenderableLineRow,
|
||||
availableLines: ReadonlyArray<ReviewRenderableLineRow>,
|
||||
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 (
|
||||
<ScrollView
|
||||
horizontal
|
||||
bounces={false}
|
||||
showsHorizontalScrollIndicator={false}
|
||||
className="border-b border-border bg-card"
|
||||
>
|
||||
<View style={{ minWidth: props.viewportWidth }}>
|
||||
{props.file.rows.map((row) => {
|
||||
if (row.kind === "hunk") {
|
||||
return (
|
||||
<View
|
||||
key={row.id}
|
||||
className="border-b border-border/60 bg-sky-500/10 px-2 py-2"
|
||||
style={{ minWidth: props.viewportWidth }}
|
||||
>
|
||||
<Text className="font-mono text-[12px] leading-[18px] text-sky-700 dark:text-sky-300">
|
||||
{row.header}
|
||||
{row.context ? ` ${row.context}` : ""}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const tokens =
|
||||
row.change === "delete"
|
||||
? (props.highlightedFile?.deletionLines[row.deletionTokenIndex ?? -1] ?? null)
|
||||
: (props.highlightedFile?.additionLines[row.additionTokenIndex ?? -1] ?? null);
|
||||
|
||||
return (
|
||||
<ReviewLineRow
|
||||
key={row.id}
|
||||
line={row}
|
||||
tokens={tokens}
|
||||
viewportWidth={props.viewportWidth}
|
||||
selectionState={
|
||||
anchorLineId === row.id
|
||||
? "anchor"
|
||||
: selectedLineIds?.has(row.id)
|
||||
? "selected"
|
||||
: null
|
||||
}
|
||||
onComment={() => {
|
||||
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);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: 18,
|
||||
right: 18,
|
||||
bottom: Math.max(props.bottomInset, 10) + 18,
|
||||
flexDirection: "row",
|
||||
justifyContent: "center",
|
||||
gap: 10,
|
||||
}}
|
||||
>
|
||||
<Pressable
|
||||
className="min-h-[48px] flex-1 flex-row items-center justify-center gap-2 rounded-full bg-blue-600 px-5"
|
||||
onPress={props.onOpenComment}
|
||||
>
|
||||
<SymbolView name="text.bubble" size={16} tintColor="#ffffff" type="monochrome" />
|
||||
<Text className="text-[15px] font-t3-bold text-white">
|
||||
Comment on {formatReviewSelectedRangeLabel(props.target)}
|
||||
</Text>
|
||||
</Pressable>
|
||||
|
||||
<Pressable
|
||||
className="h-12 w-12 items-center justify-center rounded-full bg-blue-600"
|
||||
onPress={props.onClear}
|
||||
>
|
||||
<SymbolView name="xmark" size={16} tintColor="#ffffff" type="monochrome" />
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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<ReadonlyArray<GitReviewDiffSection>>([]);
|
||||
const [turnDiffById, setTurnDiffById] = useState<Record<string, string>>({});
|
||||
const [loadingTurnIds, setLoadingTurnIds] = useState<Record<string, boolean>>({});
|
||||
const [selectedSectionId, setSelectedSectionId] = useState<string | null>(null);
|
||||
const [loadingGitDiffs, setLoadingGitDiffs] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [expandedFileIdsBySection, setExpandedFileIdsBySection] = useState<
|
||||
Record<string, ReadonlyArray<string> | undefined>
|
||||
>({});
|
||||
const [highlightedFileByKey, setHighlightedFileByKey] = useState<
|
||||
Record<string, ReviewHighlightedFile>
|
||||
>({});
|
||||
const [pendingCommentSelection, setPendingCommentSelection] =
|
||||
useState<PendingCommentSelection | null>(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<string, OrchestrationCheckpointSummary>;
|
||||
}, [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(
|
||||
<View key="review-error" className="border-b border-border bg-card px-4 py-3">
|
||||
<Text className="text-[13px] font-t3-bold text-foreground">Review unavailable</Text>
|
||||
<Text className="text-[12px] leading-[18px] text-foreground-muted">{error}</Text>
|
||||
</View>,
|
||||
);
|
||||
}
|
||||
|
||||
if (parsedDiff.kind !== "empty" && parsedDiff.notice) {
|
||||
children.push(
|
||||
<View
|
||||
key="review-notice"
|
||||
className="border-b border-amber-200 bg-amber-50 px-4 py-3 dark:border-amber-900/60 dark:bg-amber-950/40"
|
||||
>
|
||||
<Text className="text-[12px] font-t3-bold uppercase text-amber-700 dark:text-amber-300">
|
||||
Partial diff
|
||||
</Text>
|
||||
<Text className="text-[12px] leading-[18px] text-amber-800 dark:text-amber-200">
|
||||
{parsedDiff.notice}
|
||||
</Text>
|
||||
</View>,
|
||||
);
|
||||
}
|
||||
|
||||
if (!selectedSection) {
|
||||
children.push(
|
||||
<View key="review-empty-state" className="border-b border-border bg-card px-4 py-5">
|
||||
<Text className="text-[14px] font-t3-bold text-foreground">No review diffs</Text>
|
||||
<Text className="text-[12px] leading-[18px] text-foreground-muted">
|
||||
This thread has no ready turn diffs and the worktree diff is empty.
|
||||
</Text>
|
||||
</View>,
|
||||
);
|
||||
return { children, stickyHeaderIndices };
|
||||
}
|
||||
|
||||
if (selectedSection.isLoading && selectedSection.diff === null) {
|
||||
children.push(
|
||||
<View
|
||||
key="review-loading"
|
||||
className="items-center gap-3 border-b border-border bg-card px-4 py-6"
|
||||
>
|
||||
<ActivityIndicator size="small" />
|
||||
<Text className="text-[12px] text-foreground-muted">Loading diff…</Text>
|
||||
</View>,
|
||||
);
|
||||
return { children, stickyHeaderIndices };
|
||||
}
|
||||
|
||||
if (parsedDiff.kind === "empty") {
|
||||
children.push(
|
||||
<View key="review-no-changes" className="border-b border-border bg-card px-4 py-5">
|
||||
<Text className="text-[14px] font-t3-bold text-foreground">No changes</Text>
|
||||
<Text className="text-[12px] leading-[18px] text-foreground-muted">
|
||||
{selectedSection.subtitle ?? "This diff is empty."}
|
||||
</Text>
|
||||
</View>,
|
||||
);
|
||||
return { children, stickyHeaderIndices };
|
||||
}
|
||||
|
||||
if (parsedDiff.kind === "raw") {
|
||||
children.push(
|
||||
<View key="review-raw" className="gap-3 border-b border-border bg-card px-4 py-4">
|
||||
<Text className="text-[12px] leading-[18px] text-foreground-muted">
|
||||
{parsedDiff.reason}
|
||||
</Text>
|
||||
<ScrollView horizontal showsHorizontalScrollIndicator={false} bounces={false}>
|
||||
<Text selectable className="font-mono text-[12px] leading-[19px] text-foreground">
|
||||
{parsedDiff.text}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
</View>,
|
||||
);
|
||||
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(
|
||||
<ReviewFileCard
|
||||
key={`review-file-header:${file.id}`}
|
||||
file={file}
|
||||
expanded={isExpanded}
|
||||
onToggle={() =>
|
||||
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(
|
||||
<ReviewFileBody
|
||||
key={`review-file-body:${file.id}`}
|
||||
file={file}
|
||||
sectionTitle={selectedSection.title}
|
||||
highlightedFile={fileHighlights}
|
||||
pendingSelection={pendingCommentSelection}
|
||||
selectedTarget={activeCommentTarget}
|
||||
viewportWidth={Math.max(width, 280)}
|
||||
onPressLine={(_line, availableLines, lineIndex) => {
|
||||
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 (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerTransparent: true,
|
||||
headerShadowVisible: false,
|
||||
headerTintColor: headerIcon,
|
||||
headerStyle: {
|
||||
backgroundColor: "transparent",
|
||||
},
|
||||
headerTitle: () => (
|
||||
<View style={{ alignItems: "center" }}>
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 18,
|
||||
fontWeight: "900",
|
||||
color: headerForeground,
|
||||
letterSpacing: -0.4,
|
||||
}}
|
||||
>
|
||||
Files Changed
|
||||
</NativeText>
|
||||
<View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
|
||||
{headerDiffSummary.additions && headerDiffSummary.deletions ? (
|
||||
<>
|
||||
<NativeText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
color: "#16a34a",
|
||||
}}
|
||||
>
|
||||
{headerDiffSummary.additions}
|
||||
</NativeText>
|
||||
<NativeText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
color: "#e11d48",
|
||||
}}
|
||||
>
|
||||
{headerDiffSummary.deletions}
|
||||
</NativeText>
|
||||
</>
|
||||
) : (
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
color: headerMuted,
|
||||
}}
|
||||
>
|
||||
{selectedSection?.title ?? "Review changes"}
|
||||
</NativeText>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu icon="ellipsis.circle" title="Select diff" separateBackground>
|
||||
{reviewSections.map((section) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={section.id}
|
||||
icon={section.id === selectedSection?.id ? "checkmark" : "circle"}
|
||||
onPress={() => setSelectedSectionId(section.id)}
|
||||
subtitle={section.subtitle ?? undefined}
|
||||
>
|
||||
<Stack.Toolbar.Label>{section.title}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="arrow.clockwise"
|
||||
disabled={
|
||||
loadingGitDiffs ||
|
||||
(selectedSection?.kind === "turn" && loadingTurnIds[selectedSection.id] === true)
|
||||
}
|
||||
onPress={() => void refreshSelectedSection()}
|
||||
subtitle="Reload current diff"
|
||||
>
|
||||
<Stack.Toolbar.Label>Refresh</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<View className="flex-1 bg-sheet">
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="never"
|
||||
contentInset={{ top: topContentInset }}
|
||||
contentOffset={{ x: 0, y: -topContentInset }}
|
||||
scrollIndicatorInsets={{ top: topContentInset }}
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
stickyHeaderIndices={reviewContent.stickyHeaderIndices}
|
||||
stickyHeaderHiddenOnScroll={false}
|
||||
contentContainerStyle={{
|
||||
paddingTop: REVIEW_HEADER_SPACING,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
}}
|
||||
>
|
||||
{reviewContent.children}
|
||||
</ScrollView>
|
||||
|
||||
<ReviewSelectionActionBar
|
||||
target={activeCommentTarget}
|
||||
bottomInset={insets.bottom}
|
||||
onOpenComment={() => {
|
||||
if (activeCommentTarget && environmentId && threadId) {
|
||||
router.push({
|
||||
pathname: "/threads/[environmentId]/[threadId]/review-comment",
|
||||
params: { environmentId, threadId },
|
||||
});
|
||||
}
|
||||
}}
|
||||
onClear={() => {
|
||||
clearReviewCommentTarget();
|
||||
setPendingCommentSelection(null);
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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<ParsedDiffLine>;
|
||||
}
|
||||
|
||||
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<ParsedDiffFile> {
|
||||
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);
|
||||
}
|
||||
@@ -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<ReviewRenderableLineRow>;
|
||||
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<ReviewRenderableLineRow> {
|
||||
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<ReviewCommentTarget, "sectionTitle" | "filePath" | "lines">,
|
||||
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<ReviewRenderableLineRow>,
|
||||
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 [
|
||||
"<review_comment>",
|
||||
comment.trim(),
|
||||
"```diff",
|
||||
formatReviewSelectedDiff(target),
|
||||
"```",
|
||||
"</review_comment>",
|
||||
].join("\n");
|
||||
}
|
||||
@@ -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<OrchestrationCheckpointSummary> &
|
||||
Pick<OrchestrationCheckpointSummary, "turnId" | "checkpointTurnCount" | "completedAt">,
|
||||
): 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 @@",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<string>;
|
||||
readonly deletionLines: ReadonlyArray<string>;
|
||||
readonly rows: ReadonlyArray<ReviewRenderableRow>;
|
||||
}
|
||||
|
||||
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<ReviewRenderableFile>;
|
||||
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<OrchestrationCheckpointSummary>(
|
||||
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<T>(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<ReviewRenderableRow> {
|
||||
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<OrchestrationCheckpointSummary, "checkpointTurnCount">,
|
||||
): string {
|
||||
return `turn:${checkpoint.checkpointTurnCount}`;
|
||||
}
|
||||
|
||||
export function getReadyReviewCheckpoints(
|
||||
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
|
||||
): ReadonlyArray<OrchestrationCheckpointSummary> {
|
||||
return Arr.sort(
|
||||
checkpoints.filter((checkpoint) => checkpoint.status === "ready"),
|
||||
readyCheckpointOrder,
|
||||
);
|
||||
}
|
||||
|
||||
export function buildReviewSectionItems(input: {
|
||||
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
|
||||
readonly gitSections: ReadonlyArray<GitReviewDiffSection>;
|
||||
readonly turnDiffById: Readonly<Record<string, string | undefined>>;
|
||||
readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
|
||||
}): ReadonlyArray<ReviewSectionItem> {
|
||||
const turnItems = getReadyReviewCheckpoints(input.checkpoints).map<ReviewSectionItem>(
|
||||
(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<ReviewSectionItem>((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<ReviewSectionItem>,
|
||||
): 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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<ReadonlyArray<ReviewHighlightedToken>>;
|
||||
readonly deletionLines: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>;
|
||||
}
|
||||
|
||||
const SHIKI_THEME_BY_SCHEME = {
|
||||
light: "github-light-default",
|
||||
dark: "github-dark-default",
|
||||
} as const;
|
||||
|
||||
const highlightCache = new Map<string, Promise<ReviewHighlightedFile>>();
|
||||
const loadedLanguages = new Set<string>(["text"]);
|
||||
type ShikiHighlighter = {
|
||||
loadLanguage: (...langs: string[]) => Promise<void>;
|
||||
codeToTokensBase: (
|
||||
code: string,
|
||||
options: { readonly lang: string; readonly theme: string },
|
||||
) => Promise<Array<Array<{ content: string; color?: string; fontStyle?: number }>>>;
|
||||
};
|
||||
let highlighterPromise: Promise<ShikiHighlighter> | null = null;
|
||||
|
||||
function cleanLastNewline(value: string): string {
|
||||
return value.endsWith("\n") ? value.slice(0, -1) : value;
|
||||
}
|
||||
|
||||
function joinPatchLines(lines: ReadonlyArray<string>): 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<ShikiHighlighter>;
|
||||
}
|
||||
|
||||
async function resolveLanguage(file: ReviewRenderableFile): Promise<string> {
|
||||
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<{ content: string; color?: string; fontStyle?: number }>>,
|
||||
): ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>> {
|
||||
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<ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>> {
|
||||
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<ReviewHighlightedFile> {
|
||||
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;
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -6,14 +6,29 @@ import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
|
||||
type ThreadRouteInput =
|
||||
| Pick<SelectedThreadRef, "environmentId" | "threadId">
|
||||
| Pick<EnvironmentScopedThreadShell, "environmentId" | "id">;
|
||||
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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<GitRangeContext, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Read review-oriented diffs for dirty worktree changes and branch changes against base.
|
||||
*/
|
||||
readonly getReviewDiffs: (
|
||||
input: GitReviewDiffsInput,
|
||||
) => Effect.Effect<GitReviewDiffsResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Read a Git config value from the local repository.
|
||||
*/
|
||||
|
||||
@@ -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)),
|
||||
);
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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", () => ({
|
||||
|
||||
@@ -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]({})),
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
+1
-1
@@ -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",
|
||||
|
||||
@@ -95,6 +95,7 @@ export interface WsRpcClient {
|
||||
readonly preparePullRequestThread: RpcUnaryMethod<
|
||||
typeof WS_METHODS.gitPreparePullRequestThread
|
||||
>;
|
||||
readonly getReviewDiffs: RpcUnaryMethod<typeof WS_METHODS.gitGetReviewDiffs>;
|
||||
};
|
||||
readonly server: {
|
||||
readonly getConfig: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetConfig>;
|
||||
@@ -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]({})),
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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<GitPreparePullRequestThreadResult>;
|
||||
getReviewDiffs: (input: GitReviewDiffsInput) => Promise<GitReviewDiffsResult>;
|
||||
pull: (input: GitPullInput) => Promise<GitPullResult>;
|
||||
refreshStatus: (input: GitStatusInput) => Promise<GitStatusResult>;
|
||||
onStatus: (
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.");
|
||||
}
|
||||
@@ -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.",
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user