project.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. import { describe, expect } from "bun:test"
  2. import { Project } from "@/project/project"
  3. import { $ } from "bun"
  4. import path from "path"
  5. import { tmpdirScoped } from "../fixture/fixture"
  6. import { GlobalBus } from "../../src/bus/global"
  7. import { Database } from "@kirincode-ai/core/database/database"
  8. import { ProjectTable } from "@kirincode-ai/core/project/sql"
  9. import { SessionTable } from "@kirincode-ai/core/session/sql"
  10. import { WorkspaceTable } from "@kirincode-ai/core/control-plane/workspace.sql"
  11. import { eq } from "drizzle-orm"
  12. import { Hash } from "@kirincode-ai/core/util/hash"
  13. import { SessionID } from "@/session/schema"
  14. import { WorkspaceV2 } from "@kirincode-ai/core/workspace"
  15. import { Cause, Effect, Exit, Layer, Stream } from "effect"
  16. import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
  17. import { ProjectV2 } from "@kirincode-ai/core/project"
  18. import { CrossSpawnSpawner } from "@kirincode-ai/core/cross-spawn-spawner"
  19. import { testEffect } from "../lib/effect"
  20. import { RuntimeFlags } from "@/effect/runtime-flags"
  21. import { AppNodeBuilder } from "@kirincode-ai/core/effect/app-node-builder"
  22. import { LayerNode } from "@kirincode-ai/core/effect/layer-node"
  23. const encoder = new TextEncoder()
  24. const projectTestNode = LayerNode.group([Project.node, Database.node, CrossSpawnSpawner.node])
  25. const it = testEffect(AppNodeBuilder.build(projectTestNode))
  26. function remoteProjectID(remote: string) {
  27. return ProjectV2.ID.make(Hash.fast(`git-remote:${remote}`))
  28. }
  29. /**
  30. * Creates a mock ChildProcessSpawner layer that intercepts git subcommands
  31. * matching `failArg` and returns exit code 128, while delegating everything
  32. * else to the real CrossSpawnSpawner.
  33. */
  34. function mockGitFailure(failArg: string) {
  35. return Layer.effect(
  36. ChildProcessSpawner.ChildProcessSpawner,
  37. Effect.gen(function* () {
  38. const real = yield* ChildProcessSpawner.ChildProcessSpawner
  39. return ChildProcessSpawner.make(
  40. Effect.fnUntraced(function* (command) {
  41. const std = ChildProcess.isStandardCommand(command) ? command : undefined
  42. if (std?.command === "git" && std.args.some((a) => a === failArg)) {
  43. return ChildProcessSpawner.makeHandle({
  44. pid: ChildProcessSpawner.ProcessId(0),
  45. exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(128)),
  46. isRunning: Effect.succeed(false),
  47. kill: () => Effect.void,
  48. stdin: { [Symbol.for("effect/Sink/TypeId")]: Symbol.for("effect/Sink/TypeId") } as any,
  49. stdout: Stream.empty,
  50. stderr: Stream.make(encoder.encode("fatal: simulated failure\n")),
  51. all: Stream.empty,
  52. getInputFd: () => ({ [Symbol.for("effect/Sink/TypeId")]: Symbol.for("effect/Sink/TypeId") }) as any,
  53. getOutputFd: () => Stream.empty,
  54. unref: Effect.succeed(Effect.void),
  55. })
  56. }
  57. return yield* real.spawn(command)
  58. }),
  59. )
  60. }),
  61. ).pipe(Layer.provide(AppNodeBuilder.build(CrossSpawnSpawner.node)))
  62. }
  63. function projectLayerWithFailure(failArg: string) {
  64. return AppNodeBuilder.build(Project.node, [
  65. [ProjectV2.node, projectV2FailureLayer()],
  66. [CrossSpawnSpawner.node, mockGitFailure(failArg)],
  67. ])
  68. }
  69. function projectV2FailureLayer() {
  70. return Layer.succeed(
  71. ProjectV2.Service,
  72. ProjectV2.Service.of({
  73. directories: () => Effect.succeed([]),
  74. resolve: (input) =>
  75. Effect.succeed({
  76. id: ProjectV2.ID.global,
  77. directory: input,
  78. vcs: { type: "git" as const, store: input },
  79. }),
  80. commit: () => Effect.void,
  81. }),
  82. )
  83. }
  84. const failureIt = (failArg: string) =>
  85. testEffect(AppNodeBuilder.build(projectTestNode, [[Project.node, projectLayerWithFailure(failArg)]]))
  86. const iconDiscoveryIt = testEffect(
  87. AppNodeBuilder.build(projectTestNode, [[RuntimeFlags.node, RuntimeFlags.layer({ experimentalIconDiscovery: true })]]),
  88. )
  89. function waitForProjectIcon(id: ProjectV2.ID, attempts = 50): Effect.Effect<Project.Info, never, Project.Service> {
  90. return Effect.gen(function* () {
  91. const project = yield* Project.Service
  92. const info = yield* project.get(id)
  93. if (info?.icon?.url) return info
  94. if (attempts <= 0) throw new Error(`Project icon was not discovered: ${id}`)
  95. yield* Effect.sleep("10 millis")
  96. return yield* waitForProjectIcon(id, attempts - 1)
  97. })
  98. }
  99. describe("Project.fromDirectory", () => {
  100. it.live("should handle git repository with no commits", () =>
  101. Effect.gen(function* () {
  102. const project = yield* Project.Service
  103. const tmp = yield* tmpdirScoped()
  104. yield* Effect.promise(() => $`git init`.cwd(tmp).quiet())
  105. const result = yield* project.fromDirectory(tmp)
  106. expect(result.project).toBeDefined()
  107. expect(result.project.id).toBe(ProjectV2.ID.global)
  108. expect(result.project.vcs).toBe("git")
  109. expect(result.project.worktree).toBe(tmp)
  110. const kirincodeFile = path.join(tmp, ".git", "kirincode")
  111. expect(yield* Effect.promise(() => Bun.file(opencodeFile).exists())).toBe(false)
  112. }),
  113. )
  114. it.live("should handle git repository with commits", () =>
  115. Effect.gen(function* () {
  116. const project = yield* Project.Service
  117. const tmp = yield* tmpdirScoped({ git: true })
  118. const result = yield* project.fromDirectory(tmp)
  119. expect(result.project).toBeDefined()
  120. expect(result.project.id).not.toBe(ProjectV2.ID.global)
  121. expect(result.project.vcs).toBe("git")
  122. expect(result.project.worktree).toBe(tmp)
  123. }),
  124. )
  125. it.live("returns global for non-git directory", () =>
  126. Effect.gen(function* () {
  127. const project = yield* Project.Service
  128. const tmp = yield* tmpdirScoped()
  129. const result = yield* project.fromDirectory(tmp)
  130. expect(result.project.id).toBe(ProjectV2.ID.global)
  131. }),
  132. )
  133. it.live("derives stable project ID from root commit", () =>
  134. Effect.gen(function* () {
  135. const project = yield* Project.Service
  136. const tmp = yield* tmpdirScoped({ git: true })
  137. const result = yield* project.fromDirectory(tmp)
  138. const next = yield* project.fromDirectory(tmp)
  139. expect(next.project.id).toBe(result.project.id)
  140. }),
  141. )
  142. it.live("prefers normalized origin remote over root commit", () =>
  143. Effect.gen(function* () {
  144. const project = yield* Project.Service
  145. const tmp = yield* tmpdirScoped({ git: true })
  146. yield* Effect.promise(() => $`git remote add origin git@github.com:Test-Org/Test-Repo.git`.cwd(tmp).quiet())
  147. const result = yield* project.fromDirectory(tmp)
  148. expect(result.project.id).toBe(remoteProjectID("github.com/Test-Org/Test-Repo"))
  149. }),
  150. )
  151. it.live("normalizes equivalent origin URL forms to the same project ID", () =>
  152. Effect.gen(function* () {
  153. const project = yield* Project.Service
  154. const ssh = yield* tmpdirScoped({ git: true })
  155. const https = yield* tmpdirScoped({ git: true })
  156. yield* Effect.promise(() => $`git remote add origin git@github.com:owner/repo.git`.cwd(ssh).quiet())
  157. yield* Effect.promise(() => $`git remote add origin https://github.com/owner/repo.git`.cwd(https).quiet())
  158. const result = yield* project.fromDirectory(ssh)
  159. const next = yield* project.fromDirectory(https)
  160. expect(result.project.id).toBe(remoteProjectID("github.com/owner/repo"))
  161. expect(next.project.id).toBe(result.project.id)
  162. }),
  163. )
  164. it.live("migrates cached root project data when origin becomes available", () =>
  165. Effect.gen(function* () {
  166. const { db } = yield* Database.Service
  167. const tmp = yield* tmpdirScoped({ git: true })
  168. const projects = yield* Project.Service
  169. const rootResult = yield* projects.fromDirectory(tmp)
  170. const rootProject = rootResult.project
  171. const remoteID = remoteProjectID("github.com/acme/app")
  172. const sessionID = crypto.randomUUID() as SessionID
  173. const workspaceID = WorkspaceV2.ID.ascending()
  174. yield* db
  175. .insert(SessionTable)
  176. .values({
  177. id: sessionID,
  178. project_id: rootProject.id,
  179. slug: sessionID,
  180. directory: tmp,
  181. title: "test",
  182. version: "0.0.0-test",
  183. time_created: Date.now(),
  184. time_updated: Date.now(),
  185. })
  186. .run()
  187. .pipe(Effect.orDie)
  188. yield* db
  189. .insert(WorkspaceTable)
  190. .values({ id: workspaceID, type: "local", name: "test", project_id: rootProject.id })
  191. .run()
  192. .pipe(Effect.orDie)
  193. yield* Effect.promise(() => $`git remote add origin git@github.com:acme/app.git`.cwd(tmp).quiet())
  194. const result = yield* projects.fromDirectory(tmp)
  195. expect(result.project.id).toBe(remoteID)
  196. expect(
  197. yield* db.select().from(ProjectTable).where(eq(ProjectTable.id, rootProject.id)).get().pipe(Effect.orDie),
  198. ).toBeUndefined()
  199. expect(
  200. (yield* db.select().from(SessionTable).where(eq(SessionTable.id, sessionID)).get().pipe(Effect.orDie))
  201. ?.project_id,
  202. ).toBe(remoteID)
  203. expect(
  204. (yield* db.select().from(WorkspaceTable).where(eq(WorkspaceTable.id, workspaceID)).get().pipe(Effect.orDie))
  205. ?.project_id,
  206. ).toBe(remoteID)
  207. }),
  208. )
  209. })
  210. describe("Project.fromDirectory git failure paths", () => {
  211. it.live("keeps vcs when rev-list exits non-zero (no commits)", () =>
  212. Effect.gen(function* () {
  213. const project = yield* Project.Service
  214. const tmp = yield* tmpdirScoped()
  215. yield* Effect.promise(() => $`git init`.cwd(tmp).quiet())
  216. // rev-list fails because HEAD doesn't exist yet: this is the natural scenario.
  217. const result = yield* project.fromDirectory(tmp)
  218. expect(result.project.vcs).toBe("git")
  219. expect(result.project.id).toBe(ProjectV2.ID.global)
  220. expect(result.project.worktree).toBe(tmp)
  221. }),
  222. )
  223. failureIt("--show-toplevel").live("handles show-toplevel failure gracefully", () =>
  224. Effect.gen(function* () {
  225. const project = yield* Project.Service
  226. const tmp = yield* tmpdirScoped({ git: true })
  227. const result = yield* project.fromDirectory(tmp)
  228. expect(result.project.worktree).toBe(tmp)
  229. expect(result.sandbox).toBe(tmp)
  230. }),
  231. )
  232. failureIt("--git-common-dir").live("handles git-common-dir failure gracefully", () =>
  233. Effect.gen(function* () {
  234. const project = yield* Project.Service
  235. const tmp = yield* tmpdirScoped({ git: true })
  236. const result = yield* project.fromDirectory(tmp)
  237. expect(result.project.worktree).toBe(tmp)
  238. expect(result.sandbox).toBe(tmp)
  239. }),
  240. )
  241. })
  242. describe("Project.fromDirectory with worktrees", () => {
  243. it.live("should set worktree to root when called from root", () =>
  244. Effect.gen(function* () {
  245. const project = yield* Project.Service
  246. const tmp = yield* tmpdirScoped({ git: true })
  247. const result = yield* project.fromDirectory(tmp)
  248. expect(result.project.worktree).toBe(tmp)
  249. expect(result.sandbox).toBe(tmp)
  250. expect(result.project.sandboxes).not.toContain(tmp)
  251. }),
  252. )
  253. it.live("tracks a linked worktree as the opened project directory", () =>
  254. Effect.gen(function* () {
  255. const project = yield* Project.Service
  256. const tmp = yield* tmpdirScoped({ git: true })
  257. const worktreePath = path.join(tmp, "..", path.basename(tmp) + "-worktree")
  258. yield* Effect.addFinalizer(() =>
  259. Effect.promise(() =>
  260. $`git worktree remove ${worktreePath}`
  261. .cwd(tmp)
  262. .quiet()
  263. .catch(() => {}),
  264. ),
  265. )
  266. yield* Effect.promise(() => $`git worktree add ${worktreePath} -b test-branch-${Date.now()}`.cwd(tmp).quiet())
  267. const result = yield* project.fromDirectory(worktreePath)
  268. expect(result.project.worktree).toBe(worktreePath)
  269. expect(result.sandbox).toBe(worktreePath)
  270. expect(result.project.sandboxes).not.toContain(worktreePath)
  271. expect(result.project.sandboxes).not.toContain(tmp)
  272. }),
  273. )
  274. it.live("worktree should share project ID with main repo", () =>
  275. Effect.gen(function* () {
  276. const project = yield* Project.Service
  277. const tmp = yield* tmpdirScoped({ git: true })
  278. const result = yield* project.fromDirectory(tmp)
  279. const worktreePath = path.join(tmp, "..", path.basename(tmp) + "-wt-shared")
  280. yield* Effect.addFinalizer(() =>
  281. Effect.promise(() =>
  282. $`git worktree remove ${worktreePath}`
  283. .cwd(tmp)
  284. .quiet()
  285. .catch(() => {}),
  286. ),
  287. )
  288. yield* Effect.promise(() => $`git worktree add ${worktreePath} -b shared-${Date.now()}`.cwd(tmp).quiet())
  289. const next = yield* project.fromDirectory(worktreePath)
  290. expect(next.project.id).toBe(result.project.id)
  291. const cache = path.join(tmp, ".git", "kirincode")
  292. const exists = yield* Effect.promise(() => Bun.file(cache).exists())
  293. expect(exists).toBe(true)
  294. }),
  295. )
  296. it.live("separate clones of the same repo should share project ID", () =>
  297. Effect.gen(function* () {
  298. const project = yield* Project.Service
  299. const tmp = yield* tmpdirScoped({ git: true })
  300. // Create a bare remote, push, then clone into a second directory
  301. const bare = tmp + "-bare"
  302. const clone = tmp + "-clone"
  303. yield* Effect.addFinalizer(() =>
  304. Effect.promise(() => $`rm -rf ${bare} ${clone}`.quiet().nothrow()).pipe(Effect.ignore),
  305. )
  306. yield* Effect.promise(() => $`git clone --bare ${tmp} ${bare}`.quiet())
  307. yield* Effect.promise(() => $`git clone ${bare} ${clone}`.quiet())
  308. const result = yield* project.fromDirectory(tmp)
  309. const next = yield* project.fromDirectory(clone)
  310. expect(next.project.id).toBe(result.project.id)
  311. }),
  312. )
  313. it.live("should accumulate multiple worktrees in sandboxes", () =>
  314. Effect.gen(function* () {
  315. const project = yield* Project.Service
  316. const tmp = yield* tmpdirScoped({ git: true })
  317. const worktree1 = path.join(tmp, "..", path.basename(tmp) + "-wt1")
  318. const worktree2 = path.join(tmp, "..", path.basename(tmp) + "-wt2")
  319. yield* Effect.addFinalizer(() =>
  320. Effect.gen(function* () {
  321. yield* Effect.promise(() =>
  322. $`git worktree remove ${worktree1}`
  323. .cwd(tmp)
  324. .quiet()
  325. .catch(() => {}),
  326. )
  327. yield* Effect.promise(() =>
  328. $`git worktree remove ${worktree2}`
  329. .cwd(tmp)
  330. .quiet()
  331. .catch(() => {}),
  332. )
  333. }),
  334. )
  335. yield* Effect.promise(() => $`git worktree add ${worktree1} -b branch-${Date.now()}`.cwd(tmp).quiet())
  336. yield* Effect.promise(() => $`git worktree add ${worktree2} -b branch-${Date.now() + 1}`.cwd(tmp).quiet())
  337. yield* project.fromDirectory(worktree1)
  338. const result = yield* project.fromDirectory(worktree2)
  339. expect(result.project.worktree).toBe(worktree1)
  340. expect(result.project.sandboxes).toContain(worktree2)
  341. expect(result.project.sandboxes).not.toContain(tmp)
  342. }),
  343. )
  344. })
  345. describe("Project.discover", () => {
  346. iconDiscoveryIt.live("discovers favicon from fromDirectory when enabled", () =>
  347. Effect.gen(function* () {
  348. const project = yield* Project.Service
  349. const tmp = yield* tmpdirScoped({ git: true })
  350. const pngData = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
  351. yield* Effect.promise(() => Bun.write(path.join(tmp, "favicon.png"), pngData))
  352. const result = yield* project.fromDirectory(tmp)
  353. const updated = yield* waitForProjectIcon(result.project.id)
  354. expect(updated.icon?.url).toStartWith("data:")
  355. expect(updated.icon?.url).toContain("base64")
  356. }),
  357. )
  358. it.live("should discover favicon.png in root", () =>
  359. Effect.gen(function* () {
  360. const project = yield* Project.Service
  361. const tmp = yield* tmpdirScoped({ git: true })
  362. const result = yield* project.fromDirectory(tmp)
  363. const pngData = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
  364. yield* Effect.promise(() => Bun.write(path.join(tmp, "favicon.png"), pngData))
  365. yield* project.discover(result.project)
  366. const updated = yield* project.get(result.project.id)
  367. expect(updated).toBeDefined()
  368. expect(updated!.icon).toBeDefined()
  369. expect(updated!.icon?.url).toStartWith("data:")
  370. expect(updated!.icon?.url).toContain("base64")
  371. expect(updated!.icon?.color).toBeUndefined()
  372. }),
  373. )
  374. it.live("should not discover non-image files", () =>
  375. Effect.gen(function* () {
  376. const project = yield* Project.Service
  377. const tmp = yield* tmpdirScoped({ git: true })
  378. const result = yield* project.fromDirectory(tmp)
  379. yield* Effect.promise(() => Bun.write(path.join(tmp, "favicon.txt"), "not an image"))
  380. yield* project.discover(result.project)
  381. const updated = yield* project.get(result.project.id)
  382. expect(updated).toBeDefined()
  383. expect(updated!.icon).toBeUndefined()
  384. }),
  385. )
  386. it.live("should not discover favicon when override is set", () =>
  387. Effect.gen(function* () {
  388. const project = yield* Project.Service
  389. const tmp = yield* tmpdirScoped({ git: true })
  390. const result = yield* project.fromDirectory(tmp)
  391. yield* project.update({
  392. projectID: result.project.id,
  393. icon: { override: "data:image/png;base64,override" },
  394. })
  395. const updatedProject = yield* project.get(result.project.id)
  396. if (!updatedProject) throw new Error("Project not found")
  397. const pngData = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
  398. yield* Effect.promise(() => Bun.write(path.join(tmp, "favicon.png"), pngData))
  399. yield* project.discover(updatedProject)
  400. const updated = yield* project.get(result.project.id)
  401. expect(updated).toBeDefined()
  402. expect(updated!.icon?.override).toBe("data:image/png;base64,override")
  403. expect(updated!.icon?.url).toBeUndefined()
  404. }),
  405. )
  406. })
  407. describe("Project.update", () => {
  408. it.live("should update name", () =>
  409. Effect.gen(function* () {
  410. const project = yield* Project.Service
  411. const tmp = yield* tmpdirScoped({ git: true })
  412. const result = yield* project.fromDirectory(tmp)
  413. const updated = yield* project.update({
  414. projectID: result.project.id,
  415. name: "New Project Name",
  416. })
  417. expect(updated.name).toBe("New Project Name")
  418. const fromDb = yield* project.get(result.project.id)
  419. expect(fromDb?.name).toBe("New Project Name")
  420. }),
  421. )
  422. it.live("should update icon url", () =>
  423. Effect.gen(function* () {
  424. const project = yield* Project.Service
  425. const tmp = yield* tmpdirScoped({ git: true })
  426. const result = yield* project.fromDirectory(tmp)
  427. const updated = yield* project.update({
  428. projectID: result.project.id,
  429. icon: { url: "https://example.com/icon.png" },
  430. })
  431. expect(updated.icon?.url).toBe("https://example.com/icon.png")
  432. const fromDb = yield* project.get(result.project.id)
  433. expect(fromDb?.icon?.url).toBe("https://example.com/icon.png")
  434. }),
  435. )
  436. it.live("should update icon color", () =>
  437. Effect.gen(function* () {
  438. const project = yield* Project.Service
  439. const tmp = yield* tmpdirScoped({ git: true })
  440. const result = yield* project.fromDirectory(tmp)
  441. const updated = yield* project.update({
  442. projectID: result.project.id,
  443. icon: { color: "#ff0000" },
  444. })
  445. expect(updated.icon?.color).toBe("#ff0000")
  446. const fromDb = yield* project.get(result.project.id)
  447. expect(fromDb?.icon?.color).toBe("#ff0000")
  448. }),
  449. )
  450. it.live("should update icon override", () =>
  451. Effect.gen(function* () {
  452. const project = yield* Project.Service
  453. const tmp = yield* tmpdirScoped({ git: true })
  454. const result = yield* project.fromDirectory(tmp)
  455. const updated = yield* project.update({
  456. projectID: result.project.id,
  457. icon: { override: "data:image/png;base64,abc123" },
  458. })
  459. expect(updated.icon?.override).toBe("data:image/png;base64,abc123")
  460. const fromDb = yield* project.get(result.project.id)
  461. expect(fromDb?.icon?.override).toBe("data:image/png;base64,abc123")
  462. }),
  463. )
  464. it.live("should update commands", () =>
  465. Effect.gen(function* () {
  466. const project = yield* Project.Service
  467. const tmp = yield* tmpdirScoped({ git: true })
  468. const result = yield* project.fromDirectory(tmp)
  469. const updated = yield* project.update({
  470. projectID: result.project.id,
  471. commands: { start: "npm run dev" },
  472. })
  473. expect(updated.commands?.start).toBe("npm run dev")
  474. const fromDb = yield* project.get(result.project.id)
  475. expect(fromDb?.commands?.start).toBe("npm run dev")
  476. }),
  477. )
  478. it.live("should fail when project not found", () =>
  479. Effect.gen(function* () {
  480. const project = yield* Project.Service
  481. const exit = yield* project
  482. .update({ projectID: ProjectV2.ID.make("nonexistent-project-id"), name: "Should Fail" })
  483. .pipe(Effect.exit)
  484. expect(Exit.isFailure(exit)).toBe(true)
  485. if (Exit.isFailure(exit)) {
  486. const error = Cause.squash(exit.cause)
  487. expect(error).toMatchObject({ _tag: "Project.NotFoundError", projectID: "nonexistent-project-id" })
  488. }
  489. }),
  490. )
  491. it.live("should emit GlobalBus event on update", () =>
  492. Effect.gen(function* () {
  493. const project = yield* Project.Service
  494. const tmp = yield* tmpdirScoped({ git: true })
  495. const result = yield* project.fromDirectory(tmp)
  496. let eventPayload: any = null
  497. const on = (data: any) => {
  498. eventPayload = data
  499. }
  500. GlobalBus.on("event", on)
  501. yield* Effect.addFinalizer(() => Effect.sync(() => GlobalBus.off("event", on)))
  502. yield* project.update({ projectID: result.project.id, name: "Updated Name" })
  503. expect(eventPayload).not.toBeNull()
  504. expect(eventPayload.payload.type).toBe("project.updated")
  505. expect(eventPayload.payload.properties.name).toBe("Updated Name")
  506. }),
  507. )
  508. it.live("should update multiple fields at once", () =>
  509. Effect.gen(function* () {
  510. const project = yield* Project.Service
  511. const tmp = yield* tmpdirScoped({ git: true })
  512. const result = yield* project.fromDirectory(tmp)
  513. const updated = yield* project.update({
  514. projectID: result.project.id,
  515. name: "Multi Update",
  516. icon: { url: "https://example.com/favicon.ico", override: "data:image/png;base64,abc123", color: "#00ff00" },
  517. commands: { start: "make start" },
  518. })
  519. expect(updated.name).toBe("Multi Update")
  520. expect(updated.icon?.url).toBe("https://example.com/favicon.ico")
  521. expect(updated.icon?.override).toBe("data:image/png;base64,abc123")
  522. expect(updated.icon?.color).toBe("#00ff00")
  523. expect(updated.commands?.start).toBe("make start")
  524. }),
  525. )
  526. })
  527. describe("Project.list and Project.get", () => {
  528. it.live("list returns all projects", () =>
  529. Effect.gen(function* () {
  530. const project = yield* Project.Service
  531. const tmp = yield* tmpdirScoped({ git: true })
  532. const result = yield* project.fromDirectory(tmp)
  533. const all = yield* project.list()
  534. expect(all.length).toBeGreaterThan(0)
  535. expect(all.find((p) => p.id === result.project.id)).toBeDefined()
  536. }),
  537. )
  538. it.live("get returns project by id", () =>
  539. Effect.gen(function* () {
  540. const project = yield* Project.Service
  541. const tmp = yield* tmpdirScoped({ git: true })
  542. const result = yield* project.fromDirectory(tmp)
  543. const found = yield* project.get(result.project.id)
  544. expect(found).toBeDefined()
  545. expect(found!.id).toBe(result.project.id)
  546. }),
  547. )
  548. it.live("get returns undefined for unknown id", () =>
  549. Effect.gen(function* () {
  550. const project = yield* Project.Service
  551. const found = yield* project.get(ProjectV2.ID.make("nonexistent"))
  552. expect(found).toBeUndefined()
  553. }),
  554. )
  555. })
  556. describe("Project.setInitialized", () => {
  557. it.live("sets time_initialized on project", () =>
  558. Effect.gen(function* () {
  559. const project = yield* Project.Service
  560. const tmp = yield* tmpdirScoped({ git: true })
  561. const result = yield* project.fromDirectory(tmp)
  562. expect(result.project.time.initialized).toBeUndefined()
  563. yield* project.setInitialized(result.project.id)
  564. const updated = yield* project.get(result.project.id)
  565. expect(updated?.time.initialized).toBeDefined()
  566. }),
  567. )
  568. })
  569. describe("Project.addSandbox and Project.removeSandbox", () => {
  570. it.live("addSandbox adds directory and removeSandbox removes it", () =>
  571. Effect.gen(function* () {
  572. const project = yield* Project.Service
  573. const tmp = yield* tmpdirScoped({ git: true })
  574. const result = yield* project.fromDirectory(tmp)
  575. const sandboxDir = path.join(tmp, "sandbox-test")
  576. yield* project.addSandbox(result.project.id, sandboxDir)
  577. let found = yield* project.get(result.project.id)
  578. expect(found?.sandboxes).toContain(sandboxDir)
  579. yield* project.removeSandbox(result.project.id, sandboxDir)
  580. found = yield* project.get(result.project.id)
  581. expect(found?.sandboxes).not.toContain(sandboxDir)
  582. }),
  583. )
  584. it.live("addSandbox emits GlobalBus event", () =>
  585. Effect.gen(function* () {
  586. const project = yield* Project.Service
  587. const tmp = yield* tmpdirScoped({ git: true })
  588. const result = yield* project.fromDirectory(tmp)
  589. const sandboxDir = path.join(tmp, "sandbox-event")
  590. const events: any[] = []
  591. const on = (evt: any) => events.push(evt)
  592. GlobalBus.on("event", on)
  593. yield* Effect.addFinalizer(() => Effect.sync(() => GlobalBus.off("event", on)))
  594. yield* project.addSandbox(result.project.id, sandboxDir)
  595. expect(events.some((e) => e.payload.type === Project.Event.Updated.type)).toBe(true)
  596. }),
  597. )
  598. })
  599. describe("Project.fromDirectory with bare repos", () => {
  600. it.live("worktree from bare repo should cache in bare repo, not parent", () =>
  601. Effect.gen(function* () {
  602. const project = yield* Project.Service
  603. const tmp = yield* tmpdirScoped({ git: true })
  604. const parentDir = path.dirname(tmp)
  605. const barePath = path.join(parentDir, `bare-${Date.now()}.git`)
  606. const worktreePath = path.join(parentDir, `worktree-${Date.now()}`)
  607. yield* Effect.addFinalizer(() =>
  608. Effect.promise(() => $`rm -rf ${barePath} ${worktreePath}`.quiet().nothrow()).pipe(Effect.ignore),
  609. )
  610. yield* Effect.promise(() => $`git clone --bare ${tmp} ${barePath}`.quiet())
  611. yield* Effect.promise(() => $`git worktree add ${worktreePath} HEAD`.cwd(barePath).quiet())
  612. const result = yield* project.fromDirectory(worktreePath)
  613. expect(result.project.id).not.toBe(ProjectV2.ID.global)
  614. expect(result.project.worktree).toBe(worktreePath)
  615. const correctCache = path.join(barePath, "kirincode")
  616. const wrongCache = path.join(parentDir, ".git", "kirincode")
  617. expect(yield* Effect.promise(() => Bun.file(correctCache).exists())).toBe(true)
  618. expect(yield* Effect.promise(() => Bun.file(wrongCache).exists())).toBe(false)
  619. }),
  620. )
  621. it.live("different bare repos under same parent should not share project ID", () =>
  622. Effect.gen(function* () {
  623. const project = yield* Project.Service
  624. const tmp1 = yield* tmpdirScoped({ git: true })
  625. const tmp2 = yield* tmpdirScoped({ git: true })
  626. const parentDir = path.dirname(tmp1)
  627. const bareA = path.join(parentDir, `bare-a-${Date.now()}.git`)
  628. const bareB = path.join(parentDir, `bare-b-${Date.now()}.git`)
  629. const worktreeA = path.join(parentDir, `wt-a-${Date.now()}`)
  630. const worktreeB = path.join(parentDir, `wt-b-${Date.now()}`)
  631. yield* Effect.addFinalizer(() =>
  632. Effect.promise(() => $`rm -rf ${bareA} ${bareB} ${worktreeA} ${worktreeB}`.quiet().nothrow()).pipe(
  633. Effect.ignore,
  634. ),
  635. )
  636. yield* Effect.promise(() => $`git clone --bare ${tmp1} ${bareA}`.quiet())
  637. yield* Effect.promise(() => $`git clone --bare ${tmp2} ${bareB}`.quiet())
  638. yield* Effect.promise(() => $`git worktree add ${worktreeA} HEAD`.cwd(bareA).quiet())
  639. yield* Effect.promise(() => $`git worktree add ${worktreeB} HEAD`.cwd(bareB).quiet())
  640. const result = yield* project.fromDirectory(worktreeA)
  641. const next = yield* project.fromDirectory(worktreeB)
  642. expect(result.project.id).not.toBe(next.project.id)
  643. const cacheA = path.join(bareA, "kirincode")
  644. const cacheB = path.join(bareB, "kirincode")
  645. const wrongCache = path.join(parentDir, ".git", "kirincode")
  646. expect(yield* Effect.promise(() => Bun.file(cacheA).exists())).toBe(true)
  647. expect(yield* Effect.promise(() => Bun.file(cacheB).exists())).toBe(true)
  648. expect(yield* Effect.promise(() => Bun.file(wrongCache).exists())).toBe(false)
  649. }),
  650. )
  651. it.live("bare repo without .git suffix is still detected via core.bare", () =>
  652. Effect.gen(function* () {
  653. const project = yield* Project.Service
  654. const tmp = yield* tmpdirScoped({ git: true })
  655. const parentDir = path.dirname(tmp)
  656. const barePath = path.join(parentDir, `bare-no-suffix-${Date.now()}`)
  657. const worktreePath = path.join(parentDir, `worktree-${Date.now()}`)
  658. yield* Effect.addFinalizer(() =>
  659. Effect.promise(() => $`rm -rf ${barePath} ${worktreePath}`.quiet().nothrow()).pipe(Effect.ignore),
  660. )
  661. yield* Effect.promise(() => $`git clone --bare ${tmp} ${barePath}`.quiet())
  662. yield* Effect.promise(() => $`git worktree add ${worktreePath} HEAD`.cwd(barePath).quiet())
  663. const result = yield* project.fromDirectory(worktreePath)
  664. expect(result.project.id).not.toBe(ProjectV2.ID.global)
  665. expect(result.project.worktree).toBe(worktreePath)
  666. const correctCache = path.join(barePath, "kirincode")
  667. expect(yield* Effect.promise(() => Bun.file(correctCache).exists())).toBe(true)
  668. }),
  669. )
  670. })