session-diff-fallback.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import { execFileSync } from 'node:child_process';
  2. import { mkdtemp, mkdir, writeFile, appendFile, rm } from 'node:fs/promises';
  3. import { tmpdir } from 'node:os';
  4. import path from 'node:path';
  5. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
  6. import { closeLocalRuntimeDb } from '../../src/persistence/db.js';
  7. import { SqliteLocalTurnDiffStore } from '../../src/persistence/sqlite-persistence.js';
  8. import { readLocalSessionDiff } from '../../src/turns/diff-api.js';
  9. let root: string;
  10. let workspaceDir: string;
  11. let dataDir: string;
  12. let diffStore: SqliteLocalTurnDiffStore;
  13. const pendingReads = new Set<ReturnType<typeof readLocalSessionDiff>>();
  14. function git(...args: string[]): string {
  15. return execFileSync('git', args, { cwd: workspaceDir, encoding: 'utf8' });
  16. }
  17. async function write(file: string, content: string | Buffer): Promise<void> {
  18. await mkdir(path.dirname(path.join(workspaceDir, file)), { recursive: true });
  19. await writeFile(path.join(workspaceDir, file), content);
  20. }
  21. function commit(): void {
  22. git('add', '--all');
  23. git('commit', '-qm', 'Synthetic baseline');
  24. }
  25. async function read(messageId?: string) {
  26. const pending = readLocalSessionDiff({
  27. diffStore,
  28. session: { sessionId: 'test-session', workspaceDir },
  29. messageId,
  30. });
  31. pendingReads.add(pending);
  32. try {
  33. return await pending;
  34. } finally {
  35. pendingReads.delete(pending);
  36. }
  37. }
  38. beforeEach(async () => {
  39. root = await mkdtemp(path.join(tmpdir(), 'session-diff-'));
  40. workspaceDir = path.join(root, 'workspace');
  41. dataDir = path.join(root, 'data');
  42. await mkdir(workspaceDir);
  43. // Keep user hooks, attributes, diff drivers and quoting defaults out of fixtures.
  44. vi.stubEnv('GIT_CONFIG_NOSYSTEM', '1');
  45. vi.stubEnv('GIT_CONFIG_GLOBAL', path.join(root, 'no-global-config'));
  46. for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_PREFIX']) {
  47. vi.stubEnv(key, undefined);
  48. }
  49. git('init', '-q');
  50. git('config', 'user.name', 'Diff Test');
  51. git('config', 'user.email', 'diff-test@example.com');
  52. git('config', 'core.autocrlf', 'false');
  53. git('config', 'diff.renames', 'true');
  54. await write('baseline.txt', 'unchanged\n');
  55. commit();
  56. diffStore = new SqliteLocalTurnDiffStore(dataDir);
  57. });
  58. afterEach(async () => {
  59. // A Vitest timeout does not cancel the Git processes started by a read.
  60. // Drain them before changing their environment or deleting their cwd; otherwise
  61. // Windows reports EBUSY and unfinished work can overlap the next fixture.
  62. await Promise.allSettled(pendingReads);
  63. closeLocalRuntimeDb(dataDir);
  64. vi.unstubAllEnvs();
  65. await rm(root, { recursive: true, force: true });
  66. }, process.platform === 'win32' ? 30_000 : 10_000);
  67. const portableNames = ['中文.txt', 'with spaces.txt', 'dir/{before after}.txt'];
  68. const posixNames = [
  69. 'tab\tname.txt',
  70. 'line\nname.txt',
  71. 'literal => arrow.txt',
  72. ' quote"slash\\.txt',
  73. ' trailing.txt ',
  74. ];
  75. describe.each(['true', 'false'])('session diff fallback with core.quotePath=%s', (quotePath) => {
  76. beforeEach(() => {
  77. git('config', 'core.quotePath', quotePath);
  78. });
  79. // This integration case creates a commit, migrates SQLite and runs real Git.
  80. // Real Windows runs have exhausted its default 5s test deadline.
  81. it('preserves Unicode paths and attaches each tracked patch through the public API', async () => {
  82. for (const file of portableNames) await write(file, 'first\n');
  83. commit();
  84. for (const [index, file] of portableNames.entries()) {
  85. await appendFile(path.join(workspaceDir, file), `added-${index}\n`);
  86. }
  87. const result = await read();
  88. expect(result.diffs).toHaveLength(portableNames.length);
  89. for (const [index, file] of portableNames.entries()) {
  90. expect(result.diffs.find((entry) => entry.file === file)).toMatchObject({
  91. file,
  92. additions: 1,
  93. deletions: 0,
  94. status: 'modified',
  95. diff: expect.stringContaining(`+added-${index}\n`),
  96. });
  97. }
  98. }, process.platform === 'win32' ? 15_000 : 5_000);
  99. it('reports rename edits against the destination path', async () => {
  100. await write('before.txt', 'a\nb\nc\nd\ne\nf\n');
  101. commit();
  102. git('mv', 'before.txt', 'after.txt');
  103. await appendFile(path.join(workspaceDir, 'after.txt'), 'added\n');
  104. expect((await read('missing-message')).diffs).toEqual([
  105. {
  106. file: 'after.txt',
  107. additions: 1,
  108. deletions: 0,
  109. status: 'renamed',
  110. diff: expect.stringContaining('+added\n'),
  111. },
  112. ]);
  113. });
  114. it('keeps additions, deletions, binary changes and untracked paths distinct', async () => {
  115. await write('deleted 中文.txt', 'remove\n');
  116. await write('binary.bin', Buffer.from([0, 1, 2]));
  117. commit();
  118. await rm(path.join(workspaceDir, 'deleted 中文.txt'));
  119. await write('binary.bin', Buffer.from([0, 3, 4]));
  120. await write('staged 中文.txt', 'staged\n');
  121. git('add', '--', 'staged 中文.txt');
  122. for (const file of portableNames) await write(file, 'untracked\n++content\n');
  123. await write('untracked.bin', Buffer.from([0, 5, 6]));
  124. await write('empty.txt', '');
  125. const { diffs } = await read();
  126. expect(diffs).toHaveLength(portableNames.length + 5);
  127. expect(diffs.find((entry) => entry.file === 'deleted 中文.txt')).toMatchObject({
  128. additions: 0,
  129. deletions: 1,
  130. status: 'deleted',
  131. diff: expect.stringContaining('-remove\n'),
  132. });
  133. expect(diffs.find((entry) => entry.file === 'staged 中文.txt')).toMatchObject({
  134. additions: 1,
  135. deletions: 0,
  136. status: 'added',
  137. diff: expect.stringContaining('+staged\n'),
  138. });
  139. for (const file of ['binary.bin', 'untracked.bin']) {
  140. expect(diffs.find((entry) => entry.file === file)).toMatchObject({
  141. additions: 0,
  142. deletions: 0,
  143. diff: expect.stringContaining('Binary files '),
  144. });
  145. }
  146. for (const file of portableNames) {
  147. expect(diffs.find((entry) => entry.file === file)).toMatchObject({
  148. additions: 2,
  149. deletions: 0,
  150. status: 'added',
  151. diff: expect.stringContaining('+++content\n'),
  152. });
  153. }
  154. expect(diffs.find((entry) => entry.file === 'empty.txt')).toMatchObject({
  155. additions: 0,
  156. deletions: 0,
  157. status: 'added',
  158. });
  159. });
  160. it.skipIf(process.platform === 'win32')(
  161. 'preserves POSIX whitespace, escape and arrow names for tracked and untracked files',
  162. async () => {
  163. for (const file of posixNames) await write(file, 'first\n');
  164. commit();
  165. for (const [index, file] of posixNames.entries()) {
  166. await appendFile(path.join(workspaceDir, file), `tracked-${index}\n`);
  167. await write(`untracked/${file}`, `untracked-${index}\n`);
  168. }
  169. const { diffs } = await read();
  170. expect(diffs).toHaveLength(posixNames.length * 2);
  171. for (const [index, file] of posixNames.entries()) {
  172. expect(diffs.find((entry) => entry.file === file)).toMatchObject({
  173. additions: 1,
  174. deletions: 0,
  175. diff: expect.stringContaining(`+tracked-${index}\n`),
  176. });
  177. expect(diffs.find((entry) => entry.file === `untracked/${file}`)).toMatchObject({
  178. additions: 1,
  179. deletions: 0,
  180. diff: expect.stringContaining(`+untracked-${index}\n`),
  181. });
  182. }
  183. },
  184. );
  185. it('retains a rename-only patch with zero line changes', async () => {
  186. await write('old 中文.txt', 'same\n');
  187. commit();
  188. git('mv', 'old 中文.txt', 'new 中文.txt');
  189. expect((await read()).diffs).toEqual([
  190. {
  191. file: 'new 中文.txt',
  192. additions: 0,
  193. deletions: 0,
  194. status: 'renamed',
  195. diff: expect.stringContaining('similarity index 100%'),
  196. },
  197. ]);
  198. });
  199. it.skipIf(process.platform === 'win32')(
  200. 'consumes both rename paths without splitting tabs or literal arrows',
  201. async () => {
  202. const source = 'dir/old\tline\n{left => right}.txt';
  203. const destination = 'dir/new\tline\n{right => left}.txt';
  204. await write(source, 'a\nb\nc\nd\ne\nf\n');
  205. commit();
  206. git('mv', source, destination);
  207. await appendFile(path.join(workspaceDir, destination), 'renamed\n');
  208. expect((await read()).diffs).toEqual([
  209. {
  210. file: destination,
  211. additions: 1,
  212. deletions: 0,
  213. status: 'renamed',
  214. diff: expect.stringContaining('+renamed\n'),
  215. },
  216. ]);
  217. },
  218. );
  219. it('handles brace-compressed renames and copies with destination stats and patches', async () => {
  220. await write('dir/old 中文.txt', 'a\nb\nc\nd\ne\nf\n');
  221. await write('copy-source.txt', 'unique\ncopy\nsource\nlines\nhere\nend\n');
  222. commit();
  223. git('mv', 'dir/old 中文.txt', 'dir/new 中文.txt');
  224. await appendFile(path.join(workspaceDir, 'dir/new 中文.txt'), 'renamed\n');
  225. await appendFile(path.join(workspaceDir, 'copy-source.txt'), 'source-edit\n');
  226. await write('copy 中文.txt', 'unique\ncopy\nsource\nlines\nhere\nend\ncopied\n');
  227. git('add', '--', 'copy 中文.txt');
  228. git('config', 'diff.renames', 'copies');
  229. const { diffs } = await read();
  230. expect(diffs).toHaveLength(3);
  231. expect(diffs.find((entry) => entry.file === 'dir/new 中文.txt')).toMatchObject({
  232. additions: 1,
  233. deletions: 0,
  234. status: 'renamed',
  235. diff: expect.stringContaining('+renamed\n'),
  236. });
  237. expect(diffs.find((entry) => entry.file === 'copy 中文.txt')).toMatchObject({
  238. additions: 1,
  239. deletions: 0,
  240. status: 'copied',
  241. diff: expect.stringContaining('+copied\n'),
  242. });
  243. expect(diffs.find((entry) => entry.file === 'copy-source.txt')).toMatchObject({
  244. additions: 1,
  245. deletions: 0,
  246. status: 'modified',
  247. diff: expect.stringContaining('+source-edit\n'),
  248. });
  249. });
  250. });
  251. it('returns an empty diff for a clean workspace', async () => {
  252. expect(await read()).toEqual({ diffs: [] });
  253. });
  254. it('prefers stored session/message diffs and falls back only when the selected record is absent', async () => {
  255. await write('live.txt', 'live\n');
  256. const fileChanges = [{ file: 'stored.txt', additions: 7, deletions: 2, diff: 'stored patch' }];
  257. await diffStore.upsert({
  258. sessionId: 'test-session',
  259. turnId: 'test-turn',
  260. changeSetId: 'test-change',
  261. assistantMessageId: 'test-message',
  262. workspaceDir,
  263. capturedAtMs: Date.now(),
  264. status: 'active',
  265. fileChanges,
  266. });
  267. for (const messageId of [undefined, 'test-message']) {
  268. expect(await read(messageId)).toEqual({ diffs: fileChanges, changeSetId: 'test-change' });
  269. }
  270. expect((await read('absent-message')).diffs).toEqual([
  271. {
  272. file: 'live.txt',
  273. additions: 1,
  274. deletions: 0,
  275. status: 'added',
  276. diff: expect.stringContaining('+live\n'),
  277. },
  278. ]);
  279. });
  280. it('associates patches without relying on color or path prefixes', async () => {
  281. await write('中文.txt', 'first\n');
  282. commit();
  283. await appendFile(path.join(workspaceDir, '中文.txt'), 'added\n');
  284. git('config', 'color.ui', 'always');
  285. git('config', 'diff.noprefix', 'true');
  286. expect((await read()).diffs).toEqual([
  287. {
  288. file: '中文.txt',
  289. additions: 1,
  290. deletions: 0,
  291. status: 'modified',
  292. diff: expect.stringContaining('+added\n'),
  293. },
  294. ]);
  295. });