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

reviewTurnDiffs.ts

132 lines5.3 KB

1import { turnDiffSections } from "@t3tools/client-runtime/state/thread-repositories";
2import type { EnvironmentId, OrchestrationGetTurnDiffResult, ThreadId } from "@t3tools/contracts";
3import { quoteGitPatchPath, unquoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
4import * as Effect from "effect/Effect";
5import { Atom, type AtomRegistry } from "effect/reactivity";
6​
7const TRUNCATION_MARKER = /(?:\r?\n){1,2}\[truncated\]\s*$/;
8const QUOTED_PATH = String.raw`"(?:[^"\\]|\\.)*"`;
9const GIT_HEADER_PATHS = new RegExp(`^(${QUOTED_PATH}|a/.*?) (${QUOTED_PATH}|b/.*)$`);
10const BINARY_FILES = new RegExp(
11 `^Binary files (${QUOTED_PATH}|.+?) and (${QUOTED_PATH}|.+) differ$`,
12);
13const HEADER_PATH_LINES = [
14 ["--- ", "a/"],
15 ["+++ ", "b/"],
16 ["rename from ", ""],
17 ["rename to ", ""],
18 ["copy from ", ""],
19 ["copy to ", ""],
20] as const;
21​
22function pathInFolder(token: string, folder: string, side: "a/" | "b/" | ""): string {
23 const quoted = token.length >= 2 && token.startsWith('"') && token.endsWith('"');
24 const path = quoted ? unquoteGitPatchPath(token) : token;
25 if (path === "/dev/null" || !path.startsWith(side)) return token;
26 return quoteGitPatchPath(`${side}${folder}/${path.slice(side.length)}`);
28​
29function gitHeaderPaths(paths: string): readonly [string, string] | null {
30 // An unchanged name is repeated, which settles where a name holding " b/" ends.
31 const middle = (paths.length - 1) / 2;
32 if (
33 Number.isInteger(middle) &&
34 paths.startsWith("a/") &&
35 paths.startsWith(" b/", middle) &&
36 paths.slice(2, middle) === paths.slice(middle + 3)
37 ) {
38 return [paths.slice(0, middle), paths.slice(middle + 1)];
39 }
40 const match = GIT_HEADER_PATHS.exec(paths);
41 return match ? [match[1]!, match[2]!] : null;
43​
44function patchInFolder(patch: string, folder: string): string {
45 let inHeader = false;
46 return patch
47 .split("\n")
48 .map((line) => {
49 if (line.startsWith("diff --git ")) {
50 inHeader = true;
51 const paths = gitHeaderPaths(line.slice("diff --git ".length));
52 return paths === null
53 ? line
54 : `diff --git ${pathInFolder(paths[0], folder, "a/")} ${pathInFolder(paths[1], folder, "b/")}`;
55 }
56 if (!inHeader) return line;
57 if (line.startsWith("@@") || line === "GIT binary patch") {
58 inHeader = false;
59 return line;
60 }
61 for (const [lead, side] of HEADER_PATH_LINES) {
62 if (!line.startsWith(lead)) continue;
63 const tab = line.endsWith("\t") ? "\t" : "";
64 const token = line.slice(lead.length, line.length - tab.length);
65 return `${lead}${pathInFolder(token, folder, side)}${tab}`;
66 }
67 const binary = BINARY_FILES.exec(line);
68 return binary
69 ? // oxlint-disable-next-line t3code/no-untranslated-copy -- a line of Git patch text, parsed as a diff
70 `Binary files ${pathInFolder(binary[1]!, folder, "a/")} and ${pathInFolder(binary[2]!, folder, "b/")} differ`
71 : line;
72 })
73 .join("\n");
75​
76/**
77 * A turn diff as the one patch review shows. Each tracked repository's files are renamed from
78 * the thread's folder, so the same path in two repositories stays two files and a review comment
79 * names a path the agent can open.
80 */
81export function reviewTurnDiffText(diff: Parameters<typeof turnDiffSections>[0]): string {
82 const sections = turnDiffSections(diff, "");
83 if (sections.every((section) => section.repositoryPath === null)) return diff.diff;
84 let truncated = false;
85 const patches = sections.map((section) => {
86 const marker = TRUNCATION_MARKER.exec(section.diff);
87 truncated ||= marker !== null;
88 const text = marker === null ? section.diff : section.diff.slice(0, marker.index);
89 const patch =
90 section.relativePath === "" || section.relativePath === "."
91 ? text
92 : patchInFolder(text, section.relativePath);
93 return patch.endsWith("\n") ? patch : `${patch}\n`;
94 });
95 return `${patches.join("")}${truncated ? "\n[truncated]" : ""}`;
97​
98const EMPTY_TURN_DIFFS = Object.freeze<Readonly<Record<number, string>>>({});
99​
100// The last answered diff of each single turn, keyed by its turn count, so review keeps showing
101// turns it already loaded while the environment is disconnected and no turn query is mounted.
102const lastTurnDiffsFamily = Atom.family((key: string) =>
103 Atom.make(EMPTY_TURN_DIFFS).pipe(
104 Atom.keepAlive,
105 Atom.withLabel(`mobile:review:turn-diffs:${key}`),
106 ),
107);
108​
109export function lastReviewTurnDiffsAtom(environmentId: EnvironmentId, threadId: ThreadId) {
110 return lastTurnDiffsFamily(JSON.stringify([environmentId, threadId]));
112​
113export const recordReviewTurnDiffAnswer = (
114 target: {
115 readonly environmentId: EnvironmentId;
116 readonly input: { readonly ignoreWhitespace?: boolean };
117 },
118 value: OrchestrationGetTurnDiffResult,
119 registry: AtomRegistry.AtomRegistry,
120) =>
121 Effect.sync(() => {
122 // Review shows one turn with whitespace changes; other ranges and whitespace-ignoring
123 // reads are not what a review section displays.
124 if (target.input.ignoreWhitespace === true || value.fromTurnCount !== value.toTurnCount - 1) {
125 return;
126 }
127 const atom = lastReviewTurnDiffsAtom(target.environmentId, value.threadId);
128 const current = registry.get(atom);
129 const diff = reviewTurnDiffText(value);
130 if (current[value.toTurnCount] === diff) return;
131 registry.set(atom, { ...current, [value.toTurnCount]: diff });
132 });