ShadowCheckpointService.test.ts 25 KB

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