location-filesystem.test.ts 17 KB

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