project.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. import { describe, expect, test } from "bun:test"
  2. import { Project } from "../../src/project/project"
  3. import { Log } from "../../src/util/log"
  4. import { $ } from "bun"
  5. import path from "path"
  6. import { tmpdir } from "../fixture/fixture"
  7. import { GlobalBus } from "../../src/bus/global"
  8. import { ProjectID } from "../../src/project/schema"
  9. import { Effect, Layer, Stream } from "effect"
  10. import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
  11. import { NodeFileSystem, NodePath } from "@effect/platform-node"
  12. import { AppFileSystem } from "../../src/filesystem"
  13. import * as CrossSpawnSpawner from "../../src/effect/cross-spawn-spawner"
  14. Log.init({ print: false })
  15. const encoder = new TextEncoder()
  16. /**
  17. * Creates a mock ChildProcessSpawner layer that intercepts git subcommands
  18. * matching `failArg` and returns exit code 128, while delegating everything
  19. * else to the real CrossSpawnSpawner.
  20. */
  21. function mockGitFailure(failArg: string) {
  22. return Layer.effect(
  23. ChildProcessSpawner.ChildProcessSpawner,
  24. Effect.gen(function* () {
  25. const real = yield* ChildProcessSpawner.ChildProcessSpawner
  26. return ChildProcessSpawner.make(
  27. Effect.fnUntraced(function* (command) {
  28. const std = ChildProcess.isStandardCommand(command) ? command : undefined
  29. if (std?.command === "git" && std.args.some((a) => a === failArg)) {
  30. return ChildProcessSpawner.makeHandle({
  31. pid: ChildProcessSpawner.ProcessId(0),
  32. exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(128)),
  33. isRunning: Effect.succeed(false),
  34. kill: () => Effect.void,
  35. stdin: { [Symbol.for("effect/Sink/TypeId")]: Symbol.for("effect/Sink/TypeId") } as any,
  36. stdout: Stream.empty,
  37. stderr: Stream.make(encoder.encode("fatal: simulated failure\n")),
  38. all: Stream.empty,
  39. getInputFd: () => ({ [Symbol.for("effect/Sink/TypeId")]: Symbol.for("effect/Sink/TypeId") }) as any,
  40. getOutputFd: () => Stream.empty,
  41. })
  42. }
  43. return yield* real.spawn(command)
  44. }),
  45. )
  46. }),
  47. ).pipe(Layer.provide(CrossSpawnSpawner.layer), Layer.provide(NodeFileSystem.layer), Layer.provide(NodePath.layer))
  48. }
  49. function projectLayerWithFailure(failArg: string) {
  50. return Project.layer.pipe(
  51. Layer.provide(mockGitFailure(failArg)),
  52. Layer.provide(AppFileSystem.defaultLayer),
  53. Layer.provide(NodePath.layer),
  54. )
  55. }
  56. describe("Project.fromDirectory", () => {
  57. test("should handle git repository with no commits", async () => {
  58. await using tmp = await tmpdir()
  59. await $`git init`.cwd(tmp.path).quiet()
  60. const { project } = await Project.fromDirectory(tmp.path)
  61. expect(project).toBeDefined()
  62. expect(project.id).toBe(ProjectID.global)
  63. expect(project.vcs).toBe("git")
  64. expect(project.worktree).toBe(tmp.path)
  65. const opencodeFile = path.join(tmp.path, ".git", "opencode")
  66. expect(await Bun.file(opencodeFile).exists()).toBe(false)
  67. })
  68. test("should handle git repository with commits", async () => {
  69. await using tmp = await tmpdir({ git: true })
  70. const { project } = await Project.fromDirectory(tmp.path)
  71. expect(project).toBeDefined()
  72. expect(project.id).not.toBe(ProjectID.global)
  73. expect(project.vcs).toBe("git")
  74. expect(project.worktree).toBe(tmp.path)
  75. const opencodeFile = path.join(tmp.path, ".git", "opencode")
  76. expect(await Bun.file(opencodeFile).exists()).toBe(true)
  77. })
  78. test("returns global for non-git directory", async () => {
  79. await using tmp = await tmpdir()
  80. const { project } = await Project.fromDirectory(tmp.path)
  81. expect(project.id).toBe(ProjectID.global)
  82. })
  83. test("derives stable project ID from root commit", async () => {
  84. await using tmp = await tmpdir({ git: true })
  85. const { project: a } = await Project.fromDirectory(tmp.path)
  86. const { project: b } = await Project.fromDirectory(tmp.path)
  87. expect(b.id).toBe(a.id)
  88. })
  89. })
  90. describe("Project.fromDirectory git failure paths", () => {
  91. test("keeps vcs when rev-list exits non-zero (no commits)", async () => {
  92. await using tmp = await tmpdir()
  93. await $`git init`.cwd(tmp.path).quiet()
  94. // rev-list fails because HEAD doesn't exist yet — this is the natural scenario
  95. const { project } = await Project.fromDirectory(tmp.path)
  96. expect(project.vcs).toBe("git")
  97. expect(project.id).toBe(ProjectID.global)
  98. expect(project.worktree).toBe(tmp.path)
  99. })
  100. test("handles show-toplevel failure gracefully", async () => {
  101. await using tmp = await tmpdir({ git: true })
  102. const layer = projectLayerWithFailure("--show-toplevel")
  103. const { project, sandbox } = await Effect.runPromise(
  104. Project.Service.use((svc) => svc.fromDirectory(tmp.path)).pipe(Effect.provide(layer)),
  105. )
  106. expect(project.worktree).toBe(tmp.path)
  107. expect(sandbox).toBe(tmp.path)
  108. })
  109. test("handles git-common-dir failure gracefully", async () => {
  110. await using tmp = await tmpdir({ git: true })
  111. const layer = projectLayerWithFailure("--git-common-dir")
  112. const { project, sandbox } = await Effect.runPromise(
  113. Project.Service.use((svc) => svc.fromDirectory(tmp.path)).pipe(Effect.provide(layer)),
  114. )
  115. expect(project.worktree).toBe(tmp.path)
  116. expect(sandbox).toBe(tmp.path)
  117. })
  118. })
  119. describe("Project.fromDirectory with worktrees", () => {
  120. test("should set worktree to root when called from root", async () => {
  121. await using tmp = await tmpdir({ git: true })
  122. const { project, sandbox } = await Project.fromDirectory(tmp.path)
  123. expect(project.worktree).toBe(tmp.path)
  124. expect(sandbox).toBe(tmp.path)
  125. expect(project.sandboxes).not.toContain(tmp.path)
  126. })
  127. test("should set worktree to root when called from a worktree", async () => {
  128. await using tmp = await tmpdir({ git: true })
  129. const worktreePath = path.join(tmp.path, "..", path.basename(tmp.path) + "-worktree")
  130. try {
  131. await $`git worktree add ${worktreePath} -b test-branch-${Date.now()}`.cwd(tmp.path).quiet()
  132. const { project, sandbox } = await Project.fromDirectory(worktreePath)
  133. expect(project.worktree).toBe(tmp.path)
  134. expect(sandbox).toBe(worktreePath)
  135. expect(project.sandboxes).toContain(worktreePath)
  136. expect(project.sandboxes).not.toContain(tmp.path)
  137. } finally {
  138. await $`git worktree remove ${worktreePath}`
  139. .cwd(tmp.path)
  140. .quiet()
  141. .catch(() => {})
  142. }
  143. })
  144. test("worktree should share project ID with main repo", async () => {
  145. await using tmp = await tmpdir({ git: true })
  146. const { project: main } = await Project.fromDirectory(tmp.path)
  147. const worktreePath = path.join(tmp.path, "..", path.basename(tmp.path) + "-wt-shared")
  148. try {
  149. await $`git worktree add ${worktreePath} -b shared-${Date.now()}`.cwd(tmp.path).quiet()
  150. const { project: wt } = await Project.fromDirectory(worktreePath)
  151. expect(wt.id).toBe(main.id)
  152. // Cache should live in the common .git dir, not the worktree's .git file
  153. const cache = path.join(tmp.path, ".git", "opencode")
  154. const exists = await Bun.file(cache).exists()
  155. expect(exists).toBe(true)
  156. } finally {
  157. await $`git worktree remove ${worktreePath}`
  158. .cwd(tmp.path)
  159. .quiet()
  160. .catch(() => {})
  161. }
  162. })
  163. test("separate clones of the same repo should share project ID", async () => {
  164. await using tmp = await tmpdir({ git: true })
  165. // Create a bare remote, push, then clone into a second directory
  166. const bare = tmp.path + "-bare"
  167. const clone = tmp.path + "-clone"
  168. try {
  169. await $`git clone --bare ${tmp.path} ${bare}`.quiet()
  170. await $`git clone ${bare} ${clone}`.quiet()
  171. const { project: a } = await Project.fromDirectory(tmp.path)
  172. const { project: b } = await Project.fromDirectory(clone)
  173. expect(b.id).toBe(a.id)
  174. } finally {
  175. await $`rm -rf ${bare} ${clone}`.quiet().nothrow()
  176. }
  177. })
  178. test("should accumulate multiple worktrees in sandboxes", async () => {
  179. await using tmp = await tmpdir({ git: true })
  180. const worktree1 = path.join(tmp.path, "..", path.basename(tmp.path) + "-wt1")
  181. const worktree2 = path.join(tmp.path, "..", path.basename(tmp.path) + "-wt2")
  182. try {
  183. await $`git worktree add ${worktree1} -b branch-${Date.now()}`.cwd(tmp.path).quiet()
  184. await $`git worktree add ${worktree2} -b branch-${Date.now() + 1}`.cwd(tmp.path).quiet()
  185. await Project.fromDirectory(worktree1)
  186. const { project } = await Project.fromDirectory(worktree2)
  187. expect(project.worktree).toBe(tmp.path)
  188. expect(project.sandboxes).toContain(worktree1)
  189. expect(project.sandboxes).toContain(worktree2)
  190. expect(project.sandboxes).not.toContain(tmp.path)
  191. } finally {
  192. await $`git worktree remove ${worktree1}`
  193. .cwd(tmp.path)
  194. .quiet()
  195. .catch(() => {})
  196. await $`git worktree remove ${worktree2}`
  197. .cwd(tmp.path)
  198. .quiet()
  199. .catch(() => {})
  200. }
  201. })
  202. })
  203. describe("Project.discover", () => {
  204. test("should discover favicon.png in root", async () => {
  205. await using tmp = await tmpdir({ git: true })
  206. const { project } = await Project.fromDirectory(tmp.path)
  207. const pngData = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
  208. await Bun.write(path.join(tmp.path, "favicon.png"), pngData)
  209. await Project.discover(project)
  210. const updated = Project.get(project.id)
  211. expect(updated).toBeDefined()
  212. expect(updated!.icon).toBeDefined()
  213. expect(updated!.icon?.url).toStartWith("data:")
  214. expect(updated!.icon?.url).toContain("base64")
  215. expect(updated!.icon?.color).toBeUndefined()
  216. })
  217. test("should not discover non-image files", async () => {
  218. await using tmp = await tmpdir({ git: true })
  219. const { project } = await Project.fromDirectory(tmp.path)
  220. await Bun.write(path.join(tmp.path, "favicon.txt"), "not an image")
  221. await Project.discover(project)
  222. const updated = Project.get(project.id)
  223. expect(updated).toBeDefined()
  224. expect(updated!.icon).toBeUndefined()
  225. })
  226. })
  227. describe("Project.update", () => {
  228. test("should update name", async () => {
  229. await using tmp = await tmpdir({ git: true })
  230. const { project } = await Project.fromDirectory(tmp.path)
  231. const updated = await Project.update({
  232. projectID: project.id,
  233. name: "New Project Name",
  234. })
  235. expect(updated.name).toBe("New Project Name")
  236. const fromDb = Project.get(project.id)
  237. expect(fromDb?.name).toBe("New Project Name")
  238. })
  239. test("should update icon url", async () => {
  240. await using tmp = await tmpdir({ git: true })
  241. const { project } = await Project.fromDirectory(tmp.path)
  242. const updated = await Project.update({
  243. projectID: project.id,
  244. icon: { url: "https://example.com/icon.png" },
  245. })
  246. expect(updated.icon?.url).toBe("https://example.com/icon.png")
  247. const fromDb = Project.get(project.id)
  248. expect(fromDb?.icon?.url).toBe("https://example.com/icon.png")
  249. })
  250. test("should update icon color", async () => {
  251. await using tmp = await tmpdir({ git: true })
  252. const { project } = await Project.fromDirectory(tmp.path)
  253. const updated = await Project.update({
  254. projectID: project.id,
  255. icon: { color: "#ff0000" },
  256. })
  257. expect(updated.icon?.color).toBe("#ff0000")
  258. const fromDb = Project.get(project.id)
  259. expect(fromDb?.icon?.color).toBe("#ff0000")
  260. })
  261. test("should update commands", async () => {
  262. await using tmp = await tmpdir({ git: true })
  263. const { project } = await Project.fromDirectory(tmp.path)
  264. const updated = await Project.update({
  265. projectID: project.id,
  266. commands: { start: "npm run dev" },
  267. })
  268. expect(updated.commands?.start).toBe("npm run dev")
  269. const fromDb = Project.get(project.id)
  270. expect(fromDb?.commands?.start).toBe("npm run dev")
  271. })
  272. test("should throw error when project not found", async () => {
  273. await expect(
  274. Project.update({
  275. projectID: ProjectID.make("nonexistent-project-id"),
  276. name: "Should Fail",
  277. }),
  278. ).rejects.toThrow("Project not found: nonexistent-project-id")
  279. })
  280. test("should emit GlobalBus event on update", async () => {
  281. await using tmp = await tmpdir({ git: true })
  282. const { project } = await Project.fromDirectory(tmp.path)
  283. let eventPayload: any = null
  284. const on = (data: any) => { eventPayload = data }
  285. GlobalBus.on("event", on)
  286. try {
  287. await Project.update({
  288. projectID: project.id,
  289. name: "Updated Name",
  290. })
  291. expect(eventPayload).not.toBeNull()
  292. expect(eventPayload.payload.type).toBe("project.updated")
  293. expect(eventPayload.payload.properties.name).toBe("Updated Name")
  294. } finally {
  295. GlobalBus.off("event", on)
  296. }
  297. })
  298. test("should update multiple fields at once", async () => {
  299. await using tmp = await tmpdir({ git: true })
  300. const { project } = await Project.fromDirectory(tmp.path)
  301. const updated = await Project.update({
  302. projectID: project.id,
  303. name: "Multi Update",
  304. icon: { url: "https://example.com/favicon.ico", color: "#00ff00" },
  305. commands: { start: "make start" },
  306. })
  307. expect(updated.name).toBe("Multi Update")
  308. expect(updated.icon?.url).toBe("https://example.com/favicon.ico")
  309. expect(updated.icon?.color).toBe("#00ff00")
  310. expect(updated.commands?.start).toBe("make start")
  311. })
  312. })
  313. describe("Project.list and Project.get", () => {
  314. test("list returns all projects", async () => {
  315. await using tmp = await tmpdir({ git: true })
  316. const { project } = await Project.fromDirectory(tmp.path)
  317. const all = Project.list()
  318. expect(all.length).toBeGreaterThan(0)
  319. expect(all.find((p) => p.id === project.id)).toBeDefined()
  320. })
  321. test("get returns project by id", async () => {
  322. await using tmp = await tmpdir({ git: true })
  323. const { project } = await Project.fromDirectory(tmp.path)
  324. const found = Project.get(project.id)
  325. expect(found).toBeDefined()
  326. expect(found!.id).toBe(project.id)
  327. })
  328. test("get returns undefined for unknown id", () => {
  329. const found = Project.get(ProjectID.make("nonexistent"))
  330. expect(found).toBeUndefined()
  331. })
  332. })
  333. describe("Project.setInitialized", () => {
  334. test("sets time_initialized on project", async () => {
  335. await using tmp = await tmpdir({ git: true })
  336. const { project } = await Project.fromDirectory(tmp.path)
  337. expect(project.time.initialized).toBeUndefined()
  338. Project.setInitialized(project.id)
  339. const updated = Project.get(project.id)
  340. expect(updated?.time.initialized).toBeDefined()
  341. })
  342. })
  343. describe("Project.addSandbox and Project.removeSandbox", () => {
  344. test("addSandbox adds directory and removeSandbox removes it", async () => {
  345. await using tmp = await tmpdir({ git: true })
  346. const { project } = await Project.fromDirectory(tmp.path)
  347. const sandboxDir = path.join(tmp.path, "sandbox-test")
  348. await Project.addSandbox(project.id, sandboxDir)
  349. let found = Project.get(project.id)
  350. expect(found?.sandboxes).toContain(sandboxDir)
  351. await Project.removeSandbox(project.id, sandboxDir)
  352. found = Project.get(project.id)
  353. expect(found?.sandboxes).not.toContain(sandboxDir)
  354. })
  355. test("addSandbox emits GlobalBus event", async () => {
  356. await using tmp = await tmpdir({ git: true })
  357. const { project } = await Project.fromDirectory(tmp.path)
  358. const sandboxDir = path.join(tmp.path, "sandbox-event")
  359. const events: any[] = []
  360. const on = (evt: any) => events.push(evt)
  361. GlobalBus.on("event", on)
  362. await Project.addSandbox(project.id, sandboxDir)
  363. GlobalBus.off("event", on)
  364. expect(events.some((e) => e.payload.type === Project.Event.Updated.type)).toBe(true)
  365. })
  366. })