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

reviewModel.ts

550 lines16.1 KB

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