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

toolCallDiff.ts

167 lines7.3 KB

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