location-filesystem.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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, Exit, Layer, Schema } from "effect"
  6. import { FSUtil } from "@opencode-ai/core/fs-util"
  7. import { Location } from "@opencode-ai/core/location"
  8. import { FileSystem } from "@opencode-ai/core/filesystem"
  9. import { Ripgrep } from "@opencode-ai/core/filesystem/ripgrep"
  10. import { Global } from "@opencode-ai/core/global"
  11. import { AbsolutePath, RelativePath } from "@opencode-ai/core/schema"
  12. import { tmpdir } from "./fixture/tmpdir"
  13. import { location } from "./fixture/location"
  14. import { it } from "./lib/effect"
  15. function provide(directory: string, filesystem = FSUtil.defaultLayer, data = Global.Path.data) {
  16. return Effect.provide(
  17. FileSystem.layer.pipe(
  18. Layer.provide(
  19. Layer.mergeAll(
  20. filesystem,
  21. Ripgrep.defaultLayer,
  22. Layer.succeed(Location.Service, Location.Service.of(location({ directory: AbsolutePath.make(directory) }))),
  23. Global.layerWith({ data }),
  24. ),
  25. ),
  26. ),
  27. )
  28. }
  29. function withTmp<A, E, R>(f: (directory: string) => Effect.Effect<A, E, R>) {
  30. return Effect.acquireRelease(
  31. Effect.promise(() => tmpdir()),
  32. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  33. ).pipe(Effect.flatMap((tmp) => f(tmp.path)))
  34. }
  35. describe("FileSystem", () => {
  36. it.live("accepts generated managed output paths and rejects other absolute paths", () =>
  37. withTmp((directory) => {
  38. const worktree = directory
  39. const data = path.join(directory, "data")
  40. return Effect.gen(function* () {
  41. const managed = path.join(data, "tool-output")
  42. const output = path.join(managed, "tool_123")
  43. const unrelated = path.join(directory, "secret.txt")
  44. yield* Effect.promise(() => fs.mkdir(managed, { recursive: true }))
  45. yield* Effect.promise(() => fs.writeFile(output, "failure here"))
  46. yield* Effect.promise(() => fs.writeFile(unrelated, "secret"))
  47. const service = yield* FileSystem.Service
  48. expect(yield* service.read({ path: output })).toMatchObject({ type: "text", content: "failure here" })
  49. expect((yield* service.resolveRoot({ path: output })).real).toBe(output)
  50. expect(yield* Effect.exit(service.read({ path: unrelated }))).toMatchObject({ _tag: "Failure" })
  51. expect(yield* Effect.exit(service.read({ path: managed }))).toMatchObject({ _tag: "Failure" })
  52. }).pipe(provide(worktree, FSUtil.defaultLayer, data))
  53. }),
  54. )
  55. it.live("reads text and binary files", () =>
  56. withTmp((directory) =>
  57. Effect.gen(function* () {
  58. yield* Effect.promise(() => fs.writeFile(path.join(directory, "hello.txt"), "hello"))
  59. yield* Effect.promise(() => fs.writeFile(path.join(directory, "data.bin"), Buffer.from([0, 1, 2])))
  60. const service = yield* FileSystem.Service
  61. expect(yield* service.read({ path: RelativePath.make("hello.txt") })).toEqual({
  62. type: "text",
  63. content: "hello",
  64. mime: "text/plain",
  65. })
  66. expect(yield* service.read({ path: RelativePath.make("data.bin") })).toEqual({
  67. type: "binary",
  68. content: "AAEC",
  69. encoding: "base64",
  70. mime: "application/octet-stream",
  71. })
  72. expect(Exit.isFailure(yield* service.readTool({ path: RelativePath.make("data.bin") }).pipe(Effect.exit))).toBe(
  73. true,
  74. )
  75. }).pipe(provide(directory)),
  76. ),
  77. )
  78. it.live("pages large UTF-8 text files by line with continuation", () =>
  79. withTmp((directory) =>
  80. Effect.gen(function* () {
  81. const lines = Array.from({ length: 30 }, (_, index) => `line-${index + 1}-é`.padEnd(2_000, "x"))
  82. yield* Effect.promise(() => fs.writeFile(path.join(directory, "large.txt"), lines.join("\n")))
  83. const service = yield* FileSystem.Service
  84. const input = { path: RelativePath.make("large.txt") }
  85. const result = yield* service.readTool(input)
  86. expect(result).toMatchObject({
  87. type: "text-page",
  88. offset: 1,
  89. truncated: true,
  90. })
  91. const first = result.type === "text-page" ? result : yield* Effect.die(new Error("Expected a text page"))
  92. expect(first.next).toBeDefined()
  93. const next = first.next!
  94. expect(yield* service.readTool(input, { offset: next, limit: 1 })).toEqual({
  95. type: "text-page",
  96. content: lines[next - 1],
  97. mime: "text/plain",
  98. offset: next,
  99. truncated: true,
  100. next: next + 1,
  101. })
  102. expect(yield* service.readTool(input, { offset: 30 })).toEqual({
  103. type: "text-page",
  104. content: lines[29],
  105. mime: "text/plain",
  106. offset: 30,
  107. truncated: false,
  108. })
  109. }).pipe(provide(directory)),
  110. ),
  111. )
  112. it.live("rejects paged text when a late NUL appears after the requested page", () =>
  113. withTmp((directory) =>
  114. Effect.gen(function* () {
  115. const file = path.join(directory, "late-binary.txt")
  116. yield* Effect.promise(() =>
  117. fs.writeFile(
  118. file,
  119. Buffer.concat([Buffer.from("first\nsecond\n"), Buffer.alloc(80_000, 0x61), Buffer.from([0])]),
  120. ),
  121. )
  122. const service = yield* FileSystem.Service
  123. expect(
  124. Exit.isFailure(
  125. yield* service.readTool({ path: RelativePath.make("late-binary.txt") }, { limit: 1 }).pipe(Effect.exit),
  126. ),
  127. ).toBe(true)
  128. }).pipe(provide(directory)),
  129. ),
  130. )
  131. it.live("rejects paged text when invalid UTF-8 appears near EOF", () =>
  132. withTmp((directory) =>
  133. Effect.gen(function* () {
  134. const file = path.join(directory, "invalid-utf8.txt")
  135. yield* Effect.promise(() =>
  136. fs.writeFile(
  137. file,
  138. Buffer.concat([Buffer.from("first\nsecond\n"), Buffer.alloc(80_000, 0x61), Buffer.from([0xc3, 0x28])]),
  139. ),
  140. )
  141. const service = yield* FileSystem.Service
  142. expect(
  143. Exit.isFailure(
  144. yield* service.readTool({ path: RelativePath.make("invalid-utf8.txt") }, { limit: 1 }).pipe(Effect.exit),
  145. ),
  146. ).toBe(true)
  147. }).pipe(provide(directory)),
  148. ),
  149. )
  150. it.live("rejects PDFs for direct, large, and paged reads", () =>
  151. withTmp((directory) =>
  152. Effect.gen(function* () {
  153. const small = path.join(directory, "small.pdf")
  154. const large = path.join(directory, "large.pdf")
  155. yield* Effect.promise(() => fs.writeFile(small, "%PDF-1.7\nsmall"))
  156. yield* Effect.promise(() =>
  157. fs.writeFile(large, Buffer.concat([Buffer.from("%PDF-1.7\n"), Buffer.alloc(80_000)])),
  158. )
  159. const service = yield* FileSystem.Service
  160. expect(
  161. Exit.isFailure(yield* service.readTool({ path: RelativePath.make("small.pdf") }).pipe(Effect.exit)),
  162. ).toBe(true)
  163. expect(
  164. Exit.isFailure(yield* service.readTool({ path: RelativePath.make("large.pdf") }).pipe(Effect.exit)),
  165. ).toBe(true)
  166. expect(
  167. Exit.isFailure(
  168. yield* service.readTool({ path: RelativePath.make("large.pdf") }, { limit: 1 }).pipe(Effect.exit),
  169. ),
  170. ).toBe(true)
  171. }).pipe(provide(directory)),
  172. ),
  173. )
  174. it.live("rejects signature-bearing media beyond the ingestion cap before loading", () =>
  175. withTmp((directory) =>
  176. Effect.gen(function* () {
  177. const file = path.join(directory, "huge.png")
  178. yield* Effect.promise(async () => {
  179. const handle = await fs.open(file, "w")
  180. try {
  181. await handle.write(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), 0, 8, 0)
  182. await handle.truncate(FileSystem.MAX_MEDIA_INGEST_BYTES + 1)
  183. } finally {
  184. await handle.close()
  185. }
  186. })
  187. const service = yield* FileSystem.Service
  188. const exit = yield* service.readTool({ path: RelativePath.make("huge.png") }).pipe(Effect.exit)
  189. expect(Exit.isFailure(exit)).toBe(true)
  190. if (Exit.isFailure(exit)) expect(String(exit.cause)).toContain("Media exceeds")
  191. }).pipe(provide(directory)),
  192. ),
  193. )
  194. it.live("closes descriptors after successful and failed reads", () =>
  195. withTmp((directory) => {
  196. let active = 0
  197. const filesystem = Layer.effect(
  198. FSUtil.Service,
  199. Effect.gen(function* () {
  200. const service = yield* FSUtil.Service
  201. return FSUtil.Service.of({
  202. ...service,
  203. open: (target, options) =>
  204. Effect.acquireRelease(
  205. service.open(target, options).pipe(Effect.tap(() => Effect.sync(() => active++))),
  206. () => Effect.sync(() => active--),
  207. ),
  208. })
  209. }),
  210. ).pipe(Layer.provide(FSUtil.defaultLayer))
  211. return Effect.gen(function* () {
  212. const text = path.join(directory, "text.txt")
  213. const binary = path.join(directory, "binary.pdf")
  214. yield* Effect.promise(() => fs.writeFile(text, "hello"))
  215. yield* Effect.promise(() => fs.writeFile(binary, "%PDF-1.7"))
  216. const service = yield* FileSystem.Service
  217. const before =
  218. process.platform === "win32"
  219. ? undefined
  220. : yield* Effect.promise(() => fs.readdir("/dev/fd").then((entries) => entries.length))
  221. for (let index = 0; index < 50; index++) {
  222. yield* service.readTool({ path: RelativePath.make("text.txt") })
  223. yield* service.readTool({ path: RelativePath.make("binary.pdf") }).pipe(Effect.exit)
  224. }
  225. expect(active).toBe(0)
  226. if (before !== undefined) {
  227. const after = yield* Effect.promise(() => fs.readdir("/dev/fd").then((entries) => entries.length))
  228. expect(after).toBeLessThanOrEqual(before + 2)
  229. }
  230. yield* Effect.promise(() => fs.rename(text, text + ".moved"))
  231. yield* Effect.promise(() => fs.rename(binary, binary + ".moved"))
  232. }).pipe(provide(directory, filesystem))
  233. }),
  234. )
  235. it.live("lists direct children with relative paths and resolved URIs", () =>
  236. withTmp((directory) =>
  237. Effect.gen(function* () {
  238. yield* Effect.promise(() => fs.mkdir(path.join(directory, "src")))
  239. yield* Effect.promise(() => fs.writeFile(path.join(directory, "README.md"), "# Test"))
  240. const service = yield* FileSystem.Service
  241. const entries = yield* service.list()
  242. expect(entries.map(({ uri: _uri, ...entry }) => entry)).toEqual([
  243. {
  244. path: RelativePath.make("src"),
  245. type: "directory",
  246. mime: "application/x-directory",
  247. },
  248. {
  249. path: RelativePath.make("README.md"),
  250. type: "file",
  251. mime: "text/markdown",
  252. },
  253. ])
  254. expect(
  255. yield* Effect.promise(() => Promise.all(entries.map((entry) => fs.realpath(fileURLToPath(entry.uri))))),
  256. ).toEqual(
  257. yield* Effect.promise(() =>
  258. Promise.all([fs.realpath(path.join(directory, "src")), fs.realpath(path.join(directory, "README.md"))]),
  259. ),
  260. )
  261. }).pipe(provide(directory)),
  262. ),
  263. )
  264. it.live("lists stable bounded pages", () =>
  265. withTmp((directory) =>
  266. Effect.gen(function* () {
  267. yield* Effect.promise(async () => {
  268. await fs.mkdir(path.join(directory, "src"))
  269. await fs.writeFile(path.join(directory, "README.md"), "# Test")
  270. })
  271. const service = yield* FileSystem.Service
  272. expect(yield* service.listPage({ limit: 1 })).toMatchObject({
  273. entries: [{ path: "src", type: "directory" }],
  274. truncated: true,
  275. next: 2,
  276. })
  277. expect(yield* service.listPage({ offset: 2, limit: 1 })).toMatchObject({
  278. entries: [{ path: "README.md", type: "file" }],
  279. truncated: false,
  280. })
  281. expect((yield* service.resolveList()).resource).toBe(".")
  282. }).pipe(provide(directory)),
  283. ),
  284. )
  285. it.live("materializes only the selected direct children for a page", () =>
  286. withTmp((directory) => {
  287. const realPaths: string[] = []
  288. const filesystem = Layer.effect(
  289. FSUtil.Service,
  290. Effect.gen(function* () {
  291. const service = yield* FSUtil.Service
  292. return FSUtil.Service.of({
  293. ...service,
  294. realPath: (target) =>
  295. Effect.sync(() => realPaths.push(target)).pipe(Effect.andThen(service.realPath(target))),
  296. })
  297. }),
  298. ).pipe(Layer.provide(FSUtil.defaultLayer))
  299. return Effect.gen(function* () {
  300. yield* Effect.promise(async () => {
  301. await fs.mkdir(path.join(directory, "src"))
  302. await fs.writeFile(path.join(directory, "alpha.txt"), "alpha")
  303. await fs.writeFile(path.join(directory, "beta.txt"), "beta")
  304. })
  305. const service = yield* FileSystem.Service
  306. expect(yield* service.listPage({ offset: 2, limit: 1 })).toMatchObject({
  307. entries: [{ path: "alpha.txt", type: "file" }],
  308. truncated: true,
  309. next: 3,
  310. })
  311. expect(realPaths.filter((target) => target !== directory)).toEqual([path.join(directory, "alpha.txt")])
  312. }).pipe(provide(directory, filesystem))
  313. }),
  314. )
  315. it.live("materializes selected page entries with at most 16 concurrent real path lookups", () =>
  316. withTmp((directory) => {
  317. let active = 0
  318. let maximum = 0
  319. const filesystem = Layer.effect(
  320. FSUtil.Service,
  321. Effect.gen(function* () {
  322. const service = yield* FSUtil.Service
  323. return FSUtil.Service.of({
  324. ...service,
  325. realPath: (target) =>
  326. target === directory
  327. ? service.realPath(target)
  328. : Effect.acquireUseRelease(
  329. Effect.sync(() => {
  330. active++
  331. maximum = Math.max(maximum, active)
  332. }),
  333. () => Effect.sleep("10 millis").pipe(Effect.andThen(service.realPath(target))),
  334. () => Effect.sync(() => active--),
  335. ),
  336. })
  337. }),
  338. ).pipe(Layer.provide(FSUtil.defaultLayer))
  339. return Effect.gen(function* () {
  340. yield* Effect.promise(() =>
  341. Promise.all(Array.from({ length: 32 }, (_, index) => fs.writeFile(path.join(directory, `${index}.txt`), ""))),
  342. )
  343. const service = yield* FileSystem.Service
  344. expect((yield* service.listPage({ limit: 32 })).entries).toHaveLength(32)
  345. expect(maximum).toBe(16)
  346. }).pipe(provide(directory, filesystem))
  347. }),
  348. )
  349. it.live("caps direct list page service calls at 2000 entries", () =>
  350. withTmp((directory) =>
  351. Effect.gen(function* () {
  352. yield* Effect.promise(() =>
  353. Promise.all(
  354. Array.from({ length: 2_001 }, (_, index) =>
  355. fs.writeFile(path.join(directory, `${index.toString().padStart(4, "0")}.txt`), ""),
  356. ),
  357. ),
  358. )
  359. const service = yield* FileSystem.Service
  360. const target = yield* service.resolveList()
  361. expect((yield* service.listPageResolved(target, { limit: 2_001 })).entries).toHaveLength(2_000)
  362. }).pipe(provide(directory)),
  363. ),
  364. )
  365. test("rejects page limits over 2000", () => {
  366. const decode = Schema.decodeUnknownSync(FileSystem.ListPageInput)
  367. expect(() => decode({ limit: 2_001 })).toThrow()
  368. })
  369. it.live("rejects escaping list paths and omits escaping symlink children", () =>
  370. withTmp((directory) =>
  371. Effect.gen(function* () {
  372. if (process.platform === "win32") return
  373. const outside = `${directory}-outside`
  374. yield* Effect.promise(async () => {
  375. await fs.mkdir(outside)
  376. await fs.writeFile(path.join(outside, "secret.txt"), "secret")
  377. await fs.symlink(outside, path.join(directory, "escape"))
  378. })
  379. const service = yield* FileSystem.Service
  380. expect(
  381. Exit.isFailure(yield* service.listPage({ path: RelativePath.make("../outside") }).pipe(Effect.exit)),
  382. ).toBe(true)
  383. expect((yield* service.listPage()).entries).toEqual([])
  384. yield* Effect.promise(() => fs.rm(outside, { recursive: true, force: true }))
  385. }).pipe(provide(directory)),
  386. ),
  387. )
  388. it.live("paginates visible entries after omitting escaping symlink children", () =>
  389. withTmp((directory) =>
  390. Effect.gen(function* () {
  391. if (process.platform === "win32") return
  392. const outside = `${directory}-outside`
  393. yield* Effect.promise(async () => {
  394. await fs.mkdir(outside)
  395. await fs.symlink(outside, path.join(directory, "a-escape"))
  396. await fs.writeFile(path.join(directory, "b-visible.txt"), "visible")
  397. })
  398. const service = yield* FileSystem.Service
  399. expect(yield* service.listPage({ limit: 1 })).toMatchObject({
  400. entries: [{ path: "b-visible.txt", type: "file" }],
  401. truncated: false,
  402. })
  403. yield* Effect.promise(() => fs.rm(outside, { recursive: true, force: true }))
  404. }).pipe(provide(directory)),
  405. ),
  406. )
  407. it.live("rejects paths outside the location", () =>
  408. withTmp((directory) =>
  409. Effect.gen(function* () {
  410. const service = yield* FileSystem.Service
  411. expect(
  412. Exit.isFailure(yield* service.read({ path: RelativePath.make("../outside.txt") }).pipe(Effect.exit)),
  413. ).toBe(true)
  414. }).pipe(provide(directory)),
  415. ),
  416. )
  417. })