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

reviewModel.ts

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