import { describe, expect } from "bun:test" import fs from "node:fs/promises" import os from "node:os" import path from "node:path" import { inspect } from "node:util" import { Cause, Deferred, Effect, Exit, PlatformError, Redacted, Stream } from "effect" import { ChildProcess, ChildProcessSpawner } from "effect/process" import { CrossSpawnSpawner } from "@opencode/util/cross-spawn-spawner" import { LayerNode } from "@opencode/util/effect/layer-node" import { Teardown } from "@opencode/util/teardown" import { appExecutionAlias } from "../fixture/app-execution-alias" import { testEffect } from "../lib/effect" const live = LayerNode.compile(CrossSpawnSpawner.node) const fx = testEffect(live) const pwsh = appExecutionAlias("pwsh.exe") function js(code: string, opts?: ChildProcess.CommandOptions) { return ChildProcess.make("node", ["-e", code], opts) } function decodeByteStream(stream: Stream.Stream) { return Stream.mkUint8Array(stream).pipe(Effect.map((bytes) => new TextDecoder("utf-8").decode(bytes).trim())) } function alive(pid: number) { try { process.kill(pid, 0) return true } catch { return false } } async function tmpdir() { const dir = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-core-test-")) return { path: dir, async [Symbol.asyncDispose]() { await fs.rm(dir, { recursive: true, force: true }) }, } } async function gone(pid: number, timeout = 5_000) { const end = Date.now() + timeout while (Date.now() < end) { if (!alive(pid)) return true await new Promise((resolve) => setTimeout(resolve, 50)) } return !alive(pid) } describe("cross-spawn spawner", () => { describe("basic spawning", () => { fx.effect( "captures stdout", Effect.gen(function* () { const out = yield* ChildProcessSpawner.ChildProcessSpawner.use((svc) => svc.string(ChildProcess.make(process.execPath, ["-e", 'process.stdout.write("ok")'])), ) expect(out).toBe("ok") }), ) fx.effect( "returns non-zero exit code", Effect.gen(function* () { const handle = yield* js("process.exit(42)") const code = yield* handle.exitCode expect(code).toBe(ChildProcessSpawner.ExitCode(42)) }), ) }) describe("cwd option", () => { fx.effect( "uses cwd when spawning commands", Effect.gen(function* () { const tmp = yield* Effect.acquireRelease( Effect.promise(() => tmpdir()), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ) const out = yield* ChildProcessSpawner.ChildProcessSpawner.use((svc) => svc.string( ChildProcess.make(process.execPath, ["-e", "process.stdout.write(process.cwd())"], { cwd: tmp.path }), ), ) expect(yield* Effect.promise(() => fs.realpath(out))).toBe(yield* Effect.promise(() => fs.realpath(tmp.path))) }), ) fx.effect( "fails for invalid cwd", Effect.gen(function* () { const exit = yield* Effect.exit( ChildProcessSpawner.ChildProcessSpawner.use((svc) => svc.spawn(ChildProcess.make("echo", ["test"], { cwd: "/nonexistent/directory/path" })), ), ) expect(Exit.isFailure(exit)).toBe(true) }), ) }) describe("env option", () => { fx.effect( "passes environment variables with extendEnv", Effect.gen(function* () { const handle = yield* js('process.stdout.write(process.env.TEST_VAR ?? "")', { env: { TEST_VAR: "test_value" }, extendEnv: true, }) const out = yield* decodeByteStream(handle.stdout) expect(out).toBe("test_value") }), ) }) describe("stderr", () => { fx.live( "captures both streams across backpressure", Effect.gen(function* () { const handle = yield* js( 'process.stdout.write("o".repeat(256 * 1024)); process.stderr.write("e".repeat(256 * 1024))', ) const output = yield* Effect.all([decodeByteStream(handle.stdout), decodeByteStream(handle.stderr)], { concurrency: "unbounded", }) expect(output).toEqual(["o".repeat(256 * 1024), "e".repeat(256 * 1024)]) expect(yield* handle.exitCode).toBe(ChildProcessSpawner.ExitCode(0)) }), ) fx.effect( "captures both stdout and stderr", Effect.gen(function* () { const handle = yield* js( [ "let pending = 2", "const done = () => {", " pending -= 1", " if (pending === 0) setTimeout(() => process.exit(0), 0)", "}", 'process.stdout.write("stdout\\n", done)', 'process.stderr.write("stderr\\n", done)', ].join("\n"), ) const [stdout, stderr] = yield* Effect.all([decodeByteStream(handle.stdout), decodeByteStream(handle.stderr)], { concurrency: 2, }) expect(stdout).toBe("stdout") expect(stderr).toBe("stderr") }), ) }) describe("combined output (all)", () => { fx.effect( "captures stderr via .all when no stdout", Effect.gen(function* () { const handle = yield* js('process.stderr.write("hello from stderr")') const all = yield* decodeByteStream(handle.all) expect(all).toBe("hello from stderr") }), ) }) describe("delayed output consumption", () => { for (const combined of [false, true]) { fx.live( `retains ${combined ? "combined" : "separate"} output after process completion`, Effect.gen(function* () { const handle = yield* js( 'require("node:fs").writeSync(1, "stdout\\n"); require("node:fs").writeSync(2, "stderr\\n")', ) expect(yield* handle.exitCode).toBe(ChildProcessSpawner.ExitCode(0)) if (combined) { const output = yield* decodeByteStream(handle.all) expect(output).toContain("stdout") expect(output).toContain("stderr") return } const output = yield* Effect.all([decodeByteStream(handle.stdout), decodeByteStream(handle.stderr)], { concurrency: "unbounded", }) expect(output).toEqual(["stdout", "stderr"]) }), ) } }) describe("stdin", () => { fx.effect( "allows providing standard input to a command", Effect.gen(function* () { const input = "a b c" const stdin = Stream.make(Buffer.from(input, "utf-8")) const handle = yield* js( 'process.stdin.setEncoding("utf8"); let out = ""; process.stdin.on("data", (chunk) => out += chunk); process.stdin.on("end", () => process.stdout.write(out))', { stdin }, ) const out = yield* decodeByteStream(handle.stdout) yield* handle.exitCode expect(out).toBe("a b c") }), ) }) describe("process control", () => { for (const mode of ["exit", "SIGKILL"] as const) { const test = mode === "SIGKILL" && process.platform === "win32" ? fx.live.skip : fx.live test( `finishes capture after ${mode} while a grandchild holds stdio`, Effect.gen(function* () { const tmp = yield* Effect.acquireRelease( Effect.promise(() => tmpdir()), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ) const pidFile = path.join(tmp.path, "child.pid") yield* Effect.addFinalizer(() => Effect.tryPromise(async () => process.kill(Number(await fs.readFile(pidFile, "utf8")), "SIGKILL")).pipe( Effect.ignore, ), ) const ready = yield* Deferred.make() // The grandchild keeps both pipes open independently of the foreground process. const handle = yield* ChildProcess.make( "node", [path.join(import.meta.dir, "../fixture/held-stdio.cjs"), mode, pidFile], { stdin: "ignore", forceKillAfter: 100 }, ) const [exit, stdout, stderr] = yield* Effect.all( [ Effect.exit(handle.exitCode), decodeByteStream(handle.stdout), decodeByteStream(handle.stderr.pipe(Stream.tap(() => Deferred.succeed(ready, undefined)))), mode === "SIGKILL" ? Deferred.await(ready).pipe(Effect.andThen(handle.kill({ killSignal: "SIGKILL" }))) : Effect.void, ], { concurrency: "unbounded" }, ).pipe(Effect.timeout("3 seconds")) // Completion must retain foreground output without waiting for the inherited pipes to close. expect(stdout).toBe("foreground-out") expect(stderr).toBe("foreground-err") expect(Exit.isSuccess(exit)).toBe(mode === "exit") if (Exit.isSuccess(exit)) expect(exit.value).toBe(ChildProcessSpawner.ExitCode(0)) expect(yield* handle.isRunning).toBe(false) expect(alive(Number(yield* Effect.promise(() => fs.readFile(pidFile, "utf8"))))).toBe(true) }), 10_000, ) } fx.live( "stops tracking a released child while a grandchild holds stdio", Effect.gen(function* () { const tmp = yield* Effect.acquireRelease( Effect.promise(() => tmpdir()), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ) const pidFile = path.join(tmp.path, "child.pid") yield* Effect.addFinalizer(() => Effect.tryPromise(async () => process.kill(Number(await fs.readFile(pidFile, "utf8")), "SIGKILL")).pipe( Effect.ignore, ), ) const label = yield* Effect.scoped( Effect.gen(function* () { const handle = yield* ChildProcess.make( "node", [path.join(import.meta.dir, "../fixture/held-stdio.cjs"), "exit", pidFile], { stdin: "ignore" }, ) const label = `child ${handle.pid} running:` expect(Teardown.pending().some((item) => item.label.startsWith(label))).toBe(true) yield* handle.exitCode return label }), ) // Checked before yielding to the event loop: release itself settles the entry, not a later "close" event. expect(Teardown.pending().some((item) => item.label.startsWith(label))).toBe(false) expect(alive(Number(yield* Effect.promise(() => fs.readFile(pidFile, "utf8"))))).toBe(true) }), 10_000, ) fx.effect( "kills a running process", Effect.gen(function* () { const exit = yield* Effect.exit( Effect.gen(function* () { const handle = yield* js("setTimeout(() => {}, 10_000)") yield* handle.kill() return yield* handle.exitCode }), ) expect(Exit.isFailure(exit) ? true : exit.value !== ChildProcessSpawner.ExitCode(0)).toBe(true) }), ) fx.effect( "uses the configured kill signal when scope exits", Effect.gen(function* () { const pid = yield* Effect.scoped( Effect.gen(function* () { const handle = yield* js("setInterval(() => {}, 10_000)", { killSignal: "SIGKILL" }) return Number(handle.pid) }), ) const done = yield* Effect.promise(() => gone(pid)) expect(done).toBe(true) }), ) fx.live( "forceKillAfter escalates for stubborn processes", Effect.gen(function* () { if (process.platform === "win32") return const exit = yield* Effect.exit( Effect.gen(function* () { const handle = yield* js('process.on("SIGTERM", () => {}); setInterval(() => {}, 10_000)') yield* handle.kill({ forceKillAfter: 100 }) return yield* handle.exitCode }), ) expect(Exit.isFailure(exit) ? true : exit.value !== ChildProcessSpawner.ExitCode(0)).toBe(true) }), ) }) describe("error handling", () => { fx.effect( "fails for invalid command", Effect.gen(function* () { const exit = yield* Effect.exit( Effect.gen(function* () { const handle = yield* ChildProcess.make("nonexistent-command-12345") return yield* handle.exitCode }), ) expect(Exit.isFailure(exit) ? true : exit.value !== ChildProcessSpawner.ExitCode(0)).toBe(true) }), ) fx.effect( "rejects NUL characters without exposing Redacted values", Effect.gen(function* () { const secret = Redacted.make("hunter2\0") const commands = [ () => ChildProcess.make("echo", [secret]), () => ChildProcess.make`echo ${secret}`, () => ChildProcess.make("echo", [], { env: { SECRET: secret } }), ] for (const command of commands) { const exit = yield* Effect.exit(Effect.scoped(Effect.flatMap(command(), (handle) => handle.exitCode))) expect(Exit.isFailure(exit)).toBe(true) if (Exit.isSuccess(exit)) continue expect(Cause.hasDies(exit.cause)).toBe(false) const error = Cause.squash(exit.cause) expect(PlatformError.isPlatformError(error) && error.reason._tag).toBe("BadArgument") expect(inspect(exit, { depth: Infinity })).not.toContain("hunter2") } }), ) fx.live( "reports a duplex write failure to a later reader without an uncaught error", Effect.gen(function* () { if (process.platform === "win32") return const uncaught: Array = [] const onUncaught = (error: unknown) => uncaught.push(error) yield* Effect.acquireRelease( Effect.sync(() => process.on("uncaughtException", onUncaught)), () => Effect.sync(() => process.off("uncaughtException", onUncaught)), ) // Under `bun test` (1.4.4) the process's first child with an extra fd never emits "spawn", so spawn one without. yield* Effect.scoped(Effect.flatMap(ChildProcess.make("true"), (warmUp) => warmUp.exitCode)) // The child closes fd3 before signalling readiness on stdout. const handle = yield* ChildProcess.make("sh", ["-c", "exec 3>&-; echo ready; exec sleep 10"], { additionalFds: { fd3: { type: "duplex" } }, }) yield* Stream.runDrain(Stream.take(handle.stdout, 1)) // Write before anyone reads fd3, and start reading only after the write has failed. const writeError = yield* Effect.flip( Stream.run(Stream.make(new TextEncoder().encode("request")), handle.getInputFd(3)), ) const readError = yield* Effect.flip(Stream.runDrain(handle.getOutputFd(3)).pipe(Effect.timeout("2 seconds"))) expect(writeError._tag).toBe("PlatformError") expect(uncaught).toEqual([]) expect(readError._tag).toBe("PlatformError") }), ) }) describe("pipeline", () => { fx.effect( "three-stage pipeline", Effect.gen(function* () { const handle = yield* js('process.stdout.write("hello world")').pipe( ChildProcess.pipeTo( js( 'process.stdin.setEncoding("utf8"); let out = ""; process.stdin.on("data", (chunk) => out += chunk); process.stdin.on("end", () => process.stdout.write(out.toUpperCase()))', ), ), ChildProcess.pipeTo( js( 'process.stdin.setEncoding("utf8"); let out = ""; process.stdin.on("data", (chunk) => out += chunk); process.stdin.on("end", () => process.stdout.write(out.replaceAll(" ", "-")))', ), ), ) const out = yield* decodeByteStream(handle.stdout) yield* handle.exitCode expect(out).toBe("HELLO-WORLD") }), ) fx.effect( "pipes stderr with { from: 'stderr' }", Effect.gen(function* () { const handle = yield* js('process.stderr.write("error")').pipe( ChildProcess.pipeTo( js( 'process.stdin.setEncoding("utf8"); let out = ""; process.stdin.on("data", (chunk) => out += chunk); process.stdin.on("end", () => process.stdout.write(out))', ), { from: "stderr" }, ), ) const out = yield* decodeByteStream(handle.stdout) yield* handle.exitCode expect(out).toBe("error") }), ) fx.effect( "pipes combined output with { from: 'all' }", Effect.gen(function* () { const handle = yield* js('process.stdout.write("stdout\\n"); process.stderr.write("stderr\\n")').pipe( ChildProcess.pipeTo( js( 'process.stdin.setEncoding("utf8"); let out = ""; process.stdin.on("data", (chunk) => out += chunk); process.stdin.on("end", () => process.stdout.write(out))', ), { from: "all" }, ), ) const out = yield* decodeByteStream(handle.stdout) yield* handle.exitCode expect(out).toContain("stdout") expect(out).toContain("stderr") }), ) }) describe("Windows-specific", () => { fx.effect( "uses shell routing on Windows", Effect.gen(function* () { if (process.platform !== "win32") return const out = yield* ChildProcessSpawner.ChildProcessSpawner.use((svc) => svc.string( ChildProcess.make("set", ["OPENCODE_TEST_SHELL"], { shell: true, extendEnv: true, env: { OPENCODE_TEST_SHELL: "ok" }, }), ), ) expect(out).toContain("OPENCODE_TEST_SHELL=ok") }), ) fx.effect( "runs cmd scripts with spaces on Windows without shell", Effect.gen(function* () { if (process.platform !== "win32") return const tmp = yield* Effect.acquireRelease( Effect.promise(() => tmpdir()), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ) const dir = path.join(tmp.path, "with space") const file = path.join(dir, "echo cmd.cmd") yield* Effect.promise(() => fs.mkdir(dir, { recursive: true })) yield* Effect.promise(() => fs.writeFile(file, "@echo off\r\nif %~1==--stdio exit /b 0\r\nexit /b 7\r\n")) const code = yield* ChildProcessSpawner.ChildProcessSpawner.use((svc) => svc.exitCode( ChildProcess.make(file, ["--stdio"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", }), ), ) expect(code).toBe(ChildProcessSpawner.ExitCode(0)) }), ) // Skipped where PowerShell 7 is not installed from the Microsoft Store for the user; see the fixture. const storePwsh = pwsh ? fx.live : fx.live.skip storePwsh( "keeps every line of a command run through an app execution alias", Effect.gen(function* () { const out = yield* ChildProcessSpawner.ChildProcessSpawner.use((svc) => svc.string( ChildProcess.make(pwsh!.file, ["-NoProfile", "-NonInteractive", "-Command", "echo one\necho two"]), ), ) expect(out.trim().split(/\r?\n/)).toEqual(["one", "two"]) }), ) }) })