tool-read-filesystem.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import { describe, expect } from "bun:test"
  2. import fs from "fs/promises"
  3. import path from "path"
  4. import { Environment } from "@opencode-ai/core/environment"
  5. import { AbsolutePath } from "@opencode-ai/core/schema"
  6. import { ReadToolFileSystem } from "@opencode-ai/core/tool/read-filesystem"
  7. import { CrossSpawnSpawner } from "@opencode-ai/util/cross-spawn-spawner"
  8. import { LayerNodePlatform } from "@opencode-ai/util/effect/app-node-platform"
  9. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  10. import { Effect, FileSystem } from "effect"
  11. import { ChildProcessSpawner } from "effect/unstable/process"
  12. import { testEffect } from "./lib/effect"
  13. const it = testEffect(LayerNode.compile(LayerNode.group([CrossSpawnSpawner.node, LayerNodePlatform.filesystem])))
  14. const fixture = Effect.gen(function* () {
  15. const files = yield* FileSystem.FileSystem
  16. const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
  17. const directory = yield* files.makeTempDirectoryScoped()
  18. return { environment: Environment.makeFiles(Environment.makeLocalDriver(spawner)), files, directory }
  19. })
  20. const absolute = (value: string) => AbsolutePath.make(value)
  21. describe("ReadToolFileSystem", () => {
  22. it.effect("preserves the environment not-found error", () =>
  23. Effect.gen(function* () {
  24. const { environment, directory } = yield* fixture
  25. const file = path.join(directory, "missing.txt")
  26. const error = yield* ReadToolFileSystem.read(environment, absolute(file), "missing.txt").pipe(Effect.flip)
  27. expect(error).toBeInstanceOf(Environment.NotFound)
  28. }),
  29. )
  30. it.effect("returns a listing when read reports a directory", () =>
  31. Effect.gen(function* () {
  32. const { environment, files, directory } = yield* fixture
  33. yield* files.makeDirectory(path.join(directory, "folder"))
  34. yield* files.writeFileString(path.join(directory, "file.txt"), "hello")
  35. const result = yield* ReadToolFileSystem.read(environment, absolute(directory), "folder")
  36. expect(result).toMatchObject({
  37. type: "list-page",
  38. entries: [
  39. { path: `folder${path.sep}`, type: "directory" },
  40. { path: "file.txt", type: "file" },
  41. ],
  42. })
  43. }),
  44. )
  45. it.effect("reads malformed UTF-8 lossily and still rejects null-byte binary content", () =>
  46. Effect.gen(function* () {
  47. const { environment, files, directory } = yield* fixture
  48. const binary = path.join(directory, "archive.dat")
  49. const malformed = path.join(directory, "malformed.txt")
  50. yield* files.writeFile(binary, Uint8Array.of(0, 1, 2, 3))
  51. yield* files.writeFile(malformed, Uint8Array.of(0x68, 0x69, 0x80))
  52. const binaryError = yield* ReadToolFileSystem.read(environment, absolute(binary), "archive.dat").pipe(Effect.flip)
  53. const malformedResult = yield* ReadToolFileSystem.read(environment, absolute(malformed), "malformed.txt")
  54. expect(binaryError).toBeInstanceOf(ReadToolFileSystem.BinaryFileError)
  55. expect(binaryError.message).toBe("Cannot read binary file: archive.dat")
  56. expect(malformedResult).toMatchObject({ type: "file", content: "hi\uFFFD", encoding: "utf8" })
  57. }),
  58. )
  59. it.effect("reads text despite a binary-associated extension", () =>
  60. Effect.gen(function* () {
  61. const { environment, files, directory } = yield* fixture
  62. const file = path.join(directory, "notes.docx")
  63. yield* files.writeFileString(file, "plain text")
  64. const result = yield* ReadToolFileSystem.read(environment, absolute(file), "notes.docx")
  65. expect(result).toMatchObject({ type: "file", content: "plain text", encoding: "utf8" })
  66. }),
  67. )
  68. it.effect("lists unresolved symlinks, including broken and escaping links", () =>
  69. Effect.gen(function* () {
  70. if (process.platform === "win32") return
  71. const { environment, files, directory } = yield* fixture
  72. const outside = yield* files.makeTempDirectoryScoped()
  73. yield* files.makeDirectory(path.join(directory, "folder"))
  74. yield* files.writeFileString(path.join(directory, "file.txt"), "hello")
  75. yield* Effect.promise(() => fs.symlink(path.join(outside, "target.txt"), path.join(directory, "escape")))
  76. yield* Effect.promise(() => fs.symlink(path.join(directory, "missing.txt"), path.join(directory, "broken")))
  77. const result = yield* ReadToolFileSystem.read(environment, absolute(directory), "folder")
  78. expect(result.type).toBe("list-page")
  79. if (result.type !== "list-page") return
  80. expect(result.entries.map((entry) => ({ ...entry, path: String(entry.path) }))).toEqual([
  81. { path: `folder${path.sep}`, type: "directory" },
  82. { path: "broken", type: "symlink" },
  83. { path: "escape", type: "symlink" },
  84. { path: "file.txt", type: "file" },
  85. ])
  86. }),
  87. )
  88. it.effect("reads a symlinked directory as a listing", () =>
  89. Effect.gen(function* () {
  90. if (process.platform === "win32") return
  91. const { environment, files, directory } = yield* fixture
  92. const target = path.join(directory, "target")
  93. const link = path.join(directory, "link")
  94. yield* files.makeDirectory(target)
  95. yield* files.writeFileString(path.join(target, "file.txt"), "hello")
  96. yield* Effect.promise(() => fs.symlink(target, link))
  97. const result = yield* ReadToolFileSystem.read(environment, absolute(link), "link")
  98. expect(result).toMatchObject({
  99. type: "list-page",
  100. entries: [{ path: "file.txt", type: "file" }],
  101. })
  102. }),
  103. )
  104. it.effect("reports out-of-range pagination as a typed error", () =>
  105. Effect.gen(function* () {
  106. const { environment, files, directory } = yield* fixture
  107. const file = path.join(directory, "short.txt")
  108. yield* files.writeFileString(file, "one\n")
  109. const error = yield* ReadToolFileSystem.read(environment, absolute(file), "short.txt", { offset: 2 }).pipe(
  110. Effect.flip,
  111. )
  112. expect(error).toBeInstanceOf(ReadToolFileSystem.OffsetOutOfRangeError)
  113. expect(error.message).toBe("Offset 2 is out of range")
  114. }),
  115. )
  116. it.effect("pages text with one-based offsets", () =>
  117. Effect.gen(function* () {
  118. const { environment, files, directory } = yield* fixture
  119. const file = path.join(directory, "lines.txt")
  120. yield* files.writeFileString(file, "one\r\ntwo\nthree")
  121. const result = yield* ReadToolFileSystem.read(environment, absolute(file), "lines.txt", {
  122. offset: 2,
  123. limit: 1,
  124. })
  125. expect(result).toMatchObject({ type: "text-page", content: "two", offset: 2, truncated: true, next: 3 })
  126. }),
  127. )
  128. it.effect("truncates long lines", () =>
  129. Effect.gen(function* () {
  130. const { environment, files, directory } = yield* fixture
  131. const file = path.join(directory, "long.txt")
  132. yield* files.writeFileString(file, "a".repeat(2_001))
  133. const result = yield* ReadToolFileSystem.read(environment, absolute(file), "long.txt", { limit: 1 })
  134. expect(result).toMatchObject({
  135. type: "text-page",
  136. content: `${"a".repeat(2_000)}... (line truncated to 2000 chars)`,
  137. truncated: false,
  138. })
  139. }),
  140. )
  141. it.effect("enforces line and byte budgets with continuation offsets", () =>
  142. Effect.gen(function* () {
  143. const { environment, files, directory } = yield* fixture
  144. const linesFile = path.join(directory, "many-lines.txt")
  145. const bytesFile = path.join(directory, "many-bytes.txt")
  146. yield* files.writeFileString(linesFile, Array.from({ length: 2_001 }, (_, index) => String(index)).join("\n"))
  147. yield* files.writeFileString(bytesFile, Array.from({ length: 200 }, () => "a".repeat(2_000)).join("\n"))
  148. const ranges: Array<{ readonly offset: number; readonly length: number } | undefined> = []
  149. const tracked = {
  150. ...environment,
  151. read: (path: string, range?: { readonly offset: number; readonly length: number }) =>
  152. Effect.sync(() => ranges.push(range)).pipe(Effect.andThen(environment.read(path, range))),
  153. }
  154. const lines = yield* ReadToolFileSystem.read(environment, absolute(linesFile), "many-lines.txt", { limit: 2_000 })
  155. const bytes = yield* ReadToolFileSystem.read(tracked, absolute(bytesFile), "many-bytes.txt", {})
  156. expect(lines).toMatchObject({ type: "text-page", truncated: true, next: 2_001 })
  157. expect(lines.type === "text-page" ? lines.content.split("\n") : []).toHaveLength(2_000)
  158. expect(bytes).toMatchObject({ type: "text-page", truncated: true, next: 26 })
  159. expect(bytes.type === "text-page" ? Buffer.byteLength(bytes.content) : Infinity).toBeLessThanOrEqual(
  160. ReadToolFileSystem.MAX_READ_BYTES,
  161. )
  162. expect(ranges).toEqual([{ offset: 0, length: 256 * 1024 }])
  163. }),
  164. )
  165. it.effect("sorts and pages directory entries", () =>
  166. Effect.gen(function* () {
  167. const { environment, files, directory } = yield* fixture
  168. yield* files.makeDirectory(path.join(directory, "z"))
  169. yield* files.makeDirectory(path.join(directory, "a"))
  170. yield* files.writeFileString(path.join(directory, "b.txt"), "")
  171. const result = yield* ReadToolFileSystem.read(environment, absolute(directory), "folder", {
  172. offset: 2,
  173. limit: 1,
  174. })
  175. expect(result).toMatchObject({
  176. type: "list-page",
  177. entries: [{ path: `z${path.sep}`, type: "directory" }],
  178. truncated: true,
  179. next: 3,
  180. })
  181. }),
  182. )
  183. it.effect("stops checking for null bytes after the requested page", () =>
  184. Effect.gen(function* () {
  185. const { environment, files, directory } = yield* fixture
  186. const file = path.join(directory, "nul.txt")
  187. yield* files.writeFile(file, Uint8Array.from([...new TextEncoder().encode("one\n"), 0]))
  188. const result = yield* ReadToolFileSystem.read(environment, absolute(file), "nul.txt", { limit: 1 })
  189. expect(result).toMatchObject({ type: "text-page", content: "one", truncated: true, next: 2 })
  190. }),
  191. )
  192. it.effect("reads page two after fetching more than the first 256KB range", () =>
  193. Effect.gen(function* () {
  194. const { environment, files, directory } = yield* fixture
  195. const file = path.join(directory, "large.txt")
  196. yield* files.writeFileString(file, `${"a".repeat(300 * 1024)}\nsecond\n`)
  197. const result = yield* ReadToolFileSystem.read(environment, absolute(file), "large.txt", {
  198. offset: 2,
  199. limit: 1,
  200. })
  201. expect(result).toMatchObject({ type: "text-page", content: "second", offset: 2, truncated: false })
  202. }),
  203. )
  204. it.effect("preserves the media ingestion limit message", () =>
  205. Effect.gen(function* () {
  206. const { environment, files, directory } = yield* fixture
  207. const file = path.join(directory, "oversized.png")
  208. yield* files.writeFile(file, Uint8Array.of(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a))
  209. yield* files.truncate(file, ReadToolFileSystem.MAX_MEDIA_INGEST_BYTES + 1)
  210. const error = yield* ReadToolFileSystem.read(environment, absolute(file), "oversized.png").pipe(Effect.flip)
  211. expect(error).toBeInstanceOf(ReadToolFileSystem.MediaIngestLimitError)
  212. expect(error.message).toBe(
  213. `Media exceeds ${ReadToolFileSystem.MAX_MEDIA_INGEST_BYTES} byte ingestion limit: oversized.png`,
  214. )
  215. }),
  216. )
  217. it.effect("reads PDFs as bounded media", () =>
  218. Effect.gen(function* () {
  219. const { environment, files, directory } = yield* fixture
  220. const file = path.join(directory, "document.pdf")
  221. yield* files.writeFileString(file, "%PDF-1.7\ncontent")
  222. const result = yield* ReadToolFileSystem.read(environment, absolute(file), "document.pdf")
  223. expect(result).toMatchObject({
  224. type: "file",
  225. content: Buffer.from("%PDF-1.7\ncontent").toString("base64"),
  226. encoding: "base64",
  227. mime: "application/pdf",
  228. })
  229. }),
  230. )
  231. })