diff-api.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. import { execFile as execFileCallback, spawn } from 'node:child_process';
  2. import { promisify } from 'node:util';
  3. import type {
  4. LocalFileDiff,
  5. LocalTurnDiffRecord,
  6. LocalTurnDiffStore,
  7. } from '../persistence/ports.js';
  8. import type { LocalSessionRecord } from '../sessions/controller.js';
  9. import { json } from '../api/host-helpers.js';
  10. import { applyLocalTurnDiffSnapshotMutation } from './file-changes.js';
  11. const execFile = promisify(execFileCallback);
  12. // Read paths and metrics as NUL records; patch headers are presentation only.
  13. const WORKSPACE_DIFF_ARGS = [
  14. '--raw',
  15. '--numstat',
  16. '-z',
  17. '--patch',
  18. '--no-color',
  19. '--no-ext-diff',
  20. '--no-textconv',
  21. ];
  22. export interface LocalDiffSession {
  23. readonly sessionId: string;
  24. readonly workspaceDir: string;
  25. }
  26. export interface LocalSessionDiffView {
  27. readonly diffs: LocalFileDiff[];
  28. readonly changeSetId?: string;
  29. }
  30. export interface LocalTurnDiffSelector {
  31. readonly assistantMessageId?: string;
  32. readonly turnId?: string;
  33. readonly changeSetId?: string;
  34. }
  35. export interface LocalTurnDiffView {
  36. readonly fileChanges: LocalFileDiff[];
  37. readonly sourceMessageId?: string;
  38. readonly changeSetId?: string;
  39. readonly status?: string;
  40. readonly revertedAt?: number;
  41. readonly undoable?: boolean;
  42. readonly canUndo?: boolean;
  43. readonly canReapply?: boolean;
  44. }
  45. export type LocalTurnDiffMutationBody = {
  46. readonly success: boolean;
  47. readonly error?: string;
  48. } & Partial<LocalTurnDiffView>;
  49. export interface LocalTurnDiffMutationOutcome {
  50. readonly status: 200 | 404 | 409;
  51. readonly body: LocalTurnDiffMutationBody;
  52. }
  53. export async function readLocalSessionDiff(input: {
  54. diffStore: LocalTurnDiffStore;
  55. session: LocalDiffSession;
  56. messageId?: string;
  57. }): Promise<LocalSessionDiffView> {
  58. const record = input.messageId
  59. ? await input.diffStore.getByAssistantMessage(input.session.sessionId, input.messageId)
  60. : await input.diffStore.latestForSession(input.session.sessionId);
  61. if (record) return { diffs: record.fileChanges, changeSetId: record.changeSetId };
  62. const live = await readWorkspaceDiff(input.session.workspaceDir);
  63. return { diffs: live.fileChanges };
  64. }
  65. export async function readLocalTurnDiff(input: {
  66. diffStore: LocalTurnDiffStore;
  67. sessionId: string;
  68. selector?: LocalTurnDiffSelector;
  69. }): Promise<LocalTurnDiffView> {
  70. const record = await findTurnDiffRecord(input.diffStore, input.sessionId, input.selector ?? {});
  71. if (!record) return { fileChanges: [] };
  72. const latest = await input.diffStore.latestForSession(input.sessionId);
  73. return serializeTurnDiffRecord(record, latest?.changeSetId === record.changeSetId);
  74. }
  75. export async function mutateLocalTurnDiff(input: {
  76. diffStore: LocalTurnDiffStore;
  77. sessionId: string;
  78. selector?: LocalTurnDiffSelector;
  79. action: 'revert' | 'reapply';
  80. nowMs: () => number;
  81. }): Promise<LocalTurnDiffMutationOutcome> {
  82. const record = await findTurnDiffRecord(input.diffStore, input.sessionId, input.selector ?? {});
  83. if (!record) {
  84. return { status: 404, body: { success: false, error: 'Turn diff not found' } };
  85. }
  86. if (input.action === 'revert' && record.status === 'reverted') {
  87. return { status: 200, body: { success: true, ...serializeTurnDiffRecord(record, true) } };
  88. }
  89. if (input.action === 'reapply' && record.status === 'active') {
  90. return { status: 200, body: { success: true, ...serializeTurnDiffRecord(record, true) } };
  91. }
  92. const latest = await input.diffStore.latestForSession(input.sessionId);
  93. if (latest?.changeSetId !== record.changeSetId) {
  94. return {
  95. status: 409,
  96. body: { success: false, error: 'Only the latest turn diff can be changed' },
  97. };
  98. }
  99. const result = await applyTurnDiffMutation(record, input.action);
  100. if (!result.ok) {
  101. return { status: 409, body: { success: false, error: result.error } };
  102. }
  103. const updated = await input.diffStore.updateStatus(
  104. input.sessionId,
  105. record.changeSetId,
  106. input.action === 'revert' ? 'reverted' : 'active',
  107. input.action === 'revert' ? input.nowMs() : undefined,
  108. );
  109. return {
  110. status: 200,
  111. body: { success: true, ...serializeTurnDiffRecord(updated ?? record, true) },
  112. };
  113. }
  114. export async function routeLocalSessionDiffApi(input: {
  115. diffStore: LocalTurnDiffStore;
  116. session: LocalSessionRecord;
  117. url: URL;
  118. }): Promise<Response> {
  119. const messageId =
  120. input.url.searchParams.get('messageID') ??
  121. input.url.searchParams.get('messageId') ??
  122. input.url.searchParams.get('assistantMessageId');
  123. return json(
  124. await readLocalSessionDiff({
  125. diffStore: input.diffStore,
  126. session: input.session,
  127. ...(messageId ? { messageId } : {}),
  128. }),
  129. );
  130. }
  131. export async function routeLocalTurnDiffApi(input: {
  132. diffStore: LocalTurnDiffStore;
  133. session: LocalSessionRecord;
  134. url: URL;
  135. }): Promise<Response> {
  136. const result = await readLocalTurnDiff({
  137. diffStore: input.diffStore,
  138. sessionId: input.session.sessionId,
  139. selector: readTurnDiffSelector(input.url.searchParams),
  140. });
  141. return json(toLegacyTurnDiffBody(result));
  142. }
  143. export async function routeLocalTurnDiffMutationApi(input: {
  144. diffStore: LocalTurnDiffStore;
  145. session: LocalSessionRecord;
  146. action: 'revert' | 'reapply';
  147. body: Record<string, unknown>;
  148. nowMs: () => number;
  149. }): Promise<Response> {
  150. const result = await mutateLocalTurnDiff({
  151. diffStore: input.diffStore,
  152. sessionId: input.session.sessionId,
  153. selector: readTurnDiffSelector(input.body),
  154. action: input.action,
  155. nowMs: input.nowMs,
  156. });
  157. return json(toLegacyTurnDiffBody(result.body), { status: result.status });
  158. }
  159. async function applyTurnDiffMutation(
  160. record: LocalTurnDiffRecord,
  161. action: 'revert' | 'reapply',
  162. ): Promise<{ ok: true } | { ok: false; error: string }> {
  163. if (record.undoable && record.undo?.length) {
  164. const result = await applyLocalTurnDiffSnapshotMutation(record, action);
  165. return result.success
  166. ? { ok: true }
  167. : { ok: false, error: result.reason ?? 'Turn diff conflict' };
  168. }
  169. if (!record.rawDiff) return { ok: false, error: 'Turn diff is not undoable' };
  170. return applyGitPatch({
  171. cwd: record.workspaceDir,
  172. patch: record.rawDiff,
  173. reverse: action === 'revert',
  174. });
  175. }
  176. function serializeTurnDiffRecord(
  177. record: LocalTurnDiffRecord,
  178. isLatest: boolean,
  179. ): LocalTurnDiffView {
  180. const undoable = record.undoable === true || Boolean(record.rawDiff);
  181. return {
  182. fileChanges: record.fileChanges,
  183. sourceMessageId: record.assistantMessageId,
  184. changeSetId: record.changeSetId,
  185. status: record.status,
  186. revertedAt: record.revertedAt,
  187. undoable,
  188. canUndo: undoable && isLatest && record.status === 'active',
  189. canReapply: undoable && isLatest && record.status === 'reverted',
  190. };
  191. }
  192. async function findTurnDiffRecord(
  193. store: LocalTurnDiffStore,
  194. sessionId: string,
  195. selector: LocalTurnDiffSelector,
  196. ): Promise<LocalTurnDiffRecord | undefined> {
  197. if (selector.changeSetId) return store.getByChangeSetId(sessionId, selector.changeSetId);
  198. if (selector.assistantMessageId) {
  199. return store.getByAssistantMessage(sessionId, selector.assistantMessageId);
  200. }
  201. if (selector.turnId) return store.getByTurn(sessionId, selector.turnId);
  202. return store.latestForSession(sessionId);
  203. }
  204. function readTurnDiffSelector(
  205. source: URLSearchParams | Record<string, unknown>,
  206. ): LocalTurnDiffSelector {
  207. const read = (key: string): string | undefined => {
  208. if (source instanceof URLSearchParams) return source.get(key) ?? undefined;
  209. return typeof source[key] === 'string' ? source[key] : undefined;
  210. };
  211. const assistantMessageId = read('assistantMessageId') ?? read('messageId') ?? read('messageID');
  212. return {
  213. ...(read('changeSetId') ? { changeSetId: read('changeSetId') } : {}),
  214. ...(assistantMessageId ? { assistantMessageId } : {}),
  215. ...(read('turnId') ? { turnId: read('turnId') } : {}),
  216. };
  217. }
  218. function toLegacyTurnDiffBody(
  219. view: LocalTurnDiffView | LocalTurnDiffMutationBody,
  220. ): Record<string, unknown> {
  221. const { fileChanges, ...rest } = view;
  222. return {
  223. ...rest,
  224. ...(fileChanges ? { file_changes: fileChanges } : {}),
  225. };
  226. }
  227. async function readWorkspaceDiff(
  228. workspaceDir: string,
  229. ): Promise<{ fileChanges: LocalFileDiff[]; rawDiff?: string }> {
  230. try {
  231. const result = await execGit(['diff', 'HEAD', ...WORKSPACE_DIFF_ARGS, '--'], workspaceDir);
  232. const trackedDiffs = parseGitDiffSummary(result.stdout);
  233. const untracked = await readUntrackedFiles(workspaceDir);
  234. const untrackedDiffs = await Promise.all(
  235. untracked.map((file) => readUntrackedFileDiff(workspaceDir, file)),
  236. );
  237. const raw = [
  238. ...trackedDiffs.flatMap((item) => item.diff ?? []),
  239. ...untrackedDiffs.flatMap((item) => item.rawDiff ?? []),
  240. ]
  241. .filter(Boolean)
  242. .join('\n');
  243. const fileChanges = [...trackedDiffs, ...untrackedDiffs.map((item) => item.fileChange)];
  244. return { fileChanges, ...(raw ? { rawDiff: raw } : {}) };
  245. } catch {
  246. return { fileChanges: [] };
  247. }
  248. }
  249. async function execGit(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }> {
  250. return execFile('git', args, {
  251. cwd,
  252. env: cleanGitEnv(),
  253. maxBuffer: 10 * 1024 * 1024,
  254. });
  255. }
  256. function parseGitDiffSummary(output: string): LocalFileDiff[] {
  257. if (!output) return [];
  258. // --raw --numstat -z --patch emits raw records, then numstat records,
  259. // then an extra NUL before the patches. Git uses the same order for raw
  260. // records and patch blocks, including rename-only and binary changes.
  261. const boundary = output.indexOf('\0\0');
  262. if (boundary < 0) throw new Error('Git diff is missing its patch boundary');
  263. const records = output.slice(0, boundary).split('\0');
  264. const files: Array<{ file: string; status: string }> = [];
  265. let index = 0;
  266. while (records[index]?.startsWith(':')) {
  267. const status = records[index++]!.split(' ').at(-1)!;
  268. const source = records[index++];
  269. const file = /^[RC]/u.test(status) ? records[index++] : source;
  270. if (!file) throw new Error('Git diff is missing a raw path');
  271. files.push({ file, status: mapGitStatus(status) });
  272. }
  273. const stats = new Map<string, { additions: number; deletions: number }>();
  274. while (index < records.length) {
  275. const [additions, deletions, ...pathParts] = records[index++]!.split('\t');
  276. let file = pathParts.join('\t');
  277. // Renames/copies have an empty numstat path followed by old and new paths.
  278. if (!file) {
  279. index += 1;
  280. file = records[index++] ?? '';
  281. }
  282. if (!file) throw new Error('Git diff is missing a numstat path');
  283. stats.set(file, {
  284. additions: numericDiffStat(additions),
  285. deletions: numericDiffStat(deletions),
  286. });
  287. }
  288. const patches = output
  289. .slice(boundary + 2)
  290. .split(/(?=^diff --git )/mu)
  291. .filter(Boolean);
  292. if (files.length !== patches.length) {
  293. throw new Error('Git diff raw paths and patch blocks do not match');
  294. }
  295. return files.map(({ file, status }, position) => {
  296. const stat = stats.get(file);
  297. if (!stat) throw new Error('Git diff is missing file metrics');
  298. return { file, status, ...stat, diff: patches[position] };
  299. });
  300. }
  301. async function readUntrackedFiles(workspaceDir: string): Promise<string[]> {
  302. try {
  303. const result = await execGit(
  304. ['ls-files', '--others', '--exclude-standard', '-z'],
  305. workspaceDir,
  306. );
  307. return result.stdout.split('\0').filter(Boolean);
  308. } catch {
  309. return [];
  310. }
  311. }
  312. async function readUntrackedFileDiff(
  313. workspaceDir: string,
  314. file: string,
  315. ): Promise<{ fileChange: LocalFileDiff; rawDiff?: string }> {
  316. try {
  317. const rawDiff = await execFile(
  318. 'git',
  319. ['diff', '--no-index', ...WORKSPACE_DIFF_ARGS, '--', '/dev/null', file],
  320. {
  321. cwd: workspaceDir,
  322. env: cleanGitEnv(),
  323. maxBuffer: 10 * 1024 * 1024,
  324. },
  325. ).catch((err: unknown) => {
  326. const error = err as { stdout?: string; code?: number };
  327. if (error.code === 1 && typeof error.stdout === 'string') return { stdout: error.stdout };
  328. throw err;
  329. });
  330. const parsed = parseGitDiffSummary(rawDiff.stdout)[0];
  331. if (!parsed) throw new Error('Git diff is missing an untracked file');
  332. return {
  333. fileChange: { ...parsed, file, status: 'added' },
  334. ...(parsed.diff ? { rawDiff: parsed.diff } : {}),
  335. };
  336. } catch {
  337. return {
  338. fileChange: {
  339. file,
  340. additions: 0,
  341. deletions: 0,
  342. status: 'added',
  343. },
  344. };
  345. }
  346. }
  347. function mapGitStatus(status: string | undefined): string {
  348. const code = status?.[0];
  349. if (code === 'A') return 'added';
  350. if (code === 'D') return 'deleted';
  351. if (code === 'R') return 'renamed';
  352. if (code === 'C') return 'copied';
  353. return 'modified';
  354. }
  355. function numericDiffStat(value: string | undefined): number {
  356. const parsed = Number(value);
  357. return Number.isFinite(parsed) ? parsed : 0;
  358. }
  359. function applyGitPatch(input: {
  360. cwd: string;
  361. patch: string;
  362. reverse: boolean;
  363. }): Promise<{ ok: true } | { ok: false; error: string }> {
  364. return new Promise((resolve) => {
  365. const args = ['apply', '--whitespace=nowarn', ...(input.reverse ? ['--reverse'] : [])];
  366. const child = spawn('git', args, { cwd: input.cwd, env: cleanGitEnv() });
  367. let stderr = '';
  368. child.stderr.setEncoding('utf8');
  369. child.stderr.on('data', (chunk) => {
  370. stderr += chunk;
  371. });
  372. child.on('error', (err) => {
  373. resolve({ ok: false, error: err.message });
  374. });
  375. child.on('close', (code) => {
  376. if (code === 0) {
  377. resolve({ ok: true });
  378. return;
  379. }
  380. resolve({ ok: false, error: stderr.trim() || `git apply exited with ${String(code)}` });
  381. });
  382. child.stdin.end(input.patch);
  383. });
  384. }
  385. function cleanGitEnv(): NodeJS.ProcessEnv {
  386. const env = { ...process.env };
  387. delete env['GIT_DIR'];
  388. delete env['GIT_WORK_TREE'];
  389. delete env['GIT_INDEX_FILE'];
  390. delete env['GIT_PREFIX'];
  391. delete env['GIT_OBJECT_DIRECTORY'];
  392. delete env['GIT_ALTERNATE_OBJECT_DIRECTORIES'];
  393. return env;
  394. }