tool-write.test.ts 12 KB

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