write.test.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import { afterEach, describe, expect } from "bun:test"
  2. import { LayerNode } from "@kirincode-ai/core/effect/layer-node"
  3. import { Effect, Layer } from "effect"
  4. import path from "path"
  5. import fs from "fs/promises"
  6. import { WriteTool } from "../../src/tool/write"
  7. import { LSP } from "@/lsp/lsp"
  8. import { FSUtil } from "@kirincode-ai/core/fs-util"
  9. import { EventV2Bridge } from "../../src/event-v2-bridge"
  10. import { Format } from "../../src/format"
  11. import { Truncate } from "@/tool/truncate"
  12. import { Tool } from "@/tool/tool"
  13. import { Agent } from "../../src/agent/agent"
  14. import { SessionID, MessageID } from "../../src/session/schema"
  15. import { CrossSpawnSpawner } from "@kirincode-ai/core/cross-spawn-spawner"
  16. import { disposeAllInstances, TestInstance } from "../fixture/fixture"
  17. import { testEffect } from "../lib/effect"
  18. const ctx = {
  19. sessionID: SessionID.make("ses_test-write-session"),
  20. messageID: MessageID.make("msg_test"),
  21. callID: "",
  22. agent: "build",
  23. abort: AbortSignal.any([]),
  24. messages: [],
  25. metadata: () => Effect.void,
  26. ask: () => Effect.void,
  27. }
  28. afterEach(async () => {
  29. await disposeAllInstances()
  30. })
  31. const it = testEffect(
  32. LayerNode.compile(
  33. LayerNode.group([
  34. LSP.node,
  35. FSUtil.node,
  36. EventV2Bridge.node,
  37. Format.node,
  38. CrossSpawnSpawner.node,
  39. Truncate.node,
  40. Agent.node,
  41. ]),
  42. ),
  43. )
  44. const init = Effect.fn("WriteToolTest.init")(function* () {
  45. const info = yield* WriteTool
  46. return yield* info.init()
  47. })
  48. const run = Effect.fn("WriteToolTest.run")(function* (
  49. args: Tool.InferParameters<typeof WriteTool>,
  50. next: Tool.Context = ctx,
  51. ) {
  52. const tool = yield* init()
  53. return yield* tool.execute(args, next)
  54. })
  55. describe("tool.write", () => {
  56. describe("new file creation", () => {
  57. it.instance("writes content to new file", () =>
  58. Effect.gen(function* () {
  59. const test = yield* TestInstance
  60. const filepath = path.join(test.directory, "newfile.txt")
  61. const result = yield* run({ filePath: filepath, content: "Hello, World!" })
  62. expect(result.output).toContain("Wrote file successfully")
  63. expect(result.metadata.exists).toBe(false)
  64. const content = yield* Effect.promise(() => fs.readFile(filepath, "utf-8"))
  65. expect(content).toBe("Hello, World!")
  66. }),
  67. )
  68. it.instance("creates parent directories if needed", () =>
  69. Effect.gen(function* () {
  70. const test = yield* TestInstance
  71. const filepath = path.join(test.directory, "nested", "deep", "file.txt")
  72. yield* run({ filePath: filepath, content: "nested content" })
  73. const content = yield* Effect.promise(() => fs.readFile(filepath, "utf-8"))
  74. expect(content).toBe("nested content")
  75. }),
  76. )
  77. it.instance("handles relative paths by resolving to instance directory", () =>
  78. Effect.gen(function* () {
  79. const test = yield* TestInstance
  80. yield* run({ filePath: "relative.txt", content: "relative content" })
  81. const content = yield* Effect.promise(() => fs.readFile(path.join(test.directory, "relative.txt"), "utf-8"))
  82. expect(content).toBe("relative content")
  83. }),
  84. )
  85. })
  86. describe("existing file overwrite", () => {
  87. it.instance("overwrites existing file content", () =>
  88. Effect.gen(function* () {
  89. const test = yield* TestInstance
  90. const filepath = path.join(test.directory, "existing.txt")
  91. yield* Effect.promise(() => fs.writeFile(filepath, "old content", "utf-8"))
  92. const result = yield* run({ filePath: filepath, content: "new content" })
  93. expect(result.output).toContain("Wrote file successfully")
  94. expect(result.metadata.exists).toBe(true)
  95. const content = yield* Effect.promise(() => fs.readFile(filepath, "utf-8"))
  96. expect(content).toBe("new content")
  97. }),
  98. )
  99. it.instance("preserves BOM when overwriting existing files", () =>
  100. Effect.gen(function* () {
  101. const test = yield* TestInstance
  102. const filepath = path.join(test.directory, "existing.cs")
  103. const bom = String.fromCharCode(0xfeff)
  104. yield* Effect.promise(() => fs.writeFile(filepath, `${bom}using System;\n`, "utf-8"))
  105. yield* run({ filePath: filepath, content: "using Up;\n" })
  106. const content = yield* Effect.promise(() => fs.readFile(filepath, "utf-8"))
  107. expect(content.charCodeAt(0)).toBe(0xfeff)
  108. expect(content.slice(1)).toBe("using Up;\n")
  109. }),
  110. )
  111. it.instance(
  112. "restores BOM after formatter strips it",
  113. () =>
  114. Effect.gen(function* () {
  115. const test = yield* TestInstance
  116. const filepath = path.join(test.directory, "formatted.cs")
  117. const bom = String.fromCharCode(0xfeff)
  118. yield* Effect.promise(() => fs.writeFile(filepath, `${bom}using System;\n`, "utf-8"))
  119. yield* run({ filePath: filepath, content: "using Up;\n" })
  120. const content = yield* Effect.promise(() => fs.readFile(filepath, "utf-8"))
  121. expect(content.charCodeAt(0)).toBe(0xfeff)
  122. expect(content.slice(1)).toBe("using Up;\n")
  123. }),
  124. {
  125. config: {
  126. formatter: {
  127. stripbom: {
  128. extensions: [".cs"],
  129. command: [
  130. "node",
  131. "-e",
  132. "const fs = require('fs'); const file = process.argv[1]; let text = fs.readFileSync(file, 'utf8'); if (text.charCodeAt(0) === 0xfeff) text = text.slice(1); fs.writeFileSync(file, text, 'utf8')",
  133. "$FILE",
  134. ],
  135. },
  136. },
  137. },
  138. },
  139. )
  140. it.instance("returns diff in metadata for existing files", () =>
  141. Effect.gen(function* () {
  142. const test = yield* TestInstance
  143. const filepath = path.join(test.directory, "file.txt")
  144. yield* Effect.promise(() => fs.writeFile(filepath, "old", "utf-8"))
  145. const result = yield* run({ filePath: filepath, content: "new" })
  146. expect(result.metadata).toHaveProperty("filepath", filepath)
  147. expect(result.metadata).toHaveProperty("exists", true)
  148. }),
  149. )
  150. })
  151. describe("file permissions", () => {
  152. it.instance("sets file permissions when writing sensitive data", () =>
  153. Effect.gen(function* () {
  154. const test = yield* TestInstance
  155. const filepath = path.join(test.directory, "sensitive.json")
  156. yield* run({ filePath: filepath, content: JSON.stringify({ secret: "data" }) })
  157. if (process.platform !== "win32") {
  158. const stats = yield* Effect.promise(() => fs.stat(filepath))
  159. expect(stats.mode & 0o777).toBe(0o644)
  160. }
  161. }),
  162. )
  163. })
  164. describe("content types", () => {
  165. it.instance("writes JSON content", () =>
  166. Effect.gen(function* () {
  167. const test = yield* TestInstance
  168. const filepath = path.join(test.directory, "data.json")
  169. const data = { key: "value", nested: { array: [1, 2, 3] } }
  170. yield* run({ filePath: filepath, content: JSON.stringify(data, null, 2) })
  171. const content = yield* Effect.promise(() => fs.readFile(filepath, "utf-8"))
  172. expect(JSON.parse(content)).toEqual(data)
  173. }),
  174. )
  175. it.instance("writes binary-safe content", () =>
  176. Effect.gen(function* () {
  177. const test = yield* TestInstance
  178. const filepath = path.join(test.directory, "binary.bin")
  179. const content = "Hello\x00World\x01\x02\x03"
  180. yield* run({ filePath: filepath, content })
  181. const buf = yield* Effect.promise(() => fs.readFile(filepath))
  182. expect(buf.toString()).toBe(content)
  183. }),
  184. )
  185. it.instance("writes empty content", () =>
  186. Effect.gen(function* () {
  187. const test = yield* TestInstance
  188. const filepath = path.join(test.directory, "empty.txt")
  189. yield* run({ filePath: filepath, content: "" })
  190. const content = yield* Effect.promise(() => fs.readFile(filepath, "utf-8"))
  191. expect(content).toBe("")
  192. const stats = yield* Effect.promise(() => fs.stat(filepath))
  193. expect(stats.size).toBe(0)
  194. }),
  195. )
  196. it.instance("writes multi-line content", () =>
  197. Effect.gen(function* () {
  198. const test = yield* TestInstance
  199. const filepath = path.join(test.directory, "multiline.txt")
  200. const lines = ["Line 1", "Line 2", "Line 3", ""].join("\n")
  201. yield* run({ filePath: filepath, content: lines })
  202. const content = yield* Effect.promise(() => fs.readFile(filepath, "utf-8"))
  203. expect(content).toBe(lines)
  204. }),
  205. )
  206. it.instance("handles different line endings", () =>
  207. Effect.gen(function* () {
  208. const test = yield* TestInstance
  209. const filepath = path.join(test.directory, "crlf.txt")
  210. const content = "Line 1\r\nLine 2\r\nLine 3"
  211. yield* run({ filePath: filepath, content })
  212. const buf = yield* Effect.promise(() => fs.readFile(filepath))
  213. expect(buf.toString()).toBe(content)
  214. }),
  215. )
  216. })
  217. describe("error handling", () => {
  218. it.instance("throws error when OS denies write access", () =>
  219. Effect.gen(function* () {
  220. const test = yield* TestInstance
  221. const readonlyPath = path.join(test.directory, "readonly.txt")
  222. yield* Effect.promise(() => fs.writeFile(readonlyPath, "test", "utf-8"))
  223. yield* Effect.promise(() => fs.chmod(readonlyPath, 0o444))
  224. const exit = yield* run({ filePath: readonlyPath, content: "new content" }).pipe(Effect.exit)
  225. expect(exit._tag).toBe("Failure")
  226. }),
  227. )
  228. })
  229. describe("title generation", () => {
  230. it.instance("returns relative path as title", () =>
  231. Effect.gen(function* () {
  232. const test = yield* TestInstance
  233. const filepath = path.join(test.directory, "src", "components", "Button.tsx")
  234. yield* Effect.promise(() => fs.mkdir(path.dirname(filepath), { recursive: true }))
  235. const result = yield* run({ filePath: filepath, content: "export const Button = () => {}" })
  236. expect(result.title).toEndWith(path.join("src", "components", "Button.tsx"))
  237. }),
  238. )
  239. })
  240. })