cross-spawn-spawner.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import { describe, expect } from "bun:test"
  2. import fs from "node:fs/promises"
  3. import os from "node:os"
  4. import path from "node:path"
  5. import { Effect, Exit, Stream } from "effect"
  6. import type * as PlatformError from "effect/PlatformError"
  7. import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
  8. import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner"
  9. import { testEffect } from "../lib/effect"
  10. const live = CrossSpawnSpawner.defaultLayer
  11. const fx = testEffect(live)
  12. function js(code: string, opts?: ChildProcess.CommandOptions) {
  13. return ChildProcess.make("node", ["-e", code], opts)
  14. }
  15. function decodeByteStream(stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>) {
  16. return Stream.runCollect(stream).pipe(
  17. Effect.map((chunks) => {
  18. const total = chunks.reduce((acc, x) => acc + x.length, 0)
  19. const out = new Uint8Array(total)
  20. let off = 0
  21. for (const chunk of chunks) {
  22. out.set(chunk, off)
  23. off += chunk.length
  24. }
  25. return new TextDecoder("utf-8").decode(out).trim()
  26. }),
  27. )
  28. }
  29. function alive(pid: number) {
  30. try {
  31. process.kill(pid, 0)
  32. return true
  33. } catch {
  34. return false
  35. }
  36. }
  37. async function tmpdir() {
  38. const dir = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-core-test-"))
  39. return {
  40. path: dir,
  41. async [Symbol.asyncDispose]() {
  42. await fs.rm(dir, { recursive: true, force: true })
  43. },
  44. }
  45. }
  46. async function gone(pid: number, timeout = 5_000) {
  47. const end = Date.now() + timeout
  48. while (Date.now() < end) {
  49. if (!alive(pid)) return true
  50. await new Promise((resolve) => setTimeout(resolve, 50))
  51. }
  52. return !alive(pid)
  53. }
  54. describe("cross-spawn spawner", () => {
  55. describe("basic spawning", () => {
  56. fx.effect(
  57. "captures stdout",
  58. Effect.gen(function* () {
  59. const out = yield* ChildProcessSpawner.ChildProcessSpawner.use((svc) =>
  60. svc.string(ChildProcess.make(process.execPath, ["-e", 'process.stdout.write("ok")'])),
  61. )
  62. expect(out).toBe("ok")
  63. }),
  64. )
  65. fx.effect(
  66. "captures multiple lines",
  67. Effect.gen(function* () {
  68. const handle = yield* js('console.log("line1"); console.log("line2"); console.log("line3")')
  69. const out = yield* decodeByteStream(handle.stdout)
  70. expect(out).toBe("line1\nline2\nline3")
  71. }),
  72. )
  73. fx.effect(
  74. "returns exit code",
  75. Effect.gen(function* () {
  76. const handle = yield* js("process.exit(0)")
  77. const code = yield* handle.exitCode
  78. expect(code).toBe(ChildProcessSpawner.ExitCode(0))
  79. }),
  80. )
  81. fx.effect(
  82. "returns non-zero exit code",
  83. Effect.gen(function* () {
  84. const handle = yield* js("process.exit(42)")
  85. const code = yield* handle.exitCode
  86. expect(code).toBe(ChildProcessSpawner.ExitCode(42))
  87. }),
  88. )
  89. })
  90. describe("cwd option", () => {
  91. fx.effect(
  92. "uses cwd when spawning commands",
  93. Effect.gen(function* () {
  94. const tmp = yield* Effect.acquireRelease(
  95. Effect.promise(() => tmpdir()),
  96. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  97. )
  98. const out = yield* ChildProcessSpawner.ChildProcessSpawner.use((svc) =>
  99. svc.string(
  100. ChildProcess.make(process.execPath, ["-e", "process.stdout.write(process.cwd())"], { cwd: tmp.path }),
  101. ),
  102. )
  103. expect(out).toBe(tmp.path)
  104. }),
  105. )
  106. fx.effect(
  107. "fails for invalid cwd",
  108. Effect.gen(function* () {
  109. const exit = yield* Effect.exit(
  110. ChildProcess.make("echo", ["test"], { cwd: "/nonexistent/directory/path" }).asEffect(),
  111. )
  112. expect(Exit.isFailure(exit)).toBe(true)
  113. }),
  114. )
  115. })
  116. describe("env option", () => {
  117. fx.effect(
  118. "passes environment variables with extendEnv",
  119. Effect.gen(function* () {
  120. const handle = yield* js('process.stdout.write(process.env.TEST_VAR ?? "")', {
  121. env: { TEST_VAR: "test_value" },
  122. extendEnv: true,
  123. })
  124. const out = yield* decodeByteStream(handle.stdout)
  125. expect(out).toBe("test_value")
  126. }),
  127. )
  128. fx.effect(
  129. "passes multiple environment variables",
  130. Effect.gen(function* () {
  131. const handle = yield* js(
  132. "process.stdout.write(`${process.env.VAR1}-${process.env.VAR2}-${process.env.VAR3}`)",
  133. {
  134. env: { VAR1: "one", VAR2: "two", VAR3: "three" },
  135. extendEnv: true,
  136. },
  137. )
  138. const out = yield* decodeByteStream(handle.stdout)
  139. expect(out).toBe("one-two-three")
  140. }),
  141. )
  142. })
  143. describe("stderr", () => {
  144. fx.effect(
  145. "captures stderr output",
  146. Effect.gen(function* () {
  147. const handle = yield* js('process.stderr.write("error message")')
  148. const err = yield* decodeByteStream(handle.stderr)
  149. expect(err).toBe("error message")
  150. }),
  151. )
  152. fx.effect(
  153. "captures both stdout and stderr",
  154. Effect.gen(function* () {
  155. const handle = yield* js(
  156. [
  157. "let pending = 2",
  158. "const done = () => {",
  159. " pending -= 1",
  160. " if (pending === 0) setTimeout(() => process.exit(0), 0)",
  161. "}",
  162. 'process.stdout.write("stdout\\n", done)',
  163. 'process.stderr.write("stderr\\n", done)',
  164. ].join("\n"),
  165. )
  166. const [stdout, stderr] = yield* Effect.all([decodeByteStream(handle.stdout), decodeByteStream(handle.stderr)], {
  167. concurrency: 2,
  168. })
  169. expect(stdout).toBe("stdout")
  170. expect(stderr).toBe("stderr")
  171. }),
  172. )
  173. })
  174. describe("combined output (all)", () => {
  175. fx.effect(
  176. "captures stdout via .all when no stderr",
  177. Effect.gen(function* () {
  178. const handle = yield* ChildProcess.make("echo", ["hello from stdout"])
  179. const all = yield* decodeByteStream(handle.all)
  180. expect(all).toBe("hello from stdout")
  181. }),
  182. )
  183. fx.effect(
  184. "captures stderr via .all when no stdout",
  185. Effect.gen(function* () {
  186. const handle = yield* js('process.stderr.write("hello from stderr")')
  187. const all = yield* decodeByteStream(handle.all)
  188. expect(all).toBe("hello from stderr")
  189. }),
  190. )
  191. })
  192. describe("stdin", () => {
  193. fx.effect(
  194. "allows providing standard input to a command",
  195. Effect.gen(function* () {
  196. const input = "a b c"
  197. const stdin = Stream.make(Buffer.from(input, "utf-8"))
  198. const handle = yield* js(
  199. 'process.stdin.setEncoding("utf8"); let out = ""; process.stdin.on("data", (chunk) => out += chunk); process.stdin.on("end", () => process.stdout.write(out))',
  200. { stdin },
  201. )
  202. const out = yield* decodeByteStream(handle.stdout)
  203. yield* handle.exitCode
  204. expect(out).toBe("a b c")
  205. }),
  206. )
  207. })
  208. describe("process control", () => {
  209. fx.effect(
  210. "kills a running process",
  211. Effect.gen(function* () {
  212. const exit = yield* Effect.exit(
  213. Effect.gen(function* () {
  214. const handle = yield* js("setTimeout(() => {}, 10_000)")
  215. yield* handle.kill()
  216. return yield* handle.exitCode
  217. }),
  218. )
  219. expect(Exit.isFailure(exit) ? true : exit.value !== ChildProcessSpawner.ExitCode(0)).toBe(true)
  220. }),
  221. )
  222. fx.effect(
  223. "kills a child when scope exits",
  224. Effect.gen(function* () {
  225. const pid = yield* Effect.scoped(
  226. Effect.gen(function* () {
  227. const handle = yield* js("setInterval(() => {}, 10_000)")
  228. return Number(handle.pid)
  229. }),
  230. )
  231. const done = yield* Effect.promise(() => gone(pid))
  232. expect(done).toBe(true)
  233. }),
  234. )
  235. fx.effect(
  236. "forceKillAfter escalates for stubborn processes",
  237. Effect.gen(function* () {
  238. if (process.platform === "win32") return
  239. const started = Date.now()
  240. const exit = yield* Effect.exit(
  241. Effect.gen(function* () {
  242. const handle = yield* js('process.on("SIGTERM", () => {}); setInterval(() => {}, 10_000)')
  243. yield* handle.kill({ forceKillAfter: 100 })
  244. return yield* handle.exitCode
  245. }),
  246. )
  247. expect(Date.now() - started).toBeLessThan(1_000)
  248. expect(Exit.isFailure(exit) ? true : exit.value !== ChildProcessSpawner.ExitCode(0)).toBe(true)
  249. }),
  250. )
  251. fx.effect(
  252. "isRunning reflects process state",
  253. Effect.gen(function* () {
  254. const handle = yield* js('process.stdout.write("done")')
  255. yield* handle.exitCode
  256. const running = yield* handle.isRunning
  257. expect(running).toBe(false)
  258. }),
  259. )
  260. })
  261. describe("error handling", () => {
  262. fx.effect(
  263. "fails for invalid command",
  264. Effect.gen(function* () {
  265. const exit = yield* Effect.exit(
  266. Effect.gen(function* () {
  267. const handle = yield* ChildProcess.make("nonexistent-command-12345")
  268. return yield* handle.exitCode
  269. }),
  270. )
  271. expect(Exit.isFailure(exit) ? true : exit.value !== ChildProcessSpawner.ExitCode(0)).toBe(true)
  272. }),
  273. )
  274. })
  275. describe("pipeline", () => {
  276. fx.effect(
  277. "pipes stdout of one command to stdin of another",
  278. Effect.gen(function* () {
  279. const handle = yield* js('process.stdout.write("hello world")').pipe(
  280. ChildProcess.pipeTo(
  281. js(
  282. 'process.stdin.setEncoding("utf8"); let out = ""; process.stdin.on("data", (chunk) => out += chunk); process.stdin.on("end", () => process.stdout.write(out.toUpperCase()))',
  283. ),
  284. ),
  285. )
  286. const out = yield* decodeByteStream(handle.stdout)
  287. yield* handle.exitCode
  288. expect(out).toBe("HELLO WORLD")
  289. }),
  290. )
  291. fx.effect(
  292. "three-stage pipeline",
  293. Effect.gen(function* () {
  294. const handle = yield* js('process.stdout.write("hello world")').pipe(
  295. ChildProcess.pipeTo(
  296. js(
  297. 'process.stdin.setEncoding("utf8"); let out = ""; process.stdin.on("data", (chunk) => out += chunk); process.stdin.on("end", () => process.stdout.write(out.toUpperCase()))',
  298. ),
  299. ),
  300. ChildProcess.pipeTo(
  301. js(
  302. 'process.stdin.setEncoding("utf8"); let out = ""; process.stdin.on("data", (chunk) => out += chunk); process.stdin.on("end", () => process.stdout.write(out.replaceAll(" ", "-")))',
  303. ),
  304. ),
  305. )
  306. const out = yield* decodeByteStream(handle.stdout)
  307. yield* handle.exitCode
  308. expect(out).toBe("HELLO-WORLD")
  309. }),
  310. )
  311. fx.effect(
  312. "pipes stderr with { from: 'stderr' }",
  313. Effect.gen(function* () {
  314. const handle = yield* js('process.stderr.write("error")').pipe(
  315. ChildProcess.pipeTo(
  316. js(
  317. 'process.stdin.setEncoding("utf8"); let out = ""; process.stdin.on("data", (chunk) => out += chunk); process.stdin.on("end", () => process.stdout.write(out))',
  318. ),
  319. { from: "stderr" },
  320. ),
  321. )
  322. const out = yield* decodeByteStream(handle.stdout)
  323. yield* handle.exitCode
  324. expect(out).toBe("error")
  325. }),
  326. )
  327. fx.effect(
  328. "pipes combined output with { from: 'all' }",
  329. Effect.gen(function* () {
  330. const handle = yield* js('process.stdout.write("stdout\\n"); process.stderr.write("stderr\\n")').pipe(
  331. ChildProcess.pipeTo(
  332. js(
  333. 'process.stdin.setEncoding("utf8"); let out = ""; process.stdin.on("data", (chunk) => out += chunk); process.stdin.on("end", () => process.stdout.write(out))',
  334. ),
  335. { from: "all" },
  336. ),
  337. )
  338. const out = yield* decodeByteStream(handle.stdout)
  339. yield* handle.exitCode
  340. expect(out).toContain("stdout")
  341. expect(out).toContain("stderr")
  342. }),
  343. )
  344. })
  345. describe("Windows-specific", () => {
  346. fx.effect(
  347. "uses shell routing on Windows",
  348. Effect.gen(function* () {
  349. if (process.platform !== "win32") return
  350. const out = yield* ChildProcessSpawner.ChildProcessSpawner.use((svc) =>
  351. svc.string(
  352. ChildProcess.make("set", ["OPENCODE_TEST_SHELL"], {
  353. shell: true,
  354. extendEnv: true,
  355. env: { OPENCODE_TEST_SHELL: "ok" },
  356. }),
  357. ),
  358. )
  359. expect(out).toContain("OPENCODE_TEST_SHELL=ok")
  360. }),
  361. )
  362. fx.effect(
  363. "runs cmd scripts with spaces on Windows without shell",
  364. Effect.gen(function* () {
  365. if (process.platform !== "win32") return
  366. const tmp = yield* Effect.acquireRelease(
  367. Effect.promise(() => tmpdir()),
  368. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  369. )
  370. const dir = path.join(tmp.path, "with space")
  371. const file = path.join(dir, "echo cmd.cmd")
  372. yield* Effect.promise(() => fs.mkdir(dir, { recursive: true }))
  373. yield* Effect.promise(() => fs.writeFile(file, "@echo off\r\nif %~1==--stdio exit /b 0\r\nexit /b 7\r\n"))
  374. const code = yield* ChildProcessSpawner.ChildProcessSpawner.use((svc) =>
  375. svc.exitCode(
  376. ChildProcess.make(file, ["--stdio"], {
  377. stdin: "pipe",
  378. stdout: "pipe",
  379. stderr: "pipe",
  380. }),
  381. ),
  382. )
  383. expect(code).toBe(ChildProcessSpawner.ExitCode(0))
  384. }),
  385. )
  386. })
  387. })