Open History to see the last commit
1import type { OrchestrationV2TurnItem } from "@t3tools/contracts";
2import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff";
3import { msg } from "gt-react";
4
5import { m, type MessageResolver } from "../i18n/messages";
6import { getRenderablePatch, resolveFileDiffPath } from "./diffRendering";
7
8type FileChange = Extract<OrchestrationV2TurnItem, { type: "file_change" }>;
9
10function toolCallPatch(item: Pick<FileChange, "diffStr" | "fileName" | "changes">) {
11 let patch = item.diffStr;
12 if (!patch) return patch;
13 const change = item.changes?.[0];
14 // OpenCode records a multi-file patch with an `Index:` line before each file.
15 const openCodePatch = (item.changes?.length ?? 0) > 1 && patch.startsWith("Index: ");
16 const rawFileOperation =
17 !openCodePatch && (change?.operation === "add" || change?.operation === "delete");
18 if (patch.startsWith("diff --git ") || patch.startsWith("--- ")) {
19 if (!rawFileOperation) return patch;
20 const parsed = getRenderablePatch(patch, "tool-call-format");
21 if (
22 parsed?.kind === "files" &&
23 parsed.files.every((file) => {
24 const path = resolveFileDiffPath(file).replaceAll("\\", "/");
25 // A multi-file patch gives an empty added or deleted file a header and no hunk.
26 return (
27 (file.hunks.length > 0 || (item.changes?.length ?? 0) > 1) &&
28 item.changes?.some((recorded) => {
29 const recordedPath = recorded.path.replaceAll("\\", "/");
30 return (
31 (recorded.operation === "add"
32 ? file.deletionLines.length === 0
33 : recorded.operation === "delete"
34 ? file.additionLines.length === 0
35 : true) &&
36 (recordedPath === path || recordedPath.endsWith(`/${path}`))
37 );
38 })
39 );
40 })
41 )
42 return patch;
43 }
44 // Codex can record added/deleted file contents or bare hunks instead of a complete patch.
45 if (rawFileOperation || !patch.trimStart().startsWith("@@ ")) {
46 if (!rawFileOperation) return patch;
47 const lines = patch.split("\n");
48 const hasFinalNewline = patch.endsWith("\n");
49 if (hasFinalNewline) lines.pop();
50 const added = change.operation === "add";
51 const range = `1,${lines.length}`;
52 patch = `@@ -${added ? "0,0" : range} +${added ? range : "0,0"} @@\n${lines.map((line) => `${added ? "+" : "-"}${line}`).join("\n")}\n${hasFinalNewline ? "" : "\\ No newline at end of file\n"}`;
53 }
54 const oldPath = change?.oldPath ?? item.fileName;
55 const newPath = change?.path ?? item.fileName;
56 const before = change?.operation === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`);
57 const after = change?.operation === "delete" ? "/dev/null" : JSON.stringify(`b/${newPath}`);
58 return `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${newPath}`)}\n--- ${before}\n+++ ${after}\n${patch.trimStart()}`;
59}
60
61// Claude records absolute paths; name files under the workspace relative to it, as other diffs do.
62// Only header lines, from the start or a `diff --git` line up to the first hunk, are rewritten.
63function relativeHeaderPaths(patch: string | undefined, workspaceRoot: string | undefined) {
64 const windows = /^(?:[A-Za-z]:[\\/]|\\\\)/.test(workspaceRoot ?? "");
65 const segments = workspaceRoot?.split(windows ? /[\\/]+/ : /\/+/);
66 while (segments?.at(-1) === "") segments.pop();
67 if (!patch || !segments?.some(Boolean)) return patch;
68 const separator = windows ? String.raw`[\\/]+` : "/+";
69 const headerPrefix = (quoted: boolean) => {
70 const root = segments
71 .map((segment) => (quoted ? JSON.stringify(segment).slice(1, -1) : segment))
72 .map((segment) => segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
73 .join(separator);
74 return new RegExp(`^(${quoted ? '"' : ""}(?:[ab]/)?)${root}${separator}`, windows ? "i" : "");
75 };
76 const rawPrefix = headerPrefix(false);
77 const quotedPrefix = headerPrefix(true);
78 const relative = (name: string) =>
79 name.replace(name.startsWith('"') ? quotedPrefix : rawPrefix, "$1");
80 let inHeader = true;
81 return patch
82 .split("\n")
83 .map((line) => {
84 if (line.startsWith("diff --git ")) {
85 inHeader = true;
86 // Split the names as Pierre's parser does, so a name containing a space stays whole.
87 const names =
88 /^diff --git ("a\/(?:[^"\\]|\\.)*"|a\/.+?) ("b\/(?:[^"\\]|\\.)*"|b\/.+?)$/.exec(line);
89 return names ? `diff --git ${relative(names[1]!)} ${relative(names[2]!)}` : line;
90 }
91 if (line.startsWith("@@")) inHeader = false;
92 const name = inHeader ? /^(---|\+\+\+)(\s+)(.*)$/.exec(line) : null;
93 return name ? `${name[1]}${name[2]}${relative(name[3]!)}` : line;
94 })
95 .join("\n");
96}
97
98function recordedText(value: string | undefined) {
99 const suffix = "\n… output truncated for transport";
100 const truncated = value !== undefined && value.endsWith(suffix);
101 return { text: truncated ? value.slice(0, -suffix.length) : value, truncated };
102}
103
104export function toolCallDiff(
105 item: Pick<FileChange, "diffStr" | "fileName" | "changes" | "oldStr" | "newStr"> &
106 Partial<Pick<FileChange, "status">>,
107 workspaceRoot?: string,
108 resolve: MessageResolver = m,
109) {
110 const diff = recordedText(item.diffStr);
111 const operation = item.changes?.[0]?.operation;
112 const emptyContent = diff.text === "" ? "" : undefined;
113 const before = recordedText(item.oldStr ?? (operation === "delete" ? emptyContent : undefined));
114 const after = recordedText(item.newStr ?? (operation === "add" ? emptyContent : undefined));
115 const truncated = diff.truncated || before.truncated || after.truncated;
116 const change = item.changes?.[0];
117 const recordedPatch =
118 !diff.text?.trim() &&
119 !truncated &&
120 item.status === "completed" &&
121 (item.changes?.length ?? 0) <= 1 &&
122 before.text !== undefined &&
123 after.text !== undefined &&
124 before.text !== after.text
125 ? structuredPatch(
126 change?.oldPath ?? item.fileName,
127 change?.path ?? item.fileName,
128 before.text,
129 after.text,
130 undefined,
131 undefined,
132 { context: 3, maxEditLength: 1_000 },
133 )
134 : undefined;
135 const patch =
136 recordedPatch && recordedPatch.hunks.length > 0
137 ? formatPatch(recordedPatch, FILE_HEADERS_ONLY)
138 : toolCallPatch({ ...item, ...(diff.text === undefined ? {} : { diffStr: diff.text }) });
139 return {
140 patch: relativeHeaderPaths(patch, workspaceRoot),
141 content: patch?.trim()
142 ? []
143 : [
144 { label: resolve(msg("Recorded content before")), text: before.text },
145 { label: resolve(msg("Recorded content after")), text: after.text },
146 ].filter((entry): entry is { label: string; text: string } => entry.text !== undefined),
147 truncated,
148 };
149}