ShadowCheckpointService.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. // npx jest src/services/checkpoints/__tests__/ShadowCheckpointService.test.ts
  2. import fs from "fs/promises"
  3. import path from "path"
  4. import os from "os"
  5. import { EventEmitter } from "events"
  6. import { simpleGit, SimpleGit } from "simple-git"
  7. import { fileExistsAtPath } from "../../../utils/fs"
  8. import * as fileSearch from "../../../services/search/file-search"
  9. import { RepoPerTaskCheckpointService } from "../RepoPerTaskCheckpointService"
  10. jest.setTimeout(10_000)
  11. const tmpDir = path.join(os.tmpdir(), "CheckpointService")
  12. const initWorkspaceRepo = async ({
  13. workspaceDir,
  14. userName = "Roo Code",
  15. userEmail = "[email protected]",
  16. testFileName = "test.txt",
  17. textFileContent = "Hello, world!",
  18. }: {
  19. workspaceDir: string
  20. userName?: string
  21. userEmail?: string
  22. testFileName?: string
  23. textFileContent?: string
  24. }) => {
  25. // Create a temporary directory for testing.
  26. await fs.mkdir(workspaceDir, { recursive: true })
  27. // Initialize git repo.
  28. const git = simpleGit(workspaceDir)
  29. await git.init()
  30. await git.addConfig("user.name", userName)
  31. await git.addConfig("user.email", userEmail)
  32. // Create test file.
  33. const testFile = path.join(workspaceDir, testFileName)
  34. await fs.writeFile(testFile, textFileContent)
  35. // Create initial commit.
  36. await git.add(".")
  37. await git.commit("Initial commit")!
  38. return { git, testFile }
  39. }
  40. describe.each([[RepoPerTaskCheckpointService, "RepoPerTaskCheckpointService"]])(
  41. "CheckpointService",
  42. (klass, prefix) => {
  43. const taskId = "test-task"
  44. let workspaceGit: SimpleGit
  45. let testFile: string
  46. let service: RepoPerTaskCheckpointService
  47. beforeEach(async () => {
  48. const shadowDir = path.join(tmpDir, `${prefix}-${Date.now()}`)
  49. const workspaceDir = path.join(tmpDir, `workspace-${Date.now()}`)
  50. const repo = await initWorkspaceRepo({ workspaceDir })
  51. workspaceGit = repo.git
  52. testFile = repo.testFile
  53. service = await klass.create({ taskId, shadowDir, workspaceDir, log: () => {} })
  54. await service.initShadowGit()
  55. })
  56. afterEach(async () => {
  57. jest.restoreAllMocks()
  58. })
  59. afterAll(async () => {
  60. await fs.rm(tmpDir, { recursive: true, force: true })
  61. })
  62. describe(`${klass.name}#getDiff`, () => {
  63. it("returns the correct diff between commits", async () => {
  64. await fs.writeFile(testFile, "Ahoy, world!")
  65. const commit1 = await service.saveCheckpoint("Ahoy, world!")
  66. expect(commit1?.commit).toBeTruthy()
  67. await fs.writeFile(testFile, "Goodbye, world!")
  68. const commit2 = await service.saveCheckpoint("Goodbye, world!")
  69. expect(commit2?.commit).toBeTruthy()
  70. const diff1 = await service.getDiff({ to: commit1!.commit })
  71. expect(diff1).toHaveLength(1)
  72. expect(diff1[0].paths.relative).toBe("test.txt")
  73. expect(diff1[0].paths.absolute).toBe(testFile)
  74. expect(diff1[0].content.before).toBe("Hello, world!")
  75. expect(diff1[0].content.after).toBe("Ahoy, world!")
  76. const diff2 = await service.getDiff({ from: service.baseHash, to: commit2!.commit })
  77. expect(diff2).toHaveLength(1)
  78. expect(diff2[0].paths.relative).toBe("test.txt")
  79. expect(diff2[0].paths.absolute).toBe(testFile)
  80. expect(diff2[0].content.before).toBe("Hello, world!")
  81. expect(diff2[0].content.after).toBe("Goodbye, world!")
  82. const diff12 = await service.getDiff({ from: commit1!.commit, to: commit2!.commit })
  83. expect(diff12).toHaveLength(1)
  84. expect(diff12[0].paths.relative).toBe("test.txt")
  85. expect(diff12[0].paths.absolute).toBe(testFile)
  86. expect(diff12[0].content.before).toBe("Ahoy, world!")
  87. expect(diff12[0].content.after).toBe("Goodbye, world!")
  88. })
  89. it("handles new files in diff", async () => {
  90. const newFile = path.join(service.workspaceDir, "new.txt")
  91. await fs.writeFile(newFile, "New file content")
  92. const commit = await service.saveCheckpoint("Add new file")
  93. expect(commit?.commit).toBeTruthy()
  94. const changes = await service.getDiff({ to: commit!.commit })
  95. const change = changes.find((c) => c.paths.relative === "new.txt")
  96. expect(change).toBeDefined()
  97. expect(change?.content.before).toBe("")
  98. expect(change?.content.after).toBe("New file content")
  99. })
  100. it("handles deleted files in diff", async () => {
  101. const fileToDelete = path.join(service.workspaceDir, "new.txt")
  102. await fs.writeFile(fileToDelete, "New file content")
  103. const commit1 = await service.saveCheckpoint("Add file")
  104. expect(commit1?.commit).toBeTruthy()
  105. await fs.unlink(fileToDelete)
  106. const commit2 = await service.saveCheckpoint("Delete file")
  107. expect(commit2?.commit).toBeTruthy()
  108. const changes = await service.getDiff({ from: commit1!.commit, to: commit2!.commit })
  109. const change = changes.find((c) => c.paths.relative === "new.txt")
  110. expect(change).toBeDefined()
  111. expect(change!.content.before).toBe("New file content")
  112. expect(change!.content.after).toBe("")
  113. })
  114. })
  115. describe(`${klass.name}#saveCheckpoint`, () => {
  116. it("creates a checkpoint if there are pending changes", async () => {
  117. await fs.writeFile(testFile, "Ahoy, world!")
  118. const commit1 = await service.saveCheckpoint("First checkpoint")
  119. expect(commit1?.commit).toBeTruthy()
  120. const details1 = await service.getDiff({ to: commit1!.commit })
  121. expect(details1[0].content.before).toContain("Hello, world!")
  122. expect(details1[0].content.after).toContain("Ahoy, world!")
  123. await fs.writeFile(testFile, "Hola, world!")
  124. const commit2 = await service.saveCheckpoint("Second checkpoint")
  125. expect(commit2?.commit).toBeTruthy()
  126. const details2 = await service.getDiff({ from: commit1!.commit, to: commit2!.commit })
  127. expect(details2[0].content.before).toContain("Ahoy, world!")
  128. expect(details2[0].content.after).toContain("Hola, world!")
  129. // Switch to checkpoint 1.
  130. await service.restoreCheckpoint(commit1!.commit)
  131. expect(await fs.readFile(testFile, "utf-8")).toBe("Ahoy, world!")
  132. // Switch to checkpoint 2.
  133. await service.restoreCheckpoint(commit2!.commit)
  134. expect(await fs.readFile(testFile, "utf-8")).toBe("Hola, world!")
  135. // Switch back to initial commit.
  136. expect(service.baseHash).toBeTruthy()
  137. await service.restoreCheckpoint(service.baseHash!)
  138. expect(await fs.readFile(testFile, "utf-8")).toBe("Hello, world!")
  139. })
  140. it("preserves workspace and index state after saving checkpoint", async () => {
  141. // Create three files with different states: staged, unstaged, and mixed.
  142. const unstagedFile = path.join(service.workspaceDir, "unstaged.txt")
  143. const stagedFile = path.join(service.workspaceDir, "staged.txt")
  144. const mixedFile = path.join(service.workspaceDir, "mixed.txt")
  145. await fs.writeFile(unstagedFile, "Initial unstaged")
  146. await fs.writeFile(stagedFile, "Initial staged")
  147. await fs.writeFile(mixedFile, "Initial mixed")
  148. await workspaceGit.add(["."])
  149. const result = await workspaceGit.commit("Add initial files")
  150. expect(result?.commit).toBeTruthy()
  151. await fs.writeFile(unstagedFile, "Modified unstaged")
  152. await fs.writeFile(stagedFile, "Modified staged")
  153. await workspaceGit.add([stagedFile])
  154. await fs.writeFile(mixedFile, "Modified mixed - staged")
  155. await workspaceGit.add([mixedFile])
  156. await fs.writeFile(mixedFile, "Modified mixed - unstaged")
  157. // Save checkpoint.
  158. const commit = await service.saveCheckpoint("Test checkpoint")
  159. expect(commit?.commit).toBeTruthy()
  160. // Verify workspace state is preserved.
  161. const status = await workspaceGit.status()
  162. // All files should be modified.
  163. expect(status.modified).toContain("unstaged.txt")
  164. expect(status.modified).toContain("staged.txt")
  165. expect(status.modified).toContain("mixed.txt")
  166. // Only staged and mixed files should be staged.
  167. expect(status.staged).not.toContain("unstaged.txt")
  168. expect(status.staged).toContain("staged.txt")
  169. expect(status.staged).toContain("mixed.txt")
  170. // Verify file contents.
  171. expect(await fs.readFile(unstagedFile, "utf-8")).toBe("Modified unstaged")
  172. expect(await fs.readFile(stagedFile, "utf-8")).toBe("Modified staged")
  173. expect(await fs.readFile(mixedFile, "utf-8")).toBe("Modified mixed - unstaged")
  174. // Verify staged changes (--cached shows only staged changes).
  175. const stagedDiff = await workspaceGit.diff(["--cached", "mixed.txt"])
  176. expect(stagedDiff).toContain("-Initial mixed")
  177. expect(stagedDiff).toContain("+Modified mixed - staged")
  178. // Verify unstaged changes (shows working directory changes).
  179. const unstagedDiff = await workspaceGit.diff(["mixed.txt"])
  180. expect(unstagedDiff).toContain("-Modified mixed - staged")
  181. expect(unstagedDiff).toContain("+Modified mixed - unstaged")
  182. })
  183. it("does not create a checkpoint if there are no pending changes", async () => {
  184. const commit0 = await service.saveCheckpoint("Zeroth checkpoint")
  185. expect(commit0?.commit).toBeFalsy()
  186. await fs.writeFile(testFile, "Ahoy, world!")
  187. const commit1 = await service.saveCheckpoint("First checkpoint")
  188. expect(commit1?.commit).toBeTruthy()
  189. const commit2 = await service.saveCheckpoint("Second checkpoint")
  190. expect(commit2?.commit).toBeFalsy()
  191. })
  192. it("includes untracked files in checkpoints", async () => {
  193. // Create an untracked file.
  194. const untrackedFile = path.join(service.workspaceDir, "untracked.txt")
  195. await fs.writeFile(untrackedFile, "I am untracked!")
  196. // Save a checkpoint with the untracked file.
  197. const commit1 = await service.saveCheckpoint("Checkpoint with untracked file")
  198. expect(commit1?.commit).toBeTruthy()
  199. // Verify the untracked file was included in the checkpoint.
  200. const details = await service.getDiff({ to: commit1!.commit })
  201. expect(details[0].content.before).toContain("")
  202. expect(details[0].content.after).toContain("I am untracked!")
  203. // Create another checkpoint with a different state.
  204. await fs.writeFile(testFile, "Changed tracked file")
  205. const commit2 = await service.saveCheckpoint("Second checkpoint")
  206. expect(commit2?.commit).toBeTruthy()
  207. // Restore first checkpoint and verify untracked file is preserved.
  208. await service.restoreCheckpoint(commit1!.commit)
  209. expect(await fs.readFile(untrackedFile, "utf-8")).toBe("I am untracked!")
  210. expect(await fs.readFile(testFile, "utf-8")).toBe("Hello, world!")
  211. // Restore second checkpoint and verify untracked file remains (since
  212. // restore preserves untracked files)
  213. await service.restoreCheckpoint(commit2!.commit)
  214. expect(await fs.readFile(untrackedFile, "utf-8")).toBe("I am untracked!")
  215. expect(await fs.readFile(testFile, "utf-8")).toBe("Changed tracked file")
  216. })
  217. it("handles file deletions correctly", async () => {
  218. await fs.writeFile(testFile, "I am tracked!")
  219. const untrackedFile = path.join(service.workspaceDir, "new.txt")
  220. await fs.writeFile(untrackedFile, "I am untracked!")
  221. const commit1 = await service.saveCheckpoint("First checkpoint")
  222. expect(commit1?.commit).toBeTruthy()
  223. await fs.unlink(testFile)
  224. await fs.unlink(untrackedFile)
  225. const commit2 = await service.saveCheckpoint("Second checkpoint")
  226. expect(commit2?.commit).toBeTruthy()
  227. // Verify files are gone.
  228. await expect(fs.readFile(testFile, "utf-8")).rejects.toThrow()
  229. await expect(fs.readFile(untrackedFile, "utf-8")).rejects.toThrow()
  230. // Restore first checkpoint.
  231. await service.restoreCheckpoint(commit1!.commit)
  232. expect(await fs.readFile(testFile, "utf-8")).toBe("I am tracked!")
  233. expect(await fs.readFile(untrackedFile, "utf-8")).toBe("I am untracked!")
  234. // Restore second checkpoint.
  235. await service.restoreCheckpoint(commit2!.commit)
  236. await expect(fs.readFile(testFile, "utf-8")).rejects.toThrow()
  237. await expect(fs.readFile(untrackedFile, "utf-8")).rejects.toThrow()
  238. })
  239. it("does not create a checkpoint for ignored files", async () => {
  240. // Create a file that matches an ignored pattern (e.g., .log file).
  241. const ignoredFile = path.join(service.workspaceDir, "ignored.log")
  242. await fs.writeFile(ignoredFile, "Initial ignored content")
  243. const commit = await service.saveCheckpoint("Ignored file checkpoint")
  244. expect(commit?.commit).toBeFalsy()
  245. await fs.writeFile(ignoredFile, "Modified ignored content")
  246. const commit2 = await service.saveCheckpoint("Ignored file modified checkpoint")
  247. expect(commit2?.commit).toBeFalsy()
  248. expect(await fs.readFile(ignoredFile, "utf-8")).toBe("Modified ignored content")
  249. })
  250. it("does not create a checkpoint for LFS files", async () => {
  251. // Create a .gitattributes file with LFS patterns.
  252. const gitattributesPath = path.join(service.workspaceDir, ".gitattributes")
  253. await fs.writeFile(gitattributesPath, "*.lfs filter=lfs diff=lfs merge=lfs -text")
  254. // Re-initialize the service to trigger a write to .git/info/exclude.
  255. service = new klass(service.taskId, service.checkpointsDir, service.workspaceDir, () => {})
  256. const excludesPath = path.join(service.checkpointsDir, ".git", "info", "exclude")
  257. expect((await fs.readFile(excludesPath, "utf-8")).split("\n")).not.toContain("*.lfs")
  258. await service.initShadowGit()
  259. expect((await fs.readFile(excludesPath, "utf-8")).split("\n")).toContain("*.lfs")
  260. const commit0 = await service.saveCheckpoint("Add gitattributes")
  261. expect(commit0?.commit).toBeTruthy()
  262. // Create a file that matches an LFS pattern.
  263. const lfsFile = path.join(service.workspaceDir, "foo.lfs")
  264. await fs.writeFile(lfsFile, "Binary file content simulation")
  265. const commit = await service.saveCheckpoint("LFS file checkpoint")
  266. expect(commit?.commit).toBeFalsy()
  267. await fs.writeFile(lfsFile, "Modified binary content")
  268. const commit2 = await service.saveCheckpoint("LFS file modified checkpoint")
  269. expect(commit2?.commit).toBeFalsy()
  270. expect(await fs.readFile(lfsFile, "utf-8")).toBe("Modified binary content")
  271. })
  272. })
  273. describe(`${klass.name}#create`, () => {
  274. it("initializes a git repository if one does not already exist", async () => {
  275. const shadowDir = path.join(tmpDir, `${prefix}2-${Date.now()}`)
  276. const workspaceDir = path.join(tmpDir, `workspace2-${Date.now()}`)
  277. await fs.mkdir(workspaceDir)
  278. const newTestFile = path.join(workspaceDir, "test.txt")
  279. await fs.writeFile(newTestFile, "Hello, world!")
  280. expect(await fs.readFile(newTestFile, "utf-8")).toBe("Hello, world!")
  281. // Ensure the git repository was initialized.
  282. const newService = await klass.create({ taskId, shadowDir, workspaceDir, log: () => {} })
  283. const { created } = await newService.initShadowGit()
  284. expect(created).toBeTruthy()
  285. const gitDir = path.join(newService.checkpointsDir, ".git")
  286. expect(await fs.stat(gitDir)).toBeTruthy()
  287. // Save a new checkpoint: Ahoy, world!
  288. await fs.writeFile(newTestFile, "Ahoy, world!")
  289. const commit1 = await newService.saveCheckpoint("Ahoy, world!")
  290. expect(commit1?.commit).toBeTruthy()
  291. expect(await fs.readFile(newTestFile, "utf-8")).toBe("Ahoy, world!")
  292. // Restore "Hello, world!"
  293. await newService.restoreCheckpoint(newService.baseHash!)
  294. expect(await fs.readFile(newTestFile, "utf-8")).toBe("Hello, world!")
  295. // Restore "Ahoy, world!"
  296. await newService.restoreCheckpoint(commit1!.commit)
  297. expect(await fs.readFile(newTestFile, "utf-8")).toBe("Ahoy, world!")
  298. await fs.rm(newService.checkpointsDir, { recursive: true, force: true })
  299. await fs.rm(newService.workspaceDir, { recursive: true, force: true })
  300. })
  301. })
  302. describe(`${klass.name}#renameNestedGitRepos`, () => {
  303. it("handles nested git repositories during initialization", async () => {
  304. // Create a new temporary workspace and service for this test.
  305. const shadowDir = path.join(tmpDir, `${prefix}-nested-git-${Date.now()}`)
  306. const workspaceDir = path.join(tmpDir, `workspace-nested-git-${Date.now()}`)
  307. // Create a primary workspace repo.
  308. await fs.mkdir(workspaceDir, { recursive: true })
  309. const mainGit = simpleGit(workspaceDir)
  310. await mainGit.init()
  311. await mainGit.addConfig("user.name", "Roo Code")
  312. await mainGit.addConfig("user.email", "[email protected]")
  313. // Create a nested repo inside the workspace.
  314. const nestedRepoPath = path.join(workspaceDir, "nested-project")
  315. await fs.mkdir(nestedRepoPath, { recursive: true })
  316. const nestedGit = simpleGit(nestedRepoPath)
  317. await nestedGit.init()
  318. await nestedGit.addConfig("user.name", "Roo Code")
  319. await nestedGit.addConfig("user.email", "[email protected]")
  320. // Add a file to the nested repo.
  321. const nestedFile = path.join(nestedRepoPath, "nested-file.txt")
  322. await fs.writeFile(nestedFile, "Content in nested repo")
  323. await nestedGit.add(".")
  324. await nestedGit.commit("Initial commit in nested repo")
  325. // Create a test file in the main workspace.
  326. const mainFile = path.join(workspaceDir, "main-file.txt")
  327. await fs.writeFile(mainFile, "Content in main repo")
  328. await mainGit.add(".")
  329. await mainGit.commit("Initial commit in main repo")
  330. // Confirm nested git directory exists before initialization.
  331. const nestedGitDir = path.join(nestedRepoPath, ".git")
  332. const headFile = path.join(nestedGitDir, "HEAD")
  333. await fs.writeFile(headFile, "HEAD")
  334. const nestedGitDisabledDir = `${nestedGitDir}_disabled`
  335. expect(await fileExistsAtPath(nestedGitDir)).toBe(true)
  336. expect(await fileExistsAtPath(nestedGitDisabledDir)).toBe(false)
  337. const renameSpy = jest.spyOn(fs, "rename")
  338. jest.spyOn(fileSearch, "executeRipgrep").mockImplementation(({ args }) => {
  339. const searchPattern = args[4]
  340. if (searchPattern.includes(".git/HEAD")) {
  341. return Promise.resolve([
  342. {
  343. path: path.relative(workspaceDir, nestedGitDir),
  344. type: "folder",
  345. label: ".git",
  346. },
  347. ])
  348. } else {
  349. return Promise.resolve([])
  350. }
  351. })
  352. const service = new klass(taskId, shadowDir, workspaceDir, () => {})
  353. await service.initShadowGit()
  354. // Verify rename was called with correct paths.
  355. expect(renameSpy.mock.calls).toHaveLength(1)
  356. expect(renameSpy.mock.calls[0][0]).toBe(nestedGitDir)
  357. expect(renameSpy.mock.calls[0][1]).toBe(nestedGitDisabledDir)
  358. jest.spyOn(require("../../../utils/fs"), "fileExistsAtPath").mockImplementation((path) => {
  359. if (path === nestedGitDir) {
  360. return Promise.resolve(true)
  361. } else if (path === nestedGitDisabledDir) {
  362. return Promise.resolve(false)
  363. }
  364. return Promise.resolve(false)
  365. })
  366. // Verify the nested git directory is back to normal after initialization.
  367. expect(await fileExistsAtPath(nestedGitDir)).toBe(true)
  368. expect(await fileExistsAtPath(nestedGitDisabledDir)).toBe(false)
  369. // Clean up.
  370. renameSpy.mockRestore()
  371. jest.restoreAllMocks()
  372. await fs.rm(shadowDir, { recursive: true, force: true })
  373. await fs.rm(workspaceDir, { recursive: true, force: true })
  374. })
  375. })
  376. describe(`${klass.name}#events`, () => {
  377. it("emits initialize event when service is created", async () => {
  378. const shadowDir = path.join(tmpDir, `${prefix}3-${Date.now()}`)
  379. const workspaceDir = path.join(tmpDir, `workspace3-${Date.now()}`)
  380. await fs.mkdir(workspaceDir, { recursive: true })
  381. const newTestFile = path.join(workspaceDir, "test.txt")
  382. await fs.writeFile(newTestFile, "Testing events!")
  383. // Create a mock implementation of emit to track events.
  384. const emitSpy = jest.spyOn(EventEmitter.prototype, "emit")
  385. // Create the service - this will trigger the initialize event.
  386. const newService = await klass.create({ taskId, shadowDir, workspaceDir, log: () => {} })
  387. await newService.initShadowGit()
  388. // Find the initialize event in the emit calls.
  389. let initializeEvent = null
  390. for (let i = 0; i < emitSpy.mock.calls.length; i++) {
  391. const call = emitSpy.mock.calls[i]
  392. if (call[0] === "initialize") {
  393. initializeEvent = call[1]
  394. break
  395. }
  396. }
  397. // Restore the spy.
  398. emitSpy.mockRestore()
  399. // Verify the event was emitted with the correct data.
  400. expect(initializeEvent).not.toBeNull()
  401. expect(initializeEvent.type).toBe("initialize")
  402. expect(initializeEvent.workspaceDir).toBe(workspaceDir)
  403. expect(initializeEvent.baseHash).toBeTruthy()
  404. expect(typeof initializeEvent.created).toBe("boolean")
  405. expect(typeof initializeEvent.duration).toBe("number")
  406. // Verify the event was emitted with the correct data.
  407. expect(initializeEvent).not.toBeNull()
  408. expect(initializeEvent.type).toBe("initialize")
  409. expect(initializeEvent.workspaceDir).toBe(workspaceDir)
  410. expect(initializeEvent.baseHash).toBeTruthy()
  411. expect(typeof initializeEvent.created).toBe("boolean")
  412. expect(typeof initializeEvent.duration).toBe("number")
  413. // Clean up.
  414. await fs.rm(shadowDir, { recursive: true, force: true })
  415. await fs.rm(workspaceDir, { recursive: true, force: true })
  416. })
  417. it("emits checkpoint event when saving checkpoint", async () => {
  418. const checkpointHandler = jest.fn()
  419. service.on("checkpoint", checkpointHandler)
  420. await fs.writeFile(testFile, "Changed content for checkpoint event test")
  421. const result = await service.saveCheckpoint("Test checkpoint event")
  422. expect(result?.commit).toBeDefined()
  423. expect(checkpointHandler).toHaveBeenCalledTimes(1)
  424. const eventData = checkpointHandler.mock.calls[0][0]
  425. expect(eventData.type).toBe("checkpoint")
  426. expect(eventData.toHash).toBeDefined()
  427. expect(eventData.toHash).toBe(result!.commit)
  428. expect(typeof eventData.duration).toBe("number")
  429. })
  430. it("emits restore event when restoring checkpoint", async () => {
  431. // First create a checkpoint to restore.
  432. await fs.writeFile(testFile, "Content for restore test")
  433. const commit = await service.saveCheckpoint("Checkpoint for restore test")
  434. expect(commit?.commit).toBeTruthy()
  435. // Change the file again.
  436. await fs.writeFile(testFile, "Changed after checkpoint")
  437. // Setup restore event listener.
  438. const restoreHandler = jest.fn()
  439. service.on("restore", restoreHandler)
  440. // Restore the checkpoint.
  441. await service.restoreCheckpoint(commit!.commit)
  442. // Verify the event was emitted.
  443. expect(restoreHandler).toHaveBeenCalledTimes(1)
  444. const eventData = restoreHandler.mock.calls[0][0]
  445. expect(eventData.type).toBe("restore")
  446. expect(eventData.commitHash).toBe(commit!.commit)
  447. expect(typeof eventData.duration).toBe("number")
  448. // Verify the file was actually restored.
  449. expect(await fs.readFile(testFile, "utf-8")).toBe("Content for restore test")
  450. })
  451. it("emits error event when an error occurs", async () => {
  452. const errorHandler = jest.fn()
  453. service.on("error", errorHandler)
  454. // Force an error by providing an invalid commit hash.
  455. const invalidCommitHash = "invalid-commit-hash"
  456. // Try to restore an invalid checkpoint.
  457. try {
  458. await service.restoreCheckpoint(invalidCommitHash)
  459. } catch (error) {
  460. // Expected to throw, we're testing the event emission.
  461. }
  462. // Verify the error event was emitted.
  463. expect(errorHandler).toHaveBeenCalledTimes(1)
  464. const eventData = errorHandler.mock.calls[0][0]
  465. expect(eventData.type).toBe("error")
  466. expect(eventData.error).toBeInstanceOf(Error)
  467. })
  468. it("supports multiple event listeners for the same event", async () => {
  469. const checkpointHandler1 = jest.fn()
  470. const checkpointHandler2 = jest.fn()
  471. service.on("checkpoint", checkpointHandler1)
  472. service.on("checkpoint", checkpointHandler2)
  473. await fs.writeFile(testFile, "Content for multiple listeners test")
  474. const result = await service.saveCheckpoint("Testing multiple listeners")
  475. // Verify both handlers were called with the same event data.
  476. expect(checkpointHandler1).toHaveBeenCalledTimes(1)
  477. expect(checkpointHandler2).toHaveBeenCalledTimes(1)
  478. const eventData1 = checkpointHandler1.mock.calls[0][0]
  479. const eventData2 = checkpointHandler2.mock.calls[0][0]
  480. expect(eventData1).toEqual(eventData2)
  481. expect(eventData1.type).toBe("checkpoint")
  482. expect(eventData1.toHash).toBe(result?.commit)
  483. })
  484. it("allows removing event listeners", async () => {
  485. const checkpointHandler = jest.fn()
  486. // Add the listener.
  487. service.on("checkpoint", checkpointHandler)
  488. // Make a change and save a checkpoint.
  489. await fs.writeFile(testFile, "Content for remove listener test - part 1")
  490. await service.saveCheckpoint("Testing listener - part 1")
  491. // Verify handler was called.
  492. expect(checkpointHandler).toHaveBeenCalledTimes(1)
  493. checkpointHandler.mockClear()
  494. // Remove the listener.
  495. service.off("checkpoint", checkpointHandler)
  496. // Make another change and save a checkpoint.
  497. await fs.writeFile(testFile, "Content for remove listener test - part 2")
  498. await service.saveCheckpoint("Testing listener - part 2")
  499. // Verify handler was not called after being removed.
  500. expect(checkpointHandler).not.toHaveBeenCalled()
  501. })
  502. })
  503. },
  504. )