7
import { assertDefined } from '@effect/vitest/utils';
8
import * as BunServices from '@effect/platform-bun/BunServices';
9
import * as Path from 'effect/Path';
10
-import { ConfigProvider, Deferred, Effect, Fiber, Layer, Runtime, Sink, Stream } from 'effect';
10
+import {
11
+ Cause,
12
+ ConfigProvider,
13
+ Deferred,
14
+ Effect,
15
+ Exit,
16
+ Fiber,
17
+ Layer,
18
+ Option,
19
+ PlatformError,
20
+ Runtime,
21
+ Sink,
22
+ Stream,
23
+} from 'effect';
24
+import { TestClock } from 'effect/testing';
25
import { ChildProcess, ChildProcessSpawner } from 'effect/process';
12
-import { afterEach, it, vi } from 'vitest';
26
+import { afterEach, beforeEach, it, vi } from 'vitest';
27
import { createCliCommandTelemetryContext } from 'src/analytics/events';
28
import { buildRunHelpersSource, inferCliInvocationPrefix } from 'src/commands/run.cmd';
29
import {
42
import { cli, MockConsole, TestLive } from 'test/__utils__';
43
import { exitCodeOf } from 'test/__utils__/exit-code';
44
import { CommandRunner } from 'src/services/command-runner';
31
-import { ChildProcessExited } from 'src/effects/child-process-exited';
45
+import { ChildProcessExited, ChildProcessSignaled } from 'src/effects/child-process-exited';
46
+import { ExitAction, exitActionFor } from 'src/run-main';
47
+import {
48
+ makeShutdownController,
49
+ ShutdownSignal,
50
+ type ShutdownController,
51
+ type TerminationSignal,
52
+} from 'src/services/shutdown-signal';
53
54
const enabledRuntimeFlagsConfigProvider = ConfigProvider.fromEnvRecord({
55
COMPOSIO_RUN_ACP_ONLY: '1',
75
const SCRIPT = 'console.log("hi")';
76
const SCRIPT_FLAGS = ['--perf-debug', '--tool-debug', '--telemetry-debug', '--help', '--version'];
77
57
-const commandRuns = vi.fn((_: ChildProcess.Command) =>
58
- Effect.succeed(ChildProcessSpawner.ExitCode(0))
78
+const commandRuns = vi.fn(
79
+ (
80
+ _: ChildProcess.Command
81
+ ): Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError> =>
82
+ Effect.succeed(ChildProcessSpawner.ExitCode(0))
83
);
84
+/** Whether the stub child is still running, which the escalation after a signal checks. */
85
+const childRunning = vi.fn(() => false);
86
87
// `composio run` starts the child through the platform `ChildProcessSpawner` so it owns the
88
// pid it forwards signals to, so the stub has to replace the spawner rather than
94
ChildProcessSpawner.makeHandle({
95
pid: ChildProcessSpawner.ProcessId(STUB_CHILD_PID),
96
exitCode: Effect.suspend(() => commandRuns(command)),
71
- isRunning: Effect.succeed(false),
97
+ isRunning: Effect.sync(() => childRunning()),
98
kill: () => Effect.void,
99
stdin: Sink.drain,
100
stdout: Stream.empty,
140
commandRuns
141
.mockReset()
142
.mockImplementation(() => Effect.succeed(ChildProcessSpawner.ExitCode(0)));
143
+ childRunning.mockReset().mockImplementation(() => false);
144
vi.unstubAllGlobals();
145
vi.restoreAllMocks();
146
});
171
);
172
});
173
147
- layer(RunTestLive())(it => {
148
- it.effect(
149
- '[Given] a terminal interrupt [Then] it forwards the signal to the child process group and unregisters its handlers',
150
- () =>
174
+ describe('signals', () => {
175
+ // The runner's controller for this run: the test delivers the CLI's signals through it.
176
+ let controller: ShutdownController = makeShutdownController();
177
+ const signalled: Array<readonly [number, string]> = [];
178
+ // Completes once `process.kill` received each signal, so a test can wait for delivery.
179
+ let delivered = new Map<string, Deferred.Deferred<void>>();
180
+ const deliveryOf = (signal: string) => {
181
+ const deferred = delivered.get(signal) ?? Deferred.makeUnsafe<void>();
182
+ delivered.set(signal, deferred);
183
+ return deferred;
184
+ };
185
+
186
+ beforeEach(() => {
187
+ controller = makeShutdownController();
188
+ signalled.length = 0;
189
+ delivered = new Map();
190
+ vi.spyOn(process, 'kill').mockImplementation((pid, signal) => {
191
+ signalled.push([Number(pid), String(signal)]);
192
+ Deferred.doneUnsafe(deliveryOf(String(signal)), Effect.void);
193
+ return true;
194
+ });
195
+ });
196
+
197
+ /** `composio run` with the CLI receiving `signal` while the child runs. */
198
+ const runWithSignals = Effect.suspend(() =>
199
+ Effect.exit(
200
+ cli(['run', 'console.log("hi")']).pipe(
201
+ Effect.provideService(ShutdownSignal, controller.service)
202
+ )
203
+ )
204
+ );
205
+
206
+ /** A child that, once the CLI took `signal`, waits for it and then ends with `ends`. */
207
+ const childEndingAfter = (
208
+ signal: 'SIGINT' | 'SIGTERM' | 'SIGHUP',
209
+ ends: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>
210
+ ) =>
211
+ commandRuns.mockImplementation(() =>
212
+ Effect.sync(() => expect(controller.offer(signal)).toBe(true)).pipe(
213
+ Effect.andThen(Deferred.await(deliveryOf(signal))),
214
+ Effect.andThen(ends)
215
+ )
216
+ );
217
+
218
+ /** The spawner's failure for a child a signal ended. */
219
+ const killedBy = (signal: TerminationSignal) =>
220
+ Effect.fail(
221
+ PlatformError.systemError({
222
+ _tag: 'Unknown',
223
+ module: 'ChildProcess',
224
+ method: 'exitCode',
225
+ cause: new Error(`Process interrupted due to receipt of signal: '${signal}'`),
226
+ })
227
+ );
228
+
229
+ layer(RunTestLive())(it => {
230
+ it.effect.each(['SIGINT', 'SIGTERM', 'SIGHUP'] as const)(
231
+ '[Given] the CLI receives %s [Then] it forwards it to the child process group',
232
+ signal =>
233
+ Effect.gen(function* () {
234
+ childEndingAfter(signal, Effect.succeed(ChildProcessSpawner.ExitCode(0)));
235
+
236
+ const exit = yield* runWithSignals;
237
+
238
+ // Negative pid: the detached child leads its own process group.
239
+ expect(signalled).toEqual([[-STUB_CHILD_PID, signal]]);
240
+ // A script that handles the signal and exits 0 makes the run succeed.
241
+ expect(exitCodeOf(exit)).toBe(0);
242
+ })
243
+ );
244
+
245
+ it.effect(
246
+ '[Given] the child exits non-zero after the signal [Then] the run mirrors its code',
247
+ () =>
248
+ Effect.gen(function* () {
249
+ childEndingAfter('SIGINT', Effect.succeed(ChildProcessSpawner.ExitCode(7)));
250
+
251
+ const exit = yield* runWithSignals;
252
+
253
+ expect(exitCodeOf(exit)).toBe(7);
254
+ })
255
+ );
256
+
257
+ it.effect('[Given] the signal ends the child [Then] the runner re-raises that signal', () =>
258
Effect.gen(function* () {
152
- const signalled: Array<readonly [number, string]> = [];
153
- vi.spyOn(process, 'kill').mockImplementation((pid, signal) => {
154
- signalled.push([Number(pid), String(signal)]);
155
- return true;
156
- });
259
+ childEndingAfter('SIGTERM', killedBy('SIGTERM'));
260
158
- const sigintBaseline = process.listenerCount('SIGINT');
159
- const sigtermBaseline = process.listenerCount('SIGTERM');
160
- const registeredWhileRunning: Array<{ sigint: number; sigterm: number }> = [];
161
-
162
- commandRuns.mockImplementation(() =>
163
- Effect.sync(() => {
164
- registeredWhileRunning.push({
165
- sigint: process.listenerCount('SIGINT') - sigintBaseline,
166
- sigterm: process.listenerCount('SIGTERM') - sigtermBaseline,
167
- });
168
- // Stand in for the terminal delivering Ctrl-C to the CLI only: the child is
169
- // detached into its own process group and never sees it directly.
170
- process
171
- .listeners('SIGINT')
172
- .slice(sigintBaseline)
173
- .forEach(listener => listener('SIGINT'));
174
- return ChildProcessSpawner.ExitCode(0);
175
- })
261
+ const exit = yield* runWithSignals;
262
+ const failure = Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
263
+
264
+ expect(failure).toBeInstanceOf(ChildProcessSignaled);
265
+ expect(Runtime.getErrorReported(failure)).toBe(false);
266
+ expect(exitActionFor(exit, Option.some('SIGTERM'))).toEqual(
267
+ ExitAction.Reraise({ signal: 'SIGTERM' })
268
);
269
+ })
270
+ );
271
178
- yield* cli(['run', 'console.log("hi")']);
272
+ it.effect(
273
+ '[Given] a child that ignores the signal [Then] it gets SIGTERM, then SIGKILL, and the run ends by the first signal',
274
+ () =>
275
+ Effect.gen(function* () {
276
+ childRunning.mockImplementation(() => true);
277
+ const killed = deliveryOf('SIGKILL');
278
+ childEndingAfter(
279
+ 'SIGINT',
280
+ Deferred.await(killed).pipe(Effect.andThen(killedBy('SIGKILL')))
281
+ );
282
180
- expect(registeredWhileRunning[0]).toEqual({ sigint: 1, sigterm: 1 });
181
- // Negative pid: the detached child leads its own process group.
182
- expect(signalled).toEqual([[-STUB_CHILD_PID, 'SIGINT']]);
183
- expect(process.listenerCount('SIGINT')).toBe(sigintBaseline);
184
- expect(process.listenerCount('SIGTERM')).toBe(sigtermBaseline);
185
- })
186
- );
283
+ const fiber = yield* Effect.forkChild(runWithSignals);
284
+ yield* Deferred.await(deliveryOf('SIGINT'));
285
+ yield* TestClock.adjust('2 seconds');
286
+ yield* Deferred.await(deliveryOf('SIGTERM'));
287
+ yield* TestClock.adjust('2 seconds');
288
+ const exit = yield* Fiber.join(fiber);
289
+
290
+ expect(signalled).toEqual([
291
+ [-STUB_CHILD_PID, 'SIGINT'],
292
+ [-STUB_CHILD_PID, 'SIGTERM'],
293
+ [-STUB_CHILD_PID, 'SIGKILL'],
294
+ ]);
295
+ // The CLI's own SIGKILL ended the script; the user cancelled with SIGINT.
296
+ expect(exitActionFor(exit, Option.some('SIGINT'))).toEqual(
297
+ ExitAction.Reraise({ signal: 'SIGINT' })
298
+ );
299
+ })
300
+ );
301
+
302
+ it.effect(
303
+ '[Given] a child that crashes by another signal during the escalation [Then] the run ends by that signal',
304
+ () =>
305
+ Effect.gen(function* () {
306
+ childRunning.mockImplementation(() => true);
307
+ // The script ignores SIGINT, then aborts while cleaning up after the CLI's SIGTERM.
308
+ childEndingAfter(
309
+ 'SIGINT',
310
+ Deferred.await(deliveryOf('SIGTERM')).pipe(Effect.andThen(killedBy('SIGABRT')))
311
+ );
312
+
313
+ const fiber = yield* Effect.forkChild(runWithSignals);
314
+ yield* Deferred.await(deliveryOf('SIGINT'));
315
+ yield* TestClock.adjust('2 seconds');
316
+ const exit = yield* Fiber.join(fiber);
317
+ const failure = Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
318
+
319
+ expect(signalled).toEqual([
320
+ [-STUB_CHILD_PID, 'SIGINT'],
321
+ [-STUB_CHILD_PID, 'SIGTERM'],
322
+ ]);
323
+ // The crash is the script's own, not the user's cancellation.
324
+ expect(failure).toBeInstanceOf(ChildProcessSignaled);
325
+ expect(exitActionFor(exit, Option.some('SIGINT'))).toEqual(
326
+ ExitAction.Reraise({ signal: 'SIGABRT' })
327
+ );
328
+ })
329
+ );
330
+
331
+ it.effect(
332
+ '[Given] a second signal [Then] forcing the exit kills the child group and re-raises',
333
+ () =>
334
+ Effect.gen(function* () {
335
+ const forced = yield* Deferred.make<{ readonly reraise: boolean }>();
336
+ commandRuns.mockImplementation(() =>
337
+ Effect.sync(() => {
338
+ controller.offer('SIGINT');
339
+ // What the runner does on the second signal, while the child still runs.
340
+ Deferred.doneUnsafe(forced, Effect.succeed(controller.force()));
341
+ return ChildProcessSpawner.ExitCode(0);
342
+ })
343
+ );
344
+
345
+ yield* runWithSignals;
346
+
347
+ expect(yield* Deferred.await(forced)).toEqual({ reraise: true });
348
+ expect(signalled).toContainEqual([-STUB_CHILD_PID, 'SIGKILL']);
349
+ })
350
+ );
351
+ });
352
});
353
354
layer(RunTestLive())(it => {