@devries-cameron20 / composio Mirror · read-only / commits / 222e32751
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 07:15 UTC

feat(cli): add `--fail-fast` to `listen` and `dev listen` (#5071)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/5040 (merged) - adds `--fail-fast` to `composio listen`, `composio dev listen` and `composio dev triggers listen`: the listener stops at the first event it fails to save, forward, or append to `--out`, prints the failure count on stderr, and exits 1 - leaves the default unchanged: without the flag a failed event is warned about, counted in the stop summary, and the exit code stays 0 - adds `makeSinkFailures` (`src/commands/triggers/sink-failures.ts`), which both listeners now use to count failures per sink and print the summary, replacing their duplicated counters - races each listener against its stop signal even without `--max-events` or `--timeout`, so `--fail-fast` can end an unbounded run - documents the flag in the bundled `composio-cli` skill and the CLI changelog - tests an unbounded `listen --fail-fast` with failing payload writes and an unbounded `dev listen --fail-fast` with a refused forward: both stop on their own and exit 1, and both fail when the stop or the exit code is removed ## Context https://github.com/ComposioHQ/composio/pull/5040 made per-event failures visible to piped callers but kept bounded runs at exit 0 ("the listener still never fails over one event"), so a script that checks only `$?` after `--max-events` or `--timeout` treats a run that lost events as a success. `kafka-console-consumer` exits 1 on a failed message unless `--skip-message-on-error` is passed; this keeps our default and makes the strict behavior opt-in.

Alberto Schiabel committed Oct 22, 2026 at 21:39 UTC 222e32751c36028217b85df8e7625a989acd3440
8 files changed +390 -87
ts/packages/cli/CHANGELOG.md
+8
@@ -2,6 +2,14 @@
2
3 ## Unreleased
4
5 +### Minor Changes
6 +
7 +- `composio listen`, `composio dev listen` and `composio dev triggers listen`
8 + gain `--fail-fast`: the listener stops at the first event it fails to save,
9 + forward, or append to `--out`, prints how many events failed on stderr, and
10 + exits 1. Without it, a failed event is still reported and skipped, and the
11 + exit code stays 0.
12 +
13 ### Patch Changes
14
15 - `composio connections list` now prints each account's `id`, its `alias`
ts/packages/cli/skills-src/composio-cli/index.ts
+5
@@ -168,6 +168,11 @@ const commands: SkillCommand[] = [
168 name: '`--timeout` and `--max-events`',
169 description: 'Stop long-running listeners cleanly.',
170 },
171 + {
172 + name: '`--fail-fast`',
173 + description:
174 + 'Stop at the first event that fails to save and exit 1, so a bounded run that lost events is not a success.',
175 + },
176 {
177 name: '`--account`',
178 description: 'Select which connected account to use by alias, word_id, or account id.',
ts/packages/cli/src/commands/listen.cmd.ts
+39 -30
@@ -1,11 +1,12 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 import { reportFailure } from 'src/effects/report-failure';
3 +import { eventCount, finishAcceptedEvents, makeSinkFailures } from './triggers/sink-failures';
4 import { commandInputError } from 'src/commands/errors';
5 import { Argument, Command, Flag } from 'effect/cli';
6 import * as FileSystem from 'effect/FileSystem';
7 import * as Path from 'effect/Path';
8 import type { ComposioClientShape } from '@composio/client/effect';
8 -import { Data, Deferred, Effect, Result, Option, Predicate } from 'effect';
9 +import { Data, Deferred, Effect, FiberSet, Result, Option, Predicate } from 'effect';
10 import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
11 import { ComposioClientSingleton, type ToolkitProjectScope } from 'src/services/composio-clients';
12 import { resolveCommandProject } from 'src/services/command-project';
@@ -86,6 +87,11 @@ const account = Flag.String('account').pipe(
87 Flag.optional
88 );
89
90 +const failFast = Flag.Boolean('fail-fast').pipe(
91 + Flag.withDescription('Stop at the first event that fails to save, and exit 1'),
92 + Flag.withDefault(false)
93 +);
94 +
95 const debug = Flag.Boolean('debug').pipe(
96 Flag.withDescription(
97 'Print verbose debug information (raw events, filter results, Pusher state)'
@@ -507,13 +513,12 @@ const resolveListenSetup = (params: {
513
514 export const listenCmd = Command.make(
515 'listen',
510 - { slug, params, maxEvents, timeout, stream, account, debug },
511 - ({ slug, params, maxEvents, timeout, stream, account, debug }) =>
516 + { slug, params, maxEvents, timeout, stream, account, failFast, debug },
517 + ({ slug, params, maxEvents, timeout, stream, account, failFast, debug }) =>
518 Effect.gen(function* () {
519 const ui = yield* TerminalUI;
520 const fs = yield* FileSystem.FileSystem;
521 const path = yield* Path.Path;
516 - const services = yield* Effect.context<never>();
522 const clientSingleton = yield* ComposioClientSingleton;
523 const realtime = yield* TriggersRealtime;
524
@@ -559,24 +564,20 @@ export const listenCmd = Command.make(
564 yield* fs.makeDirectory(triggerDir, { recursive: true });
565 yield* fs.writeFileString(streamFilePath, '', { flag: 'a' });
566
562 - const stopWhenDone = yield* Deferred.make<'max-events' | 'timeout'>();
567 + const stopWhenDone = yield* Deferred.make<'max-events' | 'timeout' | 'failed'>();
568 + // Its own signal, so a --fail-fast failure also ends finishAcceptedEvents' wait.
569 + const failed = yield* Deferred.make<void>();
570 let matchingEvents = 0;
564 - // Per-event write failures are recovered so one bad event never stops the listener; they
565 - // are counted here and summed up on plain stderr on every stop — including Ctrl+C and
566 - // SIGTERM, which runMain turns into a fiber interruption — since a piped caller sees
567 - // none of the `ui.log.warn` decoration. The release hook below runs on all of them.
568 - let eventWriteFailures = 0;
569 - const recordWriteFailure = (error: unknown) =>
570 - Effect.gen(function* () {
571 - eventWriteFailures += 1;
572 - yield* ui.log.warn(errorMessage(error));
573 - });
574 - const reportWriteFailures = () =>
575 - eventWriteFailures > 0
576 - ? ui.error(
577 - `${eventWriteFailures} event${eventWriteFailures === 1 ? '' : 's'} failed to write while listening.`
578 - )
579 - : Effect.void;
571 + const writeFailures = makeSinkFailures({
572 + ui,
573 + failFast,
574 + stop: Effect.andThen(
575 + Deferred.succeed(failed, undefined),
576 + Deferred.succeed(stopWhenDone, 'failed')
577 + ).pipe(Effect.asVoid),
578 + summary: count => `${eventCount(count)} failed to write while listening.`,
579 + });
580 + const recordWriteFailure = (error: unknown) => writeFailures.record(errorMessage(error));
581 const seenEventIds = new Set<string>();
582
583 yield* Effect.acquireUseRelease(
@@ -602,6 +603,10 @@ export const listenCmd = Command.make(
603 ),
604 createdTrigger =>
605 Effect.gen(function* () {
606 + // Scoped below: a stop other than --max-events or --timeout interrupts the event
607 + // callbacks still running before the release hook sums up.
608 + const events = yield* FiberSet.make();
609 + const runEvent = yield* FiberSet.runtime(events)();
610 yield* emitStreamLine(`listening for events ${slug} (tail at ${streamFilePath})`, ui);
611 if (debug) {
612 const debugMsg =
@@ -618,7 +623,7 @@ export const listenCmd = Command.make(
623 }
624
625 const onEvent = (eventData: Record<string, unknown>) => {
621 - Effect.runForkWith(services)(
626 + runEvent(
627 Effect.gen(function* () {
628 if (debug) {
629 yield* emitStreamLine(
@@ -709,11 +714,12 @@ export const listenCmd = Command.make(
714 );
715 }
716
712 - if (maxEventsLimit === undefined && timeoutMs === undefined) {
713 - return yield* listenEffect;
714 - }
715 -
717 + // Without --max-events, --timeout or --fail-fast nothing resolves stopWhenDone, so
718 + // this waits on the listener until it is interrupted.
719 const stopReason = yield* Effect.raceFirst(listenEffect, Deferred.await(stopWhenDone));
720 + if (stopReason === 'max-events' || stopReason === 'timeout') {
721 + yield* finishAcceptedEvents(events, failed);
722 + }
723 if (stopReason === 'max-events') {
724 yield* ui.outro(
725 formatStopMessage({
@@ -734,15 +740,15 @@ export const listenCmd = Command.make(
740 })
741 );
742 }
737 - }),
743 + }).pipe(Effect.scoped),
744 created =>
745 Effect.gen(function* () {
746 if (created !== null) {
747 yield* disableTemporaryTrigger({ client, ui, slug, triggerId: created.trigger_id });
748 }
743 - // Runs on every stop of the use phase — max-events, timeout, and the interruption
744 - // of an unlimited wait — so a piped caller always gets the failure count.
745 - yield* reportWriteFailures();
749 + // Runs on every stop of the use phase — max-events, timeout, --fail-fast, and the
750 + // interruption by Ctrl+C or SIGTERM — so a piped caller always gets the count.
751 + yield* writeFailures.report;
752 })
753 ).pipe(
754 Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>
@@ -767,6 +773,9 @@ export const listenCmd = Command.make(
773 {
774 command: 'composio listen GMAIL_NEW_GMAIL_MESSAGE --account work --timeout 5m',
775 },
776 + {
777 + command: 'composio listen GMAIL_NEW_GMAIL_MESSAGE --max-events 5 --fail-fast',
778 + },
779 {
780 command: "composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 1hr --stream '.data.threadId'",
781 },
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+66 -57
@@ -1,9 +1,10 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 import { reportFailure } from 'src/effects/report-failure';
3 +import { eventCount, finishAcceptedEvents, makeSinkFailures } from '../sink-failures';
4 import { Command, Flag } from 'effect/cli';
5 import * as FileSystem from 'effect/FileSystem';
6 import * as Path from 'effect/Path';
6 -import { Deferred, Effect, Option } from 'effect';
7 +import { Deferred, Effect, FiberSet, Option } from 'effect';
8 import { APP_CONFIG } from 'src/config';
9 import { CommandSurface, resolveSurfaceProject } from 'src/commands/surface';
10 import { TerminalUI } from 'src/services/terminal-ui';
@@ -67,6 +68,16 @@ const out = Flag.String('out').pipe(
68 Flag.optional
69 );
70
71 +const failFast = Flag.Boolean('fail-fast').pipe(
72 + Flag.withDescription(
73 + 'Stop at the first event that fails to forward or to append to --out, and exit 1'
74 + ),
75 + Flag.withDefault(false)
76 +);
77 +
78 +/** Runs one event's callback on a fiber the listener interrupts when it stops. */
79 +type RunEvent = (effect: Effect.Effect<void>) => unknown;
80 +
81 const randomUUID = () => crypto.randomUUID();
82
83 const signWebhookPayload = async ({
@@ -148,6 +159,7 @@ export const triggersCmd$Listen = Command.make(
159 maxEvents,
160 forward,
161 out,
162 + failFast,
163 },
164 ({
165 toolkits,
@@ -159,6 +171,7 @@ export const triggersCmd$Listen = Command.make(
171 maxEvents,
172 forward,
173 out,
174 + failFast,
175 }) =>
176 Effect.gen(function* () {
177 const surface = yield* CommandSurface;
@@ -168,7 +181,6 @@ export const triggersCmd$Listen = Command.make(
181 const fs = yield* FileSystem.FileSystem;
182 const path = yield* Path.Path;
183 const realtime = yield* TriggersRealtime;
171 - const services = yield* Effect.context<never>();
184 const forwardUrl = Option.getOrUndefined(forward);
185 const generatedWebhookSecret = `composio-forward-secret-${randomUUID()}`;
186 const configuredWebhookSecret = yield* APP_CONFIG.WEBHOOK_SECRET;
@@ -192,14 +204,28 @@ export const triggersCmd$Listen = Command.make(
204 };
205
206 const maxEventsLimit = Option.getOrUndefined(maxEvents);
195 - const stopWhenDone = yield* Deferred.make<void>();
207 + const stopWhenDone = yield* Deferred.make<'max-events' | 'failed'>();
208 let matchingEvents = 0;
197 - // Per-event failures are recovered so one bad event never stops the listener; they are
198 - // counted here and summed up on plain stderr on every stop — including Ctrl+C and
199 - // SIGTERM, which runMain turns into a fiber interruption — since a piped caller sees
200 - // none of the `ui.log.warn` decoration.
201 - let outputWriteFailures = 0;
202 - let forwardFailures = 0;
209 + // Its own signal, so a --fail-fast failure also ends finishAcceptedEvents' wait.
210 + const failed = yield* Deferred.make<void>();
211 + const stopOnFailure = Effect.andThen(
212 + Deferred.succeed(failed, undefined),
213 + Deferred.succeed(stopWhenDone, 'failed')
214 + ).pipe(Effect.asVoid);
215 + const forwardFailures = makeSinkFailures({
216 + ui,
217 + failFast,
218 + stop: stopOnFailure,
219 + summary: count =>
220 + `${eventCount(count)} failed to forward to ${forwardUrl} while listening.`,
221 + });
222 + const outputWriteFailures = makeSinkFailures({
223 + ui,
224 + failFast,
225 + stop: stopOnFailure,
226 + summary: count =>
227 + `${eventCount(count)} failed to append to ${outputFilePath} while listening.`,
228 + });
229 let tableHeaderPrinted = false;
230
231 yield* ui.intro('composio dev triggers listen');
@@ -228,8 +254,8 @@ export const triggersCmd$Listen = Command.make(
254 yield* ui.log.info(`Auto-stop after ${maxEventsLimit} matching events.`);
255 }
256
231 - const onEvent = (eventData: Record<string, unknown>) => {
232 - Effect.runForkWith(services)(
257 + const onEvent = (runEvent: RunEvent) => (eventData: Record<string, unknown>) => {
258 + runEvent(
259 Effect.gen(function* () {
260 const parsed = parseTriggerListenEvent(eventData);
261 if (!matchesTriggerListenFilters(filters, parsed)) {
@@ -266,14 +292,9 @@ export const triggersCmd$Listen = Command.make(
292 const logLine = `${payloadForForwarding}\n`;
293
294 if (outputFilePath) {
269 - yield* fs.writeFileString(outputFilePath, logLine, { flag: 'a' }).pipe(
270 - Effect.catch(error =>
271 - Effect.gen(function* () {
272 - outputWriteFailures += 1;
273 - yield* ui.log.warn(String(error));
274 - })
275 - )
276 - );
295 + yield* fs
296 + .writeFileString(outputFilePath, logLine, { flag: 'a' })
297 + .pipe(Effect.catch(error => outputWriteFailures.record(String(error))));
298 }
299
300 if (forwardUrl && webhookSecret) {
@@ -315,60 +336,48 @@ export const triggersCmd$Listen = Command.make(
336 catch: error =>
337 new Error(`Failed forwarding event to ${forwardUrl}: ${String(error)}`),
338 });
318 - }).pipe(
319 - Effect.catch(error =>
320 - Effect.gen(function* () {
321 - forwardFailures += 1;
322 - yield* ui.log.warn(String(error));
323 - })
324 - )
325 - );
339 + }).pipe(Effect.catch(error => forwardFailures.record(String(error))));
340 }
341
342 if (maxEventsLimit !== undefined && matchingEvents >= maxEventsLimit) {
329 - yield* Deferred.succeed(stopWhenDone, undefined).pipe(Effect.ignore);
343 + yield* Deferred.succeed(stopWhenDone, 'max-events').pipe(Effect.ignore);
344 }
345 })
346 );
347 };
348
349 // The default credentials serve the configured project; a named one needs its own.
336 - const listenEffect = (
337 - Option.isSome(surface.projectName)
350 + const listenEffect = (runEvent: RunEvent) =>
351 + (Option.isSome(surface.projectName)
352 ? realtime.listenInProject(
353 { orgId: project.orgId, projectId: project.projectId },
340 - onEvent
354 + onEvent(runEvent)
355 )
342 - : realtime.listen(onEvent)
343 - ).pipe(
344 - Effect.onInterrupt(() => ui.log.info('Stopped listening for realtime trigger events.'))
345 - );
346 -
347 - // The summary runs in an onExit finalizer, so it fires on every stop — including the
348 - // interruption of an unlimited wait, where the code after this block would not run.
349 - const reportSinkFailures = () =>
350 - Effect.gen(function* () {
351 - if (forwardFailures > 0) {
352 - yield* ui.error(
353 - `${forwardFailures} event${forwardFailures === 1 ? '' : 's'} failed to forward to ${forwardUrl} while listening.`
354 - );
355 - }
356 - if (outputWriteFailures > 0) {
357 - yield* ui.error(
358 - `${outputWriteFailures} event${outputWriteFailures === 1 ? '' : 's'} failed to append to ${outputFilePath} while listening.`
359 - );
360 - }
361 - });
356 + : realtime.listen(onEvent(runEvent))
357 + ).pipe(
358 + Effect.onInterrupt(() => ui.log.info('Stopped listening for realtime trigger events.'))
359 + );
360
361 yield* Effect.gen(function* () {
364 - if (maxEventsLimit === undefined) {
365 - return yield* listenEffect;
362 + // Scoped below: a stop other than --max-events interrupts the event callbacks still
363 + // running before the summaries print.
364 + const events = yield* FiberSet.make();
365 + const runEvent = yield* FiberSet.runtime(events)();
366 + // Without --max-events or --fail-fast nothing resolves stopWhenDone, so this waits on
367 + // the listener until it is interrupted.
368 + const stopReason = yield* Effect.raceFirst(
369 + listenEffect(runEvent),
370 + Deferred.await(stopWhenDone)
371 + );
372 + if (stopReason === 'max-events') {
373 + yield* finishAcceptedEvents(events, failed);
374 + yield* ui.outro(`Stopped after receiving ${matchingEvents} matching events.`);
375 }
367 -
368 - yield* Effect.raceFirst(listenEffect, Deferred.await(stopWhenDone));
369 - yield* ui.outro(`Stopped after receiving ${matchingEvents} matching events.`);
376 }).pipe(
371 - Effect.onExit(() => reportSinkFailures()),
377 + Effect.scoped,
378 + // An onExit finalizer, so the summaries print on every stop — including the
379 + // interruption by Ctrl+C or SIGTERM, where the code after this block would not run.
380 + Effect.onExit(() => Effect.andThen(forwardFailures.report, outputWriteFailures.report)),
381 Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>
382 reportFailure(
383 ui,
ts/packages/cli/src/commands/triggers/sink-failures.ts new
+54
@@ -0,0 +1,54 @@
1 +import { Deferred, Effect, FiberSet } from 'effect';
2 +import { reportFailure } from 'src/effects/report-failure';
3 +import type { TerminalUI } from 'src/services/terminal-ui';
4 +
5 +/**
6 + * On a normal stop (`--max-events`, `--timeout`), lets the events the listener already accepted
7 + * finish saving or forwarding, for up to 10 seconds, so the summary counts how they ended. A
8 + * `--fail-fast` failure (`failed`) ends the wait early. The listener's scope then interrupts
9 + * whatever is still running.
10 + */
11 +export const finishAcceptedEvents = (events: FiberSet.FiberSet, failed: Deferred.Deferred<void>) =>
12 + Effect.raceFirst(FiberSet.awaitEmpty(events), Deferred.await(failed)).pipe(
13 + Effect.timeoutOption('10 seconds'),
14 + Effect.asVoid
15 + );
16 +
17 +/** `1 event`, `2 events`. */
18 +export const eventCount = (count: number) => `${count} event${count === 1 ? '' : 's'}`;
19 +
20 +/**
21 + * Counts the events a listener sink (saved payloads, an output file, a forwarding URL) failed to
22 + * take. One failure never fails the listener on its own: `record` logs a warn, and with
23 + * `--fail-fast` it also runs `stop` and ends the event, so no later sink takes it. `report`
24 + * sums the count up on stderr when the listener stops, as a plain line because piped callers
25 + * see none of the `ui.log.*` decoration; with `--fail-fast` it goes through `reportFailure` and
26 + * the CLI exits 1.
27 + */
28 +export const makeSinkFailures = (params: {
29 + readonly ui: TerminalUI;
30 + readonly failFast: boolean;
31 + readonly stop: Effect.Effect<void>;
32 + /** The summary line, e.g. `2 events failed to write while listening.` */
33 + readonly summary: (count: number) => string;
34 +}) => {
35 + let count = 0;
36 + return {
37 + record: (message: string) =>
38 + Effect.gen(function* () {
39 + count += 1;
40 + yield* params.ui.log.warn(message);
41 + if (params.failFast) {
42 + yield* params.stop;
43 + return yield* Effect.interrupt;
44 + }
45 + }),
46 + report: Effect.suspend(() => {
47 + if (count === 0) {
48 + return Effect.void;
49 + }
50 + const summary = params.summary(count);
51 + return params.failFast ? reportFailure(params.ui, summary) : params.ui.error(summary);
52 + }),
53 + };
54 +};
ts/packages/cli/test/src/commands/listen.cmd.test.ts
+14
@@ -193,6 +193,20 @@ describe('CLI: composio listen', () => {
193 })
194 );
195
196 + // No --max-events or --timeout: only --fail-fast can stop this run.
197 + it.effect('[Then] --fail-fast stops at the first failed write and exits 1', () =>
198 + Effect.gen(function* () {
199 + yield* enableListen;
200 + const terminal = redirectedTerminalUI();
201 + yield* cli(['listen', 'composio.connected_account.expired', '--fail-fast']).pipe(
202 + Effect.provide(Layer.merge(payloadWritesFail, terminal.layer))
203 + );
204 +
205 + expect(terminal.stderr()).toContain('1 event failed to write while listening.');
206 + expect(process.exitCode).toBe(1);
207 + })
208 + );
209 +
210 it.effect('[Then] sums the write failures up on stderr when the timeout stops it', () =>
211 Effect.gen(function* () {
212 yield* enableListen;
ts/packages/cli/test/src/commands/triggers/sink-failures.test.ts new
+42
@@ -0,0 +1,42 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Effect, Exit } from 'effect';
3 +import { makeSinkFailures } from 'src/commands/triggers/sink-failures';
4 +import { TerminalUI } from 'src/services/terminal-ui';
5 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
6 +
7 +const recordOneFailure = (failFast: boolean) =>
8 + Effect.gen(function* () {
9 + const ui = yield* TerminalUI;
10 + let stopped = false;
11 + const failures = makeSinkFailures({
12 + ui,
13 + failFast,
14 + stop: Effect.sync(() => {
15 + stopped = true;
16 + }),
17 + summary: count => `${count} failed`,
18 + });
19 + const exit = yield* Effect.exit(failures.record('write failed'));
20 + return { exit, stopped };
21 + }).pipe(Effect.provide(redirectedTerminalUI().layer));
22 +
23 +describe('makeSinkFailures', () => {
24 + // The event must not reach a later sink, e.g. a forward after a failed --out append.
25 + it.effect('[Given] --fail-fast [Then] a failure stops the listener and ends the event', () =>
26 + Effect.gen(function* () {
27 + const { exit, stopped } = yield* recordOneFailure(true);
28 +
29 + expect(stopped).toBe(true);
30 + expect(Exit.hasInterrupts(exit)).toBe(true);
31 + })
32 + );
33 +
34 + it.effect('[Given] no --fail-fast [Then] the event goes on to its next sink', () =>
35 + Effect.gen(function* () {
36 + const { exit, stopped } = yield* recordOneFailure(false);
37 +
38 + expect(stopped).toBe(false);
39 + expect(Exit.isSuccess(exit)).toBe(true);
40 + })
41 + );
42 +});
ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts
+162
@@ -1,9 +1,11 @@
1 +import type { ServerResponse } from 'node:http';
2 import { afterEach } from 'vitest';
3 import { describe, expect, layer } from '@effect/vitest';
4 import { ConfigProvider, Effect, Fiber, Latch, Layer } from 'effect';
5 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
6 import { TriggerRealtimeSubscriptionError, TriggersRealtime } from 'src/services/triggers-realtime';
7 import { cli, TestLive } from 'test/__utils__';
8 +import { withHttpServerEffect } from 'test/__utils__/http-server';
9 import { failingFileWrites } from 'test/__utils__/services/failing-file-writes';
10 import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
11
@@ -98,6 +100,26 @@ describe('CLI: composio dev listen', () => {
100 })
101 );
102
103 + // No --max-events: only --fail-fast can stop this run.
104 + it.effect('[Then] --fail-fast stops at the first failed forward and exits 1', () =>
105 + Effect.gen(function* () {
106 + yield* enableListen;
107 + const terminal = redirectedTerminalUI();
108 + yield* cli([
109 + 'dev',
110 + 'listen',
111 + '--forward',
112 + 'http://127.0.0.1:9/composio',
113 + '--fail-fast',
114 + ]).pipe(Effect.provide(terminal.layer));
115 +
116 + expect(terminal.stderr()).toContain(
117 + '1 event failed to forward to http://127.0.0.1:9/composio while listening.'
118 + );
119 + expect(process.exitCode).toBe(1);
120 + })
121 + );
122 +
123 it.effect('[Then] sums the output-file failures up on stderr when the listener stops', () =>
124 Effect.gen(function* () {
125 yield* enableListen;
@@ -147,4 +169,144 @@ describe('CLI: composio dev listen', () => {
169 })
170 );
171 });
172 +
173 + layer(
174 + TestLive({
175 + baseConfigProvider: testConfigProvider,
176 + fixture: 'global-test-user-id',
177 + realtimeData: {
178 + events: [
179 + {
180 + id: 'evt_conn_expired_1',
181 + type: 'composio.connected_account.expired',
182 + timestamp: '2026-04-06T18:00:00.000Z',
183 + metadata: {
184 + project_id: 'consumer_project_id_test',
185 + org_id: 'org_test',
186 + },
187 + data: {
188 + id: 'con_expired_1',
189 + },
190 + },
191 + {
192 + id: 'evt_conn_expired_2',
193 + type: 'composio.connected_account.expired',
194 + timestamp: '2026-04-06T18:00:00.000Z',
195 + metadata: {
196 + project_id: 'consumer_project_id_test',
197 + org_id: 'org_test',
198 + },
199 + data: {
200 + id: 'con_expired_2',
201 + },
202 + },
203 + ],
204 + },
205 + })
206 + )('[Given] --max-events is reached while another event is still forwarding', it => {
207 + // The target answers the second request at once and fails the first one shortly after, so
208 + // the listener reaches --max-events 2 while the first event is still in flight.
209 + it.effect('[Then] waits for that event and counts its failure', () =>
210 + Effect.gen(function* () {
211 + yield* enableListen;
212 + const terminal = redirectedTerminalUI();
213 + const held: Array<ServerResponse> = [];
214 + yield* withHttpServerEffect(
215 + (_req, res) => {
216 + const first = held.shift();
217 + if (first === undefined) {
218 + held.push(res);
219 + return;
220 + }
221 + res.end();
222 + setTimeout(() => first.writeHead(500).end(), 100);
223 + },
224 + url =>
225 + cli(['dev', 'listen', '--forward', url, '--max-events', '2']).pipe(
226 + Effect.provide(terminal.layer)
227 + )
228 + );
229 +
230 + expect(terminal.stderr()).toMatch(
231 + /1 event failed to forward to http:\/\/127\.0\.0\.1:\d+ while listening\./
232 + );
233 + })
234 + );
235 + });
236 +
237 + layer(
238 + TestLive({
239 + baseConfigProvider: testConfigProvider,
240 + fixture: 'global-test-user-id',
241 + realtimeData: {
242 + events: [
243 + {
244 + id: 'evt_conn_expired_1',
245 + type: 'composio.connected_account.expired',
246 + timestamp: '2026-04-06T18:00:00.000Z',
247 + metadata: {
248 + project_id: 'consumer_project_id_test',
249 + org_id: 'org_test',
250 + },
251 + data: {
252 + id: 'con_expired_1',
253 + },
254 + },
255 + {
256 + id: 'evt_conn_expired_2',
257 + type: 'composio.connected_account.expired',
258 + timestamp: '2026-04-06T18:00:00.000Z',
259 + metadata: {
260 + project_id: 'consumer_project_id_test',
261 + org_id: 'org_test',
262 + },
263 + data: {
264 + id: 'con_expired_2',
265 + },
266 + },
267 + {
268 + id: 'evt_conn_expired_3',
269 + type: 'composio.connected_account.expired',
270 + timestamp: '2026-04-06T18:00:00.000Z',
271 + metadata: {
272 + project_id: 'consumer_project_id_test',
273 + org_id: 'org_test',
274 + },
275 + data: {
276 + id: 'con_expired_3',
277 + },
278 + },
279 + ],
280 + },
281 + })
282 + )('[Given] --fail-fast and an event fails while --max-events waits for the others', it => {
283 + // The target answers the first request, holds the second open, and fails the third shortly
284 + // after, so the failure lands while the listener waits for the held event.
285 + it.effect('[Then] the failure ends the wait and exits 1', () =>
286 + Effect.gen(function* () {
287 + yield* enableListen;
288 + const terminal = redirectedTerminalUI();
289 + const held: Array<ServerResponse> = [];
290 + let requests = 0;
291 + yield* withHttpServerEffect(
292 + (_req, res) => {
293 + requests += 1;
294 + if (requests === 1) res.end();
295 + else if (requests === 2) held.push(res);
296 + else setTimeout(() => res.writeHead(500).end(), 100);
297 + },
298 + url =>
299 + cli(['dev', 'listen', '--forward', url, '--max-events', '3', '--fail-fast']).pipe(
300 + Effect.provide(terminal.layer),
301 + Effect.ensuring(Effect.sync(() => held.forEach(res => res.end())))
302 + )
303 + );
304 +
305 + expect(terminal.stderr()).toMatch(
306 + /1 event failed to forward to http:\/\/127\.0\.0\.1:\d+ while listening\./
307 + );
308 + expect(process.exitCode).toBe(1);
309 + })
310 + );
311 + });
312 });