Add remote review diff plumbing
- Move review diff parsing and highlighting into shared mobile diff modules - Add review service and wire server, web, and mobile around remote review selection
This commit is contained in:
1 parent
eba28035d2
commit
6db3098a21
50 files changed
+1230
-11272
No files matched your search
@@ -39,7 +39,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",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@react-native-menu/menu": "^2.0.0",
|
||||
"@shikijs/core": "3.23.0",
|
||||
"@shikijs/engine-javascript": "3.23.0",
|
||||
|
||||
@@ -1,528 +0,0 @@
|
||||
import Stack from "expo-router/stack";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
type LayoutChangeEvent,
|
||||
StyleSheet,
|
||||
Text as NativeText,
|
||||
type NativeSyntheticEvent,
|
||||
useColorScheme,
|
||||
View,
|
||||
} from "react-native";
|
||||
import {
|
||||
debugReviewDiffFixtures,
|
||||
type DebugReviewDiffFixtureId,
|
||||
} from "../../features/debug/fixtures/reviewDiffFixtures";
|
||||
import {
|
||||
getResolvedNativeReviewDiffModuleName,
|
||||
type NativeReviewDiffStyle,
|
||||
type NativeReviewDiffTheme,
|
||||
resolveNativeReviewDiffView,
|
||||
} from "../../features/debug/native-review-diff/nativeReviewDiffModule";
|
||||
import {
|
||||
highlightNativeReviewDiffVisibleRows,
|
||||
streamNativeReviewDiffTokens,
|
||||
type NativeReviewDiffHighlightEngine,
|
||||
} from "../../features/debug/native-review-diff/nativeReviewDiffHighlighter";
|
||||
import {
|
||||
getNativeReviewDiffFixture,
|
||||
parseNativeReviewDiffFixture,
|
||||
} from "../../features/debug/native-review-diff/nativeReviewDiffParser";
|
||||
import {
|
||||
getPierreTerminalTheme,
|
||||
type TerminalAppearanceScheme,
|
||||
} from "../../features/terminal/terminalTheme";
|
||||
|
||||
const NATIVE_DEBUG_ROW_HEIGHT = 20;
|
||||
const NATIVE_DEBUG_CONTENT_WIDTH = 2800;
|
||||
const NATIVE_DEBUG_STYLE = {
|
||||
rowHeight: NATIVE_DEBUG_ROW_HEIGHT,
|
||||
contentWidth: NATIVE_DEBUG_CONTENT_WIDTH,
|
||||
changeBarWidth: 4,
|
||||
gutterWidth: 46,
|
||||
codePadding: 7,
|
||||
textVerticalInset: 2,
|
||||
fileHeaderHeight: 56,
|
||||
fileHeaderHorizontalMargin: 8,
|
||||
fileHeaderVerticalMargin: 6,
|
||||
fileHeaderCornerRadius: 10,
|
||||
fileHeaderHorizontalPadding: 10,
|
||||
fileHeaderPathRightPadding: 118,
|
||||
fileHeaderCountColumnWidth: 38,
|
||||
fileHeaderCountGap: 5,
|
||||
codeFontSize: 11,
|
||||
codeFontWeight: "regular",
|
||||
lineNumberFontSize: 10,
|
||||
lineNumberFontWeight: "regular",
|
||||
hunkFontSize: 11,
|
||||
hunkFontWeight: "medium",
|
||||
fileHeaderFontSize: 11,
|
||||
fileHeaderFontWeight: "semibold",
|
||||
fileHeaderMetaFontSize: 10,
|
||||
fileHeaderMetaFontWeight: "semibold",
|
||||
fileHeaderSubtextFontSize: 11,
|
||||
fileHeaderSubtextFontWeight: "medium",
|
||||
fileHeaderStatusFontSize: 9,
|
||||
fileHeaderStatusFontWeight: "bold",
|
||||
emptyStateFontSize: 12,
|
||||
emptyStateFontWeight: "medium",
|
||||
} satisfies NativeReviewDiffStyle;
|
||||
|
||||
function createNativeReviewDiffTheme(scheme: TerminalAppearanceScheme): NativeReviewDiffTheme {
|
||||
const terminalTheme = getPierreTerminalTheme(scheme);
|
||||
const [, terminalRed, , , terminalBlue] = terminalTheme.palette;
|
||||
|
||||
if (scheme === "dark") {
|
||||
return {
|
||||
background: terminalTheme.background,
|
||||
text: terminalTheme.foreground,
|
||||
mutedText: terminalTheme.mutedForeground,
|
||||
headerBackground: terminalTheme.background,
|
||||
border: terminalTheme.border,
|
||||
hunkBackground: "#071f28",
|
||||
hunkText: terminalBlue ?? "#009fff",
|
||||
addBackground: "#0d2f28",
|
||||
deleteBackground: "#391415",
|
||||
addBar: "#00cab1",
|
||||
deleteBar: terminalRed ?? "#ff2e3f",
|
||||
addText: "#5ECC71",
|
||||
deleteText: "#FF6762",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
background: "#ffffff",
|
||||
text: "#070707",
|
||||
mutedText: terminalTheme.mutedForeground,
|
||||
headerBackground: "#ffffff",
|
||||
border: terminalTheme.border,
|
||||
hunkBackground: "#e0f2ff",
|
||||
hunkText: terminalBlue ?? "#009fff",
|
||||
addBackground: "#e5f8f5",
|
||||
deleteBackground: "#ffe6e7",
|
||||
addBar: "#00cab1",
|
||||
deleteBar: terminalRed ?? "#ff2e3f",
|
||||
addText: "#199F43",
|
||||
deleteText: "#D52C36",
|
||||
};
|
||||
}
|
||||
|
||||
export default function NativeReviewDiffDebugRoute() {
|
||||
const colorScheme = useColorScheme() === "dark" ? "dark" : "light";
|
||||
const [fixtureId, setFixtureId] = useState<DebugReviewDiffFixtureId>("large");
|
||||
const [highlightEngine, setHighlightEngine] = useState<NativeReviewDiffHighlightEngine>("native");
|
||||
const [collapsedFileIds, setCollapsedFileIds] = useState<ReadonlyArray<string>>([]);
|
||||
const [viewedFileIds, setViewedFileIds] = useState<ReadonlyArray<string>>([]);
|
||||
const fixture = getNativeReviewDiffFixture(fixtureId);
|
||||
const parsed = useMemo(() => parseNativeReviewDiffFixture(fixture), [fixture]);
|
||||
const effectiveHighlightEngine: NativeReviewDiffHighlightEngine =
|
||||
fixtureId === "xl" && highlightEngine === "native" ? "javascript" : highlightEngine;
|
||||
const useVisibleOnlyHighlighting = fixtureId === "xl";
|
||||
const debugTheme = useMemo(() => createNativeReviewDiffTheme(colorScheme), [colorScheme]);
|
||||
const rowsJson = useMemo(() => JSON.stringify(parsed.rows), [parsed.rows]);
|
||||
const collapsedFileIdsJson = useMemo(() => JSON.stringify(collapsedFileIds), [collapsedFileIds]);
|
||||
const viewedFileIdsJson = useMemo(() => JSON.stringify(viewedFileIds), [viewedFileIds]);
|
||||
const themeJson = useMemo(() => JSON.stringify(debugTheme), [debugTheme]);
|
||||
const styleJson = useMemo(() => JSON.stringify(NATIVE_DEBUG_STYLE), []);
|
||||
const tokensResetKey = `${fixtureId}:${colorScheme}:${effectiveHighlightEngine}`;
|
||||
const [tokensPatchJson, setTokensPatchJson] = useState(
|
||||
JSON.stringify({ resetKey: "", tokensByRowId: {} }),
|
||||
);
|
||||
const highlightedRowIdsRef = useRef<Set<string>>(new Set());
|
||||
const visibleRangeRef = useRef({ firstRowIndex: 0, lastRowIndex: 80 });
|
||||
const visibleChunkIndexRef = useRef(0);
|
||||
const useVisibleOnlyHighlightingRef = useRef(useVisibleOnlyHighlighting);
|
||||
const [visibleHighlightRequest, setVisibleHighlightRequest] = useState(0);
|
||||
const NativeReviewDiffView = resolveNativeReviewDiffView();
|
||||
const handleSelectFixture = useCallback((nextFixtureId: DebugReviewDiffFixtureId) => {
|
||||
setFixtureId(nextFixtureId);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
useVisibleOnlyHighlightingRef.current = useVisibleOnlyHighlighting;
|
||||
}, [useVisibleOnlyHighlighting]);
|
||||
useEffect(() => {
|
||||
setCollapsedFileIds([]);
|
||||
setViewedFileIds([]);
|
||||
}, [fixtureId]);
|
||||
useEffect(() => {
|
||||
const abortController = new AbortController();
|
||||
highlightedRowIdsRef.current = new Set();
|
||||
visibleChunkIndexRef.current = 0;
|
||||
setTokensPatchJson(JSON.stringify({ resetKey: tokensResetKey, tokensByRowId: {} }));
|
||||
if (useVisibleOnlyHighlighting) {
|
||||
setVisibleHighlightRequest((request) => request + 1);
|
||||
console.log("[debug-native-diff] visible-only highlight start", {
|
||||
fixture: fixtureId,
|
||||
files: parsed.files.length,
|
||||
rows: parsed.rows.length,
|
||||
scheme: colorScheme,
|
||||
effectiveEngine: effectiveHighlightEngine,
|
||||
requestedEngine: highlightEngine,
|
||||
});
|
||||
return () => abortController.abort();
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
const startedAt = performance.now();
|
||||
console.log("[debug-native-diff] highlight start", {
|
||||
fixture: fixtureId,
|
||||
files: parsed.files.length,
|
||||
rows: parsed.rows.length,
|
||||
scheme: colorScheme,
|
||||
effectiveEngine: effectiveHighlightEngine,
|
||||
requestedEngine: highlightEngine,
|
||||
});
|
||||
|
||||
try {
|
||||
const engine = await streamNativeReviewDiffTokens({
|
||||
files: parsed.files,
|
||||
rows: parsed.rows,
|
||||
scheme: colorScheme,
|
||||
engine: effectiveHighlightEngine,
|
||||
signal: abortController.signal,
|
||||
onChunk: (chunk) => {
|
||||
if (abortController.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
|
||||
setTokensPatchJson(JSON.stringify({ resetKey: tokensResetKey, ...chunk }));
|
||||
if (chunk.chunkIndex < 5 || chunk.chunkIndex % 10 === 0) {
|
||||
console.log("[debug-native-diff] highlight chunk", {
|
||||
chunkIndex: chunk.chunkIndex,
|
||||
durationMs: chunk.durationMs,
|
||||
filePath: chunk.filePath,
|
||||
lineCount: chunk.lineCount,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (!abortController.signal.aborted) {
|
||||
console.log("[debug-native-diff] highlight complete", {
|
||||
durationMs: Math.round(performance.now() - startedAt),
|
||||
engine,
|
||||
fixture: fixtureId,
|
||||
effectiveEngine: effectiveHighlightEngine,
|
||||
requestedEngine: highlightEngine,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (!abortController.signal.aborted) {
|
||||
console.warn("[debug-native-diff] highlight failed", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => abortController.abort();
|
||||
}, [
|
||||
colorScheme,
|
||||
effectiveHighlightEngine,
|
||||
fixtureId,
|
||||
highlightEngine,
|
||||
parsed.files,
|
||||
parsed.rows,
|
||||
tokensResetKey,
|
||||
useVisibleOnlyHighlighting,
|
||||
]);
|
||||
useEffect(() => {
|
||||
if (!useVisibleOnlyHighlighting) {
|
||||
return;
|
||||
}
|
||||
|
||||
const abortController = new AbortController();
|
||||
const requestRange = visibleRangeRef.current;
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await highlightNativeReviewDiffVisibleRows({
|
||||
files: parsed.files,
|
||||
rows: parsed.rows,
|
||||
scheme: colorScheme,
|
||||
engine: effectiveHighlightEngine,
|
||||
firstRowIndex: requestRange.firstRowIndex,
|
||||
lastRowIndex: requestRange.lastRowIndex,
|
||||
alreadyHighlightedRowIds: highlightedRowIdsRef.current,
|
||||
signal: abortController.signal,
|
||||
});
|
||||
|
||||
if (abortController.signal.aborted || result.rowCount === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const rowId of Object.keys(result.tokensByRowId)) {
|
||||
highlightedRowIdsRef.current.add(rowId);
|
||||
}
|
||||
|
||||
const chunkIndex = visibleChunkIndexRef.current;
|
||||
visibleChunkIndexRef.current += 1;
|
||||
setTokensPatchJson(
|
||||
JSON.stringify({
|
||||
resetKey: tokensResetKey,
|
||||
chunkIndex,
|
||||
fileId: "visible",
|
||||
filePath: "visible rows",
|
||||
language: "diff",
|
||||
lineCount: result.rowCount,
|
||||
durationMs: result.durationMs,
|
||||
tokensByRowId: result.tokensByRowId,
|
||||
}),
|
||||
);
|
||||
if (chunkIndex < 2 || chunkIndex % 10 === 0) {
|
||||
console.log("[debug-native-diff] visible highlight chunk", {
|
||||
chunkIndex,
|
||||
durationMs: result.durationMs,
|
||||
highlightedRows: result.rowCount,
|
||||
firstRowIndex: requestRange.firstRowIndex,
|
||||
lastRowIndex: requestRange.lastRowIndex,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (!abortController.signal.aborted) {
|
||||
console.warn("[debug-native-diff] visible highlight failed", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => abortController.abort();
|
||||
}, [
|
||||
colorScheme,
|
||||
effectiveHighlightEngine,
|
||||
parsed.files,
|
||||
parsed.rows,
|
||||
tokensResetKey,
|
||||
useVisibleOnlyHighlighting,
|
||||
visibleHighlightRequest,
|
||||
]);
|
||||
useEffect(() => {
|
||||
console.log("[debug-native-diff] native view availability", {
|
||||
available: NativeReviewDiffView != null,
|
||||
moduleName: getResolvedNativeReviewDiffModuleName(),
|
||||
rowsJsonLength: rowsJson.length,
|
||||
});
|
||||
}, [NativeReviewDiffView, rowsJson.length]);
|
||||
const handleNativeContainerLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const { height, width } = event.nativeEvent.layout;
|
||||
console.log("[debug-native-diff] native container layout", {
|
||||
height: Math.round(height),
|
||||
width: Math.round(width),
|
||||
});
|
||||
}, []);
|
||||
const handleNativeLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const { height, width } = event.nativeEvent.layout;
|
||||
console.log("[debug-native-diff] native view layout", {
|
||||
height: Math.round(height),
|
||||
width: Math.round(width),
|
||||
});
|
||||
}, []);
|
||||
const handleNativeDebug = useCallback((event: NativeSyntheticEvent<Record<string, unknown>>) => {
|
||||
const payload = event.nativeEvent;
|
||||
const message = payload.message;
|
||||
|
||||
if (
|
||||
useVisibleOnlyHighlightingRef.current &&
|
||||
(message === "draw-metrics" || message === "visible-range") &&
|
||||
typeof payload.firstRowIndex === "number" &&
|
||||
typeof payload.lastRowIndex === "number"
|
||||
) {
|
||||
const previousRange = visibleRangeRef.current;
|
||||
const nextRange = {
|
||||
firstRowIndex: payload.firstRowIndex,
|
||||
lastRowIndex: payload.lastRowIndex,
|
||||
};
|
||||
const movedRows =
|
||||
Math.abs(nextRange.firstRowIndex - previousRange.firstRowIndex) +
|
||||
Math.abs(nextRange.lastRowIndex - previousRange.lastRowIndex);
|
||||
|
||||
visibleRangeRef.current = nextRange;
|
||||
if (movedRows >= 20) {
|
||||
setVisibleHighlightRequest((request) => request + 1);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
const handleToggleFile = useCallback(
|
||||
(event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
|
||||
const { fileId } = event.nativeEvent;
|
||||
if (!fileId) {
|
||||
return;
|
||||
}
|
||||
|
||||
setCollapsedFileIds((current) =>
|
||||
current.includes(fileId) ? current.filter((id) => id !== fileId) : [...current, fileId],
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
const handleToggleViewedFile = useCallback(
|
||||
(event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
|
||||
const { fileId } = event.nativeEvent;
|
||||
if (!fileId) {
|
||||
return;
|
||||
}
|
||||
|
||||
setViewedFileIds((current) => {
|
||||
if (current.includes(fileId)) {
|
||||
return current.filter((id) => id !== fileId);
|
||||
}
|
||||
|
||||
setCollapsedFileIds((collapsed) =>
|
||||
collapsed.includes(fileId) ? collapsed : [...collapsed, fileId],
|
||||
);
|
||||
return [...current, fileId];
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerShown: true,
|
||||
headerShadowVisible: false,
|
||||
headerStyle: { backgroundColor: debugTheme.background },
|
||||
headerTintColor: debugTheme.text,
|
||||
headerTitleAlign: "center",
|
||||
title: "",
|
||||
headerTitle: () => (
|
||||
<View style={{ alignItems: "center", maxWidth: 240 }}>
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: debugTheme.text,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 13,
|
||||
lineHeight: 16,
|
||||
}}
|
||||
>
|
||||
Native review diff
|
||||
</NativeText>
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: debugTheme.mutedText,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 11,
|
||||
lineHeight: 14,
|
||||
}}
|
||||
>
|
||||
{parsed.files.length} files · {parsed.rows.length} rows · +{parsed.additions} -
|
||||
{parsed.deletions} · {effectiveHighlightEngine === "native" ? "native" : "JS"}
|
||||
{fixtureId === "xl" && highlightEngine === "native" ? " fallback" : ""}
|
||||
</NativeText>
|
||||
</View>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu
|
||||
icon="line.3.horizontal.decrease.circle"
|
||||
title="Diff debug options"
|
||||
separateBackground
|
||||
>
|
||||
<Stack.Toolbar.Menu icon="sparkles" inline title="Highlighter engine">
|
||||
<Stack.Toolbar.Label>Highlighter engine</Stack.Toolbar.Label>
|
||||
{(["native", "javascript"] as const).map((engine) => {
|
||||
const isSelected = engine === highlightEngine;
|
||||
return (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={engine}
|
||||
icon="circle"
|
||||
isOn={isSelected}
|
||||
onPress={() => setHighlightEngine(engine)}
|
||||
subtitle={
|
||||
engine === "native" && fixtureId === "xl"
|
||||
? "XL currently falls back after native engine crash"
|
||||
: engine === "native"
|
||||
? "react-native-shiki-engine"
|
||||
: "JavaScript regex engine"
|
||||
}
|
||||
>
|
||||
<Stack.Toolbar.Label>
|
||||
{engine === "native" ? "Native" : "JavaScript"}
|
||||
</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
);
|
||||
})}
|
||||
</Stack.Toolbar.Menu>
|
||||
|
||||
<Stack.Toolbar.Menu icon="doc.text" inline title="Fixture">
|
||||
<Stack.Toolbar.Label>Fixture</Stack.Toolbar.Label>
|
||||
{debugReviewDiffFixtures.map((candidate) => {
|
||||
const isSelected = candidate.id === fixtureId;
|
||||
return (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={candidate.id}
|
||||
icon="doc.text"
|
||||
isOn={isSelected}
|
||||
onPress={() => handleSelectFixture(candidate.id)}
|
||||
subtitle={`${candidate.lineCount} patch lines`}
|
||||
>
|
||||
<Stack.Toolbar.Label>{candidate.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
);
|
||||
})}
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<View
|
||||
className="relative flex-1"
|
||||
style={{ backgroundColor: debugTheme.background }}
|
||||
collapsable={false}
|
||||
onLayout={handleNativeContainerLayout}
|
||||
>
|
||||
{NativeReviewDiffView ? (
|
||||
<NativeReviewDiffView
|
||||
key={fixtureId}
|
||||
collapsable={false}
|
||||
testID="native-review-diff-view"
|
||||
style={StyleSheet.absoluteFillObject}
|
||||
appearanceScheme={colorScheme}
|
||||
contentWidth={NATIVE_DEBUG_CONTENT_WIDTH}
|
||||
collapsedFileIdsJson={collapsedFileIdsJson}
|
||||
rowHeight={NATIVE_DEBUG_ROW_HEIGHT}
|
||||
rowsJson={rowsJson}
|
||||
styleJson={styleJson}
|
||||
themeJson={themeJson}
|
||||
tokensResetKey={tokensResetKey}
|
||||
tokensPatchJson={tokensPatchJson}
|
||||
viewedFileIdsJson={viewedFileIdsJson}
|
||||
onDebug={handleNativeDebug}
|
||||
onLayout={handleNativeLayout}
|
||||
onToggleFile={handleToggleFile}
|
||||
onToggleViewedFile={handleToggleViewedFile}
|
||||
/>
|
||||
) : (
|
||||
<View className="flex-1 items-center justify-center px-8">
|
||||
<NativeText
|
||||
style={{
|
||||
color: debugTheme.text,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 14,
|
||||
textAlign: "center",
|
||||
}}
|
||||
>
|
||||
Native review diff view is not available in this build.
|
||||
</NativeText>
|
||||
<NativeText
|
||||
style={{
|
||||
color: debugTheme.mutedText,
|
||||
fontFamily: "DMSans_400Regular",
|
||||
fontSize: 12,
|
||||
marginTop: 8,
|
||||
textAlign: "center",
|
||||
}}
|
||||
>
|
||||
Expected native view manager: T3ReviewDiffSurface. Rebuild the current iOS development
|
||||
client with `bun ios` after native module changes.
|
||||
</NativeText>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -78,11 +78,6 @@ export default function HomeRouteScreen() {
|
||||
</Stack.Toolbar>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Button
|
||||
icon="ladybug"
|
||||
onPress={() => router.push("/debug/native-review-diff")}
|
||||
separateBackground
|
||||
/>
|
||||
<Stack.Toolbar.Button
|
||||
icon="network"
|
||||
onPress={() => router.push("/connections")}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
# Debug Fixtures
|
||||
|
||||
These patch fixtures snapshot review-rendering worktree diffs used to develop
|
||||
the scratch review renderer. Keep them deterministic so the debug route can test
|
||||
parsing, chunked syntax highlighting, and virtualization without depending on
|
||||
the current repo state.
|
||||
|
||||
- `review-small.diff`: 155 lines, narrow model/rendering changes.
|
||||
- `review-medium.diff`: 1,955 lines, review screen and highlighter changes.
|
||||
- `review-large.diff`: 3,208 lines, broad current worktree snapshot excluding
|
||||
this fixture directory.
|
||||
- `current-working-review.diff`: alias of `review-large.diff` for quick loading
|
||||
while iterating.
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,155 +0,0 @@
|
||||
diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx
|
||||
index d61924a62..3f2ae0160 100644
|
||||
--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx
|
||||
+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx
|
||||
@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({
|
||||
default: "monospace",
|
||||
});
|
||||
|
||||
+export const REVIEW_DIFF_LINE_HEIGHT = 26;
|
||||
+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;
|
||||
+
|
||||
export function renderVisibleWhitespace(value: string): string {
|
||||
const expandedTabs = value.replace(/\t/g, " ");
|
||||
return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0"));
|
||||
@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |
|
||||
export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {
|
||||
if (props.change === "delete") {
|
||||
return (
|
||||
- <View className="w-[5px] self-stretch overflow-hidden">
|
||||
- <View className="flex-1 justify-between">
|
||||
- {Array.from({ length: 6 }, (_, index) => (
|
||||
- <View key={index} className="h-[2px] w-[5px] bg-rose-400" />
|
||||
+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
|
||||
+ <View>
|
||||
+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (
|
||||
+ <View key={index}>
|
||||
+ <View className="w-[5px] bg-rose-400" style={{ height: 1 }} />
|
||||
+ <View style={{ height: 1 }} />
|
||||
+ </View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo
|
||||
}
|
||||
|
||||
return (
|
||||
- <View className="w-[5px] self-stretch overflow-hidden">
|
||||
+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
|
||||
<View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />
|
||||
</View>
|
||||
);
|
||||
@@ -63,6 +69,7 @@ export function DiffTokenText(props: {
|
||||
if (!props.tokens || props.tokens.length === 0) {
|
||||
return (
|
||||
<NativeText
|
||||
+ numberOfLines={1}
|
||||
selectable
|
||||
className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
|
||||
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
|
||||
@@ -74,6 +81,7 @@ export function DiffTokenText(props: {
|
||||
|
||||
return (
|
||||
<NativeText
|
||||
+ numberOfLines={1}
|
||||
selectable
|
||||
className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
|
||||
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
|
||||
diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts
|
||||
index a24a99ceb..69a6e7261 100644
|
||||
--- a/apps/mobile/src/features/review/reviewModel.test.ts
|
||||
+++ b/apps/mobile/src/features/review/reviewModel.test.ts
|
||||
@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {
|
||||
});
|
||||
});
|
||||
|
||||
- it("flattens expanded files into virtualizable review items", () => {
|
||||
+ it("flattens expanded file rows into virtualized review items", () => {
|
||||
const file = makeRenderableFile({
|
||||
path: "apps/mobile/src/a.ts",
|
||||
rows: [
|
||||
@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {
|
||||
|
||||
expect(items).toEqual([
|
||||
expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),
|
||||
- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),
|
||||
- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),
|
||||
+ expect.objectContaining({
|
||||
+ kind: "hunk",
|
||||
+ fileId: file.id,
|
||||
+ file,
|
||||
+ row: file.rows[0],
|
||||
+ }),
|
||||
+ expect.objectContaining({
|
||||
+ kind: "line",
|
||||
+ fileId: file.id,
|
||||
+ file,
|
||||
+ row: file.rows[1],
|
||||
+ lineIndex: 0,
|
||||
+ }),
|
||||
]);
|
||||
});
|
||||
|
||||
diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts
|
||||
index 27e6d7ae4..1cfbf358c 100644
|
||||
--- a/apps/mobile/src/features/review/reviewModel.ts
|
||||
+++ b/apps/mobile/src/features/review/reviewModel.ts
|
||||
@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {
|
||||
readonly kind: "hunk";
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
+ readonly file: ReviewRenderableFile;
|
||||
readonly row: ReviewRenderableHunkRow;
|
||||
}
|
||||
|
||||
@@ -79,7 +80,9 @@ export interface ReviewLineListItem {
|
||||
readonly kind: "line";
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
+ readonly file: ReviewRenderableFile;
|
||||
readonly row: ReviewRenderableLineRow;
|
||||
+ readonly lineIndex: number;
|
||||
}
|
||||
|
||||
export type ReviewListItem =
|
||||
@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil
|
||||
}
|
||||
|
||||
// The flattened review list item model is inspired by pierre/diffs' iterator-first
|
||||
-// virtualization architecture, adapted here for React Native and LegendList.
|
||||
+// virtualization architecture, adapted here for React Native virtualization.
|
||||
// Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs
|
||||
// Reference files:
|
||||
// - src/utils/iterateOverDiff.ts
|
||||
@@ -350,12 +353,14 @@ export function buildReviewListItems(input: {
|
||||
}
|
||||
}
|
||||
|
||||
- file.rows.forEach((row) => {
|
||||
+ let lineIndex = 0;
|
||||
+ file.rows.forEach((row, rowIndex) => {
|
||||
if (row.kind === "hunk") {
|
||||
items.push({
|
||||
kind: "hunk",
|
||||
- id: row.id,
|
||||
+ id: `${file.id}:row:${rowIndex}:${row.id}`,
|
||||
fileId: file.id,
|
||||
+ file,
|
||||
row,
|
||||
});
|
||||
return;
|
||||
@@ -363,10 +368,13 @@ export function buildReviewListItems(input: {
|
||||
|
||||
items.push({
|
||||
kind: "line",
|
||||
- id: row.id,
|
||||
+ id: `${file.id}:row:${rowIndex}:${row.id}`,
|
||||
fileId: file.id,
|
||||
+ file,
|
||||
row,
|
||||
+ lineIndex,
|
||||
});
|
||||
+ lineIndex += 1;
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,238 +0,0 @@
|
||||
import { DEBUG_REVIEW_XL_DIFF } from "./reviewDiffXlFixture";
|
||||
|
||||
export type DebugReviewDiffFixtureId = "small" | "medium" | "large" | "xl" | "current" | "states";
|
||||
|
||||
export interface DebugReviewDiffFixture {
|
||||
readonly id: DebugReviewDiffFixtureId;
|
||||
readonly label: string;
|
||||
readonly filename: string;
|
||||
readonly lineCount: number;
|
||||
readonly diff: string;
|
||||
}
|
||||
|
||||
const DEBUG_REVIEW_STATES_DIFF = `diff --git a/apps/demo/src/main.ts b/apps/demo/src/main.ts
|
||||
index 78f5eaa12..c2874ad31 100644
|
||||
--- a/apps/demo/src/main.ts
|
||||
+++ b/apps/demo/src/main.ts
|
||||
@@ -1,18 +1,24 @@
|
||||
import { createServer } from "./server";
|
||||
import { createLogger } from "./logger";
|
||||
|
||||
-const retryLimit = 2;
|
||||
-const greeting = "Hi You, {name}! Welcome to our application.";
|
||||
+const retryLimit = 4;
|
||||
+const greeting = "Hello There, {name}! Welcome to the updated application.";
|
||||
const logger = createLogger("demo");
|
||||
|
||||
export async function boot() {
|
||||
const server = createServer({
|
||||
- port: 3000,
|
||||
- timeoutMs: 1200,
|
||||
+ port: 3030,
|
||||
+ timeoutMs: 2500,
|
||||
retryLimit,
|
||||
});
|
||||
|
||||
- logger.info("starting server");
|
||||
+ logger.info("starting review fixture server");
|
||||
+ logger.debug({ retryLimit }, "configured retry policy");
|
||||
await server.start();
|
||||
- logger.info(greeting.replace("{name}", "reviewer"));
|
||||
+ logger.info(greeting.replace("{name}", "native reviewer"));
|
||||
+
|
||||
+ if (process.env.DEMO_FIXTURE_VERBOSE === "1") {
|
||||
+ logger.debug("verbose review fixture mode enabled");
|
||||
+ }
|
||||
}
|
||||
|
||||
void boot();
|
||||
diff --git a/apps/demo/src/utils/format.ts b/apps/demo/src/utils/stringFormat.ts
|
||||
similarity index 100%
|
||||
rename from apps/demo/src/utils/format.ts
|
||||
rename to apps/demo/src/utils/stringFormat.ts
|
||||
diff --git a/apps/demo/src/oldClient.ts b/apps/demo/src/apiClient.ts
|
||||
similarity index 62%
|
||||
rename from apps/demo/src/oldClient.ts
|
||||
rename to apps/demo/src/apiClient.ts
|
||||
index 18518fca1..87e0e2bea 100644
|
||||
--- a/apps/demo/src/oldClient.ts
|
||||
+++ b/apps/demo/src/apiClient.ts
|
||||
@@ -1,15 +1,22 @@
|
||||
-export interface ClientOptions {
|
||||
- readonly baseUrl: string;
|
||||
- readonly timeoutMs: number;
|
||||
-}
|
||||
-
|
||||
-export function request(path: string, options: ClientOptions) {
|
||||
- return fetch(options.baseUrl + path, {
|
||||
- signal: AbortSignal.timeout(options.timeoutMs),
|
||||
- });
|
||||
+export interface ApiClientOptions {
|
||||
+ readonly baseUrl: string;
|
||||
+ readonly token: string;
|
||||
+ readonly timeoutMs: number;
|
||||
+}
|
||||
+
|
||||
+export async function request(path: string, options: ApiClientOptions) {
|
||||
+ const response = await fetch(options.baseUrl + "/v2" + path, {
|
||||
+ headers: {
|
||||
+ Authorization: "Bearer " + options.token,
|
||||
+ "X-Client": "native-review-debug",
|
||||
+ },
|
||||
+ signal: AbortSignal.timeout(options.timeoutMs),
|
||||
+ });
|
||||
+
|
||||
+ if (!response.ok) {
|
||||
+ throw new Error("Request failed: " + response.status);
|
||||
+ }
|
||||
+
|
||||
+ return response.json();
|
||||
}
|
||||
-
|
||||
-export function requestJson(path: string, options: ClientOptions) {
|
||||
- return request(path, options).then((response) => response.json());
|
||||
-}
|
||||
diff --git a/apps/demo/src/features/flags.ts b/apps/demo/src/features/flags.ts
|
||||
new file mode 100644
|
||||
index 000000000..755df9762
|
||||
--- /dev/null
|
||||
+++ b/apps/demo/src/features/flags.ts
|
||||
@@ -0,0 +1,29 @@
|
||||
+export type FeatureState = "enabled" | "disabled" | "preview";
|
||||
+
|
||||
+export interface FeatureFlag {
|
||||
+ readonly key: string;
|
||||
+ readonly label: string;
|
||||
+ readonly state: FeatureState;
|
||||
+}
|
||||
+
|
||||
+export const reviewFixtureFlags: ReadonlyArray<FeatureFlag> = [
|
||||
+ {
|
||||
+ key: "native-file-headers",
|
||||
+ label: "Native file headers",
|
||||
+ state: "preview",
|
||||
+ },
|
||||
+ {
|
||||
+ key: "word-diff-highlights",
|
||||
+ label: "Word diff highlights",
|
||||
+ state: "enabled",
|
||||
+ },
|
||||
+ {
|
||||
+ key: "deleted-file-markers",
|
||||
+ label: "Deleted file markers",
|
||||
+ state: "enabled",
|
||||
+ },
|
||||
+];
|
||||
+
|
||||
+export function isEnabled(flag: FeatureFlag): boolean {
|
||||
+ return flag.state !== "disabled";
|
||||
+}
|
||||
diff --git a/apps/demo/src/legacyReview.ts b/apps/demo/src/legacyReview.ts
|
||||
deleted file mode 100644
|
||||
index 9cf2f63dc..000000000
|
||||
--- a/apps/demo/src/legacyReview.ts
|
||||
+++ /dev/null
|
||||
@@ -1,22 +0,0 @@
|
||||
-export const legacyReviewMode = true;
|
||||
-
|
||||
-export function createLegacyRows(lines: ReadonlyArray<string>) {
|
||||
- return lines.map((line, index) => ({
|
||||
- id: "legacy-" + index,
|
||||
- lineNumber: index + 1,
|
||||
- text: line,
|
||||
- }));
|
||||
-}
|
||||
-
|
||||
-export function renderLegacyHeader(path: string) {
|
||||
- return {
|
||||
- title: path,
|
||||
- subtitle: "legacy renderer",
|
||||
- icon: "blue-dot",
|
||||
- };
|
||||
-}
|
||||
-
|
||||
-export function shouldUseLegacyReview() {
|
||||
- return legacyReviewMode;
|
||||
-}
|
||||
diff --git a/apps/demo/src/wordChanges.zig b/apps/demo/src/wordChanges.zig
|
||||
index 6bfcc7e37..af359829c 100644
|
||||
--- a/apps/demo/src/wordChanges.zig
|
||||
+++ b/apps/demo/src/wordChanges.zig
|
||||
@@ -1,18 +1,23 @@
|
||||
const std = @import("std");
|
||||
-const Allocator = std.heap.page_allocator;
|
||||
+const GeneralPurposeAllocator = std.heap.GeneralPurposeAllocator;
|
||||
const ArrayList = std.ArrayList;
|
||||
|
||||
pub fn main() !void {
|
||||
+ var gpa = GeneralPurposeAllocator(.{}){};
|
||||
+ defer _ = gpa.deinit();
|
||||
+ const allocator = gpa.allocator();
|
||||
+
|
||||
const stdout_writer_instance = std.io.getStdOut().writer();
|
||||
- try stdout_writer_instance.print("Hi You, {s}! Welcome to our application.", .{"Reviewer"});
|
||||
+ try stdout_writer_instance.print("Hello There, {s}! Welcome to the updated application.", .{"Reviewer"});
|
||||
|
||||
- var list = ArrayList(i32).init(Allocator);
|
||||
+ var list = ArrayList(i32).init(allocator);
|
||||
defer list.deinit();
|
||||
+ try list.append(42);
|
||||
|
||||
- const configuration_options = .{ .enable_logging = true, .max_buffer_size = 1024 };
|
||||
+ const configuration_options = .{ .enable_logging = true, .max_buffer_size = 2048 };
|
||||
_ = configuration_options;
|
||||
}
|
||||
diff --git a/apps/demo/assets/review-logo.png b/apps/demo/assets/review-logo.png
|
||||
new file mode 100644
|
||||
index 000000000..4628f44da
|
||||
--- /dev/null
|
||||
+++ b/apps/demo/assets/review-logo.png
|
||||
Binary files /dev/null and b/apps/demo/assets/review-logo.png differ
|
||||
diff --git a/apps/demo/scripts/review-fixture.sh b/apps/demo/scripts/review-fixture.sh
|
||||
old mode 100644
|
||||
new mode 100755`;
|
||||
|
||||
export const debugReviewDiffFixtures: ReadonlyArray<DebugReviewDiffFixture> = [
|
||||
{
|
||||
id: "states",
|
||||
label: "States",
|
||||
filename: "review-states.diff",
|
||||
lineCount: DEBUG_REVIEW_STATES_DIFF.split("\n").length,
|
||||
diff: DEBUG_REVIEW_STATES_DIFF,
|
||||
},
|
||||
{
|
||||
id: "xl",
|
||||
label: "XL",
|
||||
filename: "08e6d4cfbfe55af83fe5fb6b9e75364f42f1f22f.patch",
|
||||
lineCount: DEBUG_REVIEW_XL_DIFF.split("\n").length,
|
||||
diff: DEBUG_REVIEW_XL_DIFF,
|
||||
},
|
||||
{
|
||||
id: "small",
|
||||
label: "Small",
|
||||
filename: "review-small.diff",
|
||||
lineCount: 155,
|
||||
diff: 'diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx\nindex d61924a62..3f2ae0160 100644\n--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx\n+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx\n@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({\n default: "monospace",\n });\n \n+export const REVIEW_DIFF_LINE_HEIGHT = 26;\n+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;\n+\n export function renderVisibleWhitespace(value: string): string {\n const expandedTabs = value.replace(/\\t/g, " ");\n return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\\u00A0"));\n@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |\n export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {\n if (props.change === "delete") {\n return (\n- <View className="w-[5px] self-stretch overflow-hidden">\n- <View className="flex-1 justify-between">\n- {Array.from({ length: 6 }, (_, index) => (\n- <View key={index} className="h-[2px] w-[5px] bg-rose-400" />\n+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>\n+ <View>\n+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (\n+ <View key={index}>\n+ <View className="w-[5px] bg-rose-400" style={{ height: 1 }} />\n+ <View style={{ height: 1 }} />\n+ </View>\n ))}\n </View>\n </View>\n@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo\n }\n \n return (\n- <View className="w-[5px] self-stretch overflow-hidden">\n+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>\n <View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />\n </View>\n );\n@@ -63,6 +69,7 @@ export function DiffTokenText(props: {\n if (!props.tokens || props.tokens.length === 0) {\n return (\n <NativeText\n+ numberOfLines={1}\n selectable\n className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}\n style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\n@@ -74,6 +81,7 @@ export function DiffTokenText(props: {\n \n return (\n <NativeText\n+ numberOfLines={1}\n selectable\n className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}\n style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\ndiff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts\nindex a24a99ceb..69a6e7261 100644\n--- a/apps/mobile/src/features/review/reviewModel.test.ts\n+++ b/apps/mobile/src/features/review/reviewModel.test.ts\n@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {\n });\n });\n \n- it("flattens expanded files into virtualizable review items", () => {\n+ it("flattens expanded file rows into virtualized review items", () => {\n const file = makeRenderableFile({\n path: "apps/mobile/src/a.ts",\n rows: [\n@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {\n \n expect(items).toEqual([\n expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),\n- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),\n- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),\n+ expect.objectContaining({\n+ kind: "hunk",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[0],\n+ }),\n+ expect.objectContaining({\n+ kind: "line",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[1],\n+ lineIndex: 0,\n+ }),\n ]);\n });\n \ndiff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts\nindex 27e6d7ae4..1cfbf358c 100644\n--- a/apps/mobile/src/features/review/reviewModel.ts\n+++ b/apps/mobile/src/features/review/reviewModel.ts\n@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {\n readonly kind: "hunk";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableHunkRow;\n }\n \n@@ -79,7 +80,9 @@ export interface ReviewLineListItem {\n readonly kind: "line";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableLineRow;\n+ readonly lineIndex: number;\n }\n \n export type ReviewListItem =\n@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil\n }\n \n // The flattened review list item model is inspired by pierre/diffs\' iterator-first\n-// virtualization architecture, adapted here f
Line truncated
|
||||
},
|
||||
{
|
||||
id: "medium",
|
||||
label: "Medium",
|
||||
filename: "review-medium.diff",
|
||||
lineCount: 1955,
|
||||
diff: 'diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return <ReviewSheet />;\n+ return (\n+ <ReviewHighlighterProvider>\n+ <ReviewSheet />\n+ </ReviewHighlighterProvider>\n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx\nindex 82c28e81e..e148a8da2 100644\n--- a/apps/mobile/src/features/review/ReviewSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewSheet.tsx\n@@ -1,17 +1,31 @@\n import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";\n+import { Gesture, GestureDetector } from "react-native-gesture-handler";\n+import Animated, {\n+ makeMutable,\n+ type SharedValue,\n+ useAnimatedStyle,\n+ useSharedValue,\n+} from "react-native-reanimated";\n import { useLocalSearchParams, useRouter } from "expo-router";\n import Stack from "expo-router/stack";\n import { SymbolView } from "expo-symbols";\n-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";\n+import {\n+ memo,\n+ type ReactElement,\n+ useCallback,\n+ useDeferredValue,\n+ useEffect,\n+ useMemo,\n+ useRef,\n+ useState,\n+} from "react";\n import {\n ActivityIndicator,\n FlatList,\n- InteractionManager,\n type ListRenderItemInfo,\n Pressable,\n ScrollView,\n Text as NativeText,\n- type ViewToken,\n useColorScheme,\n useWindowDimensions,\n View,\n@@ -32,6 +46,7 @@ import {\n setReviewTurnDiff,\n updateReviewExpandedFileIds,\n updateReviewRevealedLargeFileIds,\n+ updateReviewViewedFileIds,\n useReviewCacheForThread,\n } from "./reviewState";\n import {\n@@ -45,11 +60,12 @@ import {\n type ReviewParsedDiff,\n type ReviewRenderableFile,\n type ReviewRenderableLineRow,\n+ type ReviewRenderableRow,\n } from "./reviewModel";\n import {\n clearReviewHighlightFileCache,\n getCachedHighlightedReviewFile,\n- highlightReviewFile,\n+ streamHighlightReviewFile,\n type ReviewDiffTheme,\n type ReviewHighlightedFile,\n type ReviewHighlightedToken,\n@@ -67,9 +83,12 @@ import {\n import {\n changeTone,\n DiffTokenText,\n+ REVIEW_DIFF_LINE_HEIGHT,\n REVIEW_MONO_FONT_FAMILY,\n ReviewChangeBar,\n } from "./reviewDiffRendering";\n+import { markReviewEvent, measureReviewWork } from "./reviewPerf";\n+import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider";\n \n interface PendingCommentSelection {\n readonly sectionTitle: string;\n@@ -87,14 +106,21 @@ interface ReviewLineActionInput {\n \n const IOS_NAV_BAR_HEIGHT = 44;\n const REVIEW_HEADER_SPACING = 0;\n-const REVIEW_LINE_GUTTER_WIDTH = 62;\n+const REVIEW_CHANGE_BAR_WIDTH = 5;\n+const REVIEW_MIN_LINE_NUMBER_WIDTH = 27;\n+const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8;\n+const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6;\n const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4;\n const REVIEW_MAX_CONTENT_WIDTH = 4_800;\n-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2;\n-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0;\n-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1;\n+const REVIEW_HUNK_ROW_HEIGHT = 35;\n+const REVIEW_FILE_HEADER_HEIGHT = 43;\n+const REVIEW_SUPPRESSED_ROW_HEIGHT = 92;\n const loggedMissingReviewTokenKeys = new Set<string>();\n \n+function waitForReviewDelay(durationMs: number): Promise<void> {\n+ return new Promise((resolve) => setTimeout(resolve, durationMs));\n+}\n+\n function isReviewDiffDebugLoggingEnabled(): boolean {\n return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n }\n@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record<string, unkno\n }\n \n function getFileHeaderChrome(changeType: ReviewRenderableFile["changeType"]): {\n- readonly rail: string;\n readonly dot: string;\n } {\n switch (changeType) {\n case "new":\n return {\n- rail: "bg-emerald-400",\n dot: "bg-emerald-400",\n };\n case "deleted":\n return {\n- rail: "bg-rose-400",\n dot: "bg-rose-400",\n };\n case "rename-pure":\n return {\n- rail: "bg-amber-400",\n dot: "bg-amber-400",\n };\n case "rename-changed":\n return {\n- rail: "bg-sky-400",\n dot: "bg-sky-400",\n };\n default:\n return {\n- rail: "bg-sky-400",\n dot: "bg-sky-400",\n };\n }\n@@ -159,51 +179,72 @@ function formatHeaderDiffSummary(parsedDiff: ReviewParsedDiff): {\n };\n }\n \n-function computeReviewListContentWidth(\Line truncated
|
||||
},
|
||||
{
|
||||
id: "large",
|
||||
label: "Large",
|
||||
filename: "review-large.diff",
|
||||
lineCount: 3208,
|
||||
diff: 'diff --git a/apps/mobile/package.json b/apps/mobile/package.json\nindex 08329e1d4..36ac93a0f 100644\n--- a/apps/mobile/package.json\n+++ b/apps/mobile/package.json\n@@ -30,6 +30,7 @@\n "config:dev": "APP_VARIANT=development expo config",\n "config:preview": "APP_VARIANT=preview expo config",\n "config:prod": "APP_VARIANT=production expo config",\n+ "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",\n "test": "vitest run",\n "typecheck": "tsc --noEmit"\n },\ndiff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx\nindex f153db701..f6095c051 100644\n--- a/apps/mobile/src/app/index.tsx\n+++ b/apps/mobile/src/app/index.tsx\n@@ -43,28 +43,50 @@ export default function HomeRouteScreen() {\n headerTintColor: iconColor,\n headerTitle: "",\n headerRight: () => (\n- <Pressable\n- onPress={() => router.push("/connections")}\n- hitSlop={8}\n- style={{\n- flexDirection: "row",\n- alignItems: "center",\n- gap: 8,\n- paddingHorizontal: 4,\n- paddingVertical: 4,\n- }}\n- >\n- <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n- <RNText\n+ <View style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>\n+ <Pressable\n+ onPress={() => router.push("/debug/syntax-highlight")}\n+ hitSlop={8}\n style={{\n- fontFamily: "DMSans_700Bold",\n- fontSize: 12,\n- color: secondaryFg,\n+ borderRadius: 999,\n+ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",\n+ paddingHorizontal: 10,\n+ paddingVertical: 5,\n }}\n >\n- {CONNECTION_LABEL[connectionState]}\n- </RNText>\n- </Pressable>\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ Debug\n+ </RNText>\n+ </Pressable>\n+ <Pressable\n+ onPress={() => router.push("/connections")}\n+ hitSlop={8}\n+ style={{\n+ flexDirection: "row",\n+ alignItems: "center",\n+ gap: 8,\n+ paddingHorizontal: 4,\n+ paddingVertical: 4,\n+ }}\n+ >\n+ <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ {CONNECTION_LABEL[connectionState]}\n+ </RNText>\n+ </Pressable>\n+ </View>\n ),\n headerSearchBarOptions: {\n placeholder: "Search threads",\ndiff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return <ReviewSheet />;\n+ return (\n+ <ReviewHighlighterProvider>\n+ <ReviewSheet />\n+ </ReviewHighlighterProvider>\n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\nindex 076a2286d..9a173224a 100644\n--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router";\n import { SymbolView } from "expo-symbols";\n import { TextInputWrapper } from "expo-paste-input";\n import { useEffect, useMemo, useState } from "react";\n-import {\n- KeyboardAvoidingView,\n- Platform,\n- Pressable,\n- ScrollView,\n- View,\n- useColorScheme,\n- useWindowDimensions,\n-} from "react-native";\n+import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";\n+import { KeyboardStickyView } from "react-native-keyboard-controller";\n import { useSafeAreaInsets } from "reactLine truncated
|
||||
},
|
||||
{
|
||||
id: "current",
|
||||
label: "Current Working",
|
||||
filename: "current-working-review.diff",
|
||||
lineCount: 3208,
|
||||
diff: 'diff --git a/apps/mobile/package.json b/apps/mobile/package.json\nindex 08329e1d4..36ac93a0f 100644\n--- a/apps/mobile/package.json\n+++ b/apps/mobile/package.json\n@@ -30,6 +30,7 @@\n "config:dev": "APP_VARIANT=development expo config",\n "config:preview": "APP_VARIANT=preview expo config",\n "config:prod": "APP_VARIANT=production expo config",\n+ "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",\n "test": "vitest run",\n "typecheck": "tsc --noEmit"\n },\ndiff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx\nindex f153db701..f6095c051 100644\n--- a/apps/mobile/src/app/index.tsx\n+++ b/apps/mobile/src/app/index.tsx\n@@ -43,28 +43,50 @@ export default function HomeRouteScreen() {\n headerTintColor: iconColor,\n headerTitle: "",\n headerRight: () => (\n- <Pressable\n- onPress={() => router.push("/connections")}\n- hitSlop={8}\n- style={{\n- flexDirection: "row",\n- alignItems: "center",\n- gap: 8,\n- paddingHorizontal: 4,\n- paddingVertical: 4,\n- }}\n- >\n- <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n- <RNText\n+ <View style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>\n+ <Pressable\n+ onPress={() => router.push("/debug/syntax-highlight")}\n+ hitSlop={8}\n style={{\n- fontFamily: "DMSans_700Bold",\n- fontSize: 12,\n- color: secondaryFg,\n+ borderRadius: 999,\n+ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",\n+ paddingHorizontal: 10,\n+ paddingVertical: 5,\n }}\n >\n- {CONNECTION_LABEL[connectionState]}\n- </RNText>\n- </Pressable>\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ Debug\n+ </RNText>\n+ </Pressable>\n+ <Pressable\n+ onPress={() => router.push("/connections")}\n+ hitSlop={8}\n+ style={{\n+ flexDirection: "row",\n+ alignItems: "center",\n+ gap: 8,\n+ paddingHorizontal: 4,\n+ paddingVertical: 4,\n+ }}\n+ >\n+ <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ {CONNECTION_LABEL[connectionState]}\n+ </RNText>\n+ </Pressable>\n+ </View>\n ),\n headerSearchBarOptions: {\n placeholder: "Search threads",\ndiff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return <ReviewSheet />;\n+ return (\n+ <ReviewHighlighterProvider>\n+ <ReviewSheet />\n+ </ReviewHighlighterProvider>\n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\nindex 076a2286d..9a173224a 100644\n--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router";\n import { SymbolView } from "expo-symbols";\n import { TextInputWrapper } from "expo-paste-input";\n import { useEffect, useMemo, useState } from "react";\n-import {\n- KeyboardAvoidingView,\n- Platform,\n- Pressable,\n- ScrollView,\n- View,\n- useColorScheme,\n- useWindowDimensions,\n-} from "react-native";\n+import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";\n+import { KeyboardStickyView } from "react-native-keyboard-controller";\n import { useSafeAreaInsets } from "reactLine truncated
|
||||
},
|
||||
];
|
||||
@@ -1,4 +0,0 @@
|
||||
// Generated from https://github.com/pingdotgg/t3code/commit/08e6d4cfbfe55af83fe5fb6b9e75364f42f1f22f.patch
|
||||
// Keep this split from reviewDiffFixtures.ts so the fixture registry stays readable.
|
||||
export const DEBUG_REVIEW_XL_DIFF =
|
||||
'From 08e6d4cfbfe55af83fe5fb6b9e75364f42f1f22f Mon Sep 17 00:00:00 2001\nFrom: Julius Marminge <julius0216@outlook.com>\nDate: Wed, 29 Apr 2026 16:13:55 -0700\nSubject: [PATCH] feat: Multi-Provider support (#2277)\n\nCo-authored-by: Claude Opus 4.7 <noreply@anthropic.com>\nCo-authored-by: codex <codex@users.noreply.github.com>\n---\n apps/desktop/src/clientPersistence.test.ts | 1 +\n .../OrchestrationEngineHarness.integration.ts | 44 +-\n .../TestProviderAdapter.integration.ts | 17 +-\n .../integration/fixtures/providerRuntime.ts | 4 +-\n .../orchestrationEngine.integration.test.ts | 178 +-\n .../providerService.integration.test.ts | 37 +-\n .../git/Layers/ClaudeTextGeneration.test.ts | 311 +--\n .../src/git/Layers/ClaudeTextGeneration.ts | 55 +-\n .../git/Layers/CodexTextGeneration.test.ts | 528 +++--\n .../src/git/Layers/CodexTextGeneration.ts | 97 +-\n .../git/Layers/CursorTextGeneration.test.ts | 311 ++-\n .../src/git/Layers/CursorTextGeneration.ts | 56 +-\n .../git/Layers/OpenCodeTextGeneration.test.ts | 354 ++--\n .../src/git/Layers/OpenCodeTextGeneration.ts | 77 +-\n .../src/git/Layers/RoutingTextGeneration.ts | 104 -\n .../src/git/Layers/TextGenerationLive.test.ts | 117 ++\n .../src/git/Layers/TextGenerationLive.ts | 101 +\n apps/server/src/observability/Metrics.test.ts | 10 +-\n .../Layers/CheckpointReactor.test.ts | 60 +-\n .../Layers/OrchestrationEngine.test.ts | 51 +-\n .../Layers/ProjectionPipeline.test.ts | 33 +-\n .../Layers/ProjectionPipeline.ts | 1 +\n .../Layers/ProjectionSnapshotQuery.test.ts | 18 +-\n .../Layers/ProjectionSnapshotQuery.ts | 6 +\n .../Layers/ProviderCommandReactor.test.ts | 438 +++-\n .../Layers/ProviderCommandReactor.ts | 183 +-\n .../Layers/ProviderRuntimeIngestion.test.ts | 229 ++-\n .../Layers/ProviderRuntimeIngestion.ts | 6 +\n .../orchestration/commandInvariants.test.ts | 13 +-\n .../src/orchestration/decider.delete.test.ts | 5 +-\n .../decider.projectScripts.test.ts | 11 +-\n .../src/orchestration/projector.test.ts | 21 +-\n .../Layers/ProjectionRepositories.test.ts | 14 +-\n .../Layers/ProjectionThreadSessions.ts | 4 +\n .../Layers/ProviderSessionRuntime.ts | 5 +\n apps/server/src/persistence/Migrations.ts | 4 +\n .../027_028_ProviderInstanceIdColumns.test.ts | 74 +\n .../027_ProviderSessionRuntimeInstanceId.ts | 38 +\n .../028_ProjectionThreadSessionInstanceId.ts | 21 +\n .../Services/ProjectionThreadSessions.ts | 2 +\n .../Services/ProviderSessionRuntime.ts | 9 +\n .../src/provider/Drivers/ClaudeDriver.ts | 157 ++\n .../src/provider/Drivers/ClaudeHome.test.ts | 52 +\n .../server/src/provider/Drivers/ClaudeHome.ts | 43 +\n .../src/provider/Drivers/CodexDriver.ts | 171 ++\n .../provider/Drivers/CodexHomeLayout.test.ts | 209 ++\n .../src/provider/Drivers/CodexHomeLayout.ts | 263 +++\n .../src/provider/Drivers/CursorDriver.ts | 148 ++\n .../src/provider/Drivers/OpenCodeDriver.ts | 135 ++\n apps/server/src/provider/Errors.ts | 41 +\n .../src/provider/Layers/ClaudeAdapter.test.ts | 339 ++--\n .../src/provider/Layers/ClaudeAdapter.ts | 63 +-\n .../src/provider/Layers/ClaudeProvider.ts | 484 ++---\n .../src/provider/Layers/CodexAdapter.test.ts | 186 +-\n .../src/provider/Layers/CodexAdapter.ts | 65 +-\n .../src/provider/Layers/CodexProvider.ts | 99 +-\n .../provider/Layers/CodexSessionRuntime.ts | 61 +-\n .../src/provider/Layers/CursorAdapter.test.ts | 213 +-\n .../src/provider/Layers/CursorAdapter.ts | 73 +-\n .../provider/Layers/CursorProvider.test.ts | 159 +-\n .../src/provider/Layers/CursorProvider.ts | 665 ++++---\n .../provider/Layers/OpenCodeAdapter.test.ts | 286 ++-\n .../src/provider/Layers/OpenCodeAdapter.ts | 1770 +++++++++--------\n .../provider/Layers/OpenCodeProvider.test.ts | 119 +-\n .../src/provider/Layers/OpenCodeProvider.ts | 378 ++--\n .../Layers/ProviderAdapterRegistry.test.ts | 148 +-\n .../Layers/ProviderAdapterRegistry.ts | 133 +-\n .../provider/Layers/ProviderEventLoggers.ts | 83 +\n .../ProviderInstanceRegistryHydration.ts | 176 ++\n .../ProviderInstanceRegistryLive.test.ts | 357 ++++\n .../Layers/ProviderInstanceRegistryLive.ts | 434 ++++\n .../provider/Layers/ProviderRegistry.test.ts | 850 ++++++--\n .../src/provider/Layers/ProviderRegistry.ts | 546 +++--\n .../provider/Layers/ProviderService.test.ts | 583 ++++--\n .../src/provider/Layers/ProviderService.ts | 418 +++-\n .../Layers/ProviderSessionDirectory.test.ts | 25 +-\n .../Layers/ProviderSessionDirectory.ts | 24 +-\n .../Layers/ProviderSessionReaper.test.ts | 31 +-\n .../Layers/scopedSafeTeardown.test.ts | 94 +\n .../src/provider/Layers/scopedSafeTeardoLine truncated
|
||||
@@ -1,156 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseNativeReviewDiffFixture } from "./nativeReviewDiffParser";
|
||||
|
||||
describe("parseNativeReviewDiffFixture", () => {
|
||||
it("adds word diff ranges to paired changed lines", () => {
|
||||
const parsed = parseNativeReviewDiffFixture({
|
||||
id: "states",
|
||||
label: "States",
|
||||
filename: "states.diff",
|
||||
lineCount: 9,
|
||||
diff: [
|
||||
"diff --git a/main.ts b/main.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/main.ts",
|
||||
"+++ b/main.ts",
|
||||
"@@ -1,3 +1,3 @@",
|
||||
" const stable = true;",
|
||||
'-const label = "Before value";',
|
||||
'+const label = "After value";',
|
||||
" const done = true;",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
const deletion = parsed.rows.find((row) => row.change === "delete");
|
||||
const addition = parsed.rows.find((row) => row.change === "add");
|
||||
|
||||
expect(deletion?.wordDiffRanges).toEqual([{ start: 15, end: 21 }]);
|
||||
expect(addition?.wordDiffRanges).toEqual([{ start: 15, end: 20 }]);
|
||||
});
|
||||
|
||||
it("does not add word diff ranges to unpaired created lines", () => {
|
||||
const parsed = parseNativeReviewDiffFixture({
|
||||
id: "states",
|
||||
label: "States",
|
||||
filename: "states.diff",
|
||||
lineCount: 9,
|
||||
diff: [
|
||||
"diff --git a/new.ts b/new.ts",
|
||||
"new file mode 100644",
|
||||
"index 0000000..2222222",
|
||||
"--- /dev/null",
|
||||
"+++ b/new.ts",
|
||||
"@@ -0,0 +1,2 @@",
|
||||
'+const label = "After value";',
|
||||
"+export default label;",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
expect(parsed.rows.filter((row) => row.kind === "line")).toHaveLength(2);
|
||||
expect(parsed.rows.every((row) => row.wordDiffRanges === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it("trims whitespace from word diff range edges", () => {
|
||||
const parsed = parseNativeReviewDiffFixture({
|
||||
id: "states",
|
||||
label: "States",
|
||||
filename: "states.diff",
|
||||
lineCount: 8,
|
||||
diff: [
|
||||
"diff --git a/main.tsx b/main.tsx",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/main.tsx",
|
||||
"+++ b/main.tsx",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
"- const status = disabled;",
|
||||
"+ const status = enabled;",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
const deletion = parsed.rows.find((row) => row.change === "delete");
|
||||
const addition = parsed.rows.find((row) => row.change === "add");
|
||||
|
||||
expect(deletion?.wordDiffRanges?.[0]?.start).toBeGreaterThanOrEqual(4);
|
||||
expect(addition?.wordDiffRanges?.[0]?.start).toBeGreaterThanOrEqual(4);
|
||||
});
|
||||
|
||||
it("keeps word diff ranges aligned to exact replacement columns", () => {
|
||||
const parsed = parseNativeReviewDiffFixture({
|
||||
id: "states",
|
||||
label: "States",
|
||||
filename: "states.diff",
|
||||
lineCount: 12,
|
||||
diff: [
|
||||
"diff --git a/main.ts b/main.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/main.ts",
|
||||
"+++ b/main.ts",
|
||||
"@@ -1,5 +1,5 @@",
|
||||
"-const retryLimit = 2;",
|
||||
"+const retryLimit = 4;",
|
||||
'-const greeting = greeting.replace("{name}", "reviewer");',
|
||||
'+const greeting = greeting.replace("{name}", "native reviewer");',
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
const changedRows = parsed.rows.filter((row) => row.kind === "line");
|
||||
|
||||
expect(changedRows[0]?.wordDiffRanges).toEqual([{ start: 19, end: 20 }]);
|
||||
expect(changedRows[1]?.wordDiffRanges).toEqual([{ start: 19, end: 20 }]);
|
||||
expect(changedRows[2]?.wordDiffRanges).toBeUndefined();
|
||||
expect(changedRows[3]?.wordDiffRanges).toEqual([{ start: 45, end: 51 }]);
|
||||
});
|
||||
|
||||
it("suppresses noisy word diff ranges for unrelated replacement lines", () => {
|
||||
const parsed = parseNativeReviewDiffFixture({
|
||||
id: "states",
|
||||
label: "States",
|
||||
filename: "states.diff",
|
||||
lineCount: 8,
|
||||
diff: [
|
||||
"diff --git a/main.tsx b/main.tsx",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/main.tsx",
|
||||
"+++ b/main.tsx",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
'- case "file-header":',
|
||||
"+ const status = enabled;",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
expect(parsed.rows.every((row) => row.wordDiffRanges === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it("adds notice rows for pure renames and metadata-only changes", () => {
|
||||
const parsed = parseNativeReviewDiffFixture({
|
||||
id: "states",
|
||||
label: "States",
|
||||
filename: "states.diff",
|
||||
lineCount: 16,
|
||||
diff: [
|
||||
"diff --git a/src/oldName.ts b/src/newName.ts",
|
||||
"similarity index 100%",
|
||||
"rename from src/oldName.ts",
|
||||
"rename to src/newName.ts",
|
||||
"diff --git a/scripts/run.sh b/scripts/run.sh",
|
||||
"old mode 100644",
|
||||
"new mode 100755",
|
||||
"diff --git a/assets/logo.png b/assets/logo.png",
|
||||
"new file mode 100644",
|
||||
"index 000000000..4628f44da",
|
||||
"--- /dev/null",
|
||||
"+++ b/assets/logo.png",
|
||||
"Binary files /dev/null and b/assets/logo.png differ",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
const noticeTexts = parsed.rows.filter((row) => row.kind === "notice").map((row) => row.text);
|
||||
|
||||
expect(noticeTexts).toEqual([
|
||||
"This file was renamed without modifications.",
|
||||
"File mode changed from 100644 to 100755.",
|
||||
"Unsupported binary format. Diff contents are not available.",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,549 +0,0 @@
|
||||
import {
|
||||
debugReviewDiffFixtures,
|
||||
type DebugReviewDiffFixture,
|
||||
type DebugReviewDiffFixtureId,
|
||||
} from "../fixtures/reviewDiffFixtures";
|
||||
import { computeWordAltDiffRanges } from "../../review/reviewWordDiffs";
|
||||
import type { NativeReviewDiffRow } from "./nativeReviewDiffModule";
|
||||
|
||||
const NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT = 4;
|
||||
const NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE = 0.45;
|
||||
|
||||
export type NativeReviewDiffLanguage =
|
||||
| "bash"
|
||||
| "diff"
|
||||
| "javascript"
|
||||
| "json"
|
||||
| "jsx"
|
||||
| "tsx"
|
||||
| "typescript"
|
||||
| "yaml";
|
||||
|
||||
export interface NativeReviewDiffFile {
|
||||
readonly id: string;
|
||||
readonly path: string;
|
||||
readonly language: NativeReviewDiffLanguage;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffParsedFixture {
|
||||
readonly fixtureId: DebugReviewDiffFixtureId;
|
||||
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
|
||||
readonly files: ReadonlyArray<NativeReviewDiffFile>;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}
|
||||
|
||||
interface NativeReviewDiffFileParseState {
|
||||
readonly path: string;
|
||||
readonly language: NativeReviewDiffLanguage;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
readonly hasRenderableRows: boolean;
|
||||
readonly isBinary: boolean;
|
||||
readonly oldMode: string | null;
|
||||
readonly newMode: string | null;
|
||||
}
|
||||
|
||||
function getDiffPathFromHeader(line: string): string {
|
||||
const match = line.match(/^diff --git a\/(.+) b\/(.+)$/);
|
||||
return match?.[2] ?? line.replace(/^diff --git /, "");
|
||||
}
|
||||
|
||||
function getDiffPreviousPathFromHeader(line: string): string | null {
|
||||
const match = line.match(/^diff --git a\/(.+) b\/(.+)$/);
|
||||
return match?.[1] ?? null;
|
||||
}
|
||||
|
||||
function parseDiffPath(line: string, prefix: "--- " | "+++ "): string | null {
|
||||
if (!line.startsWith(prefix)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rawPath = line.slice(prefix.length).trim();
|
||||
if (rawPath === "/dev/null") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return rawPath.replace(/^[ab]\//, "");
|
||||
}
|
||||
|
||||
function resolveChangeType(input: {
|
||||
readonly previousPath: string | null;
|
||||
readonly nextPath: string | null;
|
||||
}): NativeReviewDiffRow["changeType"] {
|
||||
if (!input.previousPath && input.nextPath) {
|
||||
return "new";
|
||||
}
|
||||
if (input.previousPath && !input.nextPath) {
|
||||
return "deleted";
|
||||
}
|
||||
if (input.previousPath && input.nextPath && input.previousPath !== input.nextPath) {
|
||||
return "renamed";
|
||||
}
|
||||
return "modified";
|
||||
}
|
||||
|
||||
function resolveFileHeaderChangeType(input: {
|
||||
readonly previousPath: string | null | undefined;
|
||||
readonly nextPath: string | null | undefined;
|
||||
readonly currentChangeType: NativeReviewDiffRow["changeType"];
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}): NativeReviewDiffRow["changeType"] {
|
||||
if (input.currentChangeType === "new" || input.currentChangeType === "deleted") {
|
||||
return input.currentChangeType;
|
||||
}
|
||||
|
||||
if (input.previousPath && input.nextPath && input.previousPath !== input.nextPath) {
|
||||
return input.additions + input.deletions === 0 ? "rename-pure" : "rename-changed";
|
||||
}
|
||||
|
||||
return resolveChangeType({
|
||||
nextPath: input.nextPath ?? null,
|
||||
previousPath: input.previousPath ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
function getLanguageForPath(filePath: string): NativeReviewDiffLanguage {
|
||||
const normalizedPath = filePath.toLowerCase();
|
||||
if (normalizedPath.endsWith(".tsx")) return "tsx";
|
||||
if (normalizedPath.endsWith(".ts")) return "typescript";
|
||||
if (normalizedPath.endsWith(".jsx")) return "jsx";
|
||||
if (normalizedPath.endsWith(".js") || normalizedPath.endsWith(".cjs")) return "javascript";
|
||||
if (normalizedPath.endsWith(".json") || normalizedPath.endsWith(".jsonc")) return "json";
|
||||
if (normalizedPath.endsWith(".yml") || normalizedPath.endsWith(".yaml")) return "yaml";
|
||||
if (
|
||||
normalizedPath.endsWith(".sh") ||
|
||||
normalizedPath.includes("/bin/") ||
|
||||
normalizedPath.includes("shell")
|
||||
) {
|
||||
return "bash";
|
||||
}
|
||||
return "diff";
|
||||
}
|
||||
|
||||
function parseHunkLineNumbers(line: string): { oldLine: number; newLine: number } | null {
|
||||
const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
oldLine: Number(match[1]),
|
||||
newLine: Number(match[2]),
|
||||
};
|
||||
}
|
||||
|
||||
function parseFileModeLine(line: string, prefix: "old mode " | "new mode "): string | null {
|
||||
if (!line.startsWith(prefix)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return line.slice(prefix.length).trim() || null;
|
||||
}
|
||||
|
||||
function createNoticeRow(input: {
|
||||
readonly fileId: string;
|
||||
readonly message: string;
|
||||
readonly suffix: string;
|
||||
}): NativeReviewDiffRow {
|
||||
return {
|
||||
kind: "notice",
|
||||
id: `${input.fileId}:notice:${input.suffix}`,
|
||||
fileId: input.fileId,
|
||||
text: input.message,
|
||||
};
|
||||
}
|
||||
|
||||
function getNoticeRowForFile(input: {
|
||||
readonly row: NativeReviewDiffRow;
|
||||
readonly file: NativeReviewDiffFileParseState | undefined;
|
||||
}): NativeReviewDiffRow | null {
|
||||
const { file, row } = input;
|
||||
if (!file || row.kind !== "file" || !row.fileId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (file.isBinary) {
|
||||
return createNoticeRow({
|
||||
fileId: row.fileId,
|
||||
message: "Unsupported binary format. Diff contents are not available.",
|
||||
suffix: "binary",
|
||||
});
|
||||
}
|
||||
|
||||
if (file.oldMode && file.newMode && file.oldMode !== file.newMode && !file.hasRenderableRows) {
|
||||
return createNoticeRow({
|
||||
fileId: row.fileId,
|
||||
message: `File mode changed from ${file.oldMode} to ${file.newMode}.`,
|
||||
suffix: "mode",
|
||||
});
|
||||
}
|
||||
|
||||
if (row.changeType === "rename-pure" && !file.hasRenderableRows) {
|
||||
return createNoticeRow({
|
||||
fileId: row.fileId,
|
||||
message: "This file was renamed without modifications.",
|
||||
suffix: "rename",
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function isChangedLine(row: NativeReviewDiffRow | undefined, change: "add" | "delete") {
|
||||
return row?.kind === "line" && row.change === change && typeof row.content === "string";
|
||||
}
|
||||
|
||||
function trimWordDiffRanges(
|
||||
content: string,
|
||||
ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
|
||||
): NonNullable<NativeReviewDiffRow["wordDiffRanges"]> {
|
||||
return ranges.flatMap((range) => {
|
||||
let start = Math.max(0, range.start);
|
||||
let end = Math.min(content.length, range.end);
|
||||
|
||||
while (start < end && /\s/.test(content[start] ?? "")) {
|
||||
start += 1;
|
||||
}
|
||||
|
||||
while (end > start && /\s/.test(content[end - 1] ?? "")) {
|
||||
end -= 1;
|
||||
}
|
||||
|
||||
return end > start ? [{ start, end }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function nonWhitespaceLength(value: string) {
|
||||
return value.replace(/\s/g, "").length;
|
||||
}
|
||||
|
||||
function getRangeCoverage(
|
||||
content: string,
|
||||
ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
|
||||
) {
|
||||
const meaningfulLength = nonWhitespaceLength(content);
|
||||
if (meaningfulLength === 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
const highlightedLength = ranges.reduce(
|
||||
(total, range) => total + nonWhitespaceLength(content.slice(range.start, range.end)),
|
||||
0,
|
||||
);
|
||||
return highlightedLength / meaningfulLength;
|
||||
}
|
||||
|
||||
function shouldUseWordDiffRanges(
|
||||
content: string,
|
||||
ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
|
||||
) {
|
||||
if (ranges.length === 0 || ranges.length > NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return getRangeCoverage(content, ranges) <= NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE;
|
||||
}
|
||||
|
||||
function addNativeWordDiffRanges(rows: ReadonlyArray<NativeReviewDiffRow>) {
|
||||
const nextRows = [...rows];
|
||||
let index = 0;
|
||||
|
||||
while (index < nextRows.length) {
|
||||
const deletedRowIndexes: number[] = [];
|
||||
const addedRowIndexes: number[] = [];
|
||||
const fileId = nextRows[index]?.fileId;
|
||||
|
||||
while (isChangedLine(nextRows[index], "delete") && nextRows[index]?.fileId === fileId) {
|
||||
deletedRowIndexes.push(index);
|
||||
index += 1;
|
||||
}
|
||||
|
||||
if (deletedRowIndexes.length === 0) {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
while (isChangedLine(nextRows[index], "add") && nextRows[index]?.fileId === fileId) {
|
||||
addedRowIndexes.push(index);
|
||||
index += 1;
|
||||
}
|
||||
|
||||
if (addedRowIndexes.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const pairCount = Math.min(deletedRowIndexes.length, addedRowIndexes.length);
|
||||
for (let pairIndex = 0; pairIndex < pairCount; pairIndex += 1) {
|
||||
const deletedRowIndex = deletedRowIndexes[pairIndex];
|
||||
const addedRowIndex = addedRowIndexes[pairIndex];
|
||||
const deletedRow = nextRows[deletedRowIndex];
|
||||
const addedRow = nextRows[addedRowIndex];
|
||||
if (!deletedRow?.content || !addedRow?.content) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const ranges = computeWordAltDiffRanges({
|
||||
deletionLine: deletedRow.content,
|
||||
additionLine: addedRow.content,
|
||||
});
|
||||
|
||||
const deletionRanges = trimWordDiffRanges(deletedRow.content, ranges.deletion);
|
||||
const additionRanges = trimWordDiffRanges(addedRow.content, ranges.addition);
|
||||
|
||||
if (shouldUseWordDiffRanges(deletedRow.content, deletionRanges)) {
|
||||
nextRows[deletedRowIndex] = { ...deletedRow, wordDiffRanges: deletionRanges };
|
||||
}
|
||||
|
||||
if (shouldUseWordDiffRanges(addedRow.content, additionRanges)) {
|
||||
nextRows[addedRowIndex] = { ...addedRow, wordDiffRanges: additionRanges };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nextRows;
|
||||
}
|
||||
|
||||
export function parseNativeReviewDiffFixture(
|
||||
fixture: DebugReviewDiffFixture,
|
||||
): NativeReviewDiffParsedFixture {
|
||||
const startedAt = performance.now();
|
||||
let rows: NativeReviewDiffRow[] = [];
|
||||
const files = new Map<string, NativeReviewDiffFileParseState>();
|
||||
const rawLines = fixture.diff.split(/\r?\n/);
|
||||
|
||||
let currentFileId: string | null = null;
|
||||
let currentOldLine: number | null = null;
|
||||
let currentNewLine: number | null = null;
|
||||
|
||||
function ensureCurrentFile(filePath: string, previousPath: string | null): string {
|
||||
const fileId = `file:${files.size}:${filePath}`;
|
||||
const language = getLanguageForPath(filePath);
|
||||
files.set(fileId, {
|
||||
path: filePath,
|
||||
language,
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
hasRenderableRows: false,
|
||||
isBinary: false,
|
||||
oldMode: null,
|
||||
newMode: null,
|
||||
});
|
||||
rows.push({
|
||||
kind: "file",
|
||||
id: `${fileId}:header`,
|
||||
fileId,
|
||||
filePath,
|
||||
previousPath,
|
||||
changeType: resolveChangeType({ nextPath: filePath, previousPath }),
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
});
|
||||
return fileId;
|
||||
}
|
||||
|
||||
for (let index = 0; index < rawLines.length; index += 1) {
|
||||
const rawLine = rawLines[index] ?? "";
|
||||
|
||||
if (rawLine.startsWith("diff --git ")) {
|
||||
currentFileId = ensureCurrentFile(
|
||||
getDiffPathFromHeader(rawLine),
|
||||
getDiffPreviousPathFromHeader(rawLine),
|
||||
);
|
||||
currentOldLine = null;
|
||||
currentNewLine = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!currentFileId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const previousPath = parseDiffPath(rawLine, "--- ");
|
||||
if (previousPath !== null || rawLine === "--- /dev/null") {
|
||||
rows = rows.map((row) =>
|
||||
row.id === `${currentFileId}:header`
|
||||
? {
|
||||
...row,
|
||||
previousPath,
|
||||
changeType: resolveChangeType({
|
||||
nextPath: row.filePath ?? null,
|
||||
previousPath,
|
||||
}),
|
||||
}
|
||||
: row,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const nextPath = parseDiffPath(rawLine, "+++ ");
|
||||
if (nextPath !== null || rawLine === "+++ /dev/null") {
|
||||
rows = rows.map((row) =>
|
||||
row.id === `${currentFileId}:header`
|
||||
? {
|
||||
...row,
|
||||
filePath: nextPath ?? row.filePath,
|
||||
changeType: resolveChangeType({
|
||||
nextPath,
|
||||
previousPath: row.previousPath ?? null,
|
||||
}),
|
||||
}
|
||||
: row,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const oldMode = parseFileModeLine(rawLine, "old mode ");
|
||||
if (oldMode !== null) {
|
||||
const file = files.get(currentFileId);
|
||||
if (file) {
|
||||
files.set(currentFileId, { ...file, oldMode });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const newMode = parseFileModeLine(rawLine, "new mode ");
|
||||
if (newMode !== null) {
|
||||
const file = files.get(currentFileId);
|
||||
if (file) {
|
||||
files.set(currentFileId, { ...file, newMode });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (rawLine.startsWith("Binary files ")) {
|
||||
const file = files.get(currentFileId);
|
||||
if (file) {
|
||||
files.set(currentFileId, { ...file, isBinary: true });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (rawLine.startsWith("@@ ")) {
|
||||
const file = files.get(currentFileId);
|
||||
if (file) {
|
||||
files.set(currentFileId, { ...file, hasRenderableRows: true });
|
||||
}
|
||||
const parsedLineNumbers = parseHunkLineNumbers(rawLine);
|
||||
currentOldLine = parsedLineNumbers?.oldLine ?? null;
|
||||
currentNewLine = parsedLineNumbers?.newLine ?? null;
|
||||
rows.push({
|
||||
kind: "hunk",
|
||||
id: `${currentFileId}:hunk:${index}`,
|
||||
fileId: currentFileId,
|
||||
text: rawLine,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const marker = rawLine[0];
|
||||
if (marker !== " " && marker !== "+" && marker !== "-") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const file = files.get(currentFileId);
|
||||
if (!file) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const change = marker === "+" ? "add" : marker === "-" ? "delete" : "context";
|
||||
rows.push({
|
||||
kind: "line",
|
||||
id: `${currentFileId}:line:${index}`,
|
||||
fileId: currentFileId,
|
||||
change,
|
||||
oldLineNumber: change === "add" ? null : currentOldLine,
|
||||
newLineNumber: change === "delete" ? null : currentNewLine,
|
||||
content: rawLine.slice(1),
|
||||
});
|
||||
|
||||
if (change === "add") {
|
||||
files.set(currentFileId, { ...file, additions: file.additions + 1 });
|
||||
currentNewLine = currentNewLine === null ? null : currentNewLine + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (change === "delete") {
|
||||
files.set(currentFileId, { ...file, deletions: file.deletions + 1 });
|
||||
currentOldLine = currentOldLine === null ? null : currentOldLine + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
currentOldLine = currentOldLine === null ? null : currentOldLine + 1;
|
||||
currentNewLine = currentNewLine === null ? null : currentNewLine + 1;
|
||||
}
|
||||
|
||||
rows = addNativeWordDiffRanges(rows);
|
||||
|
||||
const fileSummaries = Array.from(files, ([id, file]) => ({
|
||||
id,
|
||||
path: file.path,
|
||||
language: file.language,
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
}));
|
||||
const fileSummaryByPath = new Map(fileSummaries.map((file) => [file.path, file]));
|
||||
const rowsWithFileStats = rows.map((row): NativeReviewDiffRow => {
|
||||
if (row.kind !== "file" || !row.filePath) {
|
||||
return row;
|
||||
}
|
||||
const file = fileSummaryByPath.get(row.filePath);
|
||||
const additions = file?.additions ?? row.additions ?? 0;
|
||||
const deletions = file?.deletions ?? row.deletions ?? 0;
|
||||
return {
|
||||
kind: row.kind,
|
||||
id: row.id,
|
||||
fileId: row.fileId,
|
||||
filePath: row.filePath,
|
||||
previousPath: row.previousPath,
|
||||
changeType: resolveFileHeaderChangeType({
|
||||
previousPath: row.previousPath,
|
||||
nextPath: row.filePath,
|
||||
currentChangeType: row.changeType ?? "modified",
|
||||
additions,
|
||||
deletions,
|
||||
}),
|
||||
additions,
|
||||
deletions,
|
||||
text: row.text,
|
||||
content: row.content,
|
||||
change: row.change,
|
||||
oldLineNumber: row.oldLineNumber,
|
||||
newLineNumber: row.newLineNumber,
|
||||
wordDiffRanges: row.wordDiffRanges,
|
||||
};
|
||||
});
|
||||
const rowsWithFileNotices = rowsWithFileStats.flatMap((row): NativeReviewDiffRow[] => {
|
||||
const noticeRow = getNoticeRowForFile({
|
||||
row,
|
||||
file: row.fileId ? files.get(row.fileId) : undefined,
|
||||
});
|
||||
return noticeRow ? [row, noticeRow] : [row];
|
||||
});
|
||||
|
||||
const parsed = {
|
||||
fixtureId: fixture.id,
|
||||
rows: rowsWithFileNotices,
|
||||
files: fileSummaries,
|
||||
additions: fileSummaries.reduce((total, file) => total + file.additions, 0),
|
||||
deletions: fileSummaries.reduce((total, file) => total + file.deletions, 0),
|
||||
};
|
||||
|
||||
console.log("[debug-native-diff] parse", {
|
||||
durationMs: Math.round(performance.now() - startedAt),
|
||||
files: parsed.files.length,
|
||||
fixture: fixture.id,
|
||||
rows: parsed.rows.length,
|
||||
});
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export function getNativeReviewDiffFixture(fixtureId: DebugReviewDiffFixtureId) {
|
||||
return (
|
||||
debugReviewDiffFixtures.find((fixture) => fixture.id === fixtureId) ??
|
||||
debugReviewDiffFixtures[0]
|
||||
);
|
||||
}
|
||||
+2
-2
@@ -9,8 +9,8 @@ import tsxLanguage from "@shikijs/langs/tsx";
|
||||
import typescriptLanguage from "@shikijs/langs/typescript";
|
||||
import yamlLanguage from "@shikijs/langs/yaml";
|
||||
|
||||
import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewDiffModule";
|
||||
import type { NativeReviewDiffFile, NativeReviewDiffLanguage } from "./nativeReviewDiffParser";
|
||||
import type { NativeReviewDiffFile, NativeReviewDiffLanguage } from "./nativeReviewDiffTypes";
|
||||
import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewDiffSurface";
|
||||
|
||||
export type NativeReviewDiffHighlightScheme = "light" | "dark";
|
||||
export type NativeReviewDiffHighlightEngine = "native" | "javascript";
|
||||
+4
-4
@@ -28,7 +28,7 @@ describe("resolveNativeReviewDiffView", () => {
|
||||
});
|
||||
|
||||
it("returns null when the native review diff view config is unavailable", async () => {
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
|
||||
expect(resolveNativeReviewDiffView()).toBeNull();
|
||||
expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -36,7 +36,7 @@ describe("resolveNativeReviewDiffView", () => {
|
||||
it("returns the native review diff view when the view config is installed", async () => {
|
||||
setExpoViewConfigAvailable();
|
||||
expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
|
||||
expect(resolveNativeReviewDiffView()).toBe(nativeView);
|
||||
expect(expoModulesCoreMocks.requireNativeViewManager).toHaveBeenCalledWith(
|
||||
"T3ReviewDiffSurface",
|
||||
@@ -53,7 +53,7 @@ describe("resolveNativeReviewDiffView", () => {
|
||||
}),
|
||||
} as unknown as typeof globalThis.expo;
|
||||
expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
|
||||
expect(resolveNativeReviewDiffView()).toBeNull();
|
||||
expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -63,7 +63,7 @@ describe("resolveNativeReviewDiffView", () => {
|
||||
expoModulesCoreMocks.requireNativeViewManager.mockImplementation(() => {
|
||||
throw new Error("boom");
|
||||
});
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
|
||||
expect(resolveNativeReviewDiffView()).toBeNull();
|
||||
});
|
||||
});
|
||||
-6
@@ -127,7 +127,6 @@ export interface NativeReviewDiffViewProps extends ViewProps {
|
||||
}
|
||||
|
||||
let cachedNativeReviewDiffView: ComponentType<NativeReviewDiffViewProps> | undefined;
|
||||
let cachedNativeReviewDiffModuleName: typeof NATIVE_REVIEW_DIFF_MODULE_NAME | undefined;
|
||||
|
||||
function getExpoViewConfig(moduleName: string) {
|
||||
return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
|
||||
@@ -152,10 +151,5 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
|
||||
return null;
|
||||
}
|
||||
|
||||
cachedNativeReviewDiffModuleName = NATIVE_REVIEW_DIFF_MODULE_NAME;
|
||||
return cachedNativeReviewDiffView ?? null;
|
||||
}
|
||||
|
||||
export function getResolvedNativeReviewDiffModuleName() {
|
||||
return cachedNativeReviewDiffModuleName ?? null;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export type NativeReviewDiffLanguage =
|
||||
| "bash"
|
||||
| "diff"
|
||||
| "javascript"
|
||||
| "json"
|
||||
| "jsx"
|
||||
| "tsx"
|
||||
| "typescript"
|
||||
| "yaml";
|
||||
|
||||
export interface NativeReviewDiffFile {
|
||||
readonly id: string;
|
||||
readonly path: string;
|
||||
readonly language: NativeReviewDiffLanguage;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}
|
||||
@@ -875,9 +875,9 @@ export function ReviewSheet() {
|
||||
setLoadingGitDiffs(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await client.git.getReviewDiffs({ cwd });
|
||||
const result = await client.review.getDiffPreview({ cwd });
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewGitSections(reviewCache.threadKey, result.sections);
|
||||
setReviewGitSections(reviewCache.threadKey, result.sources);
|
||||
}
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "Failed to load review diffs.");
|
||||
|
||||
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
countReviewCommentContexts,
|
||||
formatReviewCommentContext,
|
||||
parseReviewCommentMessageSegments,
|
||||
parseReviewInlineComments,
|
||||
type ReviewCommentTarget,
|
||||
} from "./reviewCommentSelection";
|
||||
@@ -54,7 +55,27 @@ describe("review comment serialization", () => {
|
||||
startIndex: 0,
|
||||
endIndex: 1,
|
||||
text: "Please keep this configurable.",
|
||||
diff: expect.stringContaining("-const retryLimit = 2;"),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("splits chat text into review comment segments", () => {
|
||||
const serialized = `Before\n${formatReviewCommentContext(makeTarget(), "Please keep this configurable.")}\nAfter`;
|
||||
const segments = parseReviewCommentMessageSegments(serialized);
|
||||
|
||||
expect(segments).toHaveLength(3);
|
||||
expect(segments[0]).toEqual(expect.objectContaining({ kind: "text", text: "Before\n" }));
|
||||
expect(segments[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
kind: "review-comment",
|
||||
comment: expect.objectContaining({
|
||||
filePath: "apps/demo/src/main.ts",
|
||||
text: "Please keep this configurable.",
|
||||
diff: expect.stringContaining("+const retryLimit = 4;"),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(segments[2]).toEqual(expect.objectContaining({ kind: "text", text: "\nAfter" }));
|
||||
});
|
||||
});
|
||||
@@ -20,8 +20,20 @@ export interface ReviewInlineComment {
|
||||
readonly endIndex: number;
|
||||
readonly rangeLabel: string;
|
||||
readonly text: string;
|
||||
readonly diff: string;
|
||||
}
|
||||
|
||||
export type ReviewCommentMessageSegment =
|
||||
| {
|
||||
readonly kind: "text";
|
||||
readonly id: string;
|
||||
readonly text: string;
|
||||
}
|
||||
| {
|
||||
readonly kind: "review-comment";
|
||||
readonly comment: ReviewInlineComment;
|
||||
};
|
||||
|
||||
let currentTarget: ReviewCommentTarget | null = null;
|
||||
const listeners = new Set<() => void>();
|
||||
const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
|
||||
@@ -189,6 +201,38 @@ function extractReviewCommentText(rawBody: string): string {
|
||||
return commentBody.trim();
|
||||
}
|
||||
|
||||
function extractReviewCommentDiff(rawBody: string): string {
|
||||
const match = rawBody.match(/```diff\s*\n([\s\S]*?)\n```/);
|
||||
return match?.[1]?.trim() ?? "";
|
||||
}
|
||||
|
||||
function parseReviewInlineComment(
|
||||
rawAttributes: string,
|
||||
rawBody: string,
|
||||
index: number,
|
||||
): ReviewInlineComment | null {
|
||||
const attributes = readReviewCommentAttributes(rawAttributes);
|
||||
const startIndex = readNonNegativeInteger(attributes.startIndex);
|
||||
const endIndex = readNonNegativeInteger(attributes.endIndex);
|
||||
const filePath = attributes.filePath?.trim();
|
||||
const sectionId = attributes.sectionId?.trim();
|
||||
if (!filePath || !sectionId || startIndex === null || endIndex === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`,
|
||||
sectionId,
|
||||
sectionTitle: attributes.sectionTitle?.trim() || "Review",
|
||||
filePath,
|
||||
startIndex: Math.min(startIndex, endIndex),
|
||||
endIndex: Math.max(startIndex, endIndex),
|
||||
rangeLabel: attributes.rangeLabel?.trim() || "line",
|
||||
text: extractReviewCommentText(rawBody),
|
||||
diff: extractReviewCommentDiff(rawBody),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatReviewCommentContext(target: ReviewCommentTarget, comment: string): string {
|
||||
const rangeLabel = formatReviewSelectedRangeLabel(target);
|
||||
return [
|
||||
@@ -217,25 +261,57 @@ export function countReviewCommentContexts(value: string): number {
|
||||
export function parseReviewInlineComments(value: string): ReadonlyArray<ReviewInlineComment> {
|
||||
const comments: ReviewInlineComment[] = [];
|
||||
for (const [index, match] of Array.from(value.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)).entries()) {
|
||||
const attributes = readReviewCommentAttributes(match[1] ?? "");
|
||||
const startIndex = readNonNegativeInteger(attributes.startIndex);
|
||||
const endIndex = readNonNegativeInteger(attributes.endIndex);
|
||||
const filePath = attributes.filePath?.trim();
|
||||
const sectionId = attributes.sectionId?.trim();
|
||||
if (!filePath || !sectionId || startIndex === null || endIndex === null) {
|
||||
const comment = parseReviewInlineComment(match[1] ?? "", match[2] ?? "", index);
|
||||
if (!comment) {
|
||||
continue;
|
||||
}
|
||||
|
||||
comments.push({
|
||||
id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`,
|
||||
sectionId,
|
||||
sectionTitle: attributes.sectionTitle?.trim() || "Review",
|
||||
filePath,
|
||||
startIndex: Math.min(startIndex, endIndex),
|
||||
endIndex: Math.max(startIndex, endIndex),
|
||||
rangeLabel: attributes.rangeLabel?.trim() || "line",
|
||||
text: extractReviewCommentText(match[2] ?? ""),
|
||||
});
|
||||
comments.push(comment);
|
||||
}
|
||||
return comments;
|
||||
}
|
||||
|
||||
export function parseReviewCommentMessageSegments(
|
||||
value: string,
|
||||
): ReadonlyArray<ReviewCommentMessageSegment> {
|
||||
const segments: ReviewCommentMessageSegment[] = [];
|
||||
let cursor = 0;
|
||||
let parsedCommentIndex = 0;
|
||||
|
||||
for (const match of value.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)) {
|
||||
const matchIndex = match.index ?? 0;
|
||||
const beforeText = value.slice(cursor, matchIndex);
|
||||
if (beforeText.length > 0) {
|
||||
segments.push({
|
||||
kind: "text",
|
||||
id: `review-comment-text:${cursor}`,
|
||||
text: beforeText,
|
||||
});
|
||||
}
|
||||
|
||||
const comment = parseReviewInlineComment(match[1] ?? "", match[2] ?? "", parsedCommentIndex);
|
||||
if (comment) {
|
||||
segments.push({ kind: "review-comment", comment });
|
||||
parsedCommentIndex += 1;
|
||||
} else {
|
||||
segments.push({
|
||||
kind: "text",
|
||||
id: `review-comment-invalid:${matchIndex}`,
|
||||
text: match[0],
|
||||
});
|
||||
}
|
||||
|
||||
cursor = matchIndex + match[0].length;
|
||||
}
|
||||
|
||||
const rest = value.slice(cursor);
|
||||
if (rest.length > 0) {
|
||||
segments.push({
|
||||
kind: "text",
|
||||
id: `review-comment-text:${cursor}`,
|
||||
text: rest,
|
||||
});
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
@@ -3,8 +3,8 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
MessageId,
|
||||
TurnId,
|
||||
type GitReviewDiffSection,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type ReviewDiffPreviewSource,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
@@ -62,20 +62,26 @@ describe("buildReviewSectionItems", () => {
|
||||
completedAt: "2026-04-02T00:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
const gitSections: GitReviewDiffSection[] = [
|
||||
const gitSections: ReviewDiffPreviewSource[] = [
|
||||
{
|
||||
kind: "dirty",
|
||||
id: "working-tree",
|
||||
kind: "working-tree",
|
||||
title: "Dirty worktree",
|
||||
baseRef: "HEAD",
|
||||
headRef: null,
|
||||
diff: "diff --git a/a.ts b/a.ts",
|
||||
diffHash: "hash-dirty",
|
||||
truncated: false,
|
||||
},
|
||||
{
|
||||
kind: "base",
|
||||
id: "branch-range",
|
||||
kind: "branch-range",
|
||||
title: "Against main",
|
||||
baseRef: "main",
|
||||
headRef: "feature",
|
||||
diff: "diff --git a/a.ts b/a.ts",
|
||||
diffHash: "hash-base",
|
||||
truncated: false,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -91,7 +97,12 @@ describe("buildReviewSectionItems", () => {
|
||||
},
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.id)).toEqual(["turn:2", "turn:1", "git:dirty", "git:base"]);
|
||||
expect(items.map((item) => item.id)).toEqual([
|
||||
"turn:2",
|
||||
"turn:1",
|
||||
"git:working-tree",
|
||||
"git:branch-range",
|
||||
]);
|
||||
expect(items[0]).toMatchObject({ isLoading: true, diff: null });
|
||||
expect(items[1]).toMatchObject({
|
||||
isLoading: false,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { parsePatchFiles, type ChangeTypes, type FileDiffMetadata } from "@pierre/diffs/utils";
|
||||
import type { GitReviewDiffSection, OrchestrationCheckpointSummary } from "@t3tools/contracts";
|
||||
import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
export type ReviewSectionKind = "turn" | "dirty" | "base";
|
||||
export type ReviewSectionKind = "turn" | "working-tree" | "branch-range";
|
||||
|
||||
export interface ReviewSectionItem {
|
||||
readonly id: string;
|
||||
@@ -149,8 +149,8 @@ const readyCheckpointOrder = Order.make<OrchestrationCheckpointSummary>(
|
||||
compareCheckpointTurnCountDescending,
|
||||
);
|
||||
|
||||
function gitSubtitle(section: GitReviewDiffSection): string | null {
|
||||
if (section.kind === "dirty") {
|
||||
function gitSubtitle(section: ReviewDiffPreviewSource): string | null {
|
||||
if (section.kind === "working-tree") {
|
||||
return "Tracked, staged, and untracked worktree changes";
|
||||
}
|
||||
if (section.baseRef) {
|
||||
@@ -520,7 +520,7 @@ export function getReadyReviewCheckpoints(
|
||||
|
||||
export function buildReviewSectionItems(input: {
|
||||
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
|
||||
readonly gitSections: ReadonlyArray<GitReviewDiffSection>;
|
||||
readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
|
||||
readonly turnDiffById: Readonly<Record<string, string | undefined>>;
|
||||
readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
|
||||
}): ReadonlyArray<ReviewSectionItem> {
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
|
||||
import type { EnvironmentId, GitReviewDiffSection, ThreadId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, ReviewDiffPreviewSource, ThreadId } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { buildReviewParsedDiff, type ReviewParsedDiff } from "./reviewModel";
|
||||
|
||||
const EMPTY_GIT_REVIEW_SECTIONS = Object.freeze<ReadonlyArray<GitReviewDiffSection>>([]);
|
||||
const EMPTY_GIT_REVIEW_SECTIONS = Object.freeze<ReadonlyArray<ReviewDiffPreviewSource>>([]);
|
||||
const EMPTY_REVIEW_TURN_DIFFS = Object.freeze<Readonly<Record<string, string>>>({});
|
||||
const EMPTY_REVIEW_SECTION_FILE_IDS = Object.freeze<
|
||||
Readonly<Record<string, ReadonlyArray<string> | undefined>>
|
||||
@@ -134,7 +134,7 @@ export function useReviewCacheForThread(input: {
|
||||
|
||||
export function setReviewGitSections(
|
||||
threadKey: string,
|
||||
sections: ReadonlyArray<GitReviewDiffSection>,
|
||||
sections: ReadonlyArray<ReviewDiffPreviewSource>,
|
||||
): void {
|
||||
appAtomRegistry.set(reviewGitSectionsByThreadKeyAtom(threadKey), sections);
|
||||
}
|
||||
|
||||
@@ -58,6 +58,29 @@ export const COMPOSER_COLLAPSED_CHROME = 68;
|
||||
*/
|
||||
export const COMPOSER_EXPANDED_CHROME = 174;
|
||||
|
||||
/**
|
||||
* Height of the expanded-only toolbar below the text surface.
|
||||
* Used by the feed inset because KeyboardAvoidingLegendList only accounts for
|
||||
* keyboard height; the floating toolbar remains an additional overlay.
|
||||
*/
|
||||
export const COMPOSER_EXPANDED_TOOLBAR_CHROME = 54;
|
||||
|
||||
function withModelSelectionOption(
|
||||
selection: ModelSelection,
|
||||
id: string,
|
||||
value: string | boolean | undefined,
|
||||
): ModelSelection {
|
||||
const options = (selection.options ?? []).filter((option) => option.id !== id);
|
||||
if (value !== undefined) {
|
||||
options.push({ id, value });
|
||||
}
|
||||
if (options.length === 0) {
|
||||
const { options: _options, ...rest } = selection;
|
||||
return rest as ModelSelection;
|
||||
}
|
||||
return { ...selection, options } as ModelSelection;
|
||||
}
|
||||
|
||||
export interface ThreadComposerProps {
|
||||
readonly draftMessage: string;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
|
||||
@@ -33,6 +33,7 @@ import { PendingUserInputCard } from "./PendingUserInputCard";
|
||||
import {
|
||||
COMPOSER_COLLAPSED_CHROME,
|
||||
COMPOSER_EXPANDED_CHROME,
|
||||
COMPOSER_EXPANDED_TOOLBAR_CHROME,
|
||||
ThreadComposer,
|
||||
} from "./ThreadComposer";
|
||||
import { ThreadFeed } from "./ThreadFeed";
|
||||
@@ -213,7 +214,9 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const layoutVariant = props.layoutVariant ?? "compact";
|
||||
const isSplitLayout = layoutVariant === "split";
|
||||
useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
|
||||
const feedBottomInset = Math.max(estimatedOverlayHeight, measuredOverlayHeight) + 8;
|
||||
const expandedToolbarInset = composerExpanded ? COMPOSER_EXPANDED_TOOLBAR_CHROME : 0;
|
||||
const feedBottomInset =
|
||||
Math.max(estimatedOverlayHeight, measuredOverlayHeight) + expandedToolbarInset + 8;
|
||||
|
||||
const completeDrawerGesture = useCallback(() => {
|
||||
void Haptics.selectionAsync();
|
||||
|
||||
@@ -15,8 +15,11 @@ import {
|
||||
Image,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
Text as NativeText,
|
||||
type ColorValue,
|
||||
useColorScheme,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { TouchableOpacity } from "react-native-gesture-handler";
|
||||
@@ -26,6 +29,19 @@ import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import {
|
||||
parseReviewCommentMessageSegments,
|
||||
type ReviewInlineComment,
|
||||
} from "../review/reviewCommentSelection";
|
||||
import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface";
|
||||
import {
|
||||
buildNativeReviewDiffData,
|
||||
createNativeReviewDiffTheme,
|
||||
NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
|
||||
NATIVE_REVIEW_DIFF_ROW_HEIGHT,
|
||||
NATIVE_REVIEW_DIFF_STYLE,
|
||||
} from "../review/nativeReviewDiffAdapter";
|
||||
import { buildReviewParsedDiff } from "../review/reviewModel";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { MobileLayoutVariant } from "../../lib/mobileLayout";
|
||||
import type { ThreadFeedEntry } from "../../lib/threadActivity";
|
||||
@@ -101,6 +117,38 @@ interface MarkdownStyleSet {
|
||||
readonly renderers: CustomRenderers;
|
||||
}
|
||||
|
||||
interface ReviewCommentColors {
|
||||
readonly background: ColorValue;
|
||||
readonly border: ColorValue;
|
||||
readonly mutedBackground: ColorValue;
|
||||
readonly text: ColorValue;
|
||||
readonly mutedText: ColorValue;
|
||||
readonly codeBackground: ColorValue;
|
||||
}
|
||||
|
||||
function useReviewCommentColors(): ReviewCommentColors {
|
||||
const colorScheme = useColorScheme();
|
||||
const isDark = colorScheme === "dark";
|
||||
const background = isDark ? "#151515" : "#ffffff";
|
||||
const border = isDark ? "#2a2a2a" : "#d7d7d7";
|
||||
const mutedBackground = isDark ? "#242424" : "#f2f2f2";
|
||||
const text = isDark ? "#f3f3f3" : "#111111";
|
||||
const mutedText = isDark ? "#8f8f8f" : "#666666";
|
||||
const codeBackground = isDark ? "#0f0f0f" : "#ffffff";
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
background,
|
||||
border,
|
||||
mutedBackground,
|
||||
text,
|
||||
mutedText,
|
||||
codeBackground,
|
||||
}),
|
||||
[background, border, codeBackground, mutedBackground, mutedText, text],
|
||||
);
|
||||
}
|
||||
|
||||
function useMarkdownStyles(): MarkdownStyleSets {
|
||||
const bodyColor = useThemeColor("--color-md-body");
|
||||
const strongColor = useThemeColor("--color-md-strong");
|
||||
@@ -357,6 +405,8 @@ function renderFeedEntry(
|
||||
readonly iconSubtleColor: string | import("react-native").ColorValue;
|
||||
readonly userBubbleColor: string | import("react-native").ColorValue;
|
||||
readonly markdownStyles: MarkdownStyleSets;
|
||||
readonly reviewCommentColors: ReviewCommentColors;
|
||||
readonly reviewCommentBubbleWidth: number;
|
||||
},
|
||||
) {
|
||||
const entry = info.item;
|
||||
@@ -368,23 +418,24 @@ function renderFeedEntry(
|
||||
const styles = isUser ? markdownStyles.user : markdownStyles.assistant;
|
||||
const timestampLabel = `${relativeTime(message.createdAt)}${message.streaming ? " • live" : ""}`;
|
||||
const attachments = message.attachments ?? [];
|
||||
const hasReviewCommentContext = message.text.includes("<review_comment");
|
||||
|
||||
if (isUser) {
|
||||
return (
|
||||
<View className="mb-3.5 items-end gap-1.5">
|
||||
<View className="mb-5 items-end">
|
||||
<View
|
||||
className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5"
|
||||
style={{ backgroundColor: userBubbleColor }}
|
||||
style={{
|
||||
backgroundColor: userBubbleColor,
|
||||
...(hasReviewCommentContext ? { width: props.reviewCommentBubbleWidth } : null),
|
||||
}}
|
||||
>
|
||||
{message.text.trim().length > 0 ? (
|
||||
<Markdown
|
||||
options={{ gfm: true }}
|
||||
renderers={styles.renderers}
|
||||
styles={styles.styles}
|
||||
theme={styles.theme}
|
||||
>
|
||||
{message.text}
|
||||
</Markdown>
|
||||
<UserMessageContent
|
||||
text={message.text}
|
||||
markdownStyles={styles}
|
||||
reviewCommentColors={props.reviewCommentColors}
|
||||
/>
|
||||
) : null}
|
||||
{attachments.map((attachment) => {
|
||||
const uri = messageImageUrl(props.httpBaseUrl, attachment.id);
|
||||
@@ -410,7 +461,7 @@ function renderFeedEntry(
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
<Text className="px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
<Text className="mt-1.5 px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
{timestampLabel}
|
||||
</Text>
|
||||
</View>
|
||||
@@ -424,7 +475,7 @@ function renderFeedEntry(
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="mb-3.5 gap-1.5 px-1">
|
||||
<View className="mb-5 px-1">
|
||||
{message.text.trim().length > 0 ? (
|
||||
<Markdown
|
||||
options={{ gfm: true }}
|
||||
@@ -448,6 +499,7 @@ function renderFeedEntry(
|
||||
<TouchableOpacity
|
||||
key={attachment.id}
|
||||
activeOpacity={0.7}
|
||||
className="mt-1.5"
|
||||
onPress={() => props.onPressImage(uri, headers)}
|
||||
>
|
||||
<Image
|
||||
@@ -458,7 +510,7 @@ function renderFeedEntry(
|
||||
</TouchableOpacity>
|
||||
);
|
||||
})}
|
||||
<Text className="font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
<Text className="mt-1.5 font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
{timestampLabel}
|
||||
</Text>
|
||||
</View>
|
||||
@@ -467,7 +519,7 @@ function renderFeedEntry(
|
||||
|
||||
if (entry.type === "queued-message") {
|
||||
return (
|
||||
<View className="mb-3.5 gap-1.5 items-end">
|
||||
<View className="mb-5 items-end">
|
||||
<View
|
||||
className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5 opacity-60"
|
||||
style={{ backgroundColor: userBubbleColor }}
|
||||
@@ -482,7 +534,7 @@ function renderFeedEntry(
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text className="px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
<Text className="mt-1.5 px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
{entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
|
||||
</Text>
|
||||
</View>
|
||||
@@ -555,11 +607,226 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
function UserMessageContent(props: {
|
||||
readonly text: string;
|
||||
readonly markdownStyles: MarkdownStyleSet;
|
||||
readonly reviewCommentColors: ReviewCommentColors;
|
||||
}) {
|
||||
const segments = parseReviewCommentMessageSegments(props.text);
|
||||
const hasReviewComment = segments.some((segment) => segment.kind === "review-comment");
|
||||
if (!hasReviewComment) {
|
||||
return (
|
||||
<Markdown
|
||||
options={{ gfm: true }}
|
||||
renderers={props.markdownStyles.renderers}
|
||||
styles={props.markdownStyles.styles}
|
||||
theme={props.markdownStyles.theme}
|
||||
>
|
||||
{props.text}
|
||||
</Markdown>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="w-full gap-2">
|
||||
{segments.map((segment) => {
|
||||
if (segment.kind === "review-comment") {
|
||||
return (
|
||||
<ReviewCommentCard
|
||||
key={segment.comment.id}
|
||||
comment={segment.comment}
|
||||
colors={props.reviewCommentColors}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const text = segment.text.trim();
|
||||
if (text.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Markdown
|
||||
key={segment.id}
|
||||
options={{ gfm: true }}
|
||||
renderers={props.markdownStyles.renderers}
|
||||
styles={props.markdownStyles.styles}
|
||||
theme={props.markdownStyles.theme}
|
||||
>
|
||||
{text}
|
||||
</Markdown>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const ReviewCommentCard = memo(function ReviewCommentCard(props: {
|
||||
readonly comment: ReviewInlineComment;
|
||||
readonly colors: ReviewCommentColors;
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const appearanceScheme = colorScheme === "light" ? "light" : "dark";
|
||||
const NativeReviewDiffView = resolveNativeReviewDiffView();
|
||||
const patch = useMemo(() => buildReviewCommentPatch(props.comment), [props.comment]);
|
||||
const parsedDiff = useMemo(
|
||||
() => buildReviewParsedDiff(patch, `thread-review-comment:${props.comment.id}`),
|
||||
[patch, props.comment.id],
|
||||
);
|
||||
const nativeReviewDiffData = useMemo(() => buildNativeReviewDiffData(parsedDiff), [parsedDiff]);
|
||||
const compactNativeRows = useMemo(
|
||||
() => nativeReviewDiffData.rows.filter((row) => row.kind !== "file"),
|
||||
[nativeReviewDiffData.rows],
|
||||
);
|
||||
const nativeReviewDiffTheme = useMemo(
|
||||
() => createNativeReviewDiffTheme(appearanceScheme),
|
||||
[appearanceScheme],
|
||||
);
|
||||
const nativeRowsJson = useMemo(() => JSON.stringify(compactNativeRows), [compactNativeRows]);
|
||||
const nativeThemeJson = useMemo(
|
||||
() => JSON.stringify(nativeReviewDiffTheme),
|
||||
[nativeReviewDiffTheme],
|
||||
);
|
||||
const nativeStyleJson = useMemo(() => JSON.stringify(NATIVE_REVIEW_DIFF_STYLE), []);
|
||||
const nativeDiffHeight = useMemo(
|
||||
() =>
|
||||
Math.min(
|
||||
360,
|
||||
Math.max(
|
||||
112,
|
||||
compactNativeRows.length * NATIVE_REVIEW_DIFF_ROW_HEIGHT +
|
||||
NATIVE_REVIEW_DIFF_STYLE.fileHeaderVerticalMargin,
|
||||
),
|
||||
),
|
||||
[compactNativeRows.length],
|
||||
);
|
||||
const shouldRenderNativeDiff = NativeReviewDiffView != null && compactNativeRows.length > 0;
|
||||
|
||||
return (
|
||||
<View
|
||||
className="w-full overflow-hidden rounded-[16px] border"
|
||||
style={{
|
||||
backgroundColor: props.colors.background,
|
||||
borderColor: props.colors.border,
|
||||
borderCurve: "continuous",
|
||||
}}
|
||||
>
|
||||
<View
|
||||
className="flex-row items-center gap-2 border-b px-3 py-2"
|
||||
style={{ borderColor: props.colors.border }}
|
||||
>
|
||||
<View
|
||||
className="size-6 items-center justify-center rounded-[7px]"
|
||||
style={{ backgroundColor: props.colors.mutedBackground, borderCurve: "continuous" }}
|
||||
>
|
||||
<SymbolView
|
||||
name="doc.text"
|
||||
size={13}
|
||||
tintColor={props.colors.mutedText}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text
|
||||
className="font-mono text-[12px] leading-[16px]"
|
||||
numberOfLines={1}
|
||||
style={{ color: props.colors.text }}
|
||||
>
|
||||
{compactFileName(props.comment.filePath)}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
{shouldRenderNativeDiff ? (
|
||||
<View
|
||||
className="border-t"
|
||||
collapsable={false}
|
||||
style={{
|
||||
backgroundColor: nativeReviewDiffTheme.background,
|
||||
borderColor: props.colors.border,
|
||||
height: nativeDiffHeight,
|
||||
}}
|
||||
>
|
||||
<NativeReviewDiffView
|
||||
collapsable={false}
|
||||
style={StyleSheet.absoluteFillObject}
|
||||
appearanceScheme={appearanceScheme}
|
||||
contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
|
||||
rowHeight={NATIVE_REVIEW_DIFF_ROW_HEIGHT}
|
||||
rowsJson={nativeRowsJson}
|
||||
styleJson={nativeStyleJson}
|
||||
themeJson={nativeThemeJson}
|
||||
/>
|
||||
</View>
|
||||
) : props.comment.diff.trim().length > 0 ? (
|
||||
<ScrollView
|
||||
horizontal
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
showsHorizontalScrollIndicator={false}
|
||||
bounces={false}
|
||||
className="border-t"
|
||||
style={{ backgroundColor: props.colors.codeBackground, borderColor: props.colors.border }}
|
||||
contentContainerStyle={{ padding: 10 }}
|
||||
>
|
||||
<NativeText
|
||||
selectable
|
||||
style={{
|
||||
color: props.colors.text,
|
||||
fontFamily: "ui-monospace",
|
||||
fontSize: 12,
|
||||
lineHeight: 18,
|
||||
}}
|
||||
>
|
||||
{props.comment.diff.trim()}
|
||||
</NativeText>
|
||||
</ScrollView>
|
||||
) : null}
|
||||
{props.comment.text.length > 0 ? (
|
||||
<View className="border-t px-3 py-3" style={{ borderColor: props.colors.border }}>
|
||||
<Text
|
||||
selectable
|
||||
className="text-[15px] leading-[21px]"
|
||||
style={{ color: props.colors.text }}
|
||||
>
|
||||
{props.comment.text}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
function buildReviewCommentPatch(comment: ReviewInlineComment): string {
|
||||
const diff = comment.diff.trim();
|
||||
if (!diff) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (diff.startsWith("diff --git ")) {
|
||||
return diff;
|
||||
}
|
||||
|
||||
const normalizedPath = comment.filePath.replaceAll("\\", "/");
|
||||
return [
|
||||
`diff --git a/${normalizedPath} b/${normalizedPath}`,
|
||||
`--- a/${normalizedPath}`,
|
||||
`+++ b/${normalizedPath}`,
|
||||
diff,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function compactFileName(filePath: string): string {
|
||||
const normalized = filePath.replaceAll("\\", "/");
|
||||
const lastSlashIndex = normalized.lastIndexOf("/");
|
||||
return lastSlashIndex >= 0 ? normalized.slice(lastSlashIndex + 1) : normalized;
|
||||
}
|
||||
|
||||
const IOS_NAV_BAR_HEIGHT = 44;
|
||||
|
||||
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const { width: viewportWidth } = useWindowDimensions();
|
||||
const [copiedRowId, setCopiedRowId] = useState<string | null>(null);
|
||||
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
|
||||
const [expandedImage, setExpandedImage] = useState<{
|
||||
@@ -567,30 +834,22 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
headers?: Record<string, string>;
|
||||
} | null>(null);
|
||||
const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
|
||||
const contentWidth = Math.max(0, viewportWidth - horizontalPadding * 2);
|
||||
const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth);
|
||||
const insets = useSafeAreaInsets();
|
||||
const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;
|
||||
const bottomContentInset = props.contentBottomInset ?? 18;
|
||||
|
||||
const iconSubtleColor = useThemeColor("--color-icon-subtle");
|
||||
const userBubbleColor = useThemeColor("--color-user-bubble");
|
||||
const markdownStyles = useMarkdownStyles();
|
||||
const reviewCommentColors = useReviewCommentColors();
|
||||
|
||||
useEffect(() => {
|
||||
setCopiedRowId(null);
|
||||
setExpandedWorkGroups({});
|
||||
}, [props.threadId]);
|
||||
|
||||
// Scroll to end when the composer expands (keyboard opens) so the latest
|
||||
// message stays visible above the taller composer + keyboard.
|
||||
useEffect(() => {
|
||||
if (props.composerExpanded && props.feed.length > 0) {
|
||||
// Small delay to let KAV + layout settle before scrolling
|
||||
const timer = setTimeout(() => {
|
||||
void listRef.current?.scrollToEnd({ animated: true });
|
||||
}, 100);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [props.composerExpanded, props.feed.length]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (copyFeedbackTimeoutRef.current) {
|
||||
@@ -636,6 +895,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
iconSubtleColor,
|
||||
userBubbleColor,
|
||||
markdownStyles,
|
||||
reviewCommentColors,
|
||||
reviewCommentBubbleWidth,
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
@@ -643,6 +904,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
iconSubtleColor,
|
||||
userBubbleColor,
|
||||
markdownStyles,
|
||||
reviewCommentColors,
|
||||
reviewCommentBubbleWidth,
|
||||
onCopyWorkRow,
|
||||
onPressImage,
|
||||
onToggleWorkGroup,
|
||||
@@ -656,13 +919,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
<ScrollView
|
||||
style={{ flex: 1 }}
|
||||
contentInsetAdjustmentBehavior="never"
|
||||
contentInset={{ top: topContentInset }}
|
||||
contentInset={{ top: topContentInset, bottom: bottomContentInset }}
|
||||
contentOffset={{ x: 0, y: -topContentInset }}
|
||||
scrollIndicatorInsets={{ top: topContentInset }}
|
||||
scrollIndicatorInsets={{ top: topContentInset, bottom: bottomContentInset }}
|
||||
contentContainerStyle={{
|
||||
flexGrow: 1,
|
||||
paddingHorizontal: horizontalPadding,
|
||||
paddingBottom: props.contentBottomInset ?? 18,
|
||||
}}
|
||||
>
|
||||
<EmptyState
|
||||
@@ -681,13 +943,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
style={{ flex: 1 }}
|
||||
alignItemsAtEnd
|
||||
contentInsetAdjustmentBehavior="never"
|
||||
contentInset={{ top: topContentInset }}
|
||||
scrollIndicatorInsets={{ top: topContentInset }}
|
||||
contentInset={{ top: topContentInset, bottom: bottomContentInset }}
|
||||
scrollIndicatorInsets={{ top: topContentInset, bottom: bottomContentInset }}
|
||||
data={props.feed as ThreadFeedEntry[]}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(entry) => `${entry.type}:${entry.id}`}
|
||||
getItemType={(entry) =>
|
||||
entry.type === "message" ? `message:${entry.message.role}` : entry.type
|
||||
}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
estimatedItemSize={80}
|
||||
estimatedItemSize={180}
|
||||
initialScrollAtEnd
|
||||
maintainScrollAtEnd={{
|
||||
on: { layout: true, itemLayout: true, dataChange: true },
|
||||
@@ -699,7 +964,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
paddingHorizontal: horizontalPadding,
|
||||
paddingBottom: props.contentBottomInset ?? 18,
|
||||
}}
|
||||
/>
|
||||
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Context, Effect, Layer } from "effect";
|
||||
|
||||
import {
|
||||
VcsUnsupportedOperationError,
|
||||
type ReviewDiffPreviewError,
|
||||
type ReviewDiffPreviewInput,
|
||||
type ReviewDiffPreviewResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
export interface ReviewServiceShape {
|
||||
readonly getDiffPreview: (
|
||||
input: ReviewDiffPreviewInput,
|
||||
) => Effect.Effect<ReviewDiffPreviewResult, ReviewDiffPreviewError>;
|
||||
}
|
||||
|
||||
export class ReviewService extends Context.Service<ReviewService, ReviewServiceShape>()(
|
||||
"t3/review/ReviewService",
|
||||
) {}
|
||||
|
||||
function emptyDiffPreview(input: ReviewDiffPreviewInput): ReviewDiffPreviewResult {
|
||||
return {
|
||||
cwd: input.cwd,
|
||||
generatedAt: new Date().toISOString(),
|
||||
sources: [],
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeReviewService")(function* () {
|
||||
const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
|
||||
const git = yield* GitVcsDriver;
|
||||
|
||||
const getDiffPreview: ReviewServiceShape["getDiffPreview"] = Effect.fn(
|
||||
"ReviewService.getDiffPreview",
|
||||
)(function* (input) {
|
||||
const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: "auto" });
|
||||
if (!handle) {
|
||||
return emptyDiffPreview(input);
|
||||
}
|
||||
|
||||
const getDriverDiffPreview = handle.driver.getDiffPreview;
|
||||
if (!getDriverDiffPreview) {
|
||||
if (handle.kind === "git") {
|
||||
return yield* git.getReviewDiffPreview(input);
|
||||
}
|
||||
return yield* new VcsUnsupportedOperationError({
|
||||
operation: "ReviewService.getDiffPreview",
|
||||
kind: handle.kind,
|
||||
detail: `The ${handle.kind} VCS driver does not support review diff previews.`,
|
||||
});
|
||||
}
|
||||
|
||||
return yield* getDriverDiffPreview(input);
|
||||
});
|
||||
|
||||
return ReviewService.of({
|
||||
getDiffPreview,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ReviewService, make());
|
||||
@@ -111,6 +111,7 @@ import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as ReviewService from "./review/ReviewService.ts";
|
||||
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||
@@ -326,6 +327,7 @@ const buildAppUnderTest = (options?: {
|
||||
gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>;
|
||||
gitManager?: Partial<GitManagerShape>;
|
||||
sourceControlRepositoryService?: Partial<SourceControlRepositoryService.SourceControlRepositoryServiceShape>;
|
||||
reviewService?: Partial<ReviewService.ReviewServiceShape>;
|
||||
vcsStatusBroadcaster?: Partial<VcsStatusBroadcaster.VcsStatusBroadcasterShape>;
|
||||
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
|
||||
terminalManager?: Partial<TerminalManagerShape>;
|
||||
@@ -496,6 +498,14 @@ const buildAppUnderTest = (options?: {
|
||||
const vcsProvisioningLayer = VcsProvisioningService.layer.pipe(
|
||||
Layer.provide(vcsDriverRegistryLayer),
|
||||
);
|
||||
const reviewLayer = options?.layers?.reviewService
|
||||
? Layer.mock(ReviewService.ReviewService)({
|
||||
...options.layers.reviewService,
|
||||
})
|
||||
: ReviewService.layer.pipe(
|
||||
Layer.provideMerge(gitVcsDriverLayer),
|
||||
Layer.provide(vcsDriverRegistryLayer),
|
||||
);
|
||||
const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster
|
||||
? Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
|
||||
...options.layers.vcsStatusBroadcaster,
|
||||
@@ -610,6 +620,7 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provide(gitManagerLayer),
|
||||
Layer.provide(gitVcsDriverLayer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
Layer.provide(reviewLayer),
|
||||
Layer.provide(vcsProvisioningLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
|
||||
@@ -2724,8 +2735,34 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
createRef: (input) => Effect.succeed({ refName: input.refName }),
|
||||
switchRef: (input) => Effect.succeed({ refName: input.refName }),
|
||||
},
|
||||
vcsDriver: {
|
||||
isInsideWorkTree: () => Effect.succeed(true),
|
||||
reviewService: {
|
||||
getDiffPreview: (input) =>
|
||||
Effect.succeed({
|
||||
cwd: input.cwd,
|
||||
generatedAt: new Date(0).toISOString(),
|
||||
sources: [
|
||||
{
|
||||
id: "working-tree",
|
||||
kind: "working-tree",
|
||||
title: "Dirty worktree",
|
||||
baseRef: "HEAD",
|
||||
headRef: null,
|
||||
diff: "dirty-diff",
|
||||
diffHash: "hash-dirty",
|
||||
truncated: false,
|
||||
},
|
||||
{
|
||||
id: "branch-range",
|
||||
kind: "branch-range",
|
||||
title: "Against main",
|
||||
baseRef: "main",
|
||||
headRef: "feature/demo",
|
||||
diff: "base-diff",
|
||||
diffHash: "hash-base",
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -2833,6 +2870,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const diffPreview = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.reviewGetDiffPreview]({ cwd: "/tmp/repo" }),
|
||||
),
|
||||
);
|
||||
assert.equal(diffPreview.sources[0]?.diff, "dirty-diff");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
|
||||
@@ -56,6 +56,7 @@ import * as VcsProcess from "./vcs/VcsProcess.ts";
|
||||
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as ReviewService from "./review/ReviewService.ts";
|
||||
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
|
||||
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner.ts";
|
||||
@@ -199,11 +200,17 @@ const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.l
|
||||
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
|
||||
);
|
||||
|
||||
const ReviewLayerLive = ReviewService.layer.pipe(
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
);
|
||||
|
||||
const VcsLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(VcsProjectConfig.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
|
||||
Layer.provideMerge(GitWorkflowLayerLive),
|
||||
Layer.provideMerge(ReviewLayerLive),
|
||||
Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
|
||||
Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
|
||||
);
|
||||
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
type VcsCreateRefResult,
|
||||
type VcsCreateWorktreeInput,
|
||||
type VcsCreateWorktreeResult,
|
||||
type ReviewDiffPreviewInput,
|
||||
type ReviewDiffPreviewResult,
|
||||
type VcsInitInput,
|
||||
type VcsListRefsInput,
|
||||
type VcsListRefsResult,
|
||||
@@ -179,6 +181,9 @@ export interface GitVcsDriverShape {
|
||||
cwd: string,
|
||||
baseRef: string,
|
||||
) => Effect.Effect<GitRangeContext, GitCommandError>;
|
||||
readonly getReviewDiffPreview: (
|
||||
input: ReviewDiffPreviewInput,
|
||||
) => Effect.Effect<ReviewDiffPreviewResult, GitCommandError>;
|
||||
readonly readConfigValue: (
|
||||
cwd: string,
|
||||
key: string,
|
||||
|
||||
@@ -14,9 +14,15 @@ import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { createHash } from "node:crypto";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { GitCommandError, type VcsRef } from "@t3tools/contracts";
|
||||
import {
|
||||
GitCommandError,
|
||||
type ReviewDiffPreviewInput,
|
||||
type ReviewDiffPreviewSource,
|
||||
type VcsRef,
|
||||
} from "@t3tools/contracts";
|
||||
import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
|
||||
import { compactTraceAttributes } from "@t3tools/shared/observability";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
@@ -37,8 +43,19 @@ 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 = 120_000;
|
||||
const REVIEW_UNTRACKED_DIFF_MAX_OUTPUT_BYTES = 80_000;
|
||||
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 120_000;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
|
||||
function reviewDiffHash(diff: string): string {
|
||||
return createHash("sha256").update(diff).digest("hex");
|
||||
}
|
||||
|
||||
function splitNullSeparatedPaths(output: string, includeEmpty: boolean): ReadonlyArray<string> {
|
||||
return output.split("\0").filter((path) => (includeEmpty ? true : path.length > 0));
|
||||
}
|
||||
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
const STATUS_UPSTREAM_REFRESH_ENV = Object.freeze({
|
||||
@@ -1630,6 +1647,147 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
};
|
||||
});
|
||||
|
||||
const readUntrackedReviewDiffs = Effect.fn("readUntrackedReviewDiffs")(function* (cwd: string) {
|
||||
const untrackedOutput = yield* runGitStdoutWithOptions(
|
||||
"GitVcsDriver.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 { diff: "", truncated: false };
|
||||
}
|
||||
|
||||
const diffs = yield* Effect.forEach(
|
||||
untrackedPaths,
|
||||
(relativePath) =>
|
||||
executeGit(
|
||||
"GitVcsDriver.readUntrackedReviewDiffs.diff",
|
||||
cwd,
|
||||
["diff", "--no-index", "--patch", "--minimal", "--", "/dev/null", relativePath],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: REVIEW_UNTRACKED_DIFF_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
},
|
||||
),
|
||||
{ concurrency: 4 },
|
||||
);
|
||||
|
||||
return {
|
||||
diff: diffs
|
||||
.map((result) => result.stdout)
|
||||
.filter((diff) => diff.trim().length > 0)
|
||||
.join("\n"),
|
||||
truncated: diffs.some((result) => result.stdoutTruncated),
|
||||
};
|
||||
});
|
||||
|
||||
const getReviewDiffPreview = Effect.fn("getReviewDiffPreview")(function* (
|
||||
input: ReviewDiffPreviewInput,
|
||||
) {
|
||||
const details = yield* statusDetailsLocal(input.cwd);
|
||||
if (!details.isRepo) {
|
||||
return {
|
||||
cwd: input.cwd,
|
||||
generatedAt: new Date().toISOString(),
|
||||
sources: [],
|
||||
};
|
||||
}
|
||||
|
||||
const branch = details.branch;
|
||||
const baseRef =
|
||||
input.baseRef ??
|
||||
(branch
|
||||
? yield* resolveBaseBranchForNoUpstream(input.cwd, branch).pipe(
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
)
|
||||
: null);
|
||||
|
||||
const dirtyTrackedResult = yield* executeGit(
|
||||
"GitVcsDriver.getReviewDiffPreview.dirtyTracked",
|
||||
input.cwd,
|
||||
["diff", "--patch", "--minimal", "HEAD", "--"],
|
||||
{
|
||||
maxOutputBytes: REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed({
|
||||
exitCode: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const dirtyUntracked = yield* readUntrackedReviewDiffs(input.cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed({ diff: "", truncated: false })),
|
||||
);
|
||||
const dirtyDiff = [dirtyTrackedResult.stdout.trimEnd(), dirtyUntracked.diff.trimEnd()]
|
||||
.filter((diff) => diff.length > 0)
|
||||
.join("\n");
|
||||
|
||||
const baseResult =
|
||||
baseRef && branch
|
||||
? yield* executeGit(
|
||||
"GitVcsDriver.getReviewDiffPreview.base",
|
||||
input.cwd,
|
||||
["diff", "--patch", "--minimal", `${baseRef}...HEAD`],
|
||||
{
|
||||
maxOutputBytes: REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed({
|
||||
exitCode: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
),
|
||||
)
|
||||
: null;
|
||||
const baseDiff = baseResult?.stdout ?? "";
|
||||
|
||||
const sources: ReviewDiffPreviewSource[] = [
|
||||
{
|
||||
id: "working-tree",
|
||||
kind: "working-tree",
|
||||
title: "Dirty worktree",
|
||||
baseRef: "HEAD",
|
||||
headRef: null,
|
||||
diff: dirtyDiff,
|
||||
diffHash: reviewDiffHash(dirtyDiff),
|
||||
truncated: dirtyTrackedResult.stdoutTruncated || dirtyUntracked.truncated,
|
||||
},
|
||||
{
|
||||
id: "branch-range",
|
||||
kind: "branch-range",
|
||||
title: baseRef ? `Against ${baseRef}` : "Against base branch",
|
||||
baseRef,
|
||||
headRef: branch ?? "HEAD",
|
||||
diff: baseDiff,
|
||||
diffHash: reviewDiffHash(baseDiff),
|
||||
truncated: baseResult?.stdoutTruncated ?? false,
|
||||
},
|
||||
];
|
||||
|
||||
return {
|
||||
cwd: input.cwd,
|
||||
generatedAt: new Date().toISOString(),
|
||||
sources,
|
||||
};
|
||||
});
|
||||
|
||||
const readConfigValue: GitVcsDriver.GitVcsDriverShape["readConfigValue"] = (cwd, key) =>
|
||||
runGitStdout("GitVcsDriver.readConfigValue", cwd, ["config", "--get", key], true).pipe(
|
||||
Effect.map((stdout) => stdout.trim()),
|
||||
@@ -2124,6 +2282,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
pushCurrentBranch,
|
||||
pullCurrentBranch,
|
||||
readRangeContext,
|
||||
getReviewDiffPreview,
|
||||
readConfigValue,
|
||||
listRefs,
|
||||
createWorktree,
|
||||
|
||||
@@ -7,6 +7,8 @@ import type {
|
||||
VcsInitInput,
|
||||
VcsListRemotesResult,
|
||||
VcsListWorkspaceFilesResult,
|
||||
ReviewDiffPreviewInput,
|
||||
ReviewDiffPreviewResult,
|
||||
VcsRepositoryIdentity,
|
||||
} from "@t3tools/contracts";
|
||||
import { CheckpointRef } from "@t3tools/contracts";
|
||||
@@ -67,6 +69,9 @@ export interface VcsDriverShape {
|
||||
relativePaths: ReadonlyArray<string>,
|
||||
) => Effect.Effect<ReadonlyArray<string>, VcsError>;
|
||||
readonly initRepository: (input: VcsInitInput) => Effect.Effect<void, VcsError>;
|
||||
readonly getDiffPreview?: (
|
||||
input: ReviewDiffPreviewInput,
|
||||
) => Effect.Effect<ReviewDiffPreviewResult, VcsError>;
|
||||
}
|
||||
|
||||
export class VcsDriver extends Context.Service<VcsDriver, VcsDriverShape>()("t3/vcs/VcsDriver") {}
|
||||
@@ -64,6 +64,7 @@ import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePat
|
||||
import { VcsStatusBroadcaster } from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import { VcsProvisioningService } from "./vcs/VcsProvisioningService.ts";
|
||||
import { GitWorkflowService } from "./git/GitWorkflowService.ts";
|
||||
import { ReviewService } from "./review/ReviewService.ts";
|
||||
import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner.ts";
|
||||
import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
|
||||
@@ -169,6 +170,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const keybindings = yield* Keybindings;
|
||||
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const review = yield* ReviewService;
|
||||
const vcsProvisioning = yield* VcsProvisioningService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
@@ -1105,9 +1107,9 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
.pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
),
|
||||
[WS_METHODS.gitGetReviewDiffs]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.gitGetReviewDiffs, git.getReviewDiffs(input), {
|
||||
"rpc.aggregate": "git",
|
||||
[WS_METHODS.reviewGetDiffPreview]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.reviewGetDiffPreview, review.getDiffPreview(input), {
|
||||
"rpc.aggregate": "review",
|
||||
}),
|
||||
[WS_METHODS.terminalOpen]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
|
||||
|
||||
@@ -217,6 +217,7 @@ function createMockEnvironmentApi(input: {
|
||||
sourceControl: {} as EnvironmentApi["sourceControl"],
|
||||
vcs: {} as EnvironmentApi["vcs"],
|
||||
git: {} as EnvironmentApi["git"],
|
||||
review: {} as EnvironmentApi["review"],
|
||||
orchestration: {
|
||||
dispatchCommand: input.dispatchCommand,
|
||||
getTurnDiff: (() => {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { parsePatchFiles } from "@pierre/diffs";
|
||||
import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
|
||||
import { FileDiff, Virtualizer } from "@pierre/diffs/react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime";
|
||||
@@ -29,8 +28,13 @@ import { readLocalApi } from "../localApi";
|
||||
import { resolvePathLinkTarget } from "../terminal-links";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||
import { resolveDiffThemeName } from "../lib/diffRendering";
|
||||
import {
|
||||
buildFileDiffRenderKey,
|
||||
getDiffCollapseIconClassName,
|
||||
getRenderablePatch,
|
||||
resolveDiffThemeName,
|
||||
resolveFileDiffPath,
|
||||
} from "../lib/diffRendering";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { selectProjectByRef, useStore } from "../store";
|
||||
import { createThreadSelectorByRef } from "../storeSelectors";
|
||||
@@ -107,76 +111,6 @@ const DIFF_PANEL_UNSAFE_CSS = `
|
||||
}
|
||||
`;
|
||||
|
||||
type RenderablePatch =
|
||||
| {
|
||||
kind: "files";
|
||||
files: FileDiffMetadata[];
|
||||
}
|
||||
| {
|
||||
kind: "raw";
|
||||
text: string;
|
||||
reason: string;
|
||||
};
|
||||
|
||||
function getRenderablePatch(
|
||||
patch: string | undefined,
|
||||
cacheScope = "diff-panel",
|
||||
): RenderablePatch | null {
|
||||
if (!patch) return null;
|
||||
const normalizedPatch = patch.trim();
|
||||
if (normalizedPatch.length === 0) return null;
|
||||
|
||||
try {
|
||||
const parsedPatches = parsePatchFiles(
|
||||
normalizedPatch,
|
||||
buildPatchCacheKey(normalizedPatch, cacheScope),
|
||||
);
|
||||
const files = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
|
||||
if (files.length > 0) {
|
||||
return { kind: "files", files };
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "raw",
|
||||
text: normalizedPatch,
|
||||
reason: "Unsupported diff format. Showing raw patch.",
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
kind: "raw",
|
||||
text: normalizedPatch,
|
||||
reason: "Failed to parse patch. Showing raw patch.",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
|
||||
const raw = fileDiff.name ?? fileDiff.prevName ?? "";
|
||||
if (raw.startsWith("a/") || raw.startsWith("b/")) {
|
||||
return raw.slice(2);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
|
||||
return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
|
||||
}
|
||||
|
||||
function getDiffCollapseIconClassName(fileDiff: FileDiffMetadata): string {
|
||||
switch (fileDiff.type) {
|
||||
case "new":
|
||||
return "text-[var(--diffs-addition-base)]";
|
||||
case "deleted":
|
||||
return "text-[var(--diffs-deletion-base)]";
|
||||
case "change":
|
||||
case "rename-pure":
|
||||
case "rename-changed":
|
||||
return "text-[var(--diffs-modified-base)]";
|
||||
default:
|
||||
return "text-muted-foreground/80";
|
||||
}
|
||||
}
|
||||
|
||||
interface DiffPanelProps {
|
||||
mode?: DiffPanelMode;
|
||||
}
|
||||
|
||||
@@ -27,6 +27,25 @@ vi.mock("@legendapp/list/react", async () => {
|
||||
return { LegendList };
|
||||
});
|
||||
|
||||
function MockFileDiff(props: {
|
||||
fileDiff: { name?: string | null; prevName?: string | null };
|
||||
renderCustomHeader?: (fileDiff: {
|
||||
name?: string | null;
|
||||
prevName?: string | null;
|
||||
}) => React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div data-testid="file-diff">
|
||||
{props.renderCustomHeader?.(props.fileDiff)}
|
||||
{props.fileDiff.name ?? props.fileDiff.prevName ?? "diff"}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
vi.mock("@pierre/diffs/react", () => {
|
||||
return { FileDiff: MockFileDiff };
|
||||
});
|
||||
|
||||
function matchMedia() {
|
||||
return {
|
||||
matches: false,
|
||||
@@ -238,4 +257,43 @@ describe("MessagesTimeline", () => {
|
||||
expect(markup).toContain("t3code/apps/web/src/session-logic.ts");
|
||||
expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
|
||||
});
|
||||
|
||||
it("renders review comment contexts as structured cards instead of raw tags", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-1",
|
||||
kind: "message",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
message: {
|
||||
id: MessageId.make("message-2"),
|
||||
role: "user",
|
||||
text: [
|
||||
'<review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
|
||||
"Wadduo",
|
||||
"```diff",
|
||||
"@@ -0,0 +47,2 @@",
|
||||
'+ it("keeps valid zero-usage snapshots", () => {',
|
||||
"+ expect(snapshot).not.toBeNull();",
|
||||
"```",
|
||||
"</review_comment>",
|
||||
].join("\n"),
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("contextWindow.test.ts");
|
||||
expect(markup).toContain("Wadduo");
|
||||
expect(markup).toContain('data-testid="file-diff"');
|
||||
expect(markup).not.toContain(">Review comment<");
|
||||
expect(markup).not.toContain("<review_comment");
|
||||
expect(markup).not.toContain("</review_comment>");
|
||||
});
|
||||
});
|
||||
@@ -44,7 +44,9 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
|
||||
git: {
|
||||
resolvePullRequest: rpcClient.git.resolvePullRequest,
|
||||
preparePullRequestThread: rpcClient.git.preparePullRequestThread,
|
||||
getReviewDiffs: rpcClient.git.getReviewDiffs,
|
||||
},
|
||||
review: {
|
||||
getDiffPreview: rpcClient.review.getDiffPreview,
|
||||
},
|
||||
orchestration: {
|
||||
dispatchCommand: rpcClient.orchestration.dispatchCommand,
|
||||
|
||||
@@ -85,7 +85,9 @@ function createTestClient() {
|
||||
runStackedAction: vi.fn(async () => ({}) as any),
|
||||
resolvePullRequest: vi.fn(async () => undefined),
|
||||
preparePullRequestThread: vi.fn(async () => undefined),
|
||||
getReviewDiffs: vi.fn(async () => undefined),
|
||||
},
|
||||
review: {
|
||||
getDiffPreview: vi.fn(async () => undefined),
|
||||
},
|
||||
} as unknown as WsRpcClient;
|
||||
|
||||
|
||||
@@ -121,7 +121,9 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => {
|
||||
init: vi.fn(),
|
||||
resolvePullRequest: vi.fn(),
|
||||
preparePullRequestThread: vi.fn(),
|
||||
getReviewDiffs: vi.fn(),
|
||||
},
|
||||
review: {
|
||||
getDiffPreview: vi.fn(),
|
||||
},
|
||||
server: {
|
||||
getConfig: vi.fn(),
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { parsePatchFiles } from "@pierre/diffs";
|
||||
import type { FileDiffMetadata } from "@pierre/diffs/react";
|
||||
|
||||
export const DIFF_THEME_NAMES = {
|
||||
light: "pierre-light",
|
||||
dark: "pierre-dark",
|
||||
@@ -37,3 +40,73 @@ export function buildPatchCacheKey(patch: string, scope = "diff-panel"): string
|
||||
).toString(36);
|
||||
return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;
|
||||
}
|
||||
|
||||
export type RenderablePatch =
|
||||
| {
|
||||
kind: "files";
|
||||
files: FileDiffMetadata[];
|
||||
}
|
||||
| {
|
||||
kind: "raw";
|
||||
text: string;
|
||||
reason: string;
|
||||
};
|
||||
|
||||
export function getRenderablePatch(
|
||||
patch: string | undefined,
|
||||
cacheScope = "diff-panel",
|
||||
): RenderablePatch | null {
|
||||
if (!patch) return null;
|
||||
const normalizedPatch = patch.trim();
|
||||
if (normalizedPatch.length === 0) return null;
|
||||
|
||||
try {
|
||||
const parsedPatches = parsePatchFiles(
|
||||
normalizedPatch,
|
||||
buildPatchCacheKey(normalizedPatch, cacheScope),
|
||||
);
|
||||
const files = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
|
||||
if (files.length > 0) {
|
||||
return { kind: "files", files };
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "raw",
|
||||
text: normalizedPatch,
|
||||
reason: "Unsupported diff format. Showing raw patch.",
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
kind: "raw",
|
||||
text: normalizedPatch,
|
||||
reason: "Failed to parse patch. Showing raw patch.",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
|
||||
const raw = fileDiff.name ?? fileDiff.prevName ?? "";
|
||||
if (raw.startsWith("a/") || raw.startsWith("b/")) {
|
||||
return raw.slice(2);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
export function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
|
||||
return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
|
||||
}
|
||||
|
||||
export function getDiffCollapseIconClassName(fileDiff: FileDiffMetadata): string {
|
||||
switch (fileDiff.type) {
|
||||
case "new":
|
||||
return "text-[var(--diffs-addition-base)]";
|
||||
case "deleted":
|
||||
return "text-[var(--diffs-deletion-base)]";
|
||||
case "change":
|
||||
case "rename-pure":
|
||||
case "rename-changed":
|
||||
return "text-[var(--diffs-modified-base)]";
|
||||
default:
|
||||
return "text-muted-foreground/80";
|
||||
}
|
||||
}
|
||||
@@ -86,7 +86,9 @@ const rpcClientMock = {
|
||||
runStackedAction: vi.fn(),
|
||||
resolvePullRequest: vi.fn(),
|
||||
preparePullRequestThread: vi.fn(),
|
||||
getReviewDiffs: vi.fn(),
|
||||
},
|
||||
review: {
|
||||
getDiffPreview: vi.fn(),
|
||||
},
|
||||
server: {
|
||||
getConfig: vi.fn(),
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildReviewCommentRenderablePatch,
|
||||
parseReviewCommentMessageSegments,
|
||||
} from "./reviewCommentContext";
|
||||
|
||||
describe("review comment context parsing", () => {
|
||||
it("extracts comment metadata, user text, and fenced diff without raw wrapper text", () => {
|
||||
const segments = parseReviewCommentMessageSegments(
|
||||
[
|
||||
'Before <review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
|
||||
"Wadduo",
|
||||
"```diff",
|
||||
"@@ -0,0 +47,2 @@",
|
||||
'+ it("keeps valid zero-usage snapshots", () => {',
|
||||
"+ expect(snapshot).not.toBeNull();",
|
||||
"```",
|
||||
"</review_comment> after",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(segments).toHaveLength(3);
|
||||
expect(segments[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
kind: "text",
|
||||
text: expect.stringContaining("Before"),
|
||||
}),
|
||||
);
|
||||
expect(segments[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
kind: "review-comment",
|
||||
comment: expect.objectContaining({
|
||||
filePath: "apps/web/src/lib/contextWindow.test.ts",
|
||||
rangeLabel: "+47 to +58",
|
||||
text: "Wadduo",
|
||||
diff: expect.stringContaining('it("keeps valid zero-usage snapshots"'),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(segments[2]).toEqual(
|
||||
expect.objectContaining({
|
||||
kind: "text",
|
||||
text: " after",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("wraps hunk-only review diffs in a renderable file patch", () => {
|
||||
const [segment] = parseReviewCommentMessageSegments(
|
||||
[
|
||||
'<review_comment sectionId="s" filePath="src/app.ts" startIndex="0" endIndex="0">',
|
||||
"Please check this.",
|
||||
"```diff",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"```",
|
||||
"</review_comment>",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(segment?.kind).toBe("review-comment");
|
||||
if (segment?.kind !== "review-comment") return;
|
||||
|
||||
expect(buildReviewCommentRenderablePatch(segment.comment)).toBe(
|
||||
[
|
||||
"diff --git a/src/app.ts b/src/app.ts",
|
||||
"--- a/src/app.ts",
|
||||
"+++ b/src/app.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
export interface ReviewCommentContext {
|
||||
readonly id: string;
|
||||
readonly sectionId: string;
|
||||
readonly sectionTitle: string;
|
||||
readonly filePath: string;
|
||||
readonly startIndex: number;
|
||||
readonly endIndex: number;
|
||||
readonly rangeLabel: string;
|
||||
readonly text: string;
|
||||
readonly diff: string;
|
||||
}
|
||||
|
||||
export type ReviewCommentMessageSegment =
|
||||
| {
|
||||
readonly kind: "text";
|
||||
readonly id: string;
|
||||
readonly text: string;
|
||||
}
|
||||
| {
|
||||
readonly kind: "review-comment";
|
||||
readonly comment: ReviewCommentContext;
|
||||
};
|
||||
|
||||
const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
|
||||
const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g;
|
||||
const REVIEW_COMMENT_DIFF_FENCE_PATTERN = /```diff\s*\n([\s\S]*?)\n```/;
|
||||
|
||||
function unescapeReviewCommentAttribute(value: string): string {
|
||||
return value
|
||||
.replace(/</g, "<")
|
||||
.replace(/"/g, '"')
|
||||
.replace(/&/g, "&");
|
||||
}
|
||||
|
||||
function readReviewCommentAttributes(rawAttributes: string): Record<string, string> {
|
||||
const attributes: Record<string, string> = {};
|
||||
for (const match of rawAttributes.matchAll(REVIEW_COMMENT_ATTRIBUTE_PATTERN)) {
|
||||
attributes[match[1]!] = unescapeReviewCommentAttribute(match[2] ?? "");
|
||||
}
|
||||
return attributes;
|
||||
}
|
||||
|
||||
function readNonNegativeInteger(value: string | undefined): number | null {
|
||||
if (value === undefined || !/^\d+$/.test(value)) {
|
||||
return null;
|
||||
}
|
||||
return Number(value);
|
||||
}
|
||||
|
||||
function extractReviewCommentText(rawBody: string): string {
|
||||
const fenceIndex = rawBody.indexOf("```diff");
|
||||
const commentBody = fenceIndex >= 0 ? rawBody.slice(0, fenceIndex) : rawBody;
|
||||
return commentBody.trim();
|
||||
}
|
||||
|
||||
function extractReviewCommentDiff(rawBody: string): string {
|
||||
return rawBody.match(REVIEW_COMMENT_DIFF_FENCE_PATTERN)?.[1]?.trim() ?? "";
|
||||
}
|
||||
|
||||
function parseReviewCommentContext(
|
||||
rawAttributes: string,
|
||||
rawBody: string,
|
||||
index: number,
|
||||
): ReviewCommentContext | null {
|
||||
const attributes = readReviewCommentAttributes(rawAttributes);
|
||||
const startIndex = readNonNegativeInteger(attributes.startIndex);
|
||||
const endIndex = readNonNegativeInteger(attributes.endIndex);
|
||||
const filePath = attributes.filePath?.trim();
|
||||
const sectionId = attributes.sectionId?.trim();
|
||||
if (!filePath || !sectionId || startIndex === null || endIndex === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`,
|
||||
sectionId,
|
||||
sectionTitle: attributes.sectionTitle?.trim() || "Review",
|
||||
filePath,
|
||||
startIndex: Math.min(startIndex, endIndex),
|
||||
endIndex: Math.max(startIndex, endIndex),
|
||||
rangeLabel: attributes.rangeLabel?.trim() || "line",
|
||||
text: extractReviewCommentText(rawBody),
|
||||
diff: extractReviewCommentDiff(rawBody),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseReviewCommentMessageSegments(
|
||||
value: string,
|
||||
): ReadonlyArray<ReviewCommentMessageSegment> {
|
||||
const segments: ReviewCommentMessageSegment[] = [];
|
||||
let cursor = 0;
|
||||
let parsedCommentIndex = 0;
|
||||
|
||||
for (const match of value.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)) {
|
||||
const matchIndex = match.index ?? 0;
|
||||
const beforeText = value.slice(cursor, matchIndex);
|
||||
if (beforeText.length > 0) {
|
||||
segments.push({
|
||||
kind: "text",
|
||||
id: `review-comment-text:${cursor}`,
|
||||
text: beforeText,
|
||||
});
|
||||
}
|
||||
|
||||
const comment = parseReviewCommentContext(match[1] ?? "", match[2] ?? "", parsedCommentIndex);
|
||||
if (comment) {
|
||||
segments.push({ kind: "review-comment", comment });
|
||||
parsedCommentIndex += 1;
|
||||
} else {
|
||||
segments.push({
|
||||
kind: "text",
|
||||
id: `review-comment-invalid:${matchIndex}`,
|
||||
text: match[0],
|
||||
});
|
||||
}
|
||||
|
||||
cursor = matchIndex + match[0].length;
|
||||
}
|
||||
|
||||
const rest = value.slice(cursor);
|
||||
if (rest.length > 0) {
|
||||
segments.push({
|
||||
kind: "text",
|
||||
id: `review-comment-text:${cursor}`,
|
||||
text: rest,
|
||||
});
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
export function hasReviewCommentMessageSegments(value: string): boolean {
|
||||
return parseReviewCommentMessageSegments(value).some(
|
||||
(segment) => segment.kind === "review-comment",
|
||||
);
|
||||
}
|
||||
|
||||
export function buildReviewCommentRenderablePatch(comment: ReviewCommentContext): string {
|
||||
const diff = comment.diff.trim();
|
||||
if (diff.length === 0) {
|
||||
return "";
|
||||
}
|
||||
if (diff.startsWith("diff --git ")) {
|
||||
return diff;
|
||||
}
|
||||
|
||||
const normalizedPath = comment.filePath.replaceAll("\\", "/");
|
||||
return [
|
||||
`diff --git a/${normalizedPath} b/${normalizedPath}`,
|
||||
`--- a/${normalizedPath}`,
|
||||
`+++ b/${normalizedPath}`,
|
||||
diff,
|
||||
].join("\n");
|
||||
}
|
||||
@@ -56,7 +56,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",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@react-native-menu/menu": "^2.0.0",
|
||||
"@shikijs/core": "3.23.0",
|
||||
"@shikijs/engine-javascript": "3.23.0",
|
||||
|
||||
@@ -99,7 +99,9 @@ export interface WsRpcClient {
|
||||
readonly preparePullRequestThread: RpcUnaryMethod<
|
||||
typeof WS_METHODS.gitPreparePullRequestThread
|
||||
>;
|
||||
readonly getReviewDiffs: RpcUnaryMethod<typeof WS_METHODS.gitGetReviewDiffs>;
|
||||
};
|
||||
readonly review: {
|
||||
readonly getDiffPreview: RpcUnaryMethod<typeof WS_METHODS.reviewGetDiffPreview>;
|
||||
};
|
||||
readonly server: {
|
||||
readonly getConfig: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetConfig>;
|
||||
@@ -218,8 +220,10 @@ export function createWsRpcClient(
|
||||
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)),
|
||||
},
|
||||
review: {
|
||||
getDiffPreview: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.reviewGetDiffPreview](input)),
|
||||
},
|
||||
server: {
|
||||
getConfig: () => transport.request((client) => client[WS_METHODS.serverGetConfig]({})),
|
||||
|
||||
@@ -184,11 +184,6 @@ export const VcsInitInput = Schema.Struct({
|
||||
});
|
||||
export type VcsInitInput = typeof VcsInitInput.Type;
|
||||
|
||||
export const GitReviewDiffsInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type GitReviewDiffsInput = typeof GitReviewDiffsInput.Type;
|
||||
|
||||
// RPC Results
|
||||
|
||||
const VcsStatusChangeRequest = Schema.Struct({
|
||||
@@ -285,25 +280,6 @@ export const VcsSwitchRefResult = Schema.Struct({
|
||||
});
|
||||
export type VcsSwitchRefResult = typeof VcsSwitchRefResult.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({
|
||||
|
||||
@@ -19,4 +19,5 @@ export * from "./orchestration.ts";
|
||||
export * from "./editor.ts";
|
||||
export * from "./project.ts";
|
||||
export * from "./filesystem.ts";
|
||||
export * from "./review.ts";
|
||||
export * from "./rpc.ts";
|
||||
@@ -14,12 +14,11 @@ import type {
|
||||
GitPreparePullRequestThreadInput,
|
||||
GitPreparePullRequestThreadResult,
|
||||
GitPullRequestRefInput,
|
||||
GitReviewDiffsInput,
|
||||
GitReviewDiffsResult,
|
||||
GitResolvePullRequestResult,
|
||||
VcsStatusInput,
|
||||
VcsStatusResult,
|
||||
} from "./git.ts";
|
||||
import type { ReviewDiffPreviewInput, ReviewDiffPreviewResult } from "./review.ts";
|
||||
import type { FilesystemBrowseInput, FilesystemBrowseResult } from "./filesystem.ts";
|
||||
import type {
|
||||
ProjectSearchEntriesInput,
|
||||
@@ -559,7 +558,9 @@ export interface EnvironmentApi {
|
||||
preparePullRequestThread: (
|
||||
input: GitPreparePullRequestThreadInput,
|
||||
) => Promise<GitPreparePullRequestThreadResult>;
|
||||
getReviewDiffs: (input: GitReviewDiffsInput) => Promise<GitReviewDiffsResult>;
|
||||
};
|
||||
review: {
|
||||
getDiffPreview: (input: ReviewDiffPreviewInput) => Promise<ReviewDiffPreviewResult>;
|
||||
};
|
||||
orchestration: {
|
||||
dispatchCommand: (command: ClientOrchestrationCommand) => Promise<{ sequence: number }>;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Schema } from "effect";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import { GitCommandError } from "./git.ts";
|
||||
import { VcsError } from "./vcs.ts";
|
||||
|
||||
export const ReviewDiffPreviewInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
baseRef: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type ReviewDiffPreviewInput = typeof ReviewDiffPreviewInput.Type;
|
||||
|
||||
export const ReviewDiffPreviewSourceKind = Schema.Literals(["working-tree", "branch-range"]);
|
||||
export type ReviewDiffPreviewSourceKind = typeof ReviewDiffPreviewSourceKind.Type;
|
||||
|
||||
export const ReviewDiffPreviewSource = Schema.Struct({
|
||||
id: TrimmedNonEmptyString,
|
||||
kind: ReviewDiffPreviewSourceKind,
|
||||
title: TrimmedNonEmptyString,
|
||||
baseRef: Schema.NullOr(TrimmedNonEmptyString),
|
||||
headRef: Schema.NullOr(TrimmedNonEmptyString),
|
||||
diff: Schema.String,
|
||||
diffHash: TrimmedNonEmptyString,
|
||||
truncated: Schema.Boolean,
|
||||
});
|
||||
export type ReviewDiffPreviewSource = typeof ReviewDiffPreviewSource.Type;
|
||||
|
||||
export const ReviewDiffPreviewResult = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
generatedAt: Schema.String,
|
||||
sources: Schema.Array(ReviewDiffPreviewSource),
|
||||
});
|
||||
export type ReviewDiffPreviewResult = typeof ReviewDiffPreviewResult.Type;
|
||||
|
||||
export const ReviewDiffPreviewError = Schema.Union([VcsError, GitCommandError]);
|
||||
export type ReviewDiffPreviewError = typeof ReviewDiffPreviewError.Type;
|
||||
@@ -34,6 +34,11 @@ import {
|
||||
VcsStatusResult,
|
||||
VcsStatusStreamEvent,
|
||||
} from "./git.ts";
|
||||
import {
|
||||
ReviewDiffPreviewError,
|
||||
ReviewDiffPreviewInput,
|
||||
ReviewDiffPreviewResult,
|
||||
} from "./review.ts";
|
||||
import { KeybindingsConfigError } from "./keybindings.ts";
|
||||
import {
|
||||
ClientOrchestrationCommand,
|
||||
@@ -131,6 +136,9 @@ export const WS_METHODS = {
|
||||
gitResolvePullRequest: "git.resolvePullRequest",
|
||||
gitPreparePullRequestThread: "git.preparePullRequestThread",
|
||||
|
||||
// Review methods
|
||||
reviewGetDiffPreview: "review.getDiffPreview",
|
||||
|
||||
// Terminal methods
|
||||
terminalOpen: "terminal.open",
|
||||
terminalAttach: "terminal.attach",
|
||||
@@ -364,6 +372,17 @@ export const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, {
|
||||
error: VcsError,
|
||||
});
|
||||
|
||||
/**
|
||||
* Ephemeral live diff preview for compact/mobile surfaces.
|
||||
* Not the persisted T3 Review model. Future review sessions should use
|
||||
* review.open* + review.getSnapshot.
|
||||
*/
|
||||
export const WsReviewGetDiffPreviewRpc = Rpc.make(WS_METHODS.reviewGetDiffPreview, {
|
||||
payload: ReviewDiffPreviewInput,
|
||||
success: ReviewDiffPreviewResult,
|
||||
error: ReviewDiffPreviewError,
|
||||
});
|
||||
|
||||
export const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, {
|
||||
payload: TerminalOpenInput,
|
||||
success: TerminalSessionSnapshot,
|
||||
@@ -522,6 +541,7 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsVcsCreateRefRpc,
|
||||
WsVcsSwitchRefRpc,
|
||||
WsVcsInitRpc,
|
||||
WsReviewGetDiffPreviewRpc,
|
||||
WsTerminalOpenRpc,
|
||||
WsTerminalAttachRpc,
|
||||
WsTerminalWriteRpc,
|
||||
|
||||
Reference in new issue
Block a user