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

reviewModel.ts

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