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 { unquoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
6import * as Arr from "effect/Array";
7import { pipe } from "effect/Function";
8import * as Order from "effect/Order";
9
10export type ReviewSectionKind = "turn" | "working-tree" | "branch-range";
11
12const CHANGES_SECTION_ID = "git:branch-range";
13const CHANGES_TITLE = "Changes";
14const UNCOMMITTED_SUBTITLE = "Staged, unstaged, and untracked files";
15
16export interface ReviewSectionItem {
17 readonly id: string;
18 readonly kind: ReviewSectionKind;
19 readonly title: string;
20 readonly subtitle: string | null;
21 readonly diff: string | null;
22 readonly isLoading: boolean;
23 readonly files?: ReviewDiffPreviewSource["files"];
24 readonly truncated?: boolean;
25 readonly source?: ReviewDiffPreviewSource;
26}
27
28export interface ReviewRenderableHunkRow {
29 readonly kind: "hunk";
30 readonly id: string;
31 readonly header: string;
32 readonly context: string | null;
33}
34
35export interface ReviewRenderableLineRow {
36 readonly kind: "line";
37 readonly id: string;
38 readonly change: "context" | "add" | "delete";
39 readonly oldLineNumber: number | null;
40 readonly newLineNumber: number | null;
41 readonly content: string;
42 readonly additionTokenIndex: number | null;
43 readonly deletionTokenIndex: number | null;
44 readonly comparison: {
45 readonly change: "add" | "delete";
46 readonly tokenIndex: number;
47 } | null;
48}
49
50export type ReviewRenderableRow = ReviewRenderableHunkRow | ReviewRenderableLineRow;
51
52export interface ReviewRenderableFile {
53 readonly id: string;
54 readonly cacheKey: string;
55 readonly notice?: string;
56 readonly path: string;
57 readonly previousPath: string | null;
58 readonly changeType: ChangeTypes;
59 readonly additions: number;
60 readonly deletions: number;
61 readonly languageHint: string | null;
62 readonly additionLines: ReadonlyArray<string>;
63 readonly deletionLines: ReadonlyArray<string>;
64 readonly rows: ReadonlyArray<ReviewRenderableRow>;
65}
66
67export type ReviewFilePreviewState =
68 | {
69 readonly kind: "render";
70 }
71 | {
72 readonly kind: "suppressed";
73 readonly reason: "non-text" | "large";
74 readonly title: string;
75 readonly message: string;
76 readonly actionLabel: string | null;
77 };
78
79export type ReviewParsedDiff =
80 | {
81 readonly kind: "empty";
82 }
83 | {
84 readonly kind: "raw";
85 readonly text: string;
86 readonly reason: string;
87 readonly notice: string | null;
88 }
89 | {
90 readonly kind: "files";
91 readonly files: ReadonlyArray<ReviewRenderableFile>;
92 readonly fileCount: number;
93 readonly additions: number;
94 readonly deletions: number;
95 readonly notice: string | null;
96 };
97
98function checkpointTitle(checkpoint: ThreadCheckpointSummary): string {
99 return `Turn ${checkpoint.checkpointTurnCount}`;
100}
101
102function checkpointSubtitle(checkpoint: ThreadCheckpointSummary): string {
103 const fileCount = checkpoint.files.length;
104 if (checkpoint.status !== "ready") {
105 return `Diff ${checkpoint.status}`;
106 }
107 return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`;
108}
109
110function compareCheckpointTurnCountDescending(
111 left: ThreadCheckpointSummary,
112 right: ThreadCheckpointSummary,
113): -1 | 0 | 1 {
114 if (left.checkpointTurnCount === right.checkpointTurnCount) {
115 return 0;
116 }
117
118 return left.checkpointTurnCount > right.checkpointTurnCount ? -1 : 1;
119}
120
121const readyCheckpointOrder = Order.make<ThreadCheckpointSummary>(
122 compareCheckpointTurnCountDescending,
123);
124
125function gitSubtitle(section: ReviewDiffPreviewSource): string | null {
126 if (section.kind === "working-tree") {
127 return UNCOMMITTED_SUBTITLE;
128 }
129 if (section.baseRef) {
130 return `${section.baseRef} ... ${section.headRef ?? "HEAD"}`;
131 }
132 return "Base branch unavailable";
133}
134
135function stripTrailingNewline(value: string): string {
136 return value.endsWith("\n") ? value.slice(0, -1) : value;
137}
138
139function splitTruncationMarker(diff: string): {
140 readonly text: string;
141 readonly truncated: boolean;
142} {
143 const trimmed = diff.trimEnd();
144 if (!trimmed.endsWith("[truncated]")) {
145 return { text: trimmed, truncated: false };
146 }
147
148 return {
149 text: trimmed.replace(/\n*\[truncated\]\s*$/, "").trimEnd(),
150 truncated: true,
151 };
152}
153
154function runDiffParserSilently<T>(callback: () => T): T {
155 const originalConsoleError = console.error;
156 console.error = () => undefined;
157 try {
158 return callback();
159 } finally {
160 console.error = originalConsoleError;
161 }
162}
163
164const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
165const FNV_PRIME_32 = 0x01000193;
166const SECONDARY_HASH_SEED = 0x9e3779b9;
167const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
168const LARGE_DIFF_LINE_THRESHOLD = 400;
169const LARGE_DIFF_CHARACTER_THRESHOLD = 24_000;
170const NON_TEXT_FILE_EXTENSIONS = new Set([
171 "png",
172 "jpg",
173 "jpeg",
174 "gif",
175 "webp",
176 "bmp",
177 "ico",
178 "icns",
179 "avif",
180 "heic",
181 "tif",
182 "tiff",
183 "mp3",
184 "wav",
185 "flac",
186 "ogg",
187 "m4a",
188 "aac",
189 "mp4",
190 "mov",
191 "avi",
192 "mkv",
193 "webm",
194 "pdf",
195 "zip",
196 "gz",
197 "tgz",
198 "bz2",
199 "7z",
200 "rar",
201 "woff",
202 "woff2",
203 "ttf",
204 "otf",
205 "eot",
206 "wasm",
207 "exe",
208 "dll",
209 "so",
210 "dylib",
211]);
212
213function fnv1a32(input: string, seed: number, multiplier: number): number {
214 let hash = seed >>> 0;
215 for (let index = 0; index < input.length; index += 1) {
216 hash ^= input.charCodeAt(index);
217 hash = Math.imul(hash, multiplier) >>> 0;
218 }
219 return hash >>> 0;
220}
221
222function buildPatchCacheKey(patch: string, scope: string): string {
223 const normalizedPatch = patch.trim();
224 const primary = fnv1a32(normalizedPatch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
225 const secondary = fnv1a32(
226 normalizedPatch,
227 SECONDARY_HASH_SEED,
228 SECONDARY_HASH_MULTIPLIER,
229 ).toString(36);
230 return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;
231}
232
233function getFileExtension(path: string): string | null {
234 const match = /\.([a-z0-9]+)$/i.exec(path);
235 return match?.[1]?.toLowerCase() ?? null;
236}
237
238function countReviewRenderableLineRows(file: ReviewRenderableFile): number {
239 return file.rows.reduce((total, row) => total + (row.kind === "line" ? 1 : 0), 0);
240}
241
242function countReviewRenderableCharacters(file: ReviewRenderableFile): number {
243 return file.rows.reduce(
244 (total, row) => total + (row.kind === "line" ? row.content.length : row.header.length),
245 0,
246 );
247}
248
249export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFilePreviewState {
250 const extension = getFileExtension(file.path);
251 if (extension && NON_TEXT_FILE_EXTENSIONS.has(extension)) {
252 return {
253 kind: "suppressed",
254 reason: "non-text",
255 title: "Non-text file",
256 message: "Diff preview is not available for this file format.",
257 actionLabel: null,
258 };
259 }
260
261 const lineCount = countReviewRenderableLineRows(file);
262 const characterCount = countReviewRenderableCharacters(file);
263 if (lineCount > LARGE_DIFF_LINE_THRESHOLD || characterCount > LARGE_DIFF_CHARACTER_THRESHOLD) {
264 return {
265 kind: "suppressed",
266 reason: "large",
267 title: "Large diff",
268 message: "Large diffs are not rendered by default.",
269 actionLabel: "Load diff",
270 };
271 }
272
273 return { kind: "render" };
274}
275
276function fallbackHunkHeader(hunk: FileDiffMetadata["hunks"][number]): string {
277 return `@@ -${hunk.deletionStart},${hunk.deletionCount} +${hunk.additionStart},${hunk.additionCount} @@`;
278}
279
280function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRenderableRow> {
281 const rows: ReviewRenderableRow[] = [];
282 let rowIndex = 0;
283
284 file.hunks.forEach((hunk, hunkIndex) => {
285 rows.push({
286 kind: "hunk",
287 id: `${file.cacheKey ?? file.name}:hunk:${hunkIndex}`,
288 header: fallbackHunkHeader(hunk),
289 context: hunk.hunkContext ? stripTrailingNewline(hunk.hunkContext) : null,
290 });
291
292 let deletionLineNumber = hunk.deletionStart;
293 let additionLineNumber = hunk.additionStart;
294 let deletionTokenIndex = hunk.deletionLineIndex;
295 let additionTokenIndex = hunk.additionLineIndex;
296
297 hunk.hunkContent.forEach((segment) => {
298 if (segment.type === "context") {
299 for (let index = 0; index < segment.lines; index += 1) {
300 rows.push({
301 kind: "line",
302 id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
303 change: "context",
304 oldLineNumber: deletionLineNumber,
305 newLineNumber: additionLineNumber,
306 content: stripTrailingNewline(
307 file.additionLines[additionTokenIndex] ??
308 file.deletionLines[deletionTokenIndex] ??
309 "",
310 ),
311 additionTokenIndex,
312 deletionTokenIndex,
313 comparison: null,
314 });
315 deletionLineNumber += 1;
316 additionLineNumber += 1;
317 deletionTokenIndex += 1;
318 additionTokenIndex += 1;
319 }
320 return;
321 }
322
323 const pairedLineCount = Math.min(segment.deletions, segment.additions);
324 const deletionTokenIndexStart = deletionTokenIndex;
325 const additionTokenIndexStart = additionTokenIndex;
326
327 for (let index = 0; index < segment.deletions; index += 1) {
328 rows.push({
329 kind: "line",
330 id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
331 change: "delete",
332 oldLineNumber: deletionLineNumber,
333 newLineNumber: null,
334 content: stripTrailingNewline(file.deletionLines[deletionTokenIndex] ?? ""),
335 additionTokenIndex: null,
336 deletionTokenIndex,
337 comparison:
338 index < pairedLineCount
339 ? {
340 change: "add",
341 tokenIndex: additionTokenIndexStart + index,
342 }
343 : null,
344 });
345 deletionLineNumber += 1;
346 deletionTokenIndex += 1;
347 }
348
349 for (let index = 0; index < segment.additions; index += 1) {
350 rows.push({
351 kind: "line",
352 id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
353 change: "add",
354 oldLineNumber: null,
355 newLineNumber: additionLineNumber,
356 content: stripTrailingNewline(file.additionLines[additionTokenIndex] ?? ""),
357 additionTokenIndex,
358 deletionTokenIndex: null,
359 comparison:
360 index < pairedLineCount
361 ? {
362 change: "delete",
363 tokenIndex: deletionTokenIndexStart + index,
364 }
365 : null,
366 });
367 additionLineNumber += 1;
368 additionTokenIndex += 1;
369 }
370 });
371 });
372
373 return rows;
374}
375
376function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
377 const path = unquoteGitPatchPath(file.name || file.prevName || "");
378 const previousPath = file.prevName ? unquoteGitPatchPath(file.prevName) : null;
379 const additions = file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0);
380 const deletions = file.hunks.reduce((total, hunk) => total + hunk.deletionLines, 0);
381 const cacheKey = file.cacheKey ?? `${previousPath ?? "none"}:${path}:${file.type}`;
382
383 return {
384 id: cacheKey,
385 cacheKey,
386 path,
387 previousPath,
388 changeType: file.type,
389 additions,
390 deletions,
391 languageHint: file.lang ?? null,
392 additionLines: file.additionLines,
393 deletionLines: file.deletionLines,
394 rows: buildRenderableRows(file),
395 };
396}
397
398export function getReviewSectionIdForCheckpoint(
399 checkpoint: Pick<ThreadCheckpointSummary, "checkpointTurnCount">,
400): string {
401 return `turn:${checkpoint.checkpointTurnCount}`;
402}
403
404export function getReadyReviewCheckpoints(
405 checkpoints: ReadonlyArray<ThreadCheckpointSummary>,
406): ReadonlyArray<ThreadCheckpointSummary> {
407 return pipe(
408 checkpoints,
409 Arr.filter((checkpoint) => checkpoint.status === "ready"),
410 Arr.sort(readyCheckpointOrder),
411 );
412}
413
414export function buildReviewSectionItems(input: {
415 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
416 readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
417 readonly turnDiffById: Readonly<Record<string, string | undefined>>;
418 readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
419 readonly loadingGitSections: boolean;
420}): ReadonlyArray<ReviewSectionItem> {
421 const turnItems = getReadyReviewCheckpoints(input.checkpoints).map<ReviewSectionItem>(
422 (checkpoint) => {
423 const id = getReviewSectionIdForCheckpoint(checkpoint);
424 return {
425 id,
426 kind: "turn",
427 title: checkpointTitle(checkpoint),
428 subtitle: checkpointSubtitle(checkpoint),
429 diff: input.turnDiffById[id] ?? null,
430 isLoading: input.loadingTurnIds[id] === true,
431 };
432 },
433 );
434
435 const gitItems = input.gitSections.map<ReviewSectionItem>((section) => ({
436 id: `git:${section.kind}`,
437 kind: section.kind,
438 title: section.title,
439 subtitle: gitSubtitle(section),
440 diff: section.diff,
441 source: section,
442 ...(section.files ? { files: section.files } : {}),
443 truncated: section.truncated,
444 isLoading: false,
445 }));
446 // Changes is the default section, so it holds the place while git sources load.
447 const hasChangesItem = gitItems.some((item) => item.id === CHANGES_SECTION_ID);
448 const visibleGitItems =
449 input.loadingGitSections && !hasChangesItem
450 ? [
451 {
452 id: CHANGES_SECTION_ID,
453 kind: "branch-range",
454 title: CHANGES_TITLE,
455 subtitle: null,
456 diff: null,
457 isLoading: true,
458 } satisfies ReviewSectionItem,
459 ...gitItems,
460 ]
461 : gitItems;
462
463 return [...turnItems, ...visibleGitItems];
464}
465
466/** Prefers Changes, then the first section (a turn when the project is not a git repo). */
467export function getDefaultReviewSectionId(
468 sections: ReadonlyArray<ReviewSectionItem>,
469): string | null {
470 return (sections.find((section) => section.id === CHANGES_SECTION_ID) ?? 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}
531
532export function applyReviewDiffMetadata(
533 previewDiff: ReviewParsedDiff,
534 selectedSection: Pick<ReviewSectionItem, "files" | "truncated"> | null,
535): ReviewParsedDiff {
536 if (previewDiff.kind === "empty") return previewDiff;
537 const notice = selectedSection?.truncated
538 ? `This preview exceeds the size limit. Changes shown are incomplete.${selectedSection.files ? " Counts include all changes." : ""}`
539 : previewDiff.notice;
540 if (previewDiff.kind !== "files" || !selectedSection?.files) return { ...previewDiff, notice };
541 const totals = selectedSection.files.reduce(
542 (total, file) => ({
543 additions: total.additions + file.additions,
544 deletions: total.deletions + file.deletions,
545 }),
546 { additions: 0, deletions: 0 },
547 );
548 const stats = new Map(selectedSection.files.map((file) => [file.path, file]));
549 const files = previewDiff.files.map((file) => {
550 const stat = stats.get(file.path);
551 return stat ? { ...file, additions: stat.additions, deletions: stat.deletions } : file;
552 });
553 return { ...previewDiff, ...totals, files, fileCount: selectedSection.files.length, notice };
554}