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

reviewModel.ts

682 lines21.2 KB

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