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 type ReviewFilePreviewState =
63 | {
64 readonly kind: "render";
65 }
66 | {
67 readonly kind: "suppressed";
68 readonly reason: "non-text" | "large";
69 readonly title: string;
70 readonly message: string;
71 readonly actionLabel: string | null;
72 };
73
74export type ReviewParsedDiff =
75 | {
76 readonly kind: "empty";
77 }
78 | {
79 readonly kind: "raw";
80 readonly text: string;
81 readonly reason: string;
82 readonly notice: string | null;
83 }
84 | {
85 readonly kind: "files";
86 readonly files: ReadonlyArray<ReviewRenderableFile>;
87 readonly fileCount: number;
88 readonly additions: number;
89 readonly deletions: number;
90 readonly notice: string | null;
91 };
92
93function checkpointTitle(checkpoint: ThreadCheckpointSummary): string {
94 return `Turn ${checkpoint.checkpointTurnCount}`;
95}
96
97function checkpointSubtitle(checkpoint: ThreadCheckpointSummary): string {
98 const fileCount = checkpoint.files.length;
99 if (checkpoint.status !== "ready") {
100 return `Diff ${checkpoint.status}`;
101 }
102 return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`;
103}
104
105function compareCheckpointTurnCountDescending(
106 left: ThreadCheckpointSummary,
107 right: ThreadCheckpointSummary,
108): -1 | 0 | 1 {
109 if (left.checkpointTurnCount === right.checkpointTurnCount) {
110 return 0;
111 }
112
113 return left.checkpointTurnCount > right.checkpointTurnCount ? -1 : 1;
114}
115
116const readyCheckpointOrder = Order.make<ThreadCheckpointSummary>(
117 compareCheckpointTurnCountDescending,
118);
119
120function gitSubtitle(section: ReviewDiffPreviewSource): string | null {
121 if (section.kind === "working-tree") {
122 return DIRTY_WORKTREE_SUBTITLE;
123 }
124 if (section.baseRef) {
125 return `${section.baseRef} ... ${section.headRef ?? "HEAD"}`;
126 }
127 return "Base branch unavailable";
128}
129
130function stripGitPrefix(pathValue: string | undefined): string | null {
131 if (!pathValue) {
132 return null;
133 }
134 if (pathValue.startsWith("a/") || pathValue.startsWith("b/")) {
135 return pathValue.slice(2);
136 }
137 return pathValue;
138}
139
140function stripTrailingNewline(value: string): string {
141 return value.endsWith("\n") ? value.slice(0, -1) : value;
142}
143
144function splitTruncationMarker(diff: string): {
145 readonly text: string;
146 readonly truncated: boolean;
147} {
148 const trimmed = diff.trimEnd();
149 if (!trimmed.endsWith("[truncated]")) {
150 return { text: trimmed, truncated: false };
151 }
152
153 return {
154 text: trimmed.replace(/\n*\[truncated\]\s*$/, "").trimEnd(),
155 truncated: true,
156 };
157}
158
159function runDiffParserSilently<T>(callback: () => T): T {
160 const originalConsoleError = console.error;
161 console.error = () => undefined;
162 try {
163 return callback();
164 } finally {
165 console.error = originalConsoleError;
166 }
167}
168
169const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
170const FNV_PRIME_32 = 0x01000193;
171const SECONDARY_HASH_SEED = 0x9e3779b9;
172const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
173const LARGE_DIFF_LINE_THRESHOLD = 400;
174const LARGE_DIFF_CHARACTER_THRESHOLD = 24_000;
175const NON_TEXT_FILE_EXTENSIONS = new Set([
176 "png",
177 "jpg",
178 "jpeg",
179 "gif",
180 "webp",
181 "bmp",
182 "ico",
183 "icns",
184 "avif",
185 "heic",
186 "tif",
187 "tiff",
188 "mp3",
189 "wav",
190 "flac",
191 "ogg",
192 "m4a",
193 "aac",
194 "mp4",
195 "mov",
196 "avi",
197 "mkv",
198 "webm",
199 "pdf",
200 "zip",
201 "gz",
202 "tgz",
203 "bz2",
204 "7z",
205 "rar",
206 "woff",
207 "woff2",
208 "ttf",
209 "otf",
210 "eot",
211 "wasm",
212 "exe",
213 "dll",
214 "so",
215 "dylib",
216]);
217
218function fnv1a32(input: string, seed: number, multiplier: number): number {
219 let hash = seed >>> 0;
220 for (let index = 0; index < input.length; index += 1) {
221 hash ^= input.charCodeAt(index);
222 hash = Math.imul(hash, multiplier) >>> 0;
223 }
224 return hash >>> 0;
225}
226
227function buildPatchCacheKey(patch: string, scope: string): string {
228 const normalizedPatch = patch.trim();
229 const primary = fnv1a32(normalizedPatch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
230 const secondary = fnv1a32(
231 normalizedPatch,
232 SECONDARY_HASH_SEED,
233 SECONDARY_HASH_MULTIPLIER,
234 ).toString(36);
235 return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;
236}
237
238function getFileExtension(path: string): string | null {
239 const match = /\.([a-z0-9]+)$/i.exec(path);
240 return match?.[1]?.toLowerCase() ?? null;
241}
242
243function countReviewRenderableLineRows(file: ReviewRenderableFile): number {
244 return file.rows.reduce((total, row) => total + (row.kind === "line" ? 1 : 0), 0);
245}
246
247function countReviewRenderableCharacters(file: ReviewRenderableFile): number {
248 return file.rows.reduce(
249 (total, row) => total + (row.kind === "line" ? row.content.length : row.header.length),
250 0,
251 );
252}
253
254export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFilePreviewState {
255 const extension = getFileExtension(file.path);
256 if (extension && NON_TEXT_FILE_EXTENSIONS.has(extension)) {
257 return {
258 kind: "suppressed",
259 reason: "non-text",
260 title: "Non-text file",
261 message: "Diff preview is not available for this file format.",
262 actionLabel: null,
263 };
264 }
265
266 const lineCount = countReviewRenderableLineRows(file);
267 const characterCount = countReviewRenderableCharacters(file);
268 if (lineCount > LARGE_DIFF_LINE_THRESHOLD || characterCount > LARGE_DIFF_CHARACTER_THRESHOLD) {
269 return {
270 kind: "suppressed",
271 reason: "large",
272 title: "Large diff",
273 message: "Large diffs are not rendered by default.",
274 actionLabel: "Load diff",
275 };
276 }
277
278 return { kind: "render" };
279}
280
281function fallbackHunkHeader(hunk: FileDiffMetadata["hunks"][number]): string {
282 return `@@ -${hunk.deletionStart},${hunk.deletionCount} +${hunk.additionStart},${hunk.additionCount} @@`;
283}
284
285function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRenderableRow> {
286 const rows: ReviewRenderableRow[] = [];
287 let rowIndex = 0;
288
289 file.hunks.forEach((hunk, hunkIndex) => {
290 rows.push({
291 kind: "hunk",
292 id: `${file.cacheKey ?? file.name}:hunk:${hunkIndex}`,
293 header: fallbackHunkHeader(hunk),
294 context: hunk.hunkContext ? stripTrailingNewline(hunk.hunkContext) : null,
295 });
296
297 let deletionLineNumber = hunk.deletionStart;
298 let additionLineNumber = hunk.additionStart;
299 let deletionTokenIndex = hunk.deletionLineIndex;
300 let additionTokenIndex = hunk.additionLineIndex;
301
302 hunk.hunkContent.forEach((segment) => {
303 if (segment.type === "context") {
304 for (let index = 0; index < segment.lines; index += 1) {
305 rows.push({
306 kind: "line",
307 id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
308 change: "context",
309 oldLineNumber: deletionLineNumber,
310 newLineNumber: additionLineNumber,
311 content: stripTrailingNewline(
312 file.additionLines[additionTokenIndex] ??
313 file.deletionLines[deletionTokenIndex] ??
314 "",
315 ),
316 additionTokenIndex,
317 deletionTokenIndex,
318 comparison: null,
319 });
320 deletionLineNumber += 1;
321 additionLineNumber += 1;
322 deletionTokenIndex += 1;
323 additionTokenIndex += 1;
324 }
325 return;
326 }
327
328 const pairedLineCount = Math.min(segment.deletions, segment.additions);
329 const deletionTokenIndexStart = deletionTokenIndex;
330 const additionTokenIndexStart = additionTokenIndex;
331
332 for (let index = 0; index < segment.deletions; index += 1) {
333 rows.push({
334 kind: "line",
335 id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
336 change: "delete",
337 oldLineNumber: deletionLineNumber,
338 newLineNumber: null,
339 content: stripTrailingNewline(file.deletionLines[deletionTokenIndex] ?? ""),
340 additionTokenIndex: null,
341 deletionTokenIndex,
342 comparison:
343 index < pairedLineCount
344 ? {
345 change: "add",
346 tokenIndex: additionTokenIndexStart + index,
347 }
348 : null,
349 });
350 deletionLineNumber += 1;
351 deletionTokenIndex += 1;
352 }
353
354 for (let index = 0; index < segment.additions; index += 1) {
355 rows.push({
356 kind: "line",
357 id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
358 change: "add",
359 oldLineNumber: null,
360 newLineNumber: additionLineNumber,
361 content: stripTrailingNewline(file.additionLines[additionTokenIndex] ?? ""),
362 additionTokenIndex,
363 deletionTokenIndex: null,
364 comparison:
365 index < pairedLineCount
366 ? {
367 change: "delete",
368 tokenIndex: deletionTokenIndexStart + index,
369 }
370 : null,
371 });
372 additionLineNumber += 1;
373 additionTokenIndex += 1;
374 }
375 });
376 });
377
378 return rows;
379}
380
381function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
382 const path = stripGitPrefix(file.name) ?? stripGitPrefix(file.prevName) ?? file.name;
383 const previousPath = stripGitPrefix(file.prevName);
384 const additions = file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0);
385 const deletions = file.hunks.reduce((total, hunk) => total + hunk.deletionLines, 0);
386 const cacheKey = file.cacheKey ?? `${previousPath ?? "none"}:${path}:${file.type}`;
387
388 return {
389 id: cacheKey,
390 cacheKey,
391 path,
392 previousPath,
393 changeType: file.type,
394 additions,
395 deletions,
396 languageHint: file.lang ?? null,
397 additionLines: file.additionLines,
398 deletionLines: file.deletionLines,
399 rows: buildRenderableRows(file),
400 };
401}
402
403export function getReviewSectionIdForCheckpoint(
404 checkpoint: Pick<ThreadCheckpointSummary, "checkpointTurnCount">,
405): string {
406 return `turn:${checkpoint.checkpointTurnCount}`;
407}
408
409export function getReadyReviewCheckpoints(
410 checkpoints: ReadonlyArray<ThreadCheckpointSummary>,
411): ReadonlyArray<ThreadCheckpointSummary> {
412 return pipe(
413 checkpoints,
414 Arr.filter((checkpoint) => checkpoint.status === "ready"),
415 Arr.sort(readyCheckpointOrder),
416 );
417}
418
419export function buildReviewSectionItems(input: {
420 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
421 readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
422 readonly turnDiffById: Readonly<Record<string, string | undefined>>;
423 readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
424 readonly loadingGitSections: boolean;
425}): ReadonlyArray<ReviewSectionItem> {
426 const turnItems = getReadyReviewCheckpoints(input.checkpoints).map<ReviewSectionItem>(
427 (checkpoint) => {
428 const id = getReviewSectionIdForCheckpoint(checkpoint);
429 return {
430 id,
431 kind: "turn",
432 title: checkpointTitle(checkpoint),
433 subtitle: checkpointSubtitle(checkpoint),
434 diff: input.turnDiffById[id] ?? null,
435 isLoading: input.loadingTurnIds[id] === true,
436 };
437 },
438 );
439
440 const gitItems = input.gitSections.map<ReviewSectionItem>((section) => ({
441 id: `git:${section.kind}`,
442 kind: section.kind,
443 title: section.title,
444 subtitle: gitSubtitle(section),
445 diff: section.diff,
446 isLoading: false,
447 }));
448 const hasDirtyWorktreeItem = gitItems.some((item) => item.id === DIRTY_WORKTREE_SECTION_ID);
449 const visibleGitItems =
450 input.loadingGitSections && !hasDirtyWorktreeItem
451 ? [
452 {
453 id: DIRTY_WORKTREE_SECTION_ID,
454 kind: "working-tree",
455 title: DIRTY_WORKTREE_TITLE,
456 subtitle: DIRTY_WORKTREE_SUBTITLE,
457 diff: null,
458 isLoading: true,
459 } satisfies ReviewSectionItem,
460 ...gitItems,
461 ]
462 : gitItems;
463
464 return [...turnItems, ...visibleGitItems];
465}
466
467export function getDefaultReviewSectionId(
468 sections: ReadonlyArray<ReviewSectionItem>,
469): string | null {
470 return sections[0]?.id ?? null;
471}
472
473export function buildReviewParsedDiff(
474 diff: string | null | undefined,
475 cacheScope: string,
476): ReviewParsedDiff {
477 const normalized = diff?.trim();
478 if (!normalized) {
479 return { kind: "empty" };
480 }
481
482 const { text, truncated } = splitTruncationMarker(normalized);
483 if (text.length === 0) {
484 return { kind: "empty" };
485 }
486
487 const notice = truncated
488 ? "Diff output hit the server size cap. Showing the available excerpt."
489 : null;
490
491 try {
492 const parsedPatches = runDiffParserSilently(() =>
493 parsePatchFiles(text, buildPatchCacheKey(text, cacheScope)),
494 );
495 const files = pipe(
496 parsedPatches,
497 Arr.flatMap((patch) => patch.files),
498 Arr.map(mapRenderableFile),
499 );
500
501 if (files.length === 0) {
502 return {
503 kind: "raw",
504 text,
505 reason: truncated
506 ? "Diff was truncated before it could be parsed completely. Showing the raw excerpt."
507 : "Unsupported diff format. Showing raw patch.",
508 notice,
509 };
510 }
511
512 return {
513 kind: "files",
514 files,
515 fileCount: files.length,
516 additions: files.reduce((total, file) => total + file.additions, 0),
517 deletions: files.reduce((total, file) => total + file.deletions, 0),
518 notice,
519 };
520 } catch {
521 return {
522 kind: "raw",
523 text,
524 reason: truncated
525 ? "Diff was truncated before it could be parsed completely. Showing the raw excerpt."
526 : "Failed to parse patch. Showing raw patch.",
527 notice,
528 };
529 }
530}