tool-write.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import fs from "fs/promises"
  2. import path from "path"
  3. import { fileURLToPath } from "url"
  4. import { describe, expect, test } from "bun:test"
  5. import { Effect, Layer } from "effect"
  6. import { FileMutation } from "@opencode-ai/core/file-mutation"
  7. import { FSUtil } from "@opencode-ai/core/fs-util"
  8. import { Location } from "@opencode-ai/core/location"
  9. import { LocationMutation } from "@opencode-ai/core/location-mutation"
  10. import { PermissionV2 } from "@opencode-ai/core/permission"
  11. import { AbsolutePath } from "@opencode-ai/core/schema"
  12. import { SessionV2 } from "@opencode-ai/core/session"
  13. import { ToolRegistry } from "@opencode-ai/core/tool/registry"
  14. import { WriteTool } from "@opencode-ai/core/tool/write"
  15. import { location } from "./fixture/location"
  16. import { tmpdir } from "./fixture/tmpdir"
  17. import { testEffect } from "./lib/effect"
  18. const sessionID = SessionV2.ID.make("ses_write_tool_test")
  19. const assertions: PermissionV2.AssertInput[] = []
  20. const writes: string[] = []
  21. let denyAction: string | undefined
  22. const permission = Layer.succeed(
  23. PermissionV2.Service,
  24. PermissionV2.Service.of({
  25. assert: (input) =>
  26. Effect.sync(() => assertions.push(input)).pipe(
  27. Effect.andThen(
  28. input.action === denyAction ? Effect.fail(new PermissionV2.DeniedError({ rules: [] })) : Effect.void,
  29. ),
  30. ),
  31. ask: () => Effect.die("unused"),
  32. reply: () => Effect.die("unused"),
  33. get: () => Effect.die("unused"),
  34. forSession: () => Effect.die("unused"),
  35. list: () => Effect.die("unused"),
  36. }),
  37. )
  38. const reset = () => {
  39. assertions.length = 0
  40. writes.length = 0
  41. denyAction = undefined
  42. }
  43. const filesystem = Layer.effect(
  44. FSUtil.Service,
  45. Effect.gen(function* () {
  46. const fs = yield* FSUtil.Service
  47. return FSUtil.Service.of({
  48. ...fs,
  49. writeWithDirs: (target, content, mode) =>
  50. Effect.sync(() => writes.push(target)).pipe(Effect.andThen(fs.writeWithDirs(target, content, mode))),
  51. })
  52. }),
  53. ).pipe(Layer.provide(FSUtil.defaultLayer))
  54. const withTool = <A, E, R>(directory: string, body: (registry: ToolRegistry.Interface) => Effect.Effect<A, E, R>) => {
  55. const activeLocation = Layer.succeed(
  56. Location.Service,
  57. Location.Service.of(location({ directory: AbsolutePath.make(directory) })),
  58. )
  59. const resolution = LocationMutation.layer.pipe(Layer.provide(filesystem), Layer.provide(activeLocation))
  60. const mutation = FileMutation.layer.pipe(Layer.provide(filesystem))
  61. const registry = ToolRegistry.defaultLayer.pipe(Layer.provide(permission))
  62. const write = WriteTool.layer.pipe(Layer.provide(registry), Layer.provide(resolution), Layer.provide(mutation))
  63. return Effect.gen(function* () {
  64. return yield* body(yield* ToolRegistry.Service)
  65. }).pipe(Effect.provide(Layer.mergeAll(registry, resolution, mutation, write)))
  66. }
  67. const call = (input: typeof WriteTool.Parameters.Type, id = "call-write") => ({
  68. sessionID,
  69. call: { type: "tool-call" as const, id, name: "write", input },
  70. })
  71. const it = testEffect(Layer.empty)
  72. describe("WriteTool", () => {
  73. it.live("registers and creates a relative file through FileMutation once", () =>
  74. Effect.acquireUseRelease(
  75. Effect.promise(() => tmpdir()),
  76. (tmp) => {
  77. reset()
  78. return withTool(tmp.path, (registry) =>
  79. Effect.gen(function* () {
  80. expect((yield* registry.definitions()).map((tool) => tool.name)).toEqual(["write"])
  81. const settled = yield* registry.settle(call({ path: "src/new.txt", content: "created" }))
  82. expect(settled).toEqual({
  83. result: { type: "text", value: "Created file successfully: src/new.txt" },
  84. output: {
  85. structured: {
  86. operation: "write",
  87. target: path.join(yield* Effect.promise(() => fs.realpath(tmp.path)), "src", "new.txt"),
  88. resource: "src/new.txt",
  89. existed: false,
  90. },
  91. content: [{ type: "text", text: "Created file successfully: src/new.txt" }],
  92. },
  93. })
  94. expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "src", "new.txt"), "utf8"))).toBe(
  95. "created",
  96. )
  97. expect(assertions).toEqual([{ sessionID, action: "edit", resources: ["src/new.txt"], save: ["*"] }])
  98. expect(writes).toEqual([path.join(yield* Effect.promise(() => fs.realpath(tmp.path)), "src", "new.txt")])
  99. }),
  100. )
  101. },
  102. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  103. ),
  104. )
  105. it.live("overwrites a relative existing file and reports that it wrote the file", () =>
  106. Effect.acquireUseRelease(
  107. Effect.promise(() => tmpdir()),
  108. (tmp) => {
  109. reset()
  110. return Effect.promise(() => fs.writeFile(path.join(tmp.path, "existing.txt"), "before")).pipe(
  111. Effect.andThen(
  112. withTool(tmp.path, (registry) => registry.settle(call({ path: "existing.txt", content: "after" }))),
  113. ),
  114. Effect.andThen((settled) =>
  115. Effect.gen(function* () {
  116. expect(settled.result).toEqual({ type: "text", value: "Wrote file successfully: existing.txt" })
  117. expect(settled.output?.structured).toMatchObject({ resource: "existing.txt", existed: true })
  118. expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "existing.txt"), "utf8"))).toBe(
  119. "after",
  120. )
  121. expect(writes).toHaveLength(1)
  122. }),
  123. ),
  124. )
  125. },
  126. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  127. ),
  128. )
  129. it.live("preserves exactly one BOM when overwriting existing files", () =>
  130. Effect.acquireUseRelease(
  131. Effect.promise(() => tmpdir()),
  132. (tmp) => {
  133. reset()
  134. const preserved = path.join(tmp.path, "preserved.txt")
  135. const deduplicated = path.join(tmp.path, "deduplicated.txt")
  136. return Effect.promise(() =>
  137. Promise.all([fs.writeFile(preserved, "\uFEFFbefore"), fs.writeFile(deduplicated, "\uFEFFbefore")]),
  138. ).pipe(
  139. Effect.andThen(
  140. withTool(tmp.path, (registry) =>
  141. Effect.gen(function* () {
  142. yield* registry.settle(call({ path: "preserved.txt", content: "after" }, "call-preserved"))
  143. yield* registry.settle(call({ path: "deduplicated.txt", content: "\uFEFFafter" }, "call-deduplicated"))
  144. expect(yield* Effect.promise(() => fs.readFile(preserved, "utf8"))).toBe("\uFEFFafter")
  145. expect(yield* Effect.promise(() => fs.readFile(deduplicated, "utf8"))).toBe("\uFEFFafter")
  146. }),
  147. ),
  148. ),
  149. )
  150. },
  151. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  152. ),
  153. )
  154. it.live("accepts an absolute file path inside the active Location", () =>
  155. Effect.acquireUseRelease(
  156. Effect.promise(() => tmpdir()),
  157. (tmp) => {
  158. reset()
  159. const target = path.join(tmp.path, "absolute.txt")
  160. return withTool(tmp.path, (registry) => registry.execute(call({ path: target, content: "inside" }))).pipe(
  161. Effect.andThen((result) =>
  162. Effect.gen(function* () {
  163. expect(result).toEqual({ type: "text", value: "Created file successfully: absolute.txt" })
  164. expect(assertions.map((input) => input.action)).toEqual(["edit"])
  165. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("inside")
  166. }),
  167. ),
  168. )
  169. },
  170. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  171. ),
  172. )
  173. it.live("approves an explicit external absolute path before edit", () =>
  174. Effect.acquireUseRelease(
  175. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  176. ([active, outside]) => {
  177. reset()
  178. const target = path.join(outside.path, "external.txt")
  179. return withTool(active.path, (registry) => registry.settle(call({ path: target, content: "external" }))).pipe(
  180. Effect.andThen((settled) =>
  181. Effect.gen(function* () {
  182. const canonicalTarget = path.join(yield* Effect.promise(() => fs.realpath(outside.path)), "external.txt")
  183. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  184. expect(assertions[0]).toMatchObject({
  185. resources: [
  186. path.join(yield* Effect.promise(() => fs.realpath(outside.path)), "*").replaceAll("\\", "/"),
  187. ],
  188. })
  189. expect(assertions[1]).toMatchObject({ resources: [canonicalTarget.replaceAll("\\", "/")], save: ["*"] })
  190. expect(settled.output?.structured).toMatchObject({
  191. target: canonicalTarget,
  192. resource: canonicalTarget.replaceAll("\\", "/"),
  193. existed: false,
  194. })
  195. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("external")
  196. expect(writes).toEqual([canonicalTarget])
  197. }),
  198. ),
  199. )
  200. },
  201. ([active, outside]) =>
  202. Effect.promise(() =>
  203. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  204. ),
  205. ),
  206. )
  207. it.live("does not write when external_directory or edit approval is denied", () =>
  208. Effect.acquireUseRelease(
  209. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  210. ([active, outside]) =>
  211. Effect.gen(function* () {
  212. const external = path.join(outside.path, "denied.txt")
  213. reset()
  214. denyAction = "external_directory"
  215. expect(
  216. yield* withTool(active.path, (registry) => registry.execute(call({ path: external, content: "blocked" }))),
  217. ).toEqual({
  218. type: "error",
  219. value: `Unable to write ${external}`,
  220. })
  221. expect(assertions.map((input) => input.action)).toEqual(["external_directory"])
  222. expect(writes).toEqual([])
  223. reset()
  224. denyAction = "edit"
  225. expect(
  226. yield* withTool(active.path, (registry) =>
  227. registry.execute(call({ path: "denied.txt", content: "blocked" })),
  228. ),
  229. ).toEqual({
  230. type: "error",
  231. value: "Unable to write denied.txt",
  232. })
  233. expect(assertions.map((input) => input.action)).toEqual(["edit"])
  234. expect(writes).toEqual([])
  235. }),
  236. ([active, outside]) =>
  237. Effect.promise(() =>
  238. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  239. ),
  240. ),
  241. )
  242. })
  243. test("keeps the locked write schema, semantics docstring, and deferred UX TODOs visible", async () => {
  244. const source = (await fs.readFile(new URL("../src/tool/write.ts", import.meta.url), "utf8")).replaceAll("\r\n", "\n")
  245. const definition = await Effect.runPromise(
  246. withTool(path.dirname(fileURLToPath(import.meta.url)), (registry) => registry.definitions()),
  247. )
  248. const schema = definition[0]?.inputSchema as { readonly properties?: Record<string, unknown> }
  249. expect(Object.keys(schema.properties ?? {}).sort()).toEqual(["content", "path"])
  250. expect(source).toContain(
  251. "Named project references\n * are read-oriented and deliberately are not accepted by mutation tools.",
  252. )
  253. for (const todo of [
  254. "Revisit whether model-facing mutation schemas should prefer absolute `filePath` naming for trained-in compatibility after evaluating model behavior.",
  255. "Add formatter integration after V2 formatter runtime exists.",
  256. "Publish watcher/file-edit events after V2 watcher integration exists.",
  257. "Add snapshots / undo after design exists.",
  258. "Add LSP notification and diagnostics after V2 LSP runtime exists.",
  259. ]) {
  260. expect(source).toContain(`TODO: ${todo}`)
  261. }
  262. })