Open History to see the last commit
1import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
2import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";
3import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts";
4import * as Arr from "effect/Array";
5import { pipe } from "effect/Function";
6import * as Order from "effect/Order";
7
8export type ReviewSectionKind = "turn" | "working-tree" | "branch-range";
9
10const DIRTY_WORKTREE_SECTION_ID = "git:working-tree";
11const DIRTY_WORKTREE_TITLE = "Dirty worktree";
12const DIRTY_WORKTREE_SUBTITLE = "Tracked, staged, and untracked worktree changes";
13
14export interface ReviewSectionItem {
15 readonly id: string;
16 readonly kind: ReviewSectionKind;
17 readonly title: string;
18 readonly subtitle: string | null;
19 readonly diff: string | null;
20 readonly isLoading: boolean;
21}
22
23export interface ReviewRenderableHunkRow {
24 readonly kind: "hunk";
25 readonly id: string;
26 readonly header: string;
27 readonly context: string | null;
28}
29
30export interface ReviewRenderableLineRow {
31 readonly kind: "line";
32 readonly id: string;
33 readonly change: "context" | "add" | "delete";
34 readonly oldLineNumber: number | null;
35 readonly newLineNumber: number | null;
36 readonly content: string;
37 readonly additionTokenIndex: number | null;
38 readonly deletionTokenIndex: number | null;
39 readonly comparison: {
40 readonly change: "add" | "delete";
41 readonly tokenIndex: number;
42 } | null;
43}
44
45export type ReviewRenderableRow = ReviewRenderableHunkRow | ReviewRenderableLineRow;
46
47export interface ReviewRenderableFile {
48 readonly id: string;
49 readonly cacheKey: string;
50 readonly path: string;
51 readonly previousPath: string | null;
52 readonly changeType: ChangeTypes;
53 readonly additions: number;
54 readonly deletions: number;
55 readonly languageHint: string | null;
56 readonly additionLines: ReadonlyArray<string>;
57 readonly deletionLines: ReadonlyArray<string>;
58 readonly rows: ReadonlyArray<ReviewRenderableRow>;
59}
60
61export interface ReviewFileHeaderListItem {
62 readonly kind: "file-header";
63 readonly id: string;
64 readonly fileId: string;
65 readonly file: ReviewRenderableFile;
66 readonly expanded: boolean;
67}
68
69export interface ReviewFileSuppressedListItem {
70 readonly kind: "file-suppressed";
71 readonly id: string;
72 readonly fileId: string;
73 readonly message: string;
74 readonly actionLabel: string | null;
75}
76
77export interface ReviewHunkListItem {
78 readonly kind: "hunk";
79 readonly id: string;
80 readonly fileId: string;
81 readonly file: ReviewRenderableFile;
82 readonly row: ReviewRenderableHunkRow;
83}
84
85export interface ReviewLineListItem {
86 readonly kind: "line";
87 readonly id: string;
88 readonly fileId: string;
89 readonly file: ReviewRenderableFile;
90 readonly row: ReviewRenderableLineRow;
91 readonly lineIndex: number;
92}
93
94export type ReviewListItem =
95 | ReviewFileHeaderListItem
96 | ReviewFileSuppressedListItem
97 | ReviewHunkListItem
98 | ReviewLineListItem;
99
100export type ReviewFilePreviewState =
101 | {
102 readonly kind: "render";
103 }
104 | {
105 readonly kind: "suppressed";
106 readonly reason: "non-text" | "large";
107 readonly title: string;
108 readonly message: string;
109 readonly actionLabel: string | null;
110 };
111
112export type ReviewParsedDiff =
113 | {
114 readonly kind: "empty";
115 }
116 | {
117 readonly kind: "raw";
118 readonly text: string;
119 readonly reason: string;
120 readonly notice: string | null;
121 }
122 | {
123 readonly kind: "files";
124 readonly files: ReadonlyArray<ReviewRenderableFile>;
125 readonly fileCount: number;
126 readonly additions: number;
127 readonly deletions: number;
128 readonly notice: string | null;
129 };
130
131function checkpointTitle(checkpoint: OrchestrationCheckpointSummary): string {
132 return `Turn ${checkpoint.checkpointTurnCount}`;
133}
134
135function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string {
136 const fileCount = checkpoint.files.length;
137 if (checkpoint.status !== "ready") {
138 return `Diff ${checkpoint.status}`;
139 }
140 return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`;
141}
142
143function compareCheckpointTurnCountDescending(
144 left: OrchestrationCheckpointSummary,
145 right: OrchestrationCheckpointSummary,
146): -1 | 0 | 1 {
147 if (left.checkpointTurnCount === right.checkpointTurnCount) {
148 return 0;
149 }
150
151 return left.checkpointTurnCount > right.checkpointTurnCount ? -1 : 1;
152}
153
154const readyCheckpointOrder = Order.make<OrchestrationCheckpointSummary>(
155 compareCheckpointTurnCountDescending,
156);
157
158function gitSubtitle(section: ReviewDiffPreviewSource): string | null {
159 if (section.kind === "working-tree") {
160 return DIRTY_WORKTREE_SUBTITLE;
161 }
162 if (section.baseRef) {
163 return `${section.baseRef} ... ${section.headRef ?? "HEAD"}`;
164 }
165 return "Base branch unavailable";
166}
167
168function stripGitPrefix(pathValue: string | undefined): string | null {
169 if (!pathValue) {
170 return null;
171 }
172 if (pathValue.startsWith("a/") || pathValue.startsWith("b/")) {
173 return pathValue.slice(2);
174 }
175 return pathValue;
176}
177
178function stripTrailingNewline(value: string): string {
179 return value.endsWith("\n") ? value.slice(0, -1) : value;
180}
181
182function splitTruncationMarker(diff: string): {
183 readonly text: string;
184 readonly truncated: boolean;
185} {
186 const trimmed = diff.trimEnd();
187 if (!trimmed.endsWith("[truncated]")) {
188 return { text: trimmed, truncated: false };
189 }
190
191 return {
192 text: trimmed.replace(/\n*\[truncated\]\s*$/, "").trimEnd(),
193 truncated: true,
194 };
195}
196
197function runDiffParserSilently<T>(callback: () => T): T {
198 const originalConsoleError = console.error;
199 console.error = () => undefined;
200 try {
201 return callback();
202 } finally {
203 console.error = originalConsoleError;
204 }
205}
206
207const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
208const FNV_PRIME_32 = 0x01000193;
209const SECONDARY_HASH_SEED = 0x9e3779b9;
210const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
211const LARGE_DIFF_LINE_THRESHOLD = 400;
212const LARGE_DIFF_CHARACTER_THRESHOLD = 24_000;
213const NON_TEXT_FILE_EXTENSIONS = new Set([
214 "png",
215 "jpg",
216 "jpeg",
217 "gif",
218 "webp",
219 "bmp",
220 "ico",
221 "icns",
222 "avif",
223 "heic",
224 "tif",
225 "tiff",
226 "mp3",
227 "wav",
228 "flac",
229 "ogg",
230 "m4a",
231 "aac",
232 "mp4",
233 "mov",
234 "avi",
235 "mkv",
236 "webm",
237 "pdf",
238 "zip",
239 "gz",
240 "tgz",
241 "bz2",
242 "7z",
243 "rar",
244 "woff",
245 "woff2",
246 "ttf",
247 "otf",
248 "eot",
249 "wasm",
250 "exe",
251 "dll",
252 "so",
253 "dylib",
254]);
255
256function fnv1a32(input: string, seed: number, multiplier: number): number {
257 let hash = seed >>> 0;
258 for (let index = 0; index < input.length; index += 1) {
259 hash ^= input.charCodeAt(index);
260 hash = Math.imul(hash, multiplier) >>> 0;
261 }
262 return hash >>> 0;
263}
264
265function buildPatchCacheKey(patch: string, scope: string): string {
266 const normalizedPatch = patch.trim();
267 const primary = fnv1a32(normalizedPatch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
268 const secondary = fnv1a32(
269 normalizedPatch,
270 SECONDARY_HASH_SEED,
271 SECONDARY_HASH_MULTIPLIER,
272 ).toString(36);
273 return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;
274}
275
276function getFileExtension(path: string): string | null {
277 const match = /\.([a-z0-9]+)$/i.exec(path);
278 return match?.[1]?.toLowerCase() ?? null;
279}
280
281function countReviewRenderableLineRows(file: ReviewRenderableFile): number {
282 return file.rows.reduce((total, row) => total + (row.kind === "line" ? 1 : 0), 0);
283}
284
285function countReviewRenderableCharacters(file: ReviewRenderableFile): number {
286 return file.rows.reduce(
287 (total, row) => total + (row.kind === "line" ? row.content.length : row.header.length),
288 0,
289 );
290}
291
292export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFilePreviewState {
293 const extension = getFileExtension(file.path);
294 if (extension && NON_TEXT_FILE_EXTENSIONS.has(extension)) {
295 return {
296 kind: "suppressed",
297 reason: "non-text",
298 title: "Non-text file",
299 message: "Diff preview is not available for this file format.",
300 actionLabel: null,
301 };
302 }
303
304 const lineCount = countReviewRenderableLineRows(file);
305 const characterCount = countReviewRenderableCharacters(file);
306 if (lineCount > LARGE_DIFF_LINE_THRESHOLD || characterCount > LARGE_DIFF_CHARACTER_THRESHOLD) {
307 return {
308 kind: "suppressed",
309 reason: "large",
310 title: "Large diff",
311 message: "Large diffs are not rendered by default.",
312 actionLabel: "Load diff",
313 };
314 }
315
316 return { kind: "render" };
317}
318
319// The flattened review list item model is inspired by pierre/diffs' iterator-first
320// virtualization architecture, adapted here for React Native virtualization.
321// Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs
322// Reference files:
323// - src/utils/iterateOverDiff.ts
324// - src/components/VirtualizedFileDiff.ts
325export function buildReviewListItems(input: {
326 readonly files: ReadonlyArray<ReviewRenderableFile>;
327 readonly expandedFileIds: ReadonlyArray<string>;
328 readonly revealedLargeFileIds: ReadonlyArray<string>;
329}): ReadonlyArray<ReviewListItem> {
330 const expandedFileIds = new Set(input.expandedFileIds);
331 const revealedLargeFileIds = new Set(input.revealedLargeFileIds);
332 const items: ReviewListItem[] = [];
333
334 input.files.forEach((file) => {
335 const expanded = expandedFileIds.has(file.id);
336 items.push({
337 kind: "file-header",
338 id: `${file.id}:header`,
339 fileId: file.id,
340 file,
341 expanded,
342 });
343
344 if (!expanded) {
345 return;
346 }
347
348 const previewState = getReviewFilePreviewState(file);
349 if (previewState.kind === "suppressed") {
350 if (previewState.reason !== "large" || !revealedLargeFileIds.has(file.id)) {
351 items.push({
352 kind: "file-suppressed",
353 id: `${file.id}:suppressed`,
354 fileId: file.id,
355 message: previewState.message,
356 actionLabel: previewState.actionLabel,
357 });
358 return;
359 }
360 }
361
362 let lineIndex = 0;
363 file.rows.forEach((row, rowIndex) => {
364 if (row.kind === "hunk") {
365 items.push({
366 kind: "hunk",
367 id: `${file.id}:row:${rowIndex}:${row.id}`,
368 fileId: file.id,
369 file,
370 row,
371 });
372 return;
373 }
374
375 items.push({
376 kind: "line",
377 id: `${file.id}:row:${rowIndex}:${row.id}`,
378 fileId: file.id,
379 file,
380 row,
381 lineIndex,
382 });
383 lineIndex += 1;
384 });
385 });
386
387 return items;
388}
389
390function fallbackHunkHeader(hunk: FileDiffMetadata["hunks"][number]): string {
391 return `@@ -${hunk.deletionStart},${hunk.deletionCount} +${hunk.additionStart},${hunk.additionCount} @@`;
392}
393
394function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRenderableRow> {
395 const rows: ReviewRenderableRow[] = [];
396 let rowIndex = 0;
397
398 file.hunks.forEach((hunk, hunkIndex) => {
399 rows.push({
400 kind: "hunk",
401 id: `${file.cacheKey ?? file.name}:hunk:${hunkIndex}`,
402 header: fallbackHunkHeader(hunk),
403 context: hunk.hunkContext ? stripTrailingNewline(hunk.hunkContext) : null,
404 });
405
406 let deletionLineNumber = hunk.deletionStart;
407 let additionLineNumber = hunk.additionStart;
408 let deletionTokenIndex = hunk.deletionLineIndex;
409 let additionTokenIndex = hunk.additionLineIndex;
410
411 hunk.hunkContent.forEach((segment) => {
412 if (segment.type === "context") {
413 for (let index = 0; index < segment.lines; index += 1) {
414 rows.push({
415 kind: "line",
416 id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
417 change: "context",
418 oldLineNumber: deletionLineNumber,
419 newLineNumber: additionLineNumber,
420 content: stripTrailingNewline(
421 file.additionLines[additionTokenIndex] ??
422 file.deletionLines[deletionTokenIndex] ??
423 "",
424 ),
425 additionTokenIndex,
426 deletionTokenIndex,
427 comparison: null,
428 });
429 deletionLineNumber += 1;
430 additionLineNumber += 1;
431 deletionTokenIndex += 1;
432 additionTokenIndex += 1;
433 }
434 return;
435 }
436
437 const pairedLineCount = Math.min(segment.deletions, segment.additions);
438 const deletionTokenIndexStart = deletionTokenIndex;
439 const additionTokenIndexStart = additionTokenIndex;
440
441 for (let index = 0; index < segment.deletions; index += 1) {
442 rows.push({
443 kind: "line",
444 id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
445 change: "delete",
446 oldLineNumber: deletionLineNumber,
447 newLineNumber: null,
448 content: stripTrailingNewline(file.deletionLines[deletionTokenIndex] ?? ""),
449 additionTokenIndex: null,
450 deletionTokenIndex,
451 comparison:
452 index < pairedLineCount
453 ? {
454 change: "add",
455 tokenIndex: additionTokenIndexStart + index,
456 }
457 : null,
458 });
459 deletionLineNumber += 1;
460 deletionTokenIndex += 1;
461 }
462
463 for (let index = 0; index < segment.additions; index += 1) {
464 rows.push({
465 kind: "line",
466 id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
467 change: "add",
468 oldLineNumber: null,
469 newLineNumber: additionLineNumber,
470 content: stripTrailingNewline(file.additionLines[additionTokenIndex] ?? ""),
471 additionTokenIndex,
472 deletionTokenIndex: null,
473 comparison:
474 index < pairedLineCount
475 ? {
476 change: "delete",
477 tokenIndex: deletionTokenIndexStart + index,
478 }
479 : null,
480 });
481 additionLineNumber += 1;
482 additionTokenIndex += 1;
483 }
484 });
485 });
486
487 return rows;
488}
489
490function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
491 const path = stripGitPrefix(file.name) ?? stripGitPrefix(file.prevName) ?? file.name;
492 const previousPath = stripGitPrefix(file.prevName);
493 const additions = file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0);
494 const deletions = file.hunks.reduce((total, hunk) => total + hunk.deletionLines, 0);
495 const cacheKey = file.cacheKey ?? `${previousPath ?? "none"}:${path}:${file.type}`;
496
497 return {
498 id: cacheKey,
499 cacheKey,
500 path,
501 previousPath,
502 changeType: file.type,
503 additions,
504 deletions,
505 languageHint: file.lang ?? null,
506 additionLines: file.additionLines,
507 deletionLines: file.deletionLines,
508 rows: buildRenderableRows(file),
509 };
510}
511
512export function getReviewSectionIdForCheckpoint(
513 checkpoint: Pick<OrchestrationCheckpointSummary, "checkpointTurnCount">,
514): string {
515 return `turn:${checkpoint.checkpointTurnCount}`;
516}
517
518export function getReadyReviewCheckpoints(
519 checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
520): ReadonlyArray<OrchestrationCheckpointSummary> {
521 return pipe(
522 checkpoints,
523 Arr.filter((checkpoint) => checkpoint.status === "ready"),
524 Arr.sort(readyCheckpointOrder),
525 );
526}
527
528export function buildReviewSectionItems(input: {
529 readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
530 readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
531 readonly turnDiffById: Readonly<Record<string, string | undefined>>;
532 readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
533 readonly loadingGitSections: boolean;
534}): ReadonlyArray<ReviewSectionItem> {
535 const turnItems = getReadyReviewCheckpoints(input.checkpoints).map<ReviewSectionItem>(
536 (checkpoint) => {
537 const id = getReviewSectionIdForCheckpoint(checkpoint);
538 return {
539 id,
540 kind: "turn",
541 title: checkpointTitle(checkpoint),
542 subtitle: checkpointSubtitle(checkpoint),
543 diff: input.turnDiffById[id] ?? null,
544 isLoading: input.loadingTurnIds[id] === true,
545 };
546 },
547 );
548
549 const gitItems = input.gitSections.map<ReviewSectionItem>((section) => ({
550 id: `git:${section.kind}`,
551 kind: section.kind,
552 title: section.title,
553 subtitle: gitSubtitle(section),
554 diff: section.diff,
555 isLoading: false,
556 }));
557 const hasDirtyWorktreeItem = gitItems.some((item) => item.id === DIRTY_WORKTREE_SECTION_ID);
558 const visibleGitItems =
559 input.loadingGitSections && !hasDirtyWorktreeItem
560 ? [
561 {
562 id: DIRTY_WORKTREE_SECTION_ID,
563 kind: "working-tree",
564 title: DIRTY_WORKTREE_TITLE,
565 subtitle: DIRTY_WORKTREE_SUBTITLE,
566 diff: null,
567 isLoading: true,
568 } satisfies ReviewSectionItem,
569 ...gitItems,
570 ]
571 : gitItems;
572
573 return [...turnItems, ...visibleGitItems];
574}
575
576export function getDefaultReviewSectionId(
577 sections: ReadonlyArray<ReviewSectionItem>,
578): string | null {
579 return sections[0]?.id ?? null;
580}
581
582export function buildReviewParsedDiff(
583 diff: string | null | undefined,
584 cacheScope: string,
585): ReviewParsedDiff {
586 const normalized = diff?.trim();
587 if (!normalized) {
588 return { kind: "empty" };
589 }
590
591 const { text, truncated } = splitTruncationMarker(normalized);
592 if (text.length === 0) {
593 return { kind: "empty" };
594 }
595
596 const notice = truncated
597 ? "Diff output hit the server size cap. Showing the available excerpt."
598 : null;
599
600 try {
601 const parsedPatches = runDiffParserSilently(() =>
602 parsePatchFiles(text, buildPatchCacheKey(text, cacheScope)),
603 );
604 const files = pipe(
605 parsedPatches,
606 Arr.flatMap((patch) => patch.files),
607 Arr.map(mapRenderableFile),
608 );
609
610 if (files.length === 0) {
611 return {
612 kind: "raw",
613 text,
614 reason: truncated
615 ? "Diff was truncated before it could be parsed completely. Showing the raw excerpt."
616 : "Unsupported diff format. Showing raw patch.",
617 notice,
618 };
619 }
620
621 return {
622 kind: "files",
623 files,
624 fileCount: files.length,
625 additions: files.reduce((total, file) => total + file.additions, 0),
626 deletions: files.reduce((total, file) => total + file.deletions, 0),
627 notice,
628 };
629 } catch {
630 return {
631 kind: "raw",
632 text,
633 reason: truncated
634 ? "Diff was truncated before it could be parsed completely. Showing the raw excerpt."
635 : "Failed to parse patch. Showing raw patch.",
636 notice,
637 };
638 }
639}