-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathink-ui.ts
More file actions
974 lines (913 loc) · 33.5 KB
/
ink-ui.ts
File metadata and controls
974 lines (913 loc) · 33.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
/**
* InkUI — Ink-based `WizardUI` implementation.
*
* The class is a thin bridge between the imperative `WizardUI`
* surface (which the wizard runner calls into) and a React tree
* mounted via Ink's `render()`. State lives in a `WizardStore`
* (see `wizard-store.ts`) that React subscribes to via
* `useSyncExternalStore`. Each method on this class translates a
* single imperative call into one or more store mutations; React
* re-renders.
*
* Why Ink rather than OpenTUI?
*
* - **No native binary cost.** The OpenTUI implementation added
* ~10.7 MB to the compiled Bun binary (the `libopentui.so`
* plus the ~12k-line generated FFI bindings). Ink is pure JS,
* so it bundles cleanly with no platform-specific peer
* packages.
* - **Inline rendering.** Ink writes incrementally to stdout, so
* log lines naturally end up in the user's scrollback. OpenTUI
* needed an alternate-screen buffer + a post-dispose stderr
* replay to leave any trace of the run behind.
*
* **Stdin workaround for Bun.** Ink listens for `readable` events
* on its `stdin` option (default `process.stdin`) and calls
* `stdin.read()` to consume bytes. Bun's compiled binaries have a
* long-standing bug — `process.stdin` accepts `setRawMode(true)` but
* never delivers `readable` events for terminal input
* (oven-sh/bun#6862, vadimdemedes/ink#636, both still open). The
* symptom: the wizard renders fine but arrow keys, Enter, and
* Ctrl+C all do nothing.
*
* Workaround: open a fresh `/dev/tty` `ReadStream` ourselves and
* pass it to Ink as the `stdin` option. The fresh stream's
* `readable` events fire correctly because the file-descriptor
* inheritance bug only affects fd 0, not fds we open inside the
* process. We close the stream on dispose to release the libuv
* handle.
*
* **Lazy import.** The Ink app sidecar (`ink-app.js`) is a
* self-contained ESM bundle with all deps (ink, react, yoga-layout)
* inlined. It's loaded lazily by `createInkUI()` via dynamic
* `import()` so the `LoggingUI` path stays cheap to instantiate
* when interactive UI is not needed. On the Bun binary the sidecar
* is embedded in `/$bunfs/`; on the npm/Node distribution it ships
* as `dist/ink-app.js` alongside the CJS bundle.
*/
import { openSync } from "node:fs";
import { ReadStream } from "node:tty";
import { setTag } from "@sentry/node-core/light";
import { CLI_VERSION } from "../../constants.js";
import { stripAnsi } from "../../formatters/plain-detect.js";
import { formatFeedbackHint, type InitFeedbackOutcome } from "../feedback.js";
import { formatFailureReport, formatSuccessReport } from "./ink-report.js";
import { LEARN_SEQUENCE } from "./learn-content.js";
import { SENTRY_TIPS } from "./sentry-tips.js";
import {
CANCELLED,
type Cancelled,
type ConfirmOptions,
type MultiSelectOptions,
type SelectOptions,
type SpinnerExitCode,
type SpinnerHandle,
type WelcomeOptions,
type WizardLog,
type WizardSummary,
type WizardUI,
} from "./types.js";
import { WizardStore } from "./wizard-store.js";
type CreateInkUIOptions = {
initialWelcome?: WelcomeOptions;
};
type PendingWelcome = {
promise: Promise<"continue" | Cancelled>;
resolve: (value: "continue" | Cancelled) => void;
settled: boolean;
};
/** Tip rotation cadence in the sidebar — slow enough to read each tip. */
const TIP_ROTATE_INTERVAL_MS = 15_000;
/** Sentry brand purple — matches `src/lib/banner.ts`. */
const BANNER_GRADIENT = [
"#B4A4DE",
"#9C84D4",
"#8468C8",
"#6C4EBA",
"#5538A8",
"#432B8A",
];
const BANNER_ROWS = [
" ███████╗███████╗███╗ ██╗████████╗██████╗ ██╗ ██╗",
" ██╔════╝██╔════╝████╗ ██║╚══██╔══╝██╔══██╗╚██╗ ██╔╝",
" ███████╗█████╗ ██╔██╗ ██║ ██║ ██████╔╝ ╚████╔╝ ",
" ╚════██║██╔══╝ ██║╚██╗██║ ██║ ██╔══██╗ ╚██╔╝ ",
" ███████║███████╗██║ ╚████║ ██║ ██║ ██║ ██║ ",
" ╚══════╝╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ",
];
function sanitizeWelcomeOptions(opts: WelcomeOptions): WelcomeOptions {
return {
title: stripAnsi(opts.title),
body: opts.body.map(stripAnsi),
punchline: stripAnsi(opts.punchline),
};
}
function createPendingWelcome(): PendingWelcome {
let resolve!: (value: "continue" | Cancelled) => void;
const pending: PendingWelcome = {
promise: new Promise<"continue" | Cancelled>((r) => {
resolve = r;
}),
resolve: (value) => {
if (pending.settled) {
return;
}
pending.settled = true;
resolve(value);
},
settled: false,
};
return pending;
}
function seedWelcomePrompt(
store: WizardStore,
opts: WelcomeOptions,
pending: PendingWelcome
): void {
store.setLayout("intro");
store.setPrompt({
kind: "welcome",
options: sanitizeWelcomeOptions(opts),
resolve: (value) => {
store.setPrompt(null);
pending.resolve(value === null ? CANCELLED : value);
},
});
}
/**
* Log severities recognised by InkUI. Mirrors the keys of
* `ICON_BY_SEVERITY` in `ink-app.tsx`.
*/
type LogSeverity = "info" | "warn" | "error" | "success" | "message";
/**
* Severity returned for a spinner stop given its exit code.
* 0 → success, 1 → error, 2 → warn.
*/
function severityForStopCode(code: SpinnerExitCode): LogSeverity {
if (code === 1) {
return "error";
}
if (code === 2) {
return "warn";
}
return "success";
}
/**
* Resolve the Ink sidecar path/source for the current runtime context.
*
* The sidecar (`ink-app.js`) is a self-contained ESM bundle produced
* by `text-import-plugin` during the esbuild step. It inlines ink,
* react, and all local deps so it can run without `node_modules`.
*
* Three runtime contexts:
*
* 1. **Node SEA binary**: The sidecar is embedded as a SEA asset via
* fossilize's `--assets` flag. Extract with `node:sea.getAsset()`,
* write to a temp file, and `import()` it.
*
* 2. **Node/npm bundle** (`npx sentry`): The sidecar ships as
* `dist/ink-app.js` alongside the CJS bundle. The `text-import-plugin`
* emits a virtual module exporting the relative path `"./ink-app.js"`.
* Resolved via `import.meta.url` at runtime.
*
* 3. **Dev mode** (`pnpm run cli`): The absolute filesystem path to
* `ink-app.tsx` is resolved by the text-import-plugin at build time.
* In dev (tsx), it points to the source file directly.
*/
// @ts-expect-error: `with { type: "file" }` handled by text-import-plugin at build time
import inkAppPath from "./ink-app.tsx" with { type: "file" };
/**
* Open a fresh `/dev/tty` `ReadStream` for Ink to consume. Returns
* `null` when `/dev/tty` isn't available (non-TTY environment, or
* platforms that don't expose it — Windows). The caller falls back
* to `process.stdin` in that case, which works on Node but is
* broken in Bun-compiled binaries (see module docstring).
*/
function openFreshTtyForInk(): ReadStream | null {
try {
const fd = openSync("/dev/tty", "r");
return new ReadStream(fd);
} catch {
return null;
}
}
/**
* Async factory for `InkUI`. Imports `ink`, `react`, and the local
* `App` component lazily, mounts the React tree, and returns the
* bridge instance. Throws if Ink can't be loaded (e.g. missing peer
* deps).
*/
export async function createInkUI(
opts: CreateInkUIOptions = {}
): Promise<InkUI> {
// Import the Ink App sidecar. Three runtime contexts:
//
// 1. Node SEA binary: the sidecar is embedded as a SEA asset.
// Extract it via node:sea.getAsset(), write to a temp file,
// and import() it.
//
// 2. Node/npm (npx sentry@latest): inkAppPath is a relative path
// like "./ink-app.js" (emitted by text-import-plugin as a
// string literal). Resolve it to an absolute file:// URL using
// import.meta.url so Node's dynamic import() can load the
// self-contained ESM sidecar from the dist/ directory.
//
// 3. Dev mode (pnpm run cli): inkAppPath is the absolute
// filesystem path to ink-app.tsx.
let importPath: string;
let seaTmpDir: string | undefined;
// Check if running inside a Node SEA binary
let isSea = false;
try {
// biome-ignore lint/suspicious/noExplicitAny: node:sea types not yet in @types/node
const sea = require("node:sea") as any;
isSea = sea.isSea?.() === true;
} catch {
// node:sea not available (older Node or non-SEA context)
}
if (isSea) {
// Extract the embedded sidecar to a temp file and import it.
// The asset key matches what fossilize registered via --assets.
// biome-ignore lint/suspicious/noExplicitAny: node:sea types not yet in @types/node
const sea = require("node:sea") as any;
const { writeFileSync, mkdtempSync } = await import("node:fs");
const { join } = await import("node:path");
const { tmpdir } = await import("node:os");
const tmpDir = mkdtempSync(join(tmpdir(), "sentry-ink-"));
const tmpFile = join(tmpDir, "ink-app.js");
writeFileSync(tmpFile, sea.getAsset("dist-build/ink-app.js", "utf-8"));
// Node's dynamic import() requires file:// URLs for absolute paths on Windows
const { pathToFileURL } = await import("node:url");
importPath = pathToFileURL(tmpFile).href;
seaTmpDir = tmpDir;
} else if (inkAppPath.startsWith("./")) {
// Node/npm bundle — resolve relative to the bundle location
importPath = new URL(inkAppPath, import.meta.url).href;
} else {
// Dev mode — absolute filesystem path
importPath = inkAppPath;
}
const app = (await import(importPath)) as typeof import("./ink-app.js");
// Clean up SEA temp file — module is cached in memory after import()
if (seaTmpDir) {
try {
const { rmSync } = await import("node:fs");
rmSync(seaTmpDir, { recursive: true, force: true });
} catch {
// best-effort cleanup
}
}
const store = new WizardStore({
cliVersion: CLI_VERSION,
bannerRows: BANNER_ROWS.map((content, i) => ({
content,
color: BANNER_GRADIENT[i] ?? BANNER_GRADIENT[0] ?? "#FFFFFF",
})),
});
const initialWelcome = opts.initialWelcome
? createPendingWelcome()
: undefined;
if (opts.initialWelcome && initialWelcome) {
seedWelcomePrompt(store, opts.initialWelcome, initialWelcome);
}
// Open a fresh /dev/tty so Ink's `readable` event listener
// actually fires — see the module docstring for the Bun bug
// details. We hold onto the stream so we can close it on dispose
// (libuv otherwise keeps the handle alive and the process can't
// exit cleanly).
const freshStdin = openFreshTtyForInk();
// Build render options for Ink:
// - `exitOnCtrlC: false` lets us route Ctrl+C through the prompt
// cancellation path instead of yanking the process down.
// - `patchConsole: false` keeps `console.*` calls flowing to the
// real stdout — Sentry SDK breadcrumbs, debug logs, etc. would
// otherwise be swallowed by Ink's render loop.
const renderOptions: {
exitOnCtrlC: boolean;
patchConsole: boolean;
stdin?: ReadStream;
} = {
exitOnCtrlC: false,
patchConsole: false,
};
if (freshStdin) {
renderOptions.stdin = freshStdin;
}
// Enter the alternate screen buffer so the wizard occupies the full
// terminal. Clear and home the cursor before Ink's first frame so
// startup never shows stale layout from a prior render.
process.stdout.write("\x1b[?1049h\x1b[2J\x1b[H");
try {
const instance = app.mountApp(store, renderOptions);
return new InkUI(instance, store, freshStdin, initialWelcome);
} catch (error) {
// Restore the terminal if Ink rendering or UI init fails,
// otherwise the user is stuck in the alternate screen buffer.
process.stdout.write("\x1b[?1049l");
throw error;
}
}
/**
* Subset of the Ink `Instance` type we actually use.
*
* Defined structurally rather than imported from `ink` so the
* dynamic-import boundary in `createInkUI` doesn't leak Ink types
* into the rest of the bridge module. `rerender` takes
* `react.ReactNode` upstream; we widen it to a generic function
* type and only ever call `unmount`/`waitUntilExit`/`clear` from
* the bridge anyway.
*/
type InkInstance = {
unmount: () => void;
waitUntilExit: () => Promise<unknown>;
// biome-ignore lint/suspicious/noExplicitAny: dynamic-import boundary
rerender: (node: any) => void;
/**
* Clears Ink's last rendered output from the terminal. We call
* this on dispose so the final post-dispose chalk summary is
* the only thing left on screen — without it the bordered
* wizard box stays above the summary, which looked redundant.
*/
clear: () => void;
};
// ──────────────────────────── Implementation ──────────────────────────
/**
* Bridge between the imperative `WizardUI` surface and the Ink
* `App` component. Mutations land in the `WizardStore`; React
* re-renders.
*/
export class InkUI implements WizardUI {
private readonly instance: InkInstance;
private readonly store: WizardStore;
/**
* Fresh `/dev/tty` stream Ink reads from. We own this — closing
* it on dispose lets the libuv handle drain so `process.exit` (or
* a natural exit) actually fires. `null` when `/dev/tty` couldn't
* be opened (Windows, sandboxed environments) — Ink falls back to
* `process.stdin` in that case.
*/
private readonly freshStdin: ReadStream | null;
private tipTimer: ReturnType<typeof setInterval> | undefined;
private learnTimer: ReturnType<typeof setInterval> | undefined;
private tipIndex = 0;
private activePromptCancel: (() => void) | undefined;
private cancelHandler: (() => void) | undefined;
/**
* Guard so `tearDown()` runs at most once even when called from
* multiple paths (Ctrl+C in a spinner, then SIGINT, then
* `[Symbol.asyncDispose]` on the wizard-runner exit). Calling
* `unmount()` on an already-unmounted Ink instance throws on some
* Ink versions; running raw-mode restoration on a destroyed stream
* also throws. The flag short-circuits before either can happen.
*/
private torndown = false;
/**
* Guard so `requestCancel()` runs its no-active-prompt branch at
* most once. With this flag set, a subsequent Ctrl+C / SIGINT
* becomes a no-op rather than re-entering teardown — the user is
* already on the way out.
*/
private cancelRequested = false;
/**
* Final wizard outcome captured by the bridge.
*
* Ink renders inline so the log lines naturally land in scrollback
* — we don't need to replay a transcript on dispose. We do echo
* a final success/failure summary line after `unmount()` so the
* user has a clear "what happened" signal at the bottom of the
* scrollback.
*/
private outroMessage: string | undefined;
private failureMessage: string | undefined;
private feedbackHint: string | undefined;
private initialWelcome: PendingWelcome | undefined;
/**
* Resolved when the user presses any key on the outro screen.
* `[Symbol.asyncDispose]` awaits this so the `using` block keeps the
* UI alive until the user has seen and acknowledged the final screen.
*/
constructor(
instance: InkInstance,
store: WizardStore,
freshStdin: ReadStream | null,
initialWelcome?: PendingWelcome
) {
this.instance = instance;
this.store = store;
this.freshStdin = freshStdin;
this.initialWelcome = initialWelcome;
if (initialWelcome && !initialWelcome.settled) {
this.activePromptCancel = () => {
this.store.setPrompt(null);
this.activePromptCancel = undefined;
initialWelcome.resolve(CANCELLED);
};
}
this.installCancelHandler();
// Hand the App a reference to `requestCancel` via the store so
// the top-level `useInput` Ctrl+C catcher in `ink-app.tsx` can
// route through the same teardown path as SIGINT and prompt
// cancellation. Without this the App would have to call
// `process.exit(130)` directly — bypassing termios restoration
// and leaking the `/dev/tty` handle.
this.store.setRequestCancel(() => this.requestCancel());
}
// ── Lifecycle ─────────────────────────────────────────────────────
banner(_art: string): void {
// No-op — the App paints the banner inside its header from the
// gradient rows pre-loaded into the store. The runner-supplied
// ANSI string is discarded.
}
intro(_title: string): void {
// No-op. The outer box already has a title-bar feel via the
// banner; an extra "▸ sentry init" line felt redundant.
}
outro(message: string): void {
const clean = stripAnsi(message);
this.appendLog("success", clean);
this.outroMessage = clean;
}
cancel(message: string): void {
const clean = stripAnsi(message);
this.appendLog("error", clean);
this.failureMessage = clean;
}
feedback(outcome: InitFeedbackOutcome): void {
this.feedbackHint = formatFeedbackHint(outcome);
}
summary(summary: WizardSummary): void {
this.store.setSummary(summary);
}
recordFilesReading(paths: string[]): void {
this.store.recordFilesReading(paths);
}
markFilesAnalyzed(paths: string[]): void {
this.store.markFilesAnalyzed(paths);
}
setStep(
stepId: string,
status: "in_progress" | "completed" | "failed" | "skipped"
): void {
this.store.setStepStatus(stepId, status);
}
setOverlay(overlay: {
kind: string;
message: string;
retryCount: number;
}): void {
this.store.setOverlay({
kind: "health",
message: overlay.message,
retryCount: overlay.retryCount,
});
}
clearOverlay(): void {
this.store.clearOverlay();
}
setIntroMode(enabled: boolean): void {
if (enabled) {
this.store.setLayout("intro");
this.pauseSidebarTimers();
return;
}
this.store.setLayout("workflow");
this.startSidebarTimers();
}
// ── Logging ───────────────────────────────────────────────────────
log: WizardLog = {
info: (message) => this.appendLog("info", message),
warn: (message) => this.appendLog("warn", message),
error: (message) => this.appendLog("error", message),
success: (message) => this.appendLog("success", message),
message: (message) => this.appendLog("message", message),
};
// ── Spinner ───────────────────────────────────────────────────────
spinner(): SpinnerHandle {
return {
start: (message?: string) => {
const clean = stripAnsi(message ?? "");
this.store.startSpinner(clean);
if (clean) {
this.store.appendStatus(clean);
}
},
message: (message?: string) => {
if (message !== undefined) {
const clean = stripAnsi(message);
this.store.setSpinnerMessage(clean);
if (clean) {
this.store.appendStatus(clean);
}
}
},
stop: (message?: string, code: SpinnerExitCode = 0) => {
const finalMessage =
message !== undefined
? stripAnsi(message)
: this.store.getSnapshot().spinner.message;
this.store.stopSpinner();
if (finalMessage) {
this.appendLog(severityForStopCode(code), finalMessage);
}
},
};
}
// ── Prompts ───────────────────────────────────────────────────────
select<T extends string>(opts: SelectOptions<T>): Promise<T | Cancelled> {
return new Promise((resolve) => {
const initialIndex =
opts.initialValue !== undefined
? Math.max(
0,
opts.options.findIndex(
(option) => option.value === opts.initialValue
)
)
: 0;
this.activePromptCancel = () => {
this.store.setPrompt(null);
this.activePromptCancel = undefined;
resolve(CANCELLED);
};
this.store.setPrompt({
kind: "select",
message: stripAnsi(opts.message),
options: opts.options.map((option) => ({
value: option.value,
label: option.label,
...(option.hint ? { hint: option.hint } : {}),
})),
initialIndex,
resolve: (value) => {
this.store.setPrompt(null);
this.activePromptCancel = undefined;
if (value === null) {
resolve(CANCELLED);
} else {
resolve(value as T);
}
},
});
});
}
multiselect<T extends string>(
opts: MultiSelectOptions<T>
): Promise<T[] | Cancelled> {
return new Promise((resolve) => {
this.activePromptCancel = () => {
this.store.setPrompt(null);
this.activePromptCancel = undefined;
resolve(CANCELLED);
};
this.store.setPrompt({
kind: "multiselect",
message: stripAnsi(opts.message),
options: opts.options.map((option) => ({
value: option.value,
label: option.label,
...(option.hint ? { hint: option.hint } : {}),
})),
initialSelected: opts.initialValues ?? [],
required: opts.required ?? false,
resolve: (values) => {
this.store.setPrompt(null);
this.activePromptCancel = undefined;
if (values === null) {
resolve(CANCELLED);
} else {
resolve(values as T[]);
}
},
});
});
}
confirm(opts: ConfirmOptions): Promise<boolean | Cancelled> {
return new Promise<boolean | Cancelled>((resolve) => {
this.activePromptCancel = () => {
this.store.setPrompt(null);
this.activePromptCancel = undefined;
resolve(CANCELLED);
};
this.store.setPrompt({
kind: "confirm",
message: stripAnsi(opts.message),
initialValue: opts.initialValue ?? true,
resolve: (value) => {
this.store.setPrompt(null);
this.activePromptCancel = undefined;
if (value === null) {
resolve(CANCELLED);
} else {
resolve(value);
}
},
});
});
}
welcome(opts: WelcomeOptions): Promise<"continue" | Cancelled> {
this.store.setLayout("intro");
this.pauseSidebarTimers();
if (this.initialWelcome) {
if (!this.initialWelcome.settled) {
seedWelcomePrompt(this.store, opts, this.initialWelcome);
}
return this.initialWelcome.promise.finally(() => {
this.activePromptCancel = undefined;
this.initialWelcome = undefined;
});
}
return new Promise<"continue" | Cancelled>((resolve) => {
this.activePromptCancel = () => {
this.store.setPrompt(null);
this.activePromptCancel = undefined;
resolve(CANCELLED);
};
this.store.setPrompt({
kind: "welcome",
options: sanitizeWelcomeOptions(opts),
resolve: (value) => {
this.store.setPrompt(null);
this.activePromptCancel = undefined;
if (value === null) {
resolve(CANCELLED);
} else {
resolve(value);
}
},
});
});
}
// ── Disposal ──────────────────────────────────────────────────────
[Symbol.asyncDispose](): Promise<void> {
this.tearDown();
return Promise.resolve();
}
/**
* Idempotent teardown. Safe to call from `[Symbol.asyncDispose]`,
* from `requestCancel()`, or from a SIGINT handler racing both. The
* `torndown` guard short-circuits second (and later) entries so we
* never call `unmount()` on an already-unmounted Ink instance or
* `setRawMode(false)` on an already-destroyed stream — both throw
* on some platforms.
*
* Order matters:
* 1. Stop the tip-rotation interval (libuv timer ref).
* 2. Detach SIGINT listener (we don't want a second Ctrl+C
* re-entering this path while we're in the middle of it).
* 3. `instance.clear()` — rewinds Ink's render region so the
* post-dispose chalk summary lands in place of the live
* wizard chrome rather than below it.
* 4. `instance.unmount()` — releases React reconciler resources.
* 5. Restore termios on the fresh `/dev/tty` stream, then
* `pause()` + `destroy()` so libuv can drain the handle and
* the process can exit naturally.
* 6. Emit the post-dispose summary to stdout (success outro or
* failure cancel line, matching the live screen's palette).
*
* Every step is wrapped in try/catch — disposal must never throw.
*/
private tearDown(): void {
if (this.torndown) {
return;
}
this.torndown = true;
if (this.tipTimer) {
clearInterval(this.tipTimer);
this.tipTimer = undefined;
}
this.stopLearnSequence();
if (this.cancelHandler) {
process.removeListener("SIGINT", this.cancelHandler);
this.cancelHandler = undefined;
}
// Detach the cancel callback from the store so a stale Ctrl+C
// routed through the App after teardown can't re-enter.
this.store.setRequestCancel(undefined);
try {
this.instance.clear();
} catch {
// best-effort
}
try {
this.instance.unmount();
} catch {
// best-effort
}
// Leave the alternate screen buffer so the user's original
// scrollback is restored.
try {
process.stdout.write("\x1b[?1049l");
} catch {
// best-effort — stdout may already be destroyed
}
if (this.freshStdin) {
try {
this.freshStdin.setRawMode(false);
} catch {
// stream already torn down
}
try {
this.freshStdin.pause();
this.freshStdin.destroy();
} catch {
// stream already destroyed
}
}
const report = this.buildPostDisposeReport();
if (report) {
// Write to stdout (not stderr) so the summary lands in the
// same stream as the cleared Ink output. Mixing stderr in
// would risk an extra line break or out-of-order interleave
// depending on shell pipe handling.
process.stdout.write(`${report}\n`);
}
}
/**
* Cooperative cancellation entry point. Called from three places:
*
* 1. The App's top-level `useInput` Ctrl+C catcher (when no
* prompt is mounted — typically during a spinner / network
* call). Routed via `store.requestCancel()`.
* 2. The SIGINT process listener (covers raw-mode-off windows
* where Node delivers SIGINT instead of `\x03`).
* 3. (Indirectly) prompt cancellation, when an active prompt's
* own `useInput` resolves with `null`. That path doesn't go
* through `requestCancel` directly because the prompt's
* promise resolution drives the wizard runner's
* `WizardCancelledError` flow, which then runs
* `[Symbol.asyncDispose]` → `tearDown()` naturally.
*
* If a prompt IS active, we delegate to its cancel callback and
* return without exiting — the wizard runner will catch the
* resulting `WizardCancelledError` and exit cleanly via the
* `await using` path.
*
* If no prompt is active (spinner case), we tear down immediately
* and `process.exit(130)`. We can't route through the runner
* because it's blocked on `await executeTool(...)` or
* `await run.resumeAsync(...)` — there's nothing waiting to throw
* into. Exit code 130 is the SIGINT convention; the terminal is
* fully restored before exit so the user's shell prompt comes
* back cleanly.
*
* A second Ctrl+C while teardown is in progress force-exits via
* `process.exit(130)` so the user is never trapped by a stuck
* teardown.
*/
requestCancel(): void {
const promptCancel = this.activePromptCancel;
if (promptCancel) {
// Prompt path — let the runner unwind via WizardCancelledError.
// Don't tear down here; the `await using` in the runner will
// call us back through `[Symbol.asyncDispose]`.
promptCancel();
return;
}
if (this.cancelRequested) {
// Safety valve: teardown already started but hasn't finished
// (or something is stuck). Force-exit so the user isn't trapped.
setTag("wizard.outcome", "abandoned");
process.exit(130);
}
this.cancelRequested = true;
this.failureMessage = "Setup cancelled.";
this.feedback("cancelled");
this.tearDown();
// Mark as abandoned before exit so the Sentry span carries the
// outcome even though beforeExit never fires for explicit process.exit().
setTag("wizard.outcome", "abandoned");
// Match the SIGINT convention so shells (and CI) see a
// distinguishable exit. The runner's `await using` won't get a
// chance to run after this, but tearDown above already did all
// the cleanup that path would have performed.
// Defer exit by one tick so the event loop can flush the
// stdout writes from tearDown (alternate-screen escape +
// cancellation report) before the process terminates.
setImmediate(() => process.exit(130));
}
/**
* Build a compact final summary echoed to stdout after Ink
* unmounts. Ink's inline rendering means the run's log lines are
* already in the user's scrollback; this report just emphasises
* the outcome so it's the last thing on screen.
*
* Three shapes:
* - Success: outro line + summary fields + changed files.
* - Failure: cancel/error line on its own.
* - Empty: no useful state captured (early abort, etc.) —
* return `undefined` and the caller skips the
* stderr write.
*
* Failure wins over success if both are set.
*/
private buildPostDisposeReport(): string | undefined {
if (this.failureMessage) {
return formatFailureReport(
this.failureMessage,
this.store.getSnapshot().logs,
this.feedbackHint
);
}
if (!this.outroMessage) {
return;
}
return formatSuccessReport(
this.outroMessage,
this.store.getSnapshot().summary ?? undefined,
this.feedbackHint
);
}
// ── Internal helpers ──────────────────────────────────────────────
private appendLog(severity: LogSeverity, message: string): void {
this.store.appendLog(severity, stripAnsi(message));
}
private startTipRotation(): void {
if (this.tipTimer) {
return;
}
this.tipTimer = setInterval(() => {
this.tipIndex = (this.tipIndex + 1) % SENTRY_TIPS.length;
this.store.setTipIndex(this.tipIndex);
}, TIP_ROTATE_INTERVAL_MS);
}
private startLearnSequence(): void {
if (this.learnTimer) {
return;
}
const store = this.store;
this.learnTimer = setInterval(() => {
if (this.torndown) {
this.stopLearnSequence();
return;
}
const { learnState } = store.getSnapshot();
if (learnState.complete) {
this.stopLearnSequence();
if (!this.torndown) {
this.startTipRotation();
}
return;
}
const next = learnState.blockIndex + 1;
if (next >= LEARN_SEQUENCE.length) {
store.setLearnComplete();
this.stopLearnSequence();
if (!this.torndown) {
this.startTipRotation();
}
} else {
store.advanceLearnBlock();
}
}, TIP_ROTATE_INTERVAL_MS);
}
private stopLearnSequence(): void {
if (this.learnTimer) {
clearInterval(this.learnTimer);
this.learnTimer = undefined;
}
}
private startSidebarTimers(): void {
if (this.torndown) {
return;
}
if (this.store.getSnapshot().learnState.complete) {
this.startTipRotation();
return;
}
this.startLearnSequence();
}
private pauseSidebarTimers(): void {
if (this.tipTimer) {
clearInterval(this.tipTimer);
this.tipTimer = undefined;
}
this.stopLearnSequence();
}
/**
* Fallback SIGINT handler for the (rare) windows where raw mode
* is OFF and Node's terminal layer DOES deliver SIGINT for
* Ctrl+C. The primary Ctrl+C handling lives inside Ink's
* `useInput` (see `ink-app.tsx`'s top-level App component): in
* raw mode, Node sends `\x03` as a byte instead of SIGINT.
*
* This handler covers the brief window between InkUI
* construction and the first `useInput` listener being mounted,
* plus any time raw mode flickers off (Ink toggles it in a
* useEffect when the listener count drops to zero).
*
* Both this handler and the App's `useInput` Ctrl+C path funnel
* into `requestCancel()` so the cancellation flow has a single
* implementation. Uses `process.on` so the handler survives a
* prompt-delegation Ctrl+C (where `requestCancel` returns early
* without setting `cancelRequested`). If teardown is already in
* progress, `requestCancel` force-exits — protects against a
* stuck teardown holding the user hostage.
*/
private installCancelHandler(): void {
const handler = () => {
this.requestCancel();
};
this.cancelHandler = handler;
process.on("SIGINT", handler);
}
}