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 { quoteGitPatchPath } 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 // Only populated after validating the entire raw file block against its original hunk count.
65 readonly completePatchSource?: () => {
66 readonly oldContents: string;
67 readonly newContents: string;
68 };
69 readonly noEOFCRAdditions?: boolean;
70 readonly noEOFCRDeletions?: boolean;
71 readonly rows: ReadonlyArray<ReviewRenderableRow>;
72}
73
74export type ReviewFilePreviewState =
75 | {
76 readonly kind: "render";
77 }
78 | {
79 readonly kind: "suppressed";
80 readonly reason: "non-text" | "large";
81 readonly title: string;
82 readonly message: string;
83 readonly actionLabel: string | null;
84 };
85
86export type ReviewParsedDiff =
87 | {
88 readonly kind: "empty";
89 }
90 | {
91 readonly kind: "raw";
92 readonly text: string;
93 readonly reason: string;
94 readonly notice: string | null;
95 }
96 | {
97 readonly kind: "files";
98 readonly files: ReadonlyArray<ReviewRenderableFile>;
99 readonly fileCount: number;
100 readonly additions: number;
101 readonly deletions: number;
102 readonly notice: string | null;
103 };
104
105function checkpointTitle(checkpoint: ThreadCheckpointSummary): string {
106 return `Turn ${checkpoint.checkpointTurnCount}`;
107}
108
109function checkpointSubtitle(checkpoint: ThreadCheckpointSummary): string {
110 const fileCount = checkpoint.files.length;
111 if (checkpoint.status !== "ready") {
112 return `Diff ${checkpoint.status}`;
113 }
114 return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`;
115}
116
117function compareCheckpointTurnCountDescending(
118 left: ThreadCheckpointSummary,
119 right: ThreadCheckpointSummary,
120): -1 | 0 | 1 {
121 if (left.checkpointTurnCount === right.checkpointTurnCount) {
122 return 0;
123 }
124
125 return left.checkpointTurnCount > right.checkpointTurnCount ? -1 : 1;
126}
127
128const readyCheckpointOrder = Order.make<ThreadCheckpointSummary>(
129 compareCheckpointTurnCountDescending,
130);
131
132function gitSubtitle(section: ReviewDiffPreviewSource): string | null {
133 if (section.kind === "working-tree") {
134 return UNCOMMITTED_SUBTITLE;
135 }
136 if (section.baseRef) {
137 return `${section.baseRef} ... ${section.headRef ?? "HEAD"}`;
138 }
139 return "Base branch unavailable";
140}
141
142function stripTrailingNewline(value: string): string {
143 return value.endsWith("\n") ? value.slice(0, -1) : value;
144}
145
146function splitTruncationMarker(diff: string): {
147 readonly text: string;
148 readonly truncated: boolean;
149} {
150 const marker = /(?:(?:\r?\n){1,2}|^)\[truncated\]\s*$/.exec(diff);
151 if (!marker) {
152 return { text: diff, truncated: false };
153 }
154
155 return {
156 text: diff.slice(0, marker.index),
157 truncated: true,
158 };
159}
160
161function runDiffParserSilently<T>(callback: () => T): T {
162 const originalConsoleError = console.error;
163 console.error = () => undefined;
164 try {
165 return callback();
166 } finally {
167 console.error = originalConsoleError;
168 }
169}
170
171const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
172const FNV_PRIME_32 = 0x01000193;
173const SECONDARY_HASH_SEED = 0x9e3779b9;
174const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
175const LARGE_DIFF_LINE_THRESHOLD = 400;
176const LARGE_DIFF_CHARACTER_THRESHOLD = 24_000;
177const NON_TEXT_FILE_EXTENSIONS = new Set([
178 "png",
179 "jpg",
180 "jpeg",
181 "gif",
182 "webp",
183 "bmp",
184 "ico",
185 "icns",
186 "avif",
187 "heic",
188 "tif",
189 "tiff",
190 "mp3",
191 "wav",
192 "flac",
193 "ogg",
194 "m4a",
195 "aac",
196 "mp4",
197 "mov",
198 "avi",
199 "mkv",
200 "webm",
201 "pdf",
202 "zip",
203 "gz",
204 "tgz",
205 "bz2",
206 "7z",
207 "rar",
208 "woff",
209 "woff2",
210 "ttf",
211 "otf",
212 "eot",
213 "wasm",
214 "exe",
215 "dll",
216 "so",
217 "dylib",
218]);
219
220function fnv1a32(input: string, seed: number, multiplier: number): number {
221 let hash = seed >>> 0;
222 for (let index = 0; index < input.length; index += 1) {
223 hash ^= input.charCodeAt(index);
224 hash = Math.imul(hash, multiplier) >>> 0;
225 }
226 return hash >>> 0;
227}
228
229function buildPatchCacheKey(patch: string, scope: string): string {
230 const primary = fnv1a32(patch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
231 const secondary = fnv1a32(patch, SECONDARY_HASH_SEED, SECONDARY_HASH_MULTIPLIER).toString(36);
232 return `${scope}:${patch.length}:${primary}:${secondary}`;
233}
234
235// Re-parsing an unchanged page must preserve selection/collapse state. Intern only
236// its cache key (never patch contents), keeping scoped Pierre keys off every UI row.
237const reviewPatchIds = new Map<string, string>();
238
239function getReviewPatchId(cacheKey: string): string {
240 let id = reviewPatchIds.get(cacheKey);
241 if (id === undefined) {
242 id = `p${reviewPatchIds.size.toString(36)}`;
243 reviewPatchIds.set(cacheKey, id);
244 }
245 return id;
246}
247
248function getFileExtension(path: string): string | null {
249 const match = /\.([a-z0-9]+)$/i.exec(path);
250 return match?.[1]?.toLowerCase() ?? null;
251}
252
253function countReviewRenderableLineRows(file: ReviewRenderableFile): number {
254 return file.rows.reduce((total, row) => total + (row.kind === "line" ? 1 : 0), 0);
255}
256
257function countReviewRenderableCharacters(file: ReviewRenderableFile): number {
258 return file.rows.reduce(
259 (total, row) => total + (row.kind === "line" ? row.content.length : row.header.length),
260 0,
261 );
262}
263
264export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFilePreviewState {
265 const extension = getFileExtension(file.path);
266 if (extension && NON_TEXT_FILE_EXTENSIONS.has(extension)) {
267 return {
268 kind: "suppressed",
269 reason: "non-text",
270 title: "Non-text file",
271 message: "Diff preview is not available for this file format.",
272 actionLabel: null,
273 };
274 }
275
276 const lineCount = countReviewRenderableLineRows(file);
277 const characterCount = countReviewRenderableCharacters(file);
278 if (lineCount > LARGE_DIFF_LINE_THRESHOLD || characterCount > LARGE_DIFF_CHARACTER_THRESHOLD) {
279 return {
280 kind: "suppressed",
281 reason: "large",
282 title: "Large diff",
283 message: "Large diffs are not rendered by default.",
284 actionLabel: "Load diff",
285 };
286 }
287
288 return { kind: "render" };
289}
290
291function fallbackHunkHeader(hunk: FileDiffMetadata["hunks"][number]): string {
292 return `@@ -${hunk.deletionStart},${hunk.deletionCount} +${hunk.additionStart},${hunk.additionCount} @@`;
293}
294
295function buildRenderableRows(
296 file: FileDiffMetadata,
297 fileId: string,
298): ReadonlyArray<ReviewRenderableRow> {
299 const rows: ReviewRenderableRow[] = [];
300 let rowIndex = 0;
301
302 file.hunks.forEach((hunk, hunkIndex) => {
303 rows.push({
304 kind: "hunk",
305 id: `${fileId}:hunk:${hunkIndex}`,
306 header: fallbackHunkHeader(hunk),
307 context: hunk.hunkContext ? stripTrailingNewline(hunk.hunkContext) : null,
308 });
309
310 let deletionLineNumber = hunk.deletionStart;
311 let additionLineNumber = hunk.additionStart;
312 let deletionTokenIndex = hunk.deletionLineIndex;
313 let additionTokenIndex = hunk.additionLineIndex;
314
315 hunk.hunkContent.forEach((segment) => {
316 if (segment.type === "context") {
317 for (let index = 0; index < segment.lines; index += 1) {
318 rows.push({
319 kind: "line",
320 id: `${fileId}:row:${rowIndex++}`,
321 change: "context",
322 oldLineNumber: deletionLineNumber,
323 newLineNumber: additionLineNumber,
324 content: stripTrailingNewline(
325 file.additionLines[additionTokenIndex] ??
326 file.deletionLines[deletionTokenIndex] ??
327 "",
328 ),
329 additionTokenIndex,
330 deletionTokenIndex,
331 comparison: null,
332 });
333 deletionLineNumber += 1;
334 additionLineNumber += 1;
335 deletionTokenIndex += 1;
336 additionTokenIndex += 1;
337 }
338 return;
339 }
340
341 const pairedLineCount = Math.min(segment.deletions, segment.additions);
342 const deletionTokenIndexStart = deletionTokenIndex;
343 const additionTokenIndexStart = additionTokenIndex;
344
345 for (let index = 0; index < segment.deletions; index += 1) {
346 rows.push({
347 kind: "line",
348 id: `${fileId}:row:${rowIndex++}`,
349 change: "delete",
350 oldLineNumber: deletionLineNumber,
351 newLineNumber: null,
352 content: stripTrailingNewline(file.deletionLines[deletionTokenIndex] ?? ""),
353 additionTokenIndex: null,
354 deletionTokenIndex,
355 comparison:
356 index < pairedLineCount
357 ? {
358 change: "add",
359 tokenIndex: additionTokenIndexStart + index,
360 }
361 : null,
362 });
363 deletionLineNumber += 1;
364 deletionTokenIndex += 1;
365 }
366
367 for (let index = 0; index < segment.additions; index += 1) {
368 rows.push({
369 kind: "line",
370 id: `${fileId}:row:${rowIndex++}`,
371 change: "add",
372 oldLineNumber: null,
373 newLineNumber: additionLineNumber,
374 content: stripTrailingNewline(file.additionLines[additionTokenIndex] ?? ""),
375 additionTokenIndex,
376 deletionTokenIndex: null,
377 comparison:
378 index < pairedLineCount
379 ? {
380 change: "delete",
381 tokenIndex: deletionTokenIndexStart + index,
382 }
383 : null,
384 });
385 additionLineNumber += 1;
386 additionTokenIndex += 1;
387 }
388 });
389 });
390
391 return rows;
392}
393
394function completePatchSource(file: FileDiffMetadata, rawPatch: string | null | undefined) {
395 if (!rawPatch || (file.type !== "new" && file.type !== "deleted") || file.hunks.length !== 1) {
396 return undefined;
397 }
398 const added = file.type === "new";
399 const a = quoteGitPatchPath(`a/${file.name}`);
400 const b = quoteGitPatchPath(`b/${file.name}`);
401 const lines = rawPatch.split("\n");
402 if (lines.pop() !== "" || rawPatch.includes("\0")) return undefined;
403 let index = 0;
404 if (lines[index++] !== `diff --git ${a} ${b}`) return undefined;
405 if (
406 !new RegExp(`^${added ? "new" : "deleted"} file mode 100(644|755)$`).test(lines[index++] ?? "")
407 ) {
408 return undefined;
409 }
410 if (lines[index]?.startsWith("index ")) {
411 if (!/^index [0-9a-f]+\.\.[0-9a-f]+(?: 100(?:644|755))?$/.test(lines[index++] ?? "")) {
412 return undefined;
413 }
414 }
415 if (lines[index++] !== `--- ${added ? "/dev/null" : a}`) return undefined;
416 if (lines[index++] !== `+++ ${added ? b : "/dev/null"}`) return undefined;
417 // Pierre repairs both underfull and overfull hunks. Its resulting counts cannot
418 // prove that patch lines cover the whole file; read the original header instead.
419 const header = lines[index++] ?? "";
420 // GitCafe's structured hunks can start the empty side at 1 instead of git's 0.
421 // Its explicit zero count still proves that side contributes no source lines.
422 const match = (added ? /^@@ -[01],0 \+1(?:,(\d+))? @@$/ : /^@@ -1(?:,(\d+))? \+[01],0 @@$/).exec(
423 header,
424 );
425 if (!match) return undefined;
426 const count = Number(match[1] ?? 1);
427 if (!Number.isSafeInteger(count) || count <= 0) return undefined;
428 const hunk = file.hunks[0]!;
429 if (
430 hunk.hunkSpecs !== `${header}\n` ||
431 (added ? hunk.additionCount : hunk.deletionCount) !== count ||
432 (added ? file.additionLines : file.deletionLines).length !== count ||
433 (added ? file.deletionLines : file.additionLines).length !== 0
434 )
435 return undefined;
436 const bodyStart = lines.slice(0, index).reduce((length, line) => length + line.length + 1, 0);
437 const prefix = added ? "+" : "-";
438 for (let line = 0; line < count; line++) {
439 if (!lines[index++]?.startsWith(prefix)) return undefined;
440 }
441 let bodyEnd = rawPatch.length;
442 if (lines[index] === "\\ No newline at end of file") {
443 // Only the patch's LF is synthetic, including when the source ends in a bare CR.
444 bodyEnd -= "\\ No newline at end of file\n".length + 1;
445 index++;
446 }
447 if (index !== lines.length) return undefined;
448 // Keep reconstruction lazy so only requested source enters the bounded source cache.
449 return () => {
450 const contents = rawPatch.slice(bodyStart + 1, bodyEnd).replace(/\n[+-]/g, "\n");
451 return added
452 ? { oldContents: "", newContents: contents }
453 : { oldContents: contents, newContents: "" };
454 };
455}
456
457function mapRenderableFile(
458 file: FileDiffMetadata,
459 id: string,
460 rawPatch?: string | null,
461): ReviewRenderableFile {
462 const path = file.name || file.prevName || "";
463 const previousPath = file.prevName || null;
464 const additions = file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0);
465 const deletions = file.hunks.reduce((total, hunk) => total + hunk.deletionLines, 0);
466 const cacheKey = file.cacheKey ?? `${previousPath ?? "none"}:${path}:${file.type}`;
467
468 return {
469 id,
470 cacheKey,
471 path,
472 previousPath,
473 changeType: file.type,
474 additions,
475 deletions,
476 languageHint: file.lang ?? null,
477 additionLines: file.additionLines,
478 deletionLines: file.deletionLines,
479 completePatchSource: completePatchSource(file, rawPatch),
480 noEOFCRAdditions: file.hunks.some((hunk) => hunk.noEOFCRAdditions),
481 noEOFCRDeletions: file.hunks.some((hunk) => hunk.noEOFCRDeletions),
482 rows: buildRenderableRows(file, id),
483 };
484}
485
486export function getReviewSectionIdForCheckpoint(
487 checkpoint: Pick<ThreadCheckpointSummary, "checkpointTurnCount">,
488): string {
489 return `turn:${checkpoint.checkpointTurnCount}`;
490}
491
492export function getReadyReviewCheckpoints(
493 checkpoints: ReadonlyArray<ThreadCheckpointSummary>,
494): ReadonlyArray<ThreadCheckpointSummary> {
495 return pipe(
496 checkpoints,
497 Arr.filter((checkpoint) => checkpoint.status === "ready"),
498 Arr.sort(readyCheckpointOrder),
499 );
500}
501
502export function reviewTurnDiffsBySectionId(
503 checkpoints: ReadonlyArray<Pick<ThreadCheckpointSummary, "checkpointTurnCount">>,
504 diffByTurnCount: Readonly<Record<number, string | undefined>>,
505): Readonly<Record<string, string | undefined>> {
506 return Object.fromEntries(
507 checkpoints.map((checkpoint) => [
508 getReviewSectionIdForCheckpoint(checkpoint),
509 diffByTurnCount[checkpoint.checkpointTurnCount],
510 ]),
511 );
512}
513
514export function buildReviewSectionItems(input: {
515 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
516 readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
517 readonly turnDiffById: Readonly<Record<string, string | undefined>>;
518 readonly loadingGitSections: boolean;
519}): ReadonlyArray<ReviewSectionItem> {
520 const turnItems = getReadyReviewCheckpoints(input.checkpoints).map<ReviewSectionItem>(
521 (checkpoint) => {
522 const id = getReviewSectionIdForCheckpoint(checkpoint);
523 return {
524 id,
525 kind: "turn",
526 title: checkpointTitle(checkpoint),
527 subtitle: checkpointSubtitle(checkpoint),
528 diff: input.turnDiffById[id] ?? null,
529 isLoading: false,
530 };
531 },
532 );
533
534 const gitItems = input.gitSections.map<ReviewSectionItem>((section) => ({
535 id: `git:${section.kind}`,
536 kind: section.kind,
537 title: section.title,
538 subtitle: gitSubtitle(section),
539 diff: section.diff,
540 source: section,
541 ...(section.files ? { files: section.files } : {}),
542 truncated: section.truncated,
543 isLoading: false,
544 }));
545 const hasChangesItem = gitItems.some((item) => item.id === CHANGES_SECTION_ID);
546 const visibleGitItems =
547 input.loadingGitSections && !hasChangesItem
548 ? [
549 {
550 id: CHANGES_SECTION_ID,
551 kind: "branch-range",
552 title: CHANGES_TITLE,
553 subtitle: null,
554 diff: null,
555 isLoading: true,
556 } satisfies ReviewSectionItem,
557 ...gitItems,
558 ]
559 : gitItems;
560
561 return [...turnItems, ...visibleGitItems];
562}
563
564export function getDefaultReviewSectionId(
565 sections: ReadonlyArray<ReviewSectionItem>,
566): string | null {
567 return (sections.find((section) => section.id === CHANGES_SECTION_ID) ?? sections[0])?.id ?? null;
568}
569
570/**
571 * The store holds only the user's pick. While that section is missing (still loading, or the
572 * working tree went clean) the default shows, and the pick returns once the section does: the
573 * thread-feed entry relies on this, as it selects a section before the sections have loaded.
574 */
575export function resolveReviewSelectedSectionId(
576 sections: ReadonlyArray<ReviewSectionItem>,
577 storedSectionId: string | null,
578): string | null {
579 return storedSectionId !== null && sections.some((section) => section.id === storedSectionId)
580 ? storedSectionId
581 : getDefaultReviewSectionId(sections);
582}
583
584export function buildReviewParsedDiff(
585 diff: string | null | undefined,
586 cacheScope: string,
587): ReviewParsedDiff {
588 if (!diff?.trim()) {
589 return { kind: "empty" };
590 }
591
592 const { text, truncated } = splitTruncationMarker(diff);
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 cacheKey = buildPatchCacheKey(text, cacheScope);
603 const patchId = getReviewPatchId(cacheKey);
604 const parsedPatches = runDiffParserSilently(() => parsePatchFiles(text, cacheKey));
605 const rawFiles = new Map<string, string | null>();
606 if (!truncated) {
607 for (const rawFile of text.split(/(?=^diff --git )/m)) {
608 const header = rawFile.slice(0, rawFile.indexOf("\n"));
609 rawFiles.set(header, rawFiles.has(header) ? null : rawFile);
610 }
611 }
612 const files = pipe(
613 parsedPatches,
614 Arr.flatMap((patch) => patch.files),
615 Arr.map((file, index) =>
616 mapRenderableFile(
617 file,
618 `${patchId}:f${index.toString(36)}`,
619 rawFiles.get(
620 `diff --git ${quoteGitPatchPath(`a/${file.name}`)} ${quoteGitPatchPath(`b/${file.name}`)}`,
621 ),
622 ),
623 ),
624 );
625
626 if (files.length === 0) {
627 return {
628 kind: "raw",
629 text,
630 reason: truncated
631 ? "Diff was truncated before it could be parsed completely. Showing the raw excerpt."
632 : "Unsupported diff format. Showing raw patch.",
633 notice,
634 };
635 }
636
637 return {
638 kind: "files",
639 files,
640 fileCount: files.length,
641 additions: files.reduce((total, file) => total + file.additions, 0),
642 deletions: files.reduce((total, file) => total + file.deletions, 0),
643 notice,
644 };
645 } catch {
646 return {
647 kind: "raw",
648 text,
649 reason: truncated
650 ? "Diff was truncated before it could be parsed completely. Showing the raw excerpt."
651 : "Failed to parse patch. Showing raw patch.",
652 notice,
653 };
654 }
655}
656
657export function applyReviewDiffMetadata(
658 previewDiff: ReviewParsedDiff,
659 selectedSection: Pick<ReviewSectionItem, "files" | "truncated"> | null,
660): ReviewParsedDiff {
661 if (previewDiff.kind === "empty") return previewDiff;
662 const notice = selectedSection?.truncated
663 ? `This preview exceeds the size limit. Changes shown are incomplete.${selectedSection.files ? " Counts include all changes." : ""}`
664 : previewDiff.notice;
665 if (previewDiff.kind !== "files" || !selectedSection?.files) return { ...previewDiff, notice };
666 const totals = selectedSection.files.reduce(
667 (total, file) => ({
668 additions: total.additions + file.additions,
669 deletions: total.deletions + file.deletions,
670 }),
671 { additions: 0, deletions: 0 },
672 );
673 const stats = new Map(selectedSection.files.map((file) => [file.path, file]));
674 const files = previewDiff.files.map((file) => {
675 const stat = stats.get(file.path);
676 return stat ? { ...file, additions: stat.additions, deletions: stat.deletions } : file;
677 });
678 return { ...previewDiff, ...totals, files, fileCount: selectedSection.files.length, notice };
679}