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