Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

reviewModel.ts

654 lines20.3 KB

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;
27​
28export interface ReviewRenderableHunkRow {
29 readonly kind: "hunk";
30 readonly id: string;
31 readonly header: string;
32 readonly context: string | null;
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;
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>;
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}`;
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`;
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;
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";
141​
142function stripTrailingNewline(value: string): string {
143 return value.endsWith("\n") ? value.slice(0, -1) : value;
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 };
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 }
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;
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}`;
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;
247​
248function getFileExtension(path: string): string | null {
249 const match = /\.([a-z0-9]+)$/i.exec(path);
250 return match?.[1]?.toLowerCase() ?? null;
252​
253function countReviewRenderableLineRows(file: ReviewRenderableFile): number {
254 return file.rows.reduce((total, row) => total + (row.kind === "line" ? 1 : 0), 0);
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 );
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" };
290​
291function fallbackHunkHeader(hunk: FileDiffMetadata["hunks"][number]): string {
292 return `@@ -${hunk.deletionStart},${hunk.deletionCount} +${hunk.additionStart},${hunk.additionCount} @@`;
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;
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 };
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 };
485​
486export function getReviewSectionIdForCheckpoint(
487 checkpoint: Pick<ThreadCheckpointSummary, "checkpointTurnCount">,
488): string {
489 return `turn:${checkpoint.checkpointTurnCount}`;
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 );
501​
502export function buildReviewSectionItems(input: {
503 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
504 readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
505 readonly turnDiffById: Readonly<Record<string, string | undefined>>;
506 readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
507 readonly loadingGitSections: boolean;
508}): ReadonlyArray<ReviewSectionItem> {
509 const turnItems = getReadyReviewCheckpoints(input.checkpoints).map<ReviewSectionItem>(
510 (checkpoint) => {
511 const id = getReviewSectionIdForCheckpoint(checkpoint);
512 return {
513 id,
514 kind: "turn",
515 title: checkpointTitle(checkpoint),
516 subtitle: checkpointSubtitle(checkpoint),
517 diff: input.turnDiffById[id] ?? null,
518 isLoading: input.loadingTurnIds[id] === true,
519 };
520 },
521 );
522​
523 const gitItems = input.gitSections.map<ReviewSectionItem>((section) => ({
524 id: `git:${section.kind}`,
525 kind: section.kind,
526 title: section.title,
527 subtitle: gitSubtitle(section),
528 diff: section.diff,
529 source: section,
530 ...(section.files ? { files: section.files } : {}),
531 truncated: section.truncated,
532 isLoading: false,
533 }));
534 const hasChangesItem = gitItems.some((item) => item.id === CHANGES_SECTION_ID);
535 const visibleGitItems =
536 input.loadingGitSections && !hasChangesItem
537 ? [
538 {
539 id: CHANGES_SECTION_ID,
540 kind: "branch-range",
541 title: CHANGES_TITLE,
542 subtitle: null,
543 diff: null,
544 isLoading: true,
545 } satisfies ReviewSectionItem,
546 ...gitItems,
547 ]
548 : gitItems;
549​
550 return [...turnItems, ...visibleGitItems];
552​
553export function getDefaultReviewSectionId(
554 sections: ReadonlyArray<ReviewSectionItem>,
555): string | null {
556 return (sections.find((section) => section.id === CHANGES_SECTION_ID) ?? sections[0])?.id ?? null;
558​
559export function buildReviewParsedDiff(
560 diff: string | null | undefined,
561 cacheScope: string,
562): ReviewParsedDiff {
563 if (!diff?.trim()) {
564 return { kind: "empty" };
565 }
566​
567 const { text, truncated } = splitTruncationMarker(diff);
568 if (text.length === 0) {
569 return { kind: "empty" };
570 }
571​
572 const notice = truncated
573 ? "Diff output hit the server size cap. Showing the available excerpt."
574 : null;
575​
576 try {
577 const cacheKey = buildPatchCacheKey(text, cacheScope);
578 const patchId = getReviewPatchId(cacheKey);
579 const parsedPatches = runDiffParserSilently(() => parsePatchFiles(text, cacheKey));
580 const rawFiles = new Map<string, string | null>();
581 if (!truncated) {
582 for (const rawFile of text.split(/(?=^diff --git )/m)) {
583 const header = rawFile.slice(0, rawFile.indexOf("\n"));
584 rawFiles.set(header, rawFiles.has(header) ? null : rawFile);
585 }
586 }
587 const files = pipe(
588 parsedPatches,
589 Arr.flatMap((patch) => patch.files),
590 Arr.map((file, index) =>
591 mapRenderableFile(
592 file,
593 `${patchId}:f${index.toString(36)}`,
594 rawFiles.get(
595 `diff --git ${quoteGitPatchPath(`a/${file.name}`)} ${quoteGitPatchPath(`b/${file.name}`)}`,
596 ),
597 ),
598 ),
599 );
600​
601 if (files.length === 0) {
602 return {
603 kind: "raw",
604 text,
605 reason: truncated
606 ? "Diff was truncated before it could be parsed completely. Showing the raw excerpt."
607 : "Unsupported diff format. Showing raw patch.",
608 notice,
609 };
610 }
611​
612 return {
613 kind: "files",
614 files,
615 fileCount: files.length,
616 additions: files.reduce((total, file) => total + file.additions, 0),
617 deletions: files.reduce((total, file) => total + file.deletions, 0),
618 notice,
619 };
620 } catch {
621 return {
622 kind: "raw",
623 text,
624 reason: truncated
625 ? "Diff was truncated before it could be parsed completely. Showing the raw excerpt."
626 : "Failed to parse patch. Showing raw patch.",
627 notice,
628 };
629 }
631​
632export function applyReviewDiffMetadata(
633 previewDiff: ReviewParsedDiff,
634 selectedSection: Pick<ReviewSectionItem, "files" | "truncated"> | null,
635): ReviewParsedDiff {
636 if (previewDiff.kind === "empty") return previewDiff;
637 const notice = selectedSection?.truncated
638 ? `This preview exceeds the size limit. Changes shown are incomplete.${selectedSection.files ? " Counts include all changes." : ""}`
639 : previewDiff.notice;
640 if (previewDiff.kind !== "files" || !selectedSection?.files) return { ...previewDiff, notice };
641 const totals = selectedSection.files.reduce(
642 (total, file) => ({
643 additions: total.additions + file.additions,
644 deletions: total.deletions + file.deletions,
645 }),
646 { additions: 0, deletions: 0 },
647 );
648 const stats = new Map(selectedSection.files.map((file) => [file.path, file]));
649 const files = previewDiff.files.map((file) => {
650 const stat = stats.get(file.path);
651 return stat ? { ...file, additions: stat.additions, deletions: stat.deletions } : file;
652 });
653 return { ...previewDiff, ...totals, files, fileCount: selectedSection.files.length, notice };