@devries-cameron20 / composio Mirror · read-only
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, 04:45 UTC

next
ts 740 lines 26.7 KB
Raw
1 import { Writable } from 'node:stream';
2 import { describe, expect, it, layer } from '@effect/vitest';
3 import { beforeEach, vi } from 'vitest';
4 import * as p from '@clack/prompts';
5 import { CANCEL_SYMBOL } from '@clack/core';
6 import stringWidth from 'fast-string-width';
7 import { assert } from '@effect/vitest';
8 import { Cause, Data, Effect, Exit, Fiber } from 'effect';
9 import {
10 clampSpinnerMessage,
11 getTerminalCapabilities,
12 makeTerminalUI,
13 TerminalUI,
14 } from 'src/services/terminal-ui';
15 import { escapeTerminalLines, escapeTerminalText } from 'src/ui/escape-terminal-text';
16 import { TestLive, MockConsole } from 'test/__utils__';
17
18 vi.mock('@clack/prompts', async importOriginal => {
19 const actual = await importOriginal<typeof import('@clack/prompts')>();
20 return { ...actual, confirm: vi.fn(), select: vi.fn() };
21 });
22
23 class TestFailure extends Data.TaggedError('test/TestFailure')<{
24 readonly message: string;
25 }> {}
26
27 const booleanStates = [false, true] as const;
28
29 const ttyCombinations = booleanStates.flatMap(stdin =>
30 booleanStates.flatMap(stdout => booleanStates.map(stderr => ({ stdin, stdout, stderr })))
31 );
32
33 /** An intentional Node.js Writable test double matching Clack's output contract. */
34 const makeSink = (isTTY: boolean) => {
35 const chunks: string[] = [];
36 const sink = new Writable({
37 write(chunk, _encoding, callback) {
38 chunks.push(String(chunk));
39 callback();
40 },
41 });
42 return Object.assign(sink, { isTTY, chunks });
43 };
44
45 const makeStreamedUi = (tty: { stdin: boolean; stdout: boolean; stderr: boolean }) => {
46 const stdout = makeSink(tty.stdout);
47 const stderr = makeSink(tty.stderr);
48 const ui = makeTerminalUI({ stdin: { isTTY: tty.stdin }, stdout, stderr });
49 return { ui, stdout, stderr };
50 };
51
52 describe('TerminalUI', () => {
53 it.each(ttyCombinations)(
54 'derives each capability from only the streams that serve it (stdin=$stdin, stdout=$stdout, stderr=$stderr)',
55 ({ stdin, stdout, stderr }) => {
56 expect(
57 getTerminalCapabilities({
58 stdin: { isTTY: stdin },
59 stdout: { isTTY: stdout },
60 stderr: { isTTY: stderr },
61 })
62 ).toEqual({
63 stdinIsTTY: stdin,
64 stdoutIsTTY: stdout,
65 stderrIsTTY: stderr,
66 canPrompt: stdin && stderr,
67 canDecorate: stderr,
68 });
69 }
70 );
71
72 describe('each capability is decided only by its own streams (behavior, not booleans)', () => {
73 beforeEach(() => {
74 vi.mocked(p.confirm).mockReset();
75 vi.mocked(p.select).mockReset();
76 });
77
78 it.effect('maps prompt cancellation to false for confirmation and the first selection', () =>
79 Effect.gen(function* () {
80 const { ui } = makeStreamedUi({ stdin: true, stdout: true, stderr: true });
81 vi.mocked(p.confirm).mockResolvedValue(CANCEL_SYMBOL);
82 vi.mocked(p.select).mockResolvedValue(CANCEL_SYMBOL);
83 expect(yield* ui.confirm('proceed?', { defaultValue: true })).toBe(false);
84 expect(
85 yield* ui.select('pick', [
86 { value: 'first', label: 'First' },
87 { value: 'second', label: 'Second' },
88 ])
89 ).toBe('first');
90 })
91 );
92
93 it.effect(
94 'stdin redirected, stdout+stderr TTY: prompts fall back, stdout stays clean, decoration renders',
95 () =>
96 Effect.gen(function* () {
97 const { ui, stdout, stderr } = makeStreamedUi({
98 stdin: false,
99 stdout: true,
100 stderr: true,
101 });
102
103 const confirmed = yield* ui.confirm('proceed?', { defaultValue: false });
104 expect(confirmed).toBe(false);
105 expect(p.confirm).not.toHaveBeenCalled();
106
107 const selected = yield* ui.select('pick', [
108 { value: 'first', label: 'First' },
109 { value: 'second', label: 'Second' },
110 ]);
111 expect(selected).toBe('first');
112 expect(p.select).not.toHaveBeenCalled();
113
114 yield* ui.output('{"machine":"data"}');
115 expect(stdout.chunks).toEqual([]);
116
117 yield* ui.output('forced-data', { force: true });
118 expect(stdout.chunks.join('')).toContain('forced-data');
119
120 yield* ui.log.info('stdin-redirect decoration');
121 expect(stderr.chunks.join('')).toContain('stdin-redirect decoration');
122 })
123 );
124
125 it.effect(
126 'stdout piped, stdin+stderr TTY: prompting stays available, data emits, decoration renders',
127 () =>
128 Effect.gen(function* () {
129 vi.mocked(p.confirm).mockResolvedValue(false);
130 const { ui, stdout, stderr } = makeStreamedUi({
131 stdin: true,
132 stdout: false,
133 stderr: true,
134 });
135
136 const confirmed = yield* ui.confirm('proceed?', { defaultValue: true });
137 expect(p.confirm).toHaveBeenCalledTimes(1);
138 expect(confirmed).toBe(false);
139
140 yield* ui.output('{"machine":"data"}');
141 expect(stdout.chunks.join('')).toContain('{"machine":"data"}');
142
143 yield* ui.log.info('stdout-piped decoration');
144 expect(stderr.chunks.join('')).toContain('stdout-piped decoration');
145 })
146 );
147
148 it.effect(
149 'stderr captured, stdin+stdout TTY: no prompts, no decoration, stdout silent unless forced',
150 () =>
151 Effect.gen(function* () {
152 const { ui, stdout, stderr } = makeStreamedUi({
153 stdin: true,
154 stdout: true,
155 stderr: false,
156 });
157
158 const confirmed = yield* ui.confirm('proceed?', { defaultValue: true });
159 expect(confirmed).toBe(true);
160 expect(p.confirm).not.toHaveBeenCalled();
161
162 yield* ui.log.info('captured decoration');
163 expect(stderr.chunks).toEqual([]);
164
165 yield* ui.output('{"machine":"data"}');
166 expect(stdout.chunks).toEqual([]);
167
168 yield* ui.output('forced-data', { force: true });
169 expect(stdout.chunks.join('')).toContain('forced-data');
170 })
171 );
172
173 it.effect('all streams redirected: machine output still emits', () =>
174 Effect.gen(function* () {
175 const { ui, stdout, stderr } = makeStreamedUi({
176 stdin: false,
177 stdout: false,
178 stderr: false,
179 });
180
181 yield* ui.output('{"machine":"data"}');
182 expect(stdout.chunks.join('')).toContain('{"machine":"data"}');
183
184 yield* ui.log.info('invisible decoration');
185 expect(stderr.chunks).toEqual([]);
186 })
187 );
188 });
189
190 describe('a stdout write that fails', () => {
191 /**
192 * A redirected stdout whose every write fails with `code`, as the OS reports it. An `error`
193 * event nothing listens to, which would crash the process, is recorded in `unhandled`.
194 */
195 const failingStdout = (code: string) => {
196 const attempts: string[] = [];
197 const unhandled: unknown[] = [];
198 const sink = new Writable({
199 write(chunk, _encoding, callback) {
200 attempts.push(String(chunk));
201 callback(Object.assign(new Error(`${code}: write failed`), { code }));
202 },
203 });
204 const emit = sink.emit.bind(sink);
205 sink.emit = ((event: string | symbol, ...args: unknown[]) => {
206 if (event === 'error' && sink.listenerCount('error') === 0) {
207 unhandled.push(args[0]);
208 return false;
209 }
210 return emit(event, ...args);
211 }) as typeof sink.emit;
212 return Object.assign(sink, { isTTY: false, attempts, unhandled });
213 };
214
215 /** Lets the stream emit what it deferred to the next turn of the event loop. */
216 const settle = Effect.promise(() => new Promise<void>(resolve => setImmediate(resolve)));
217
218 it.effect('drops the data once the reader closed stdout (EPIPE), and the command goes on', () =>
219 Effect.gen(function* () {
220 const stdout = failingStdout('EPIPE');
221 const ui = makeTerminalUI({ stdin: { isTTY: false }, stdout, stderr: makeSink(false) });
222
223 yield* ui.output('{"first":true}');
224 yield* ui.output('{"second":true}');
225
226 yield* settle;
227
228 // Nothing more can reach a reader that went away, and its error does not crash the CLI.
229 expect(stdout.attempts).toEqual(['{"first":true}\n']);
230 expect(stdout.unhandled).toEqual([]);
231 })
232 );
233
234 it.effect('completes stdoutClosed once the reader closed stdout (EPIPE)', () =>
235 Effect.gen(function* () {
236 const ui = makeTerminalUI({
237 stdin: { isTTY: false },
238 stdout: failingStdout('EPIPE'),
239 stderr: makeSink(false),
240 });
241 const closed = yield* Effect.forkChild(ui.stdoutClosed);
242 yield* Effect.yieldNow;
243 expect(closed.pollUnsafe()).toBeUndefined();
244
245 yield* ui.output('{"first":true}');
246
247 expect(Exit.isSuccess(yield* Fiber.await(closed))).toBe(true);
248 })
249 );
250
251 it.effect('leaves stdoutClosed pending while the reader takes the data', () =>
252 Effect.gen(function* () {
253 const ui = makeTerminalUI({
254 stdin: { isTTY: false },
255 stdout: makeSink(false),
256 stderr: makeSink(false),
257 });
258 const closed = yield* Effect.forkChild(ui.stdoutClosed);
259
260 yield* ui.output('{"first":true}');
261 yield* settle;
262
263 expect(closed.pollUnsafe()).toBeUndefined();
264 yield* Fiber.interrupt(closed);
265 })
266 );
267
268 it.effect('is a defect for any other failure', () =>
269 Effect.gen(function* () {
270 const stdout = failingStdout('EIO');
271 const ui = makeTerminalUI({ stdin: { isTTY: false }, stdout, stderr: makeSink(false) });
272
273 const exit = yield* Effect.exit(ui.output('{"machine":"data"}'));
274
275 assert(Exit.isFailure(exit));
276 expect(Cause.hasDies(exit.cause)).toBe(true);
277 expect(Cause.squash(exit.cause)).toMatchObject({ code: 'EIO' });
278 })
279 );
280 });
281
282 describe('escaping external text for display', () => {
283 // Formatting fixtures: standalone controls at each range edge, CR/LF and a tab.
284 const controls = '\u0000 \u0007 \u001f \u007f \u0080 \u0085 \u009f';
285
286 it('escapes C0, DEL and C1 controls as JSON-style escapes on one line', () => {
287 expect(escapeTerminalText(`a${controls}b`)).toBe(
288 'a\\u0000 \\u0007 \\u001f \\u007f \\u0080 \\u0085 \\u009fb'
289 );
290 expect(escapeTerminalText('one\r\ntwo\tthree')).toBe('one\\u000d\\u000atwo\\u0009three');
291 });
292
293 it('keeps printable text, backslashes, combining marks and astral characters', () => {
294 const printable = 'plain C:\\temp \\u0007 e\u0301 \u{1f600} \u00a0 \u00e9';
295 expect(escapeTerminalText(printable)).toBe(printable);
296 expect(escapeTerminalLines(printable)).toBe(printable);
297 });
298
299 it('keeps LF and TAB in multiline text, folds CRLF and escapes a lone CR', () => {
300 expect(escapeTerminalLines('one\r\ntwo\tcol\rthree\n\u0007')).toBe(
301 'one\ntwo\tcol\\u000dthree\n\\u0007'
302 );
303 });
304
305 it('keeps serialized JSON decodable to the same value', () => {
306 const value = { 'key\u0085': 'v\u007f\u0007', lines: 'a\r\nb', nested: [{ c: '\u0086' }] };
307 const shown = escapeTerminalLines(JSON.stringify(value, null, 2));
308 expect(shown).not.toMatch(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/u);
309 expect(JSON.parse(shown)).toEqual(value);
310 });
311 });
312
313 describe('clampSpinnerMessage keeps live spinner messages on one terminal row', () => {
314 it('leaves a message that fits untouched', () => {
315 expect(clampSpinnerMessage(80, 'Checking for updates')).toBe('Checking for updates');
316 });
317
318 it('truncates a message longer than the row budget with an ellipsis', () => {
319 const clamped = clampSpinnerMessage(40, 'x'.repeat(100));
320 expect(clamped).toBe(`${'x'.repeat(32)}…`);
321 expect(clamped).toHaveLength(40 - 7);
322 });
323
324 it('collapses embedded newlines into spaces', () => {
325 expect(clampSpinnerMessage(80, 'line one\nline two')).toBe('line one line two');
326 });
327
328 it('never slices a message containing ANSI escape sequences', () => {
329 const colored = `\u001b[32m${'x'.repeat(100)}\u001b[0m`;
330 expect(clampSpinnerMessage(40, colored)).toBe(colored);
331 });
332
333 it('measures display columns, not UTF-16 code units', () => {
334 // 20 CJK characters are 20 code units but 40 display columns, so at 40
335 // columns they sit under a `.length` budget of 33 and over a width one.
336 // A length-based clamp would pass them through and let the frame wrap.
337 const message = '\u4f60\u597d'.repeat(10);
338 expect(message).toHaveLength(20);
339 expect(stringWidth(message)).toBe(40);
340
341 const clamped = clampSpinnerMessage(40, message);
342 expect(clamped.endsWith('…')).toBe(true);
343 expect(stringWidth(clamped)).toBeLessThanOrEqual(40 - 7);
344 });
345
346 it('measures and truncates whole grapheme clusters', () => {
347 const keycap = '1\uFE0F\u20E3';
348 expect(stringWidth(keycap)).toBe(2);
349 expect([...keycap].reduce((width, char) => width + stringWidth(char), 0)).toBe(1);
350
351 const clamped = clampSpinnerMessage(20, keycap.repeat(20));
352 expect(clamped).toMatch(/^(?:1\uFE0F\u20E3)*…$/u);
353 expect(stringWidth(clamped)).toBeLessThanOrEqual(20 - 7);
354 });
355
356 it('never cuts a surrogate pair in half', () => {
357 const clamped = clampSpinnerMessage(20, '\u{1f600}'.repeat(40));
358 expect(clamped).not.toMatch(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/);
359 expect(stringWidth(clamped)).toBeLessThanOrEqual(20 - 7);
360 });
361
362 it('degrades to the ellipsis on terminals narrower than the frame overhead', () => {
363 // Below SPINNER_RENDER_OVERHEAD + 1 columns no message length fits, so the
364 // budget bottoms out at one column rather than jumping back up to eight.
365 expect(clampSpinnerMessage(4, 'x'.repeat(100))).toBe('…');
366 });
367
368 it('keeps the rendered frame within the row at the exact budget boundary', () => {
369 const columns = 20;
370 const clamped = clampSpinnerMessage(columns, 'x'.repeat(100));
371 // frame (1) + two spaces (2) + message + three animated dots (3).
372 expect(1 + 2 + stringWidth(clamped) + 3).toBeLessThanOrEqual(columns);
373 });
374
375 // Clack ticks every 80ms and grows its animated dots by 0.125 per tick, so
376 // reaching the three dots SPINNER_RENDER_OVERHEAD reserves takes 24 ticks.
377 // A shorter advance renders a frame with no dots and never exercises them.
378 const TICKS_PAST_THREE_DOTS = 2000;
379
380 const LONG_UPGRADE_MESSAGE =
381 'New version available: @composio/cli@0.4.0 (current: @composio/cli@0.3.2). Downloading...';
382
383 const narrowUi = (columns: number) => {
384 const stdout = makeSink(true);
385 const stderr = Object.assign(makeSink(true), { columns });
386 const ui = makeTerminalUI({ stdin: { isTTY: true }, stdout, stderr });
387 return { ui, stderr };
388 };
389
390 /** Every frame clack redrew, i.e. the writes that carry the clamped message. */
391 const clampedFrames = (stderr: { chunks: string[] }) =>
392 stderr.chunks.filter(chunk => chunk.includes('…'));
393
394 /** Drives a real clack spinner with fake timers, then always restores them. */
395 const withFakeTimers = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
396 Effect.acquireUseRelease(
397 Effect.sync(() => vi.useFakeTimers()),
398 () => effect,
399 () => Effect.sync(() => vi.useRealTimers())
400 );
401
402 it.live('renders live spinner frames without wrapping in a narrow terminal', () =>
403 withFakeTimers(
404 Effect.gen(function* () {
405 const { ui, stderr } = narrowUi(40);
406
407 yield* ui.useMakeSpinner(LONG_UPGRADE_MESSAGE, spinner =>
408 Effect.gen(function* () {
409 yield* Effect.sync(() => vi.advanceTimersByTime(TICKS_PAST_THREE_DOTS));
410 yield* spinner.stop('Upgrade completed!');
411 })
412 );
413
414 const frames = clampedFrames(stderr);
415 expect(frames.length).toBeGreaterThan(0);
416 expect(frames[0]).toContain('New version available: @composio');
417 // A wrapped frame is what leaks lines on every redraw tick.
418 expect(frames).not.toContainEqual(expect.stringContaining('\n'));
419 })
420 )
421 );
422
423 it.live('clamps live message() updates, not just the start message', () =>
424 withFakeTimers(
425 Effect.gen(function* () {
426 const { ui, stderr } = narrowUi(40);
427
428 yield* ui.useMakeSpinner('Checking for updates...', spinner =>
429 Effect.gen(function* () {
430 // The upgrade flow drives its longest text through message(), not
431 // start() — reverting the clamp there must fail this test.
432 yield* spinner.message(LONG_UPGRADE_MESSAGE);
433 yield* Effect.sync(() => vi.advanceTimersByTime(TICKS_PAST_THREE_DOTS));
434 yield* spinner.stop('Upgrade completed!');
435 })
436 );
437
438 const frames = clampedFrames(stderr);
439 expect(frames.length).toBeGreaterThan(0);
440 expect(frames[0]).toContain('New version available: @composio');
441 expect(frames).not.toContainEqual(expect.stringContaining('\n'));
442 })
443 )
444 );
445
446 it.live('does not grow updates beyond the width Clack captured at construction', () =>
447 withFakeTimers(
448 Effect.gen(function* () {
449 const { ui, stderr } = narrowUi(20);
450
451 yield* ui.useMakeSpinner('Checking for updates...', spinner =>
452 Effect.gen(function* () {
453 stderr.columns = 80;
454 yield* spinner.message(LONG_UPGRADE_MESSAGE);
455 yield* Effect.sync(() => vi.advanceTimersByTime(TICKS_PAST_THREE_DOTS));
456 yield* spinner.stop('Upgrade completed!');
457 })
458 );
459
460 const frames = clampedFrames(stderr);
461 expect(frames.length).toBeGreaterThan(0);
462 expect(frames[0]).toContain('New version');
463 expect(frames).not.toContainEqual(expect.stringContaining('\n'));
464 expect(Math.max(...frames.map(frame => stringWidth(frame)))).toBeLessThanOrEqual(20);
465 })
466 )
467 );
468
469 it.live('respects a terminal that narrows after spinner construction', () =>
470 withFakeTimers(
471 Effect.gen(function* () {
472 const { ui, stderr } = narrowUi(80);
473
474 yield* ui.useMakeSpinner('Checking for updates...', spinner =>
475 Effect.gen(function* () {
476 stderr.columns = 20;
477 yield* spinner.message(LONG_UPGRADE_MESSAGE);
478 yield* Effect.sync(() => vi.advanceTimersByTime(TICKS_PAST_THREE_DOTS));
479 yield* spinner.stop('Upgrade completed!');
480 })
481 );
482
483 const frames = clampedFrames(stderr);
484 expect(frames.length).toBeGreaterThan(0);
485 expect(frames[0]).toContain('New version');
486 expect(frames).not.toContainEqual(expect.stringContaining('\n'));
487 expect(Math.max(...frames.map(frame => stringWidth(frame)))).toBeLessThanOrEqual(20);
488 })
489 )
490 );
491
492 it.live('clamps the withSpinner start message too', () =>
493 withFakeTimers(
494 Effect.gen(function* () {
495 const { ui, stderr } = narrowUi(40);
496
497 yield* ui.withSpinner(
498 LONG_UPGRADE_MESSAGE,
499 Effect.sync(() => vi.advanceTimersByTime(TICKS_PAST_THREE_DOTS))
500 );
501
502 const frames = clampedFrames(stderr);
503 expect(frames.length).toBeGreaterThan(0);
504 expect(frames).not.toContainEqual(expect.stringContaining('\n'));
505 })
506 )
507 );
508 });
509
510 layer(TestLive())(it => {
511 // -----------------------------------------------------------------------
512 // Data output
513 // -----------------------------------------------------------------------
514
515 it.effect('output writes raw data capturable by MockConsole', () =>
516 Effect.gen(function* () {
517 const ui = yield* TerminalUI;
518 yield* ui.output('ak_test123');
519
520 const lines = yield* MockConsole.getLines();
521 expect(lines).toContain('ak_test123');
522 })
523 );
524
525 it.effect('error writes raw diagnostics capturable by MockConsole', () =>
526 Effect.gen(function* () {
527 const ui = yield* TerminalUI;
528 yield* ui.error('diagnostic');
529
530 const lines = yield* MockConsole.getLines();
531 expect(lines).toContain('diagnostic');
532 })
533 );
534
535 // -----------------------------------------------------------------------
536 // Log text capture
537 // -----------------------------------------------------------------------
538
539 it.effect('log.info writes text capturable by MockConsole', () =>
540 Effect.gen(function* () {
541 const ui = yield* TerminalUI;
542 yield* ui.log.info('hello from info');
543
544 const lines = yield* MockConsole.getLines();
545 expect(lines).toContain('hello from info');
546 })
547 );
548
549 it.effect('log.success writes text capturable by MockConsole', () =>
550 Effect.gen(function* () {
551 const ui = yield* TerminalUI;
552 yield* ui.log.success('operation succeeded');
553
554 const lines = yield* MockConsole.getLines();
555 expect(lines).toContain('operation succeeded');
556 })
557 );
558
559 it.effect('log.warn writes text capturable by MockConsole', () =>
560 Effect.gen(function* () {
561 const ui = yield* TerminalUI;
562 yield* ui.log.warn('something is off');
563
564 const lines = yield* MockConsole.getLines();
565 expect(lines).toContain('something is off');
566 })
567 );
568
569 it.effect('log.error writes text capturable by MockConsole', () =>
570 Effect.gen(function* () {
571 const ui = yield* TerminalUI;
572 yield* ui.log.error('something broke');
573
574 const lines = yield* MockConsole.getLines();
575 expect(lines).toContain('something broke');
576 })
577 );
578
579 it.effect('log.step writes text capturable by MockConsole', () =>
580 Effect.gen(function* () {
581 const ui = yield* TerminalUI;
582 yield* ui.log.step('step completed');
583
584 const lines = yield* MockConsole.getLines();
585 expect(lines).toContain('step completed');
586 })
587 );
588
589 it.effect('note writes title and message capturable by MockConsole', () =>
590 Effect.gen(function* () {
591 const ui = yield* TerminalUI;
592 yield* ui.note('api_key_123', 'API Key');
593
594 const lines = yield* MockConsole.getLines();
595 const output = lines.join('\n');
596 expect(output).toContain('api_key_123');
597 expect(output).toContain('API Key');
598 })
599 );
600
601 it.effect('intro and outro write text capturable by MockConsole', () =>
602 Effect.gen(function* () {
603 const ui = yield* TerminalUI;
604 yield* ui.intro('my command');
605 yield* ui.outro('all done');
606
607 const lines = yield* MockConsole.getLines();
608 const output = lines.join('\n');
609 expect(output).toContain('my command');
610 expect(output).toContain('all done');
611 })
612 );
613
614 // -----------------------------------------------------------------------
615 // withSpinner lifecycle
616 // -----------------------------------------------------------------------
617
618 it.effect('withSpinner captures success message', () =>
619 Effect.gen(function* () {
620 const ui = yield* TerminalUI;
621 const result = yield* ui.withSpinner('loading', Effect.succeed(42), {
622 successMessage: 'loaded 42 items',
623 });
624
625 expect(result).toBe(42);
626 const lines = yield* MockConsole.getLines();
627 expect(lines).toContain('loaded 42 items');
628 })
629 );
630
631 it.effect('withSpinner propagates errors', () =>
632 Effect.gen(function* () {
633 const ui = yield* TerminalUI;
634 const failure = yield* ui
635 .withSpinner('loading', Effect.fail(new TestFailure({ message: 'network error' })))
636 .pipe(Effect.flip);
637
638 expect(failure).toEqual(new TestFailure({ message: 'network error' }));
639 })
640 );
641
642 // -----------------------------------------------------------------------
643 // useMakeSpinner — auto-cleanup on error
644 // -----------------------------------------------------------------------
645
646 it.effect('useMakeSpinner auto-stops spinner on error', () =>
647 Effect.gen(function* () {
648 const ui = yield* TerminalUI;
649
650 const failure = yield* ui
651 .useMakeSpinner('fetching data', _spinner =>
652 Effect.fail(new TestFailure({ message: 'API returned 400' }))
653 )
654 .pipe(Effect.flip);
655
656 expect(failure).toEqual(new TestFailure({ message: 'API returned 400' }));
657
658 // The spinner error message should be captured
659 const lines = yield* MockConsole.getLines();
660 expect(lines).toContain('fetching data');
661 })
662 );
663
664 it.effect('useMakeSpinner does NOT double-stop if user already stopped', () =>
665 Effect.gen(function* () {
666 const ui = yield* TerminalUI;
667
668 yield* ui.useMakeSpinner('processing', spinner =>
669 Effect.gen(function* () {
670 yield* spinner.stop('done processing');
671 })
672 );
673
674 const lines = yield* MockConsole.getLines();
675 // Should see the user's stop message, not the auto-cleanup
676 expect(lines).toContain('done processing');
677 // Should NOT see the default message as an error (which would happen with double-stop)
678 expect(lines.filter(l => l === 'processing')).toHaveLength(0);
679 })
680 );
681
682 it.effect('useMakeSpinner allows message updates before stop', () =>
683 Effect.gen(function* () {
684 const ui = yield* TerminalUI;
685
686 yield* ui.useMakeSpinner('starting', spinner =>
687 Effect.gen(function* () {
688 yield* spinner.message('step 1');
689 yield* spinner.message('step 2');
690 yield* spinner.stop('finished');
691 })
692 );
693
694 const lines = yield* MockConsole.getLines();
695 expect(lines).toContain('finished');
696 })
697 );
698
699 it.effect('useMakeSpinner returns the value from the use callback', () =>
700 Effect.gen(function* () {
701 const ui = yield* TerminalUI;
702
703 const result = yield* ui.useMakeSpinner('computing', spinner =>
704 Effect.gen(function* () {
705 yield* spinner.stop('computed');
706 return 99;
707 })
708 );
709
710 expect(result).toBe(99);
711 })
712 );
713
714 it.effect(
715 'useMakeSpinner does NOT double-error when callback calls spinner.error then fails',
716 () =>
717 Effect.gen(function* () {
718 const ui = yield* TerminalUI;
719
720 const failure = yield* ui
721 .useMakeSpinner('fetching', spinner =>
722 Effect.gen(function* () {
723 // Simulate tapError pattern: callback calls spinner.error(), then the effect fails
724 yield* spinner.error('Login timed out. Please try again.');
725 return yield* new TestFailure({ message: 'timed out' });
726 })
727 )
728 .pipe(Effect.flip);
729
730 expect(failure).toEqual(new TestFailure({ message: 'timed out' }));
731
732 const lines = yield* MockConsole.getLines();
733 // Should see the user's error message
734 expect(lines).toContain('Login timed out. Please try again.');
735 // Should NOT see the default spinner message as a second error
736 expect(lines.filter(l => l === 'fetching')).toHaveLength(0);
737 })
738 );
739 });
740 });