The best way to control Claude Code, Codex and more from any computer or phone

main
ts 476 lines 19.1 KB
Raw
1 import { buildSpawnOptions } from "@effect/platform-node-shared/internal/nodeChildProcessSpawner"
2 import * as NodeChildProcessSpawner from "@effect/platform-node-shared/NodeChildProcessSpawner"
3 import * as NodeFileSystem from "@effect/platform-node-shared/NodeFileSystem"
4 import * as NodePath from "@effect/platform-node-shared/NodePath"
5 import { assert, describe, it } from "@effect/vitest"
6 import * as ChildProcessSpawnerTest from "effect-test/process/ChildProcessSpawnerTest"
7 import * as ByteSize from "effect/ByteSize"
8 import * as Deferred from "effect/Deferred"
9 import * as Effect from "effect/Effect"
10 import * as Exit from "effect/Exit"
11 import * as FileSystem from "effect/FileSystem"
12 import * as Layer from "effect/Layer"
13 import * as ChildProcess from "effect/process/ChildProcess"
14 import * as Scope from "effect/Scope"
15 import * as Stream from "effect/Stream"
16 import NodeChildProcess, { spawnSync } from "node:child_process"
17 import { syncBuiltinESMExports } from "node:module"
18 import { join } from "node:path"
19 import { vi } from "vitest"
20
21 const NodeServices = NodeChildProcessSpawner.layer.pipe(
22 Layer.provideMerge(Layer.mergeAll(
23 NodeFileSystem.layer,
24 NodePath.layer
25 ))
26 )
27
28 ChildProcessSpawnerTest.suite("NodeChildProcessSpawner", NodeServices, {
29 processGroups: true
30 })
31
32 describe.skipIf(process.platform === "win32")("error descriptions", () => {
33 it.effect("quote arguments and escape control characters", () =>
34 Effect.gen(function*() {
35 const error = yield* Effect.flip(ChildProcess.make("nonexistent-command-12345", ["a b", "it's", "\u001b[2J"]))
36
37 assert.strictEqual(error.reason._tag, "NotFound")
38 assert.strictEqual(
39 error.reason._tag === "NotFound" ? error.reason.pathOrDescriptor : undefined,
40 "nonexistent-command-12345 'a b' 'it'\\''s' '\\u001b[2J'"
41 )
42 }).pipe(Effect.provide(NodeServices)))
43 })
44
45 describe("Windows cleanup", { concurrent: false }, () => {
46 for (const signal of [false, true]) {
47 it.skipIf(signal && process.platform === "win32")(
48 `does not taskkill a ${signal ? "signal-terminated" : "failed"} child during exit, kill or scope release`,
49 async () => {
50 const platform = Object.getOwnPropertyDescriptor(process, "platform")!
51 const taskkill = vi.spyOn(NodeChildProcess, "execFile").mockImplementation((...args) => {
52 const callback = args.at(-1)
53 if (typeof callback === "function") callback(null, "", "")
54 return new NodeChildProcess.ChildProcess()
55 })
56 syncBuiltinESMExports()
57 try {
58 await Effect.runPromise(
59 Effect.scoped(Effect.gen(function*() {
60 const handle = yield* ChildProcess.make(process.execPath, [
61 "-e",
62 signal ? "process.kill(process.pid, 'SIGTERM')" : "process.exit(1)"
63 ])
64 // Spawn natively, then exercise the Windows exit and cleanup paths.
65 Object.defineProperty(process, "platform", { value: "win32" })
66 if (signal) {
67 assert.isTrue(Exit.isFailure(yield* Effect.exit(handle.exitCode)))
68 } else {
69 assert.strictEqual(yield* handle.exitCode, 1)
70 }
71 yield* handle.kill()
72 })).pipe(Effect.provide(NodeServices))
73 )
74 assert.strictEqual(taskkill.mock.calls.length, 0)
75 } finally {
76 Object.defineProperty(process, "platform", platform)
77 taskkill.mockRestore()
78 syncBuiltinESMExports()
79 }
80 }
81 )
82 }
83 })
84
85 describe.skipIf(process.platform === "win32")("non-detached exit cleanup", { concurrent: false }, () => {
86 for (const signal of [false, true]) {
87 it.live(
88 `does not signal the process group of a ${
89 signal ? "signal-terminated" : "failed"
90 } child during exit, kill or scope release`,
91 () =>
92 Effect.gen(function*() {
93 const kill = vi.spyOn(process, "kill")
94 yield* Effect.addFinalizer(() => Effect.sync(() => kill.mockRestore()))
95 let pid = 0
96 yield* Effect.scoped(Effect.gen(function*() {
97 const handle = yield* ChildProcess.make(process.execPath, [
98 "-e",
99 signal ? "process.kill(process.pid, 'SIGTERM')" : "process.exit(1)"
100 ], { detached: false, forceKillAfter: "100 millis" })
101 pid = handle.pid
102 if (signal) {
103 assert.isTrue(Exit.isFailure(yield* Effect.exit(handle.exitCode)))
104 } else {
105 assert.strictEqual(yield* handle.exitCode, 1)
106 }
107 // The exited child's PID may now lead an unrelated process group.
108 yield* Effect.ignore(handle.kill())
109 }))
110 assert.deepStrictEqual(kill.mock.calls.filter(([target]) => target === -pid), [])
111 }).pipe(Effect.scoped, Effect.provide(NodeServices))
112 )
113 }
114
115 it.live("does not poll or force kill the process group of a child that exits during scope release", () =>
116 Effect.gen(function*() {
117 const kill = vi.spyOn(process, "kill")
118 yield* Effect.addFinalizer(() => Effect.sync(() => kill.mockRestore()))
119 let pid = 0
120 yield* Effect.scoped(Effect.gen(function*() {
121 const handle = yield* ChildProcess.make(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
122 detached: false,
123 forceKillAfter: "1 second"
124 })
125 pid = handle.pid
126 }))
127 // Signalling the live child is fine; polling or escalating after it exits is not.
128 assert.deepStrictEqual(kill.mock.calls.filter(([target, signal]) => target === -pid && signal !== "SIGTERM"), [])
129 }).pipe(Effect.scoped, Effect.provide(NodeServices)))
130 })
131
132 const zombieProbes = 3
133
134 // macOS answers EPERM rather than ESRCH while the group's remaining members are zombies.
135 const stubZombieProcessGroup = Effect.fnUntraced(function*() {
136 const nativeKill = process.kill.bind(process)
137 const group = { pid: 0, probes: 0, signals: [] as Array<string | number | undefined> }
138 const kill = vi.spyOn(process, "kill").mockImplementation((target, signal) => {
139 if (group.pid === 0 || target !== -group.pid) {
140 return nativeKill(target, signal)
141 }
142 if (signal === 0) {
143 group.probes++
144 } else {
145 group.signals.push(signal)
146 }
147 throw Object.assign(new Error("kill"), { code: group.probes <= zombieProbes ? "EPERM" : "ESRCH" })
148 })
149 yield* Effect.addFinalizer(() => Effect.sync(() => kill.mockRestore()))
150 return group
151 })
152
153 describe.skipIf(process.platform === "win32")("detached exit cleanup", { concurrent: false }, () => {
154 it.live("kill waits for a process group that exists but cannot be signalled", () =>
155 Effect.gen(function*() {
156 const group = yield* stubZombieProcessGroup()
157 const handle = yield* ChildProcess.make(process.execPath, ["-e", "setInterval(() => {}, 1000)"])
158 group.pid = handle.pid
159
160 yield* handle.kill()
161
162 assert.strictEqual(group.probes, zombieProbes + 1)
163 }).pipe(Effect.scoped, Effect.provide(NodeServices)))
164
165 it.live("kill escalates and waits for a process group whose exited leader left only zombies", () =>
166 Effect.gen(function*() {
167 const group = yield* stubZombieProcessGroup()
168 const handle = yield* ChildProcess.make(process.execPath, ["-e", ""])
169 group.pid = handle.pid
170 assert.strictEqual(yield* handle.exitCode, 0)
171
172 yield* handle.kill({ forceKillAfter: "0 millis" })
173
174 assert.deepStrictEqual(group.signals, ["SIGTERM", "SIGKILL"])
175 assert.strictEqual(group.probes, zombieProbes + 1)
176 }).pipe(Effect.scoped, Effect.provide(NodeServices)))
177 })
178
179 // Synchronous fixture runs must not block other tests with active timeout budgets.
180 describe("interrupted buffered input", { concurrent: false, timeout: 15_000 }, () => {
181 for (const input of ["stdin", "fd3"] as const) {
182 it(`does not crash the host when ${input} is interrupted`, () => {
183 // Isolate the host so an unhandled writable error becomes an assertion
184 // failure rather than an uncaught exception in the test runner.
185 const result = spawnSync(process.execPath, [join(__dirname, "fixtures", "buffered-input.ts"), input], {
186 encoding: "utf8",
187 timeout: 10_000
188 })
189 assert.strictEqual(result.error, undefined)
190 assert.strictEqual(result.status, 0, result.stderr)
191 assert.strictEqual(result.stdout, "program finished: Failure\nstill alive after 500ms\n")
192 })
193 }
194 })
195
196 describe("buildSpawnOptions", () => {
197 const base = { stdio: "pipe" } as const
198
199 it("defaults to hiding non-detached Windows children", () => {
200 assert.deepStrictEqual(buildSpawnOptions({}, base, "win32"), {
201 stdio: "pipe",
202 detached: false,
203 shell: undefined,
204 windowsHide: true
205 })
206 assert.deepStrictEqual(buildSpawnOptions({ detached: true }, base, "win32"), {
207 stdio: "pipe",
208 detached: true,
209 shell: undefined,
210 windowsHide: false
211 })
212 assert.deepStrictEqual(buildSpawnOptions({ detached: false }, base, "win32"), {
213 stdio: "pipe",
214 detached: false,
215 shell: undefined,
216 windowsHide: true
217 })
218 })
219
220 it("allows windowsHide to be configured independently of detached", () => {
221 assert.deepStrictEqual(
222 buildSpawnOptions({ detached: false, windowsHide: false }, base, "win32"),
223 {
224 stdio: "pipe",
225 detached: false,
226 shell: undefined,
227 windowsHide: false
228 }
229 )
230 assert.deepStrictEqual(
231 buildSpawnOptions({ detached: true, windowsHide: true }, base, "win32"),
232 {
233 stdio: "pipe",
234 detached: true,
235 shell: undefined,
236 windowsHide: true
237 }
238 )
239 })
240 })
241
242 it.live("kills every process in a pipeline", () =>
243 Effect.gen(function*() {
244 const fs = yield* FileSystem.FileSystem
245 const directory = yield* fs.makeTempDirectoryScoped()
246 const rootHeartbeat = `${directory}/root-heartbeat`
247 const childHeartbeat = `${directory}/child-heartbeat`
248 const handle = yield* ChildProcess.make(
249 "sh",
250 [
251 "-c",
252 "printf x >> \"$1\"; printf 'ROOT_READY\\n'; while :; do printf x >> \"$1\"; sleep 0.01; done",
253 "pipeline-root",
254 rootHeartbeat
255 ]
256 ).pipe(ChildProcess.pipeTo(ChildProcess.make(
257 "sh",
258 [
259 "-c",
260 "printf x >> \"$1\"; printf 'CHILD_READY\\n'; read -r ready; printf '%s\\n' \"$ready\"; while :; do printf x >> \"$1\"; sleep 0.01; done",
261 "pipeline-child",
262 childHeartbeat
263 ]
264 )))
265 const readyLines = yield* handle.stdout.pipe(
266 Stream.decodeText,
267 Stream.splitLines,
268 Stream.take(2),
269 Stream.runCollect
270 )
271 assert.deepStrictEqual(readyLines, ["CHILD_READY", "ROOT_READY"])
272 yield* handle.kill({ killSignal: "SIGKILL" })
273 const rootSizeAfterKill = (yield* fs.stat(rootHeartbeat)).size
274 const childSizeAfterKill = (yield* fs.stat(childHeartbeat)).size
275 yield* Effect.sleep("100 millis")
276 const rootFinalSize = (yield* fs.stat(rootHeartbeat)).size
277 const childFinalSize = (yield* fs.stat(childHeartbeat)).size
278
279 assert.strictEqual(ByteSize.toBigInt(rootFinalSize), ByteSize.toBigInt(rootSizeAfterKill))
280 assert.strictEqual(ByteSize.toBigInt(childFinalSize), ByteSize.toBigInt(childSizeAfterKill))
281 }).pipe(Effect.scoped, Effect.provide(NodeServices)))
282
283 const processGroupFixture = join(__dirname, "fixtures", "process-group.ts")
284
285 // Use native timers under TestClock.
286 const liveSleep = (millis: number) =>
287 Effect.callback<void>((resume) => {
288 const timer = setTimeout(() => resume(Effect.void), millis)
289 return Effect.sync(() => clearTimeout(timer))
290 })
291
292 const liveTimeout = (millis: number) => <A, E, R>(effect: Effect.Effect<A, E, R>) =>
293 Effect.raceFirst(effect, liveSleep(millis).pipe(Effect.andThen(Effect.die(new Error("timed out")))))
294
295 const startProcessGroup = Effect.fnUntraced(function*(
296 mode: "exit-on-signal" | "ignore-signal",
297 options?: ChildProcess.CommandOptions,
298 delays: { readonly leader: number; readonly descendant: number } = { leader: 0, descendant: 200 }
299 ) {
300 const fs = yield* FileSystem.FileSystem
301 const directory = yield* fs.makeTempDirectoryScoped()
302 const marker = `${directory}/marker`
303 const scope = yield* Scope.fork(yield* Effect.scope)
304 const handle = yield* Scope.provide(scope)(ChildProcess.make(
305 process.execPath,
306 [processGroupFixture, "leader", mode, marker, String(delays.leader), String(delays.descendant)],
307 { stdin: "ignore", ...options }
308 ))
309 const ready = yield* Deferred.make<number>()
310 yield* handle.stdout.pipe(
311 Stream.decodeText,
312 Stream.splitLines,
313 Stream.runForEach((line) =>
314 line.startsWith("READY ") ? Deferred.succeed(ready, Number(line.slice("READY ".length))) : Effect.void
315 ),
316 Effect.forkScoped
317 )
318 const descendantPid = yield* Deferred.await(ready).pipe(liveTimeout(5_000))
319 return { handle, descendantPid, marker, scope }
320 })
321
322 const killDescendant = (pid: number) =>
323 Effect.sync(() => {
324 try {
325 process.kill(pid, "SIGKILL")
326 } catch {}
327 })
328
329 const assertHeartbeatStopped = Effect.fnUntraced(function*(marker: string) {
330 const fs = yield* FileSystem.FileSystem
331 const sizeAfterKill = (yield* fs.stat(marker)).size
332 yield* liveSleep(100)
333 const finalSize = (yield* fs.stat(marker)).size
334 assert.strictEqual(finalSize, sizeAfterKill)
335 })
336
337 const timed = Effect.fnUntraced(function*<A, E, R>(effect: Effect.Effect<A, E, R>) {
338 const start = Date.now()
339 yield* effect
340 return Date.now() - start
341 })
342
343 describe.skipIf(process.platform === "win32")("process group cleanup", () => {
344 it.live("scope release cleans descendants after the leader exits successfully", () =>
345 Effect.gen(function*() {
346 const fs = yield* FileSystem.FileSystem
347 const { descendantPid, handle, marker, scope } = yield* startProcessGroup("exit-on-signal", { stdin: "pipe" })
348 yield* Effect.addFinalizer(() => killDescendant(descendantPid))
349
350 yield* Stream.run(Stream.make(new TextEncoder().encode("exit\n")), handle.stdin)
351 assert.strictEqual(yield* handle.exitCode, 0)
352 assert.doesNotThrow(() => process.kill(descendantPid, 0), "descendant must still be alive after the leader exits")
353 assert.isFalse(yield* fs.exists(marker))
354
355 yield* Scope.close(scope, Exit.void)
356
357 assert.strictEqual(yield* fs.readFileString(marker), "exited")
358 }).pipe(Effect.scoped, Effect.provide(NodeServices)))
359
360 it.live("scope release force kills descendants after the leader exits with a non-zero code", () =>
361 Effect.gen(function*() {
362 const { descendantPid, handle, marker, scope } = yield* startProcessGroup("ignore-signal", {
363 stdin: "pipe",
364 forceKillAfter: "200 millis"
365 })
366 yield* Effect.addFinalizer(() => killDescendant(descendantPid))
367
368 yield* Stream.run(Stream.make(new TextEncoder().encode("exit 1\n")), handle.stdin)
369 assert.strictEqual(yield* handle.exitCode, 1)
370
371 yield* Scope.close(scope, Exit.void).pipe(liveTimeout(2_000))
372
373 yield* assertHeartbeatStopped(marker)
374 }).pipe(Effect.scoped, Effect.provide(NodeServices)))
375
376 it.live("scope release cleans descendants after the leader is killed externally", () =>
377 Effect.gen(function*() {
378 const fs = yield* FileSystem.FileSystem
379 const { descendantPid, handle, marker, scope } = yield* startProcessGroup("exit-on-signal")
380 yield* Effect.addFinalizer(() => killDescendant(descendantPid))
381
382 process.kill(handle.pid, "SIGKILL")
383 assert.isTrue(Exit.isFailure(yield* Effect.exit(handle.exitCode)))
384 assert.doesNotThrow(() => process.kill(descendantPid, 0), "descendant must survive the leader's SIGKILL")
385 assert.isFalse(yield* fs.exists(marker))
386
387 yield* Scope.close(scope, Exit.void)
388
389 assert.isTrue(yield* fs.exists(marker), "scope release must wait for the descendant's exit marker")
390 assert.strictEqual(yield* fs.readFileString(marker), "exited")
391 }).pipe(Effect.scoped, Effect.provide(NodeServices)))
392
393 it.live("scope release waits for descendants that outlive the leader", () =>
394 Effect.gen(function*() {
395 const fs = yield* FileSystem.FileSystem
396 const { handle, marker, scope } = yield* startProcessGroup("exit-on-signal")
397
398 yield* Scope.close(scope, Exit.void)
399
400 assert.isFalse(yield* handle.isRunning)
401 assert.isTrue(yield* fs.exists(marker))
402 }).pipe(Effect.scoped, Effect.provide(NodeServices)))
403
404 it.live("scope release drains descendants after a slow leader exits", () =>
405 Effect.gen(function*() {
406 const fs = yield* FileSystem.FileSystem
407 const { descendantPid, handle, marker, scope } = yield* startProcessGroup("exit-on-signal", undefined, {
408 leader: 1_500,
409 descendant: 2_000
410 })
411 yield* Effect.addFinalizer(() => killDescendant(descendantPid))
412
413 const releaseMillis = yield* timed(Scope.close(scope, Exit.void))
414
415 assert.isAtLeast(releaseMillis, 1_500)
416 assert.isFalse(yield* handle.isRunning)
417 assert.isTrue(yield* fs.exists(marker), "scope release must wait for the descendant's exit marker")
418 assert.strictEqual(yield* fs.readFileString(marker), "exited")
419 }).pipe(Effect.provide(NodeServices)))
420
421 it.live("scope release force kills descendants that ignore the kill signal", () =>
422 Effect.gen(function*() {
423 const { marker, scope } = yield* startProcessGroup("ignore-signal", { forceKillAfter: "200 millis" })
424
425 yield* Scope.close(scope, Exit.void)
426
427 yield* assertHeartbeatStopped(marker)
428 }).pipe(Effect.scoped, Effect.provide(NodeServices)))
429
430 it.live("kill force kills descendants that ignore the kill signal", () =>
431 Effect.gen(function*() {
432 const { handle, marker, scope } = yield* startProcessGroup("ignore-signal")
433
434 yield* handle.kill({ forceKillAfter: "200 millis" })
435
436 assert.isFalse(yield* handle.isRunning)
437 yield* assertHeartbeatStopped(marker)
438 yield* Scope.close(scope, Exit.void)
439 }).pipe(Effect.scoped, Effect.provide(NodeServices)))
440
441 it.effect("forceKillAfter escalation does not depend on the Effect clock", () =>
442 Effect.gen(function*() {
443 const { marker, scope } = yield* startProcessGroup("ignore-signal", { forceKillAfter: "200 millis" })
444
445 const releaseMillis = yield* timed(Scope.close(scope, Exit.void))
446
447 assert.isBelow(releaseMillis, 2_000)
448 yield* assertHeartbeatStopped(marker)
449 }).pipe(Effect.scoped, Effect.provide(NodeServices)))
450
451 it.live("scope release returns when a descendant holds the inherited pipe without forceKillAfter", () =>
452 Effect.gen(function*() {
453 const { descendantPid, handle, scope } = yield* startProcessGroup("ignore-signal")
454
455 yield* Effect.gen(function*() {
456 const releaseMillis = yield* timed(Scope.close(scope, Exit.void))
457
458 assert.isFalse(yield* handle.isRunning)
459 assert.isAtLeast(releaseMillis, 1_000)
460 assert.isBelow(releaseMillis, 3_000)
461 }).pipe(Effect.ensuring(killDescendant(descendantPid)))
462 }).pipe(Effect.scoped, Effect.provide(NodeServices)))
463 })
464
465 it.live("scope release returns when stdout is unread and backpressured", () =>
466 Effect.gen(function*() {
467 const releaseMillis = yield* timed(Effect.scoped(Effect.gen(function*() {
468 yield* ChildProcess.make(process.execPath, [
469 "-e",
470 "process.stdout.write(\"x\".repeat(1024 * 1024)); setInterval(() => {}, 1000)"
471 ], { stdin: "ignore" })
472 yield* Effect.sleep("100 millis")
473 })))
474
475 assert.isBelow(releaseMillis, 2_000)
476 }).pipe(Effect.provide(NodeServices)))