The best way to control Claude Code, Codex and more from any computer or phone

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