Skip to content

Commit aae361c

Browse files
tris203maria-rcks
andauthored
fix(review): show complete counts and load large diffs progressively (#10822)
Co-authored-by: maria-rcks <[email protected]>
1 parent 32e8b25 commit aae361c

22 files changed

Lines changed: 1483 additions & 389 deletions

‎apps/mobile/src/features/review/ReviewSheet.tsx‎

Lines changed: 39 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -382,24 +382,40 @@ export function ReviewSheet(props: ReviewSheetProps) {
382382
useEffect(() => {
383383
showAuxiliaryPane("inspector");
384384
}, [environmentId, showAuxiliaryPane, threadId]);
385-
const { error, reviewSections, selectedSection, refreshSelectedSection, selectSection } =
386-
useReviewSections({
387-
enabled: isEnvironmentReady,
388-
environmentId,
389-
threadId,
390-
reviewCache,
391-
});
385+
const {
386+
error,
387+
reviewSections,
388+
selectedSection,
389+
refreshSelectedSection,
390+
selectSection,
391+
isSelectedSectionPending,
392+
diffPreviewRevision,
393+
} = useReviewSections({
394+
enabled: isEnvironmentReady,
395+
environmentId,
396+
threadId,
397+
reviewCache,
398+
});
392399
useReviewDiffPrewarming({
393400
threadKey: reviewCache.threadKey,
394401
sections: reviewSections,
395402
selectedSectionId: selectedSection?.id ?? null,
396403
});
397-
const { headerDiffSummary, nativeReviewDiffData, parsedDiff, pendingReviewCommentCount } =
398-
useReviewDiffData({
399-
threadKey: reviewCache.threadKey,
400-
selectedSection,
401-
draftMessage,
402-
});
404+
const {
405+
headerDiffSummary,
406+
nativeReviewDiffData,
407+
parsedDiff,
408+
pendingReviewCommentCount,
409+
loadVisibleFile,
410+
isPending: areFilePatchesPending,
411+
} = useReviewDiffData({
412+
threadKey: reviewCache.threadKey,
413+
environmentId,
414+
cwd: selectedThreadCwd,
415+
selectedSection,
416+
revision: diffPreviewRevision,
417+
draftMessage,
418+
});
403419
// Resolution returns null while Expo registers the native view (or forever
404420
// when the binary lacks it). Rendering a null component type crashes the
405421
// app, so callers must fall back — ThreadFeed's ReviewCommentCard does the
@@ -469,6 +485,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
469485

470486
const handleSelectFile = useCallback(
471487
(fileId: string | null) => {
488+
loadVisibleFile(fileId, true);
472489
commentSelection.clearSelection();
473490
if (fileId !== null && collapsedFileIds.includes(fileId)) {
474491
toggleExpandedFile(fileId);
@@ -481,13 +498,14 @@ export function ReviewSheet(props: ReviewSheetProps) {
481498
console.error("[review] Failed to navigate to diff file", error);
482499
});
483500
},
484-
[collapsedFileIds, commentSelection, toggleExpandedFile],
501+
[collapsedFileIds, commentSelection, toggleExpandedFile, loadVisibleFile],
485502
);
486503
const handleVisibleFileChange = useCallback(
487504
(event: NativeSyntheticEvent<{ readonly fileId?: string | null }>) => {
505+
loadVisibleFile(event.nativeEvent.fileId ?? null);
488506
reviewFileNavigatorRef.current?.setVisibleFile(event.nativeEvent.fileId ?? null);
489507
},
490-
[],
508+
[loadVisibleFile],
491509
);
492510
const renderInspector = useCallback(
493511
() => (
@@ -508,10 +526,11 @@ export function ReviewSheet(props: ReviewSheetProps) {
508526
(event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
509527
const { fileId } = event.nativeEvent;
510528
if (fileId) {
529+
loadVisibleFile(fileId, true);
511530
toggleExpandedFile(fileId);
512531
}
513532
},
514-
[toggleExpandedFile],
533+
[toggleExpandedFile, loadVisibleFile],
515534
);
516535

517536
const handleNativeToggleViewedFile = useCallback(
@@ -574,12 +593,12 @@ export function ReviewSheet(props: ReviewSheetProps) {
574593
(event: { nativeEvent: { event: string } }) => {
575594
const id = event.nativeEvent.event;
576595
if (id === "refresh") {
577-
void refreshSelectedSection();
596+
void handlePullToRefresh();
578597
} else if (id.startsWith("section:")) {
579598
selectSection(id.slice("section:".length));
580599
}
581600
},
582-
[refreshSelectedSection, selectSection],
601+
[handlePullToRefresh, selectSection],
583602
);
584603
const handleRetryEnvironment = useCallback(() => {
585604
void retryEnvironment(environmentId);
@@ -818,7 +837,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
818837
<NativeReviewDiffView
819838
collapsable={false}
820839
testID="review-native-diff-view"
821-
refreshing={isPullRefreshing}
840+
refreshing={isPullRefreshing || isSelectedSectionPending || areFilePatchesPending}
822841
onPullToRefresh={() => void handlePullToRefresh()}
823842
style={StyleSheet.absoluteFill}
824843
appearanceScheme={selectedTheme}
@@ -862,7 +881,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
862881
// iOS has no other refresh affordance here (the explicit
863882
// "Refresh current diff" menu is Android-only).
864883
<RefreshControl
865-
refreshing={isPullRefreshing}
884+
refreshing={isPullRefreshing || isSelectedSectionPending || areFilePatchesPending}
866885
onRefresh={() => void handlePullToRefresh()}
867886
/>
868887
}

‎apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,29 @@ function appTheme(themeId: MobileThemeId, appearance: MobileThemeAppearance) {
9898
}
9999

100100
describe("getCachedNativeReviewDiffData", () => {
101+
it.each([true, false])(
102+
"preserves available diff rows before a notice (has excerpt: %s)",
103+
(hasExcerpt) => {
104+
if (parsedDiff.kind !== "files") throw new Error("Expected a parsed file diff");
105+
const notice = "This file preview was truncated.";
106+
const result = buildNativeReviewDiffData({
107+
parsedDiff: {
108+
...parsedDiff,
109+
files: parsedDiff.files.map((file) => ({
110+
...file,
111+
rows: hasExcerpt ? file.rows : [],
112+
notice,
113+
})),
114+
},
115+
});
116+
const original = buildNativeReviewDiffData({ parsedDiff });
117+
expect(result.rows.slice(0, -1)).toEqual(
118+
hasExcerpt ? original.rows : original.rows.filter((row) => row.kind === "file"),
119+
);
120+
expect(result.rows.at(-1)).toMatchObject({ kind: "notice", text: notice });
121+
},
122+
);
123+
101124
it("reuses the row model for equivalent empty comment arrays", () => {
102125
const first = getCachedNativeReviewDiffData(buildInput([]));
103126
const second = getCachedNativeReviewDiffData(buildInput([]));

‎apps/mobile/src/features/review/nativeReviewDiffAdapter.ts‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,8 @@ interface PreparedNativeReviewFileRows {
125125
readonly filePath: string;
126126
readonly lineCount: number;
127127
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
128+
readonly commentTargetsByRowId: ReadonlyMap<string, NativeReviewDiffCommentTarget>;
129+
readonly rowIdByCommentLineId: ReadonlyMap<string, string>;
128130
commentedRows: {
129131
readonly commentsKey: string;
130132
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
@@ -136,6 +138,7 @@ interface PreparedNativeReviewDiffData extends Omit<NativeReviewDiffData, "rows"
136138
}
137139

138140
const nativeReviewDiffDataCache = new WeakMap<ReviewParsedDiff, CachedNativeReviewDiffData>();
141+
const nativeReviewFileRowsCache = new WeakMap<ReviewRenderableFile, PreparedNativeReviewFileRows>();
139142

140143
function buildReviewCommentsCacheKey(comments: ReadonlyArray<ReviewInlineComment>): string {
141144
if (comments.length === 0) {
@@ -261,6 +264,7 @@ function createNoticeRow(fileId: string, suffix: string, text: string): NativeRe
261264
}
262265

263266
function noticeRowsForFile(file: ReviewRenderableFile): ReadonlyArray<NativeReviewDiffRow> {
267+
if (file.notice) return [createNoticeRow(file.id, "loading", file.notice)];
264268
if (file.rows.length > 0) {
265269
return [];
266270
}
@@ -406,11 +410,11 @@ function mapLineRow(
406410
};
407411
}
408412

409-
function prepareFileRows(
410-
file: ReviewRenderableFile,
411-
commentTargetsByRowId: Map<string, NativeReviewDiffCommentTarget>,
412-
rowIdByCommentLineId: Map<string, string>,
413-
): PreparedNativeReviewFileRows {
413+
function prepareFileRows(file: ReviewRenderableFile): PreparedNativeReviewFileRows {
414+
const cached = nativeReviewFileRowsCache.get(file);
415+
if (cached) return cached;
416+
const commentTargetsByRowId = new Map<string, NativeReviewDiffCommentTarget>();
417+
const rowIdByCommentLineId = new Map<string, string>();
414418
const rows: NativeReviewDiffRow[] = [
415419
{
416420
kind: "file",
@@ -449,14 +453,18 @@ function prepareFileRows(
449453
});
450454

451455
rows.push(...noticeRowsForFile(file));
452-
return {
456+
const prepared: PreparedNativeReviewFileRows = {
453457
fileId: file.id,
454458
filePath: file.path,
455459
lineCount: lineRows.length,
456460
// Comments must not split the source deletion/addition runs used for word matching.
457461
rows: addNativeWordDiffRanges(rows),
462+
commentTargetsByRowId,
463+
rowIdByCommentLineId,
458464
commentedRows: null,
459465
};
466+
nativeReviewFileRowsCache.set(file, prepared);
467+
return prepared;
460468
}
461469

462470
function insertFileComments(
@@ -526,9 +534,15 @@ function prepareNativeReviewDiffData(parsedDiff: ReviewParsedDiff): PreparedNati
526534
}));
527535
const commentTargetsByRowId = new Map<string, NativeReviewDiffCommentTarget>();
528536
const rowIdByCommentLineId = new Map<string, string>();
529-
const fileRows = parsedDiff.files.map((file) =>
530-
prepareFileRows(file, commentTargetsByRowId, rowIdByCommentLineId),
531-
);
537+
const fileRows = parsedDiff.files.map(prepareFileRows);
538+
for (const file of fileRows) {
539+
for (const [rowId, target] of file.commentTargetsByRowId) {
540+
commentTargetsByRowId.set(rowId, target);
541+
}
542+
for (const [lineId, rowId] of file.rowIdByCommentLineId) {
543+
rowIdByCommentLineId.set(lineId, rowId);
544+
}
545+
}
532546

533547
return {
534548
fileRows,

‎apps/mobile/src/features/review/reviewModel.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
} from "@t3tools/contracts";
99

1010
import {
11+
applyReviewDiffMetadata,
1112
buildReviewParsedDiff,
1213
buildReviewSectionItems,
1314
getDefaultReviewSectionId,
@@ -135,6 +136,35 @@ describe("buildReviewSectionItems", () => {
135136
});
136137

137138
describe("buildReviewParsedDiff", () => {
139+
it.each([
140+
["a/example.ts", "a/example.ts"],
141+
["b/example.ts", "b/example.ts"],
142+
["a/before.ts", "b/after.ts"],
143+
])("preserves repository paths from %s to %s", (previousPath, path) => {
144+
const parsed = buildReviewParsedDiff(
145+
[
146+
`diff --git a/${previousPath} b/${path}`,
147+
...(previousPath === path
148+
? []
149+
: ["similarity index 50%", `rename from ${previousPath}`, `rename to ${path}`]),
150+
`--- a/${previousPath}`,
151+
`+++ b/${path}`,
152+
"@@ -1 +1 @@",
153+
"-before",
154+
"+after",
155+
].join("\n"),
156+
"repository-paths",
157+
);
158+
expect(parsed.kind).toBe("files");
159+
if (parsed.kind !== "files") return;
160+
expect(parsed.files[0]).toMatchObject({
161+
path,
162+
previousPath: previousPath === path ? null : previousPath,
163+
additions: 1,
164+
deletions: 1,
165+
});
166+
});
167+
138168
it("builds renderable rows from a unified patch", () => {
139169
const parsed = buildReviewParsedDiff(
140170
[
@@ -271,3 +301,34 @@ describe("buildReviewParsedDiff", () => {
271301
});
272302
});
273303
});
304+
305+
describe("applyReviewDiffMetadata", () => {
306+
it("uses complete counts even when the preview contains only part of one file", () => {
307+
const parsed = buildReviewParsedDiff(
308+
[
309+
"diff --git a/large.txt b/large.txt",
310+
"--- a/large.txt",
311+
"+++ b/large.txt",
312+
"@@ -1 +1 @@",
313+
"-before",
314+
"+after",
315+
].join("\n"),
316+
"partial",
317+
);
318+
const result = applyReviewDiffMetadata(parsed, {
319+
truncated: true,
320+
files: [
321+
{ path: "large.txt", previousPath: null, additions: 4000, deletions: 3000 },
322+
{ path: "unseen.txt", previousPath: null, additions: 100, deletions: 20 },
323+
],
324+
});
325+
expect(result.kind).toBe("files");
326+
if (result.kind !== "files") return;
327+
expect(result.fileCount).toBe(2);
328+
expect(result.additions).toBe(4100);
329+
expect(result.deletions).toBe(3020);
330+
expect(result.files[0]?.additions).toBe(4000);
331+
expect(result.notice).toContain("Counts include all changes");
332+
expect(applyReviewDiffMetadata(parsed, null)).toEqual(parsed);
333+
});
334+
});

‎apps/mobile/src/features/review/reviewModel.ts‎

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ export interface ReviewSectionItem {
1818
readonly subtitle: string | null;
1919
readonly diff: string | null;
2020
readonly isLoading: boolean;
21+
readonly files?: ReviewDiffPreviewSource["files"];
22+
readonly truncated?: boolean;
23+
readonly source?: ReviewDiffPreviewSource;
2124
}
2225

2326
export interface ReviewRenderableHunkRow {
@@ -47,6 +50,7 @@ export type ReviewRenderableRow = ReviewRenderableHunkRow | ReviewRenderableLine
4750
export interface ReviewRenderableFile {
4851
readonly id: string;
4952
readonly cacheKey: string;
53+
readonly notice?: string;
5054
readonly path: string;
5155
readonly previousPath: string | null;
5256
readonly changeType: ChangeTypes;
@@ -126,16 +130,6 @@ function gitSubtitle(section: ReviewDiffPreviewSource): string | null {
126130
return "Base branch unavailable";
127131
}
128132

129-
function stripGitPrefix(pathValue: string | undefined): string | null {
130-
if (!pathValue) {
131-
return null;
132-
}
133-
if (pathValue.startsWith("a/") || pathValue.startsWith("b/")) {
134-
return pathValue.slice(2);
135-
}
136-
return pathValue;
137-
}
138-
139133
function stripTrailingNewline(value: string): string {
140134
return value.endsWith("\n") ? value.slice(0, -1) : value;
141135
}
@@ -378,8 +372,8 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRender
378372
}
379373

380374
function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
381-
const path = stripGitPrefix(file.name) ?? stripGitPrefix(file.prevName) ?? file.name;
382-
const previousPath = stripGitPrefix(file.prevName);
375+
const path = file.name || file.prevName || "";
376+
const previousPath = file.prevName || null;
383377
const additions = file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0);
384378
const deletions = file.hunks.reduce((total, hunk) => total + hunk.deletionLines, 0);
385379
const cacheKey = file.cacheKey ?? `${previousPath ?? "none"}:${path}:${file.type}`;
@@ -442,6 +436,9 @@ export function buildReviewSectionItems(input: {
442436
title: section.title,
443437
subtitle: gitSubtitle(section),
444438
diff: section.diff,
439+
source: section,
440+
...(section.files ? { files: section.files } : {}),
441+
truncated: section.truncated,
445442
isLoading: false,
446443
}));
447444
const hasDirtyWorktreeItem = gitItems.some((item) => item.id === DIRTY_WORKTREE_SECTION_ID);
@@ -527,3 +524,27 @@ export function buildReviewParsedDiff(
527524
};
528525
}
529526
}
527+
528+
export function applyReviewDiffMetadata(
529+
previewDiff: ReviewParsedDiff,
530+
selectedSection: Pick<ReviewSectionItem, "files" | "truncated"> | null,
531+
): ReviewParsedDiff {
532+
if (previewDiff.kind === "empty") return previewDiff;
533+
const notice = selectedSection?.truncated
534+
? `This preview exceeds the size limit. Changes shown are incomplete.${selectedSection.files ? " Counts include all changes." : ""}`
535+
: previewDiff.notice;
536+
if (previewDiff.kind !== "files" || !selectedSection?.files) return { ...previewDiff, notice };
537+
const totals = selectedSection.files.reduce(
538+
(total, file) => ({
539+
additions: total.additions + file.additions,
540+
deletions: total.deletions + file.deletions,
541+
}),
542+
{ additions: 0, deletions: 0 },
543+
);
544+
const stats = new Map(selectedSection.files.map((file) => [file.path, file]));
545+
const files = previewDiff.files.map((file) => {
546+
const stat = stats.get(file.path);
547+
return stat ? { ...file, additions: stat.additions, deletions: stat.deletions } : file;
548+
});
549+
return { ...previewDiff, ...totals, files, fileCount: selectedSection.files.length, notice };
550+
}

0 commit comments

Comments
 (0)