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 // Windows separates with / or \ (\\ in a quoted header); POSIX only with /, where a \ is part of
69 // a name and a quoted header doubles it.
70 const separator = windows ? String.raw`[\\/]+` : "/+";
71 const root = segments
72 .map((segment) =>
73 segment
74 .split("\\")
75 .map((text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
76 .join(String.raw`\\\\?`),
77 )
78 .join(separator);
79 const prefix = new RegExp(String.raw`^("?(?:[ab]/)?)${root}${separator}`, windows ? "i" : "");
80 const relative = (name: string) => name.replace(prefix, "$1");
81 let inHeader = true;
82 return patch
83 .split("\n")
84 .map((line) => {
85 if (line.startsWith("diff --git ")) {
86 inHeader = true;
87 // Split the names as Pierre's parser does, so a name containing a space stays whole.
88 const names =
89 /^diff --git ("a\/(?:[^"\\]|\\.)*"|a\/.+?) ("b\/(?:[^"\\]|\\.)*"|b\/.+?)$/.exec(line);
90 return names ? `diff --git ${relative(names[1]!)} ${relative(names[2]!)}` : line;
91 }
92 if (line.startsWith("@@")) inHeader = false;
93 const name = inHeader ? /^(---|\+\+\+)(\s+)(.*)$/.exec(line) : null;
94 return name ? `${name[1]}${name[2]}${relative(name[3]!)}` : line;
95 })
96 .join("\n");
97}
98
99function recordedText(value: string | undefined) {
100 const suffix = "\n… output truncated for transport";
101 const truncated = value !== undefined && value.endsWith(suffix);
102 return { text: truncated ? value.slice(0, -suffix.length) : value, truncated };
103}
104
105export function toolCallDiff(
106 item: Pick<FileChange, "diffStr" | "fileName" | "changes" | "oldStr" | "newStr"> &
107 Partial<Pick<FileChange, "status">>,
108 workspaceRoot?: string,
109 resolve: MessageResolver = m,
110) {
111 const diff = recordedText(item.diffStr);
112 const operation = item.changes?.[0]?.operation;
113 const emptyContent = diff.text === "" ? "" : undefined;
114 const before = recordedText(item.oldStr ?? (operation === "delete" ? emptyContent : undefined));
115 const after = recordedText(item.newStr ?? (operation === "add" ? emptyContent : undefined));
116 const truncated = diff.truncated || before.truncated || after.truncated;
117 const change = item.changes?.[0];
118 const recordedPatch =
119 !diff.text?.trim() &&
120 !truncated &&
121 item.status === "completed" &&
122 (item.changes?.length ?? 0) <= 1 &&
123 before.text !== undefined &&
124 after.text !== undefined &&
125 before.text !== after.text
126 ? structuredPatch(
127 change?.oldPath ?? item.fileName,
128 change?.path ?? item.fileName,
129 before.text,
130 after.text,
131 undefined,
132 undefined,
133 { context: 3, maxEditLength: 1_000 },
134 )
135 : undefined;
136 const patch =
137 recordedPatch && recordedPatch.hunks.length > 0
138 ? formatPatch(recordedPatch, FILE_HEADERS_ONLY)
139 : toolCallPatch({ ...item, ...(diff.text === undefined ? {} : { diffStr: diff.text }) });
140 return {
141 patch: relativeHeaderPaths(patch, workspaceRoot),
142 content: patch?.trim()
143 ? []
144 : [
145 { label: resolve(msg("Recorded content before")), text: before.text },
146 { label: resolve(msg("Recorded content after")), text: after.text },
147 ].filter((entry): entry is { label: string; text: string } => entry.text !== undefined),
148 truncated,
149 };
150}