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

main
tsx 2,836 lines 94.4 KB
Raw
1 /** @jsxImportSource @alchemy.run/sigil */
2 import { PassThrough } from "node:stream";
3 import { stripVTControlCharacters } from "node:util";
4 import { expect, it } from "@alchemy.run/test";
5 import * as Console from "effect/Console";
6 import * as Context from "effect/Context";
7 import * as Effect from "effect/Effect";
8 import * as Exit from "effect/Exit";
9 import * as Fiber from "effect/Fiber";
10 import * as Layer from "effect/Layer";
11 import * as Logger from "effect/Logger";
12 import * as Alchemist from "@/Alchemist/index.ts";
13 import {
14 AnsweredPrompt,
15 Alert,
16 Box,
17 ChoiceGroup,
18 DescriptionList,
19 Heading,
20 KeyBar,
21 LiveStore,
22 PromptFrame,
23 ProgressGroup,
24 ProgressBar,
25 SectionHeading,
26 Status,
27 Toast,
28 Tabs,
29 TaskRow,
30 Text,
31 TextField,
32 useLiveStore,
33 } from "@/Cli/components/ui/index.ts";
34 import { Menu } from "@/Cli/components/ui/Interactive.tsx";
35 import { tabsWindow } from "@/Cli/components/ui/Layout.tsx";
36 import { ApprovePlan } from "@/Cli/components/view/ApprovePlan.tsx";
37 import { formatView } from "@/Cli/components/view/Format.tsx";
38 import {
39 NukeProgress,
40 NukeProgressStore,
41 nukePlan,
42 reviewNuke,
43 renderNukeDelete,
44 renderNukeScan,
45 } from "@/Cli/components/view/Nuke.tsx";
46 import { Plan, PlanTree } from "@/Cli/components/view/PlanView.tsx";
47 import {
48 ProfileDetailsBody,
49 providerBlockHeight,
50 type ProfileProviderDisplay,
51 } from "@/Cli/components/view/Profile.tsx";
52 import {
53 Dashboard,
54 DashStore,
55 runProfileDashboardSession,
56 } from "@/Cli/components/view/ProfileDashboard.tsx";
57 import { browserLoginScreen, cycleSelectScreen } from "@/Cli/components/view/Prompts.tsx";
58 import { makeRuntime } from "@/Cli/components/view/Runtime.tsx";
59 import { sigilCli } from "@/Cli/components/view/SigilCli.tsx";
60 import { stackOutputsView } from "@/Cli/components/view/StackOutputs.tsx";
61 import {
62 buildStageNodes,
63 stateExplorerScreen,
64 StateExplorerStore,
65 type StateExplorerSource,
66 } from "@/Cli/components/view/StateExplorer.tsx";
67 import { isInProgress } from "@/Cli/components/view/statusStyle.ts";
68 import { emit } from "@/Events.ts";
69 import {
70 Interaction,
71 NonInteractiveTerminal,
72 Screen,
73 TerminalCancelled,
74 layer as interactionLayer,
75 makeNonInteractive,
76 type View,
77 } from "@/Interaction.ts";
78 import type { ProviderService } from "@/Provider.ts";
79 import { renderApply } from "@/Report.ts";
80 import { Cli } from "@/Report.ts";
81 import { makePlainConsoleSink } from "@/Util/ConsoleSink.ts";
82 import { type LogRecord, recordOf } from "@/Util/LogRecord.ts";
83 import { makeResourceLogger, makeResourceOutput } from "@/Util/ResourceOutput.ts";
84 import { spinnerFramesFor } from "@/Util/Theme.ts";
85 import { deleteNode, noopNode, planWith, updateNode } from "./PlanTestNodes.ts";
86
87 class CaptureStream extends PassThrough {
88 readonly columns = 80;
89 readonly rows = 24;
90 output = "";
91
92 constructor(readonly isTTY = false) {
93 super();
94 this.on("data", (chunk) => {
95 this.output += chunk.toString();
96 });
97 }
98
99 waitFor(text: string): Promise<void> {
100 if (this.output.includes(text)) return Promise.resolve();
101 return new Promise((resolve) => {
102 const onData = () => {
103 if (!this.output.includes(text)) return;
104 this.off("data", onData);
105 resolve();
106 };
107 this.on("data", onData);
108 });
109 }
110 }
111
112 class InputStream extends PassThrough {
113 readonly isTTY = true;
114 isRaw = false;
115 private resolveReady: (() => void) | undefined;
116 readonly ready = new Promise<void>((resolve) => {
117 this.resolveReady = resolve;
118 });
119
120 setRawMode(mode: boolean) {
121 this.isRaw = mode;
122 if (mode) {
123 // Size-only consumers no longer query capabilities. Input is ready once
124 // the raw-mode reader attaches; a query may temporarily detach it.
125 setImmediate(() => {
126 if (this.listenerCount("readable") > 0) this.resolveReady?.();
127 });
128 }
129 return this;
130 }
131
132 connect(stdout: CaptureStream) {
133 stdout.on("data", (chunk) => {
134 if (!chunk.toString().includes("\x1b[c")) return;
135 // Raw mode starts before Sigil finishes querying the terminal. Answer
136 // its device query, then allow input handlers to attach before typing.
137 setImmediate(() => {
138 this.write("\x1b[?1;2c");
139 setImmediate(() => this.resolveReady?.());
140 });
141 });
142 }
143
144 ref() {
145 return this;
146 }
147
148 unref() {
149 return this;
150 }
151 }
152
153 const staticCapabilities = {
154 input: false,
155 columns: 80,
156 rows: 24,
157 colors: false,
158 unicode: true,
159 alternateScreen: false,
160 };
161
162 /** Render a view without a renderer, like help screens do. */
163 const formatStatic = (
164 view: View,
165 options?: { columns?: number; colors?: boolean; unicode?: boolean },
166 ) => formatView(view, { ...staticCapabilities, unicode: options?.unicode ?? true }, options);
167
168 const renderStatic = (
169 view: View,
170 options?: { columns?: number; colors?: boolean; unicode?: boolean },
171 ) => Effect.sync(() => formatStatic(view, options));
172
173 /** The plain renderer over a captured stdout. */
174 const makeStatic = () => {
175 const stdout = new CaptureStream();
176 const service = makeNonInteractive({
177 // SAFETY: CaptureStream implements the writable stream surface consumed here.
178 stdout: stdout as unknown as NodeJS.WriteStream,
179 colors: false,
180 unicode: true,
181 });
182 return { service, stdout };
183 };
184
185 const makeExplorerSource = () => {
186 const calls = { stacks: 0, stages: 0, resources: 0, files: 0 };
187 const source: StateExplorerSource = {
188 backend: "local",
189 listStacks: Effect.sync(() => {
190 calls.stacks++;
191 return ["app"];
192 }),
193 listStages: () =>
194 Effect.sync(() => {
195 calls.stages++;
196 return ["prod"];
197 }),
198 listResources: () =>
199 Effect.sync(() => {
200 calls.resources++;
201 return ["Api/Worker"];
202 }),
203 readFile: () =>
204 Effect.sync(() => {
205 calls.files++;
206 return { status: "created", url: "https://workers.dev" };
207 }),
208 deleteNodes: () => Effect.void,
209 };
210 return { calls, source };
211 };
212
213 const explorerSource = makeExplorerSource().source;
214 const flushEffects = () => new Promise<void>((resolve) => setImmediate(resolve));
215
216 it(
217 "builds Finder-style namespace columns from FQN names",
218 () => {
219 const nodes = buildStageNodes("app", "prod", ["Api/Worker"]);
220 expect(nodes.map((node) => node.name)).toEqual(["Api", "output"]);
221 const api = nodes[0];
222 expect(api?.kind).toBe("namespace");
223 if (api?.kind === "namespace") {
224 expect(api.children.map((node) => node.name)).toEqual(["Worker"]);
225 }
226 },
227 { tags: ["unit", "local"] },
228 );
229
230 it(
231 "loads state columns and file contents only when selected",
232 async () => {
233 const { calls, source } = makeExplorerSource();
234 const store = new StateExplorerStore(source);
235 store.loadRoot();
236 await flushEffects();
237 expect(calls).toEqual({ stacks: 1, stages: 0, resources: 0, files: 0 });
238
239 const root = store.snapshot().root;
240 expect(root.status).toBe("ready");
241 if (root.status !== "ready") return;
242 const stack = root.value[0]!;
243 store.loadChildren(stack);
244 await flushEffects();
245 expect(calls).toEqual({ stacks: 1, stages: 1, resources: 0, files: 0 });
246
247 const stages = store.snapshot().children.get(stack.id);
248 if (stages?.status !== "ready") return;
249 const stage = stages.value[0]!;
250 store.loadChildren(stage);
251 await flushEffects();
252 expect(calls).toEqual({ stacks: 1, stages: 1, resources: 1, files: 0 });
253
254 const state = store.snapshot().children.get(stage.id);
255 if (state?.status !== "ready") return;
256 const namespace = state.value.find((node) => node.kind === "namespace");
257 if (namespace?.kind !== "namespace") return;
258 store.loadFile(namespace.children[0]!);
259 await flushEffects();
260 expect(calls).toEqual({ stacks: 1, stages: 1, resources: 1, files: 1 });
261 },
262 { tags: ["unit", "local"] },
263 );
264
265 it(
266 "ignores state explorer responses from before a refresh",
267 async () => {
268 let resolveStale: ((stacks: ReadonlyArray<string>) => void) | undefined;
269 let request = 0;
270 const source: StateExplorerSource = {
271 ...explorerSource,
272 listStacks: Effect.suspend(() => {
273 request++;
274 if (request === 1) {
275 return Effect.promise(
276 () =>
277 new Promise((resolve) => {
278 resolveStale = resolve;
279 }),
280 );
281 }
282 return Effect.succeed(["fresh"]);
283 }),
284 };
285 const store = new StateExplorerStore(source);
286 store.loadRoot();
287 store.refresh();
288 await flushEffects();
289
290 resolveStale?.(["stale"]);
291 await flushEffects();
292
293 const root = store.snapshot().root;
294 expect(root.status).toBe("ready");
295 if (root.status === "ready") {
296 expect(root.value.map((node) => node.name)).toEqual(["fresh"]);
297 }
298 },
299 { tags: ["unit", "local"] },
300 );
301
302 it(
303 "prints stack outputs using inspect without wrapping long lines",
304 () => {
305 const { service } = makeStatic();
306 const apiUrl =
307 "https://cloudflareworkerexample-api-clxp5k3fbtqacxdev7mx7uuxmw.testing-2b2.workers.dev";
308 // Narrow width: `wrap="none"` output lines must overflow, not break.
309 const output = formatStatic(
310 stackOutputsView({ apiUrl, metadata: { region: "us-east-1", replicas: 2 } }),
311 { columns: 40 },
312 );
313
314 expect(output).toBe(
315 `{\n apiUrl: '${apiUrl}',\n metadata: { region: 'us-east-1', replicas: 2 }\n}`,
316 );
317 },
318 { tags: ["unit", "local"] },
319 );
320
321 it(
322 "renders detailed plans as nested YAML",
323 () => {
324 const { service } = makeStatic();
325 const tree = new PlanTree(
326 planWith([updateNode({ config: { retries: 2 } }, { config: { retries: 3 } })]),
327 { detailed: true, viewport: "full" },
328 );
329 const output = formatStatic(<Plan tree={tree} />, { columns: 80 });
330
331 expect(output).toContain("properties:");
332 expect(output).toContain("config:");
333 expect(output).toContain("│ - retries: 2");
334 expect(output).toContain("│ + retries: 3");
335 expect(output).toContain("(Test.Resource)");
336 },
337 { tags: ["unit", "local"] },
338 );
339
340 it(
341 "keeps the plan summary visible and updates it during apply",
342 () => {
343 const { service } = makeStatic();
344 const plan = {
345 ...planWith([updateNode({ version: 1 }, { version: 2 }), noopNode({ version: 1 }, "Stable")]),
346 defaultMode: "local" as const,
347 };
348 const reviewTree = new PlanTree(plan, { viewport: "full" });
349 const reviewOutput = formatStatic(<Plan tree={reviewTree} />, { columns: 80 });
350 const tree = new PlanTree(plan, { mode: "apply", label: "Starting dev stack", busy: true });
351 const output = formatStatic(<Plan tree={tree} collapsible />, { columns: 160 });
352
353 expect(reviewOutput).toContain("1 to update");
354 expect(reviewOutput).toContain("1 no change");
355 expect(output.indexOf("─")).toBeLessThan(output.indexOf("Starting dev stack"));
356 expect(output.indexOf("Plan")).toBeLessThan(output.indexOf("Worker"));
357 expect(output.indexOf("Starting dev stack")).toBeGreaterThan(output.indexOf("Worker"));
358 expect(output).toContain("1 pending");
359 expect(output).toContain("1 no change");
360 expect(
361 spinnerFramesFor(true).some((frame) => output.includes(`${frame} Starting dev stack`)),
362 ).toBe(true);
363 const keybarLine = output.split("\n").find((line) => line.includes("p hide widget"));
364 expect(keybarLine).toContain("p hide widget");
365 expect(keybarLine).toContain("Ctrl+C exit");
366 expect(keybarLine).toContain("↑/↓ scroll plan");
367 expect(keybarLine).toContain("Starting dev stack");
368
369 tree.emit({
370 type: "apply.resource.status",
371 fqn: "Worker",
372 id: "Worker",
373 resourceType: "Test.Resource",
374 status: "updating",
375 });
376 tree.setBusy(false);
377 tree.setViewport("full");
378 const updatingOutput = formatStatic(<Plan tree={tree} />, { columns: 80 });
379 expect(updatingOutput).toContain("1 updating");
380 expect(updatingOutput).not.toContain("1 pending");
381 expect(updatingOutput).toContain("1 no change");
382 expect(
383 spinnerFramesFor(true).some((frame) =>
384 updatingOutput.includes(`${frame} Starting dev stack`),
385 ),
386 ).toBe(false);
387 },
388 { tags: ["unit", "local"] },
389 );
390
391 it(
392 "keeps a large destroy summary and confirmation visible",
393 () => {
394 const { service } = makeStatic();
395 const deletions = Array.from({ length: 40 }, (_, index) => deleteNode({}, `Resource${index}`));
396 const plan = { ...planWith([], deletions), destroy: true };
397 const output = formatStatic(
398 <ApprovePlan plan={plan} controller={{ submit: () => undefined, cancel: () => undefined }} />,
399 { columns: 80 },
400 );
401
402 expect(output).toContain("Destroy");
403 expect(output).toContain("40 to delete");
404 expect(output).toContain("Destroy?");
405 expect(output).toContain("more lines");
406 expect(output).toContain("↑/↓ scroll plan");
407 },
408 { tags: ["unit", "local"] },
409 );
410
411 it(
412 "keeps apply totals on top and destroy progress on the last row",
413 () => {
414 const { service } = makeStatic();
415 const plan = {
416 ...planWith(
417 [],
418 Array.from({ length: 10 }, (_, index) => deleteNode({}, `Resource${index}`)),
419 ),
420 destroy: true,
421 };
422 const tree = new PlanTree(plan, { mode: "apply", label: "Destroying stack", busy: true });
423 tree.emit({
424 type: "apply.resource.status",
425 fqn: "Resource0",
426 id: "Resource0",
427 resourceType: "Test.Resource",
428 status: "deleted",
429 });
430
431 const output = formatStatic(<Plan tree={tree} />, { columns: 120 });
432 const lines = output.split("\n");
433 const summaryLine = lines.find((line) => line.includes("Plan ·"));
434 const progressLine = lines.find((line) => line.includes("Destroying stack"));
435
436 expect(summaryLine).toContain("1 deleted");
437 expect(summaryLine).toContain("9 pending");
438 expect(progressLine).toContain("Destroying stack (1/10)");
439 expect(spinnerFramesFor(true).some((frame) => progressLine?.includes(frame))).toBe(true);
440 expect(output.indexOf("Plan ·")).toBeLessThan(output.indexOf("Resource0"));
441 expect(output.indexOf("Destroying stack")).toBeGreaterThan(output.indexOf("Resource9"));
442 },
443 { tags: ["unit", "local"] },
444 );
445
446 it(
447 "binding rows mirror their host resource and stay out of totals",
448 () => {
449 const { service } = makeStatic();
450 const worker = {
451 ...updateNode({ a: 1 }, { a: 2 }, "Worker"),
452 bindings: [
453 { sid: "BUCKET", action: "update" as const, data: {} },
454 { sid: "OLD", action: "delete" as const, data: {} },
455 { sid: "STABLE", action: "noop" as const, data: {} },
456 ],
457 };
458 const tree = new PlanTree(planWith([worker]), {
459 mode: "apply",
460 label: "Deploying stack",
461 busy: true,
462 });
463 const render = () => formatStatic(<Plan tree={tree} />, { columns: 80 });
464
465 // Three bindings never inflate the total: only the host is work.
466 expect(tree.progress()).toEqual({ completed: 0, failures: 0, total: 1 });
467 let output = render();
468 expect(output).toContain("Deploying stack (0/1)");
469 expect(output).toContain("unbind");
470 expect(output).toContain("no change");
471
472 tree.emit({
473 type: "apply.resource.status",
474 fqn: "Worker",
475 id: "Worker",
476 resourceType: "Test.Resource",
477 status: "updating",
478 });
479 output = render();
480 expect(output).toContain("unbinding");
481 expect(output).toContain("Deploying stack (0/1)");
482
483 tree.emit({
484 type: "apply.resource.status",
485 fqn: "Worker",
486 id: "Worker",
487 resourceType: "Test.Resource",
488 status: "updated",
489 });
490 expect(tree.progress()).toEqual({ completed: 1, failures: 0, total: 1 });
491 output = render();
492 expect(output).toContain("Deploying stack (1/1)");
493 expect(output).toContain("unbound");
494 expect(output).toContain("1 updated");
495 expect(output).not.toContain("pending");
496 },
497 { tags: ["unit", "local"] },
498 );
499
500 it(
501 "binding rows follow a failed host",
502 () => {
503 const { service } = makeStatic();
504 const worker = {
505 ...updateNode({ a: 1 }, { a: 2 }, "Worker"),
506 bindings: [{ sid: "BUCKET", action: "update" as const, data: {} }],
507 };
508 const tree = new PlanTree(planWith([worker]), {
509 mode: "apply",
510 label: "Deploying stack",
511 busy: true,
512 });
513 tree.emit({
514 type: "apply.resource.status",
515 fqn: "Worker",
516 id: "Worker",
517 resourceType: "Test.Resource",
518 status: "fail",
519 message: "worker failed",
520 });
521
522 const output = formatStatic(<Plan tree={tree} />, { columns: 80 });
523 expect(tree.progress()).toEqual({ completed: 1, failures: 1, total: 1 });
524 expect(output).toContain("1 fail");
525 expect(output).toContain("Deploying stack (1/1)");
526 expect(output).toContain("worker failed");
527 expect(output).not.toContain("pending");
528 },
529 { tags: ["unit", "local"] },
530 );
531
532 it.effect(
533 "keeps native progress active until the apply outcome settles",
534 () =>
535 Effect.gen(function* () {
536 const { service, stdout } = yield* makeLive();
537 const tree = new PlanTree(planWith([updateNode({ version: 1 }, { version: 2 })]), {
538 mode: "apply",
539 label: "Deploying stack",
540 busy: true,
541 });
542 tree.emit({
543 type: "apply.resource.status",
544 fqn: "Worker",
545 id: "Worker",
546 resourceType: "Test.Resource",
547 status: "updated",
548 });
549 const live = yield* service.live(<Plan tree={tree} />);
550 yield* Effect.promise(flushEffects);
551 expect(stdout.output).toContain("\u001B]9;4;1;100\u001B\\");
552
553 const settledAt = stdout.output.length;
554 tree.finish("failure", "Deploy failed");
555 yield* Effect.promise(flushEffects);
556 expect(stdout.output.slice(settledAt)).toContain("\u001B]9;4;2;100\u001B\\");
557 yield* live.close;
558 }),
559 { tags: ["unit", "local"] },
560 );
561
562 it.effect(
563 "renders completed dev plans as a hideable output view",
564 () =>
565 Effect.gen(function* () {
566 const { service, stdout } = yield* makeLive();
567 const plan = {
568 ...planWith([updateNode({ version: 1 }, { version: 2 })]),
569 defaultMode: "local" as const,
570 };
571 const tree = new PlanTree(plan, { mode: "apply", label: "Starting dev stack" });
572 const live = yield* service.live(<Plan tree={tree} collapsible />);
573
574 yield* Effect.promise(() => stdout.waitFor("p hide widget"));
575 yield* Effect.sync(() => {
576 tree.setOutput({ endpoint: "http://localhost:3000" });
577 tree.finish("success", "Dev stack ready", "output");
578 });
579 yield* Effect.promise(() => stdout.waitFor("http://localhost:3000"));
580 expect(stdout.output).toContain("←/→ show plan");
581
582 tree.setView("plan");
583 expect(tree.snapshot().view).toBe("plan");
584
585 tree.setExpanded(false);
586 yield* Effect.promise(() => stdout.waitFor("p show plan/output"));
587
588 const { service: staticService } = makeStatic();
589 const hiddenOutput = formatStatic(<Plan tree={tree} collapsible />, {
590 columns: 80,
591 });
592 expect(hiddenOutput).not.toContain("Plan ·");
593 expect(hiddenOutput).not.toContain("Worker");
594 expect(hiddenOutput).not.toContain("http://localhost:3000");
595 expect(hiddenOutput).toContain("Dev stack ready (0/1)");
596 expect(hiddenOutput).toContain("p show plan/output");
597 yield* live.close;
598 }),
599 { tags: ["unit", "local"] },
600 );
601
602 // A dev generation keeps its widget mounted after apply settles and parks
603 // until a reload (or Ctrl+C) closes its scope. Closing that scope must remove
604 // the widget: leaving it behind stacks one stale "Dev stack ready" bar per
605 // reload under the live one.
606 it.effect(
607 "removes the dev apply widget when its generation scope closes",
608 () =>
609 Effect.gen(function* () {
610 const { service, stdout } = yield* makeLive();
611 const plan = {
612 ...planWith([updateNode({ version: 1 }, { version: 2 })]),
613 defaultMode: "local" as const,
614 };
615 const cli = sigilCli().pipe(Layer.provide(Layer.succeed(Interaction, service)));
616 let settledAt = 0;
617 yield* Effect.scoped(
618 Effect.gen(function* () {
619 yield* Effect.succeed({ endpoint: "http://localhost:3000" }).pipe(
620 renderApply(plan, { dev: true }),
621 );
622 yield* Effect.promise(() => stdout.waitFor("Dev stack ready"));
623 settledAt = stdout.output.length;
624 }),
625 ).pipe(Effect.provide(cli));
626
627 // Nothing else is live once the generation is gone, so the renderer
628 // unmounts and restores the cursor.
629 expect(stdout.output.slice(settledAt)).toContain("[?25h");
630 }),
631 { tags: ["unit", "local"] },
632 );
633
634 // `p` hides the dev widget; a hot reload opens a fresh session and must not
635 // bring it back — the user's choice outlives the generation that made it.
636 it.effect(
637 "keeps the dev plan widget hidden across hot reloads",
638 () =>
639 Effect.gen(function* () {
640 const stdin = new InputStream();
641 const { service, stdout } = yield* makeLive({ stdin });
642 const plan = {
643 ...planWith([updateNode({ version: 1 }, { version: 2 })]),
644 defaultMode: "local" as const,
645 };
646 const cli = sigilCli().pipe(Layer.provide(Layer.succeed(Interaction, service)));
647 yield* Effect.gen(function* () {
648 const { startApplySession } = yield* Cli;
649 const first = yield* startApplySession(plan, { dev: true });
650 yield* first.done("success");
651 yield* Effect.promise(() => stdout.waitFor("p hide widget"));
652 yield* Effect.promise(() => stdin.ready);
653 yield* Effect.sync(() => stdin.write("p"));
654 yield* Effect.promise(() => stdout.waitFor("p show plan/output"));
655 yield* first.close!;
656
657 const reloadedAt = stdout.output.length;
658 const second = yield* startApplySession(plan, { dev: true });
659 yield* second.done("success");
660 yield* Effect.promise(() => stdout.waitFor("Dev stack ready"));
661 const reloaded = stdout.output.slice(reloadedAt);
662 expect(reloaded).toContain("p show plan/output");
663 expect(reloaded).not.toContain("p hide widget");
664 yield* second.close!;
665 }).pipe(Effect.provide(cli));
666 }),
667 { tags: ["unit", "local"] },
668 );
669
670 it(
671 "virtualizes dev stack output",
672 () => {
673 const { service } = makeStatic();
674 const tree = new PlanTree(planWith([updateNode({}, {})]), {
675 mode: "apply",
676 label: "Dev stack ready",
677 });
678 tree.setOutput(
679 Object.fromEntries(Array.from({ length: 40 }, (_, index) => [`output${index}`, index])),
680 );
681 tree.setView("output");
682
683 const output = formatStatic(<Plan tree={tree} collapsible />, { columns: 80 });
684 expect(output).toContain("Output");
685 expect(output).toContain("earlier lines");
686 expect(output).not.toContain("Worker");
687 expect(output).toContain("←/→ show plan");
688 expect(output).toContain("↑/↓ scroll output");
689 expect(output.split("\n").length).toBeLessThanOrEqual(21);
690 },
691 { tags: ["unit", "local"] },
692 );
693
694 it(
695 "renders drift details without detailed mode",
696 () => {
697 const { service } = makeStatic();
698 const node = updateNode({ value: "declared" }, { value: "declared" });
699 node.drift = { expected: { value: "declared" }, actual: { value: "changed-out-of-band" } };
700 const tree = new PlanTree(planWith([node]), { viewport: "full" });
701 const output = formatStatic(<Plan tree={tree} />, { columns: 80 });
702
703 expect(output).not.toContain("drift:");
704 expect(output).toContain("│ - value: declared");
705 expect(output).toContain("│ + value: changed-out-of-band");
706 },
707 { tags: ["unit", "local"] },
708 );
709
710 it(
711 "replaces provider details with refresh progress in place",
712 () => {
713 const { service } = makeStatic();
714 const output = formatStatic(
715 <ProfileDetailsBody
716 providers={[
717 {
718 name: "Cloudflare",
719 method: "oauth",
720 status: "ready",
721 lines: ["accessToken: cfoa****", "expires: in 59m"],
722 },
723 { name: "GitHub", method: "gh-cli", status: "ready", lines: ["token: gho_cZ****"] },
724 ]}
725 refreshingProvider="Cloudflare"
726 />,
727 { columns: 80 },
728 );
729
730 expect(output).toContain("Cloudflare");
731 expect(output).toContain("refreshing OAuth credentials…");
732 expect(output).not.toContain("cfoa****");
733 expect(output).not.toContain("in 59m");
734 expect(output).toContain("GitHub");
735 // `key: value` detail lines render as an aligned key column + value
736 expect(output).toContain("token gho_cZ****");
737 },
738 { tags: ["unit", "local"] },
739 );
740
741 // Eight providers of varying height: 49 rows in total, twice a 24-row terminal.
742 const dashboardProviders: ReadonlyArray<ProfileProviderDisplay> = [
743 {
744 name: "AWS",
745 method: "sso",
746 status: "ready",
747 lines: [
748 "accessKeyId: ASIA****",
749 "secretAccessKey: I7hs****",
750 "sessionToken: IQoJ****",
751 "region: us-east-2",
752 "source: sso - default",
753 ],
754 },
755 {
756 name: "Cloudflare",
757 method: "stored",
758 status: "configured",
759 lines: ["apiKey: cfk_****", "email: blan****", "accountId: 2b29****", "source: stored"],
760 },
761 { name: "Fly", method: "stored", status: "configured", lines: ["apiKey: FlyV****"] },
762 {
763 name: "GitHub",
764 method: "gh-cli",
765 status: "configured",
766 lines: ["token: gho_cZ****", "source: gh-cli"],
767 },
768 { name: "Hetzner", method: "stored", status: "configured", lines: ["token: 50Kt****"] },
769 { name: "Prisma", method: "stored", status: "configured", lines: ["serviceToken: eyJr****"] },
770 {
771 name: "Railway",
772 method: "oauth",
773 status: "configured",
774 lines: [
775 "token: rw_Fe2****",
776 "tokenKind: account",
777 "apiBaseUrl: https://backboard.railway.com",
778 "source: oauth",
779 ],
780 },
781 { name: "Vercel", method: "stored", status: "reauth", lines: ["token: vc_****"] },
782 ];
783
784 const dashboardEntries = [{ name: "default", isActive: true, isDefault: true }];
785
786 // The dashboard windows providers by `providerBlockHeight`, so the number must
787 // match what a block actually renders.
788 it(
789 "sizes provider blocks by providerBlockHeight",
790 () => {
791 const { service } = makeStatic();
792 const output = formatStatic(<ProfileDetailsBody providers={dashboardProviders} focusColumn />, {
793 columns: 80,
794 });
795 const expected = dashboardProviders.reduce(
796 (rows, provider, index) => rows + providerBlockHeight(provider, index === 0),
797 0,
798 );
799 expect(output.split("\n").length).toBe(expected);
800 },
801 { tags: ["unit", "local"] },
802 );
803
804 // Providers are a table separated by blank rows, not rules; the focused
805 // provider is marked by the cursor glyph in a reserved column, never a rail.
806 it(
807 "marks the focused provider with the pointer and no rails",
808 () => {
809 const { service } = makeStatic();
810 const output = formatStatic(
811 <ProfileDetailsBody
812 providers={dashboardProviders}
813 focusColumn
814 focusedProvider="Cloudflare"
815 reauthHint="press r to re-login"
816 />,
817 { columns: 80 },
818 );
819 const lines = output.split("\n");
820 expect(lines.some((line) => /[│─]/.test(line))).toBe(false);
821 const pointed = lines.filter((line) => line.includes("❯"));
822 expect(pointed).toHaveLength(1);
823 expect(pointed[0]).toMatch(/^ ❯ Cloudflare\s+stored\s+! configured$/);
824 expect(lines.some((line) => /^ AWS\s+sso\s+✓ ready$/.test(line))).toBe(true);
825 // detail keys render as an aligned column: key, gap, value
826 expect(output).toContain("apiKey cfk_****");
827 expect(output).toContain("accountId 2b29****");
828 // the re-login hint follows the focus cursor, so it is hidden here
829 expect(output).not.toContain("press r to re-login");
830 },
831 { tags: ["unit", "local"] },
832 );
833
834 it(
835 "windows the profile dashboard's providers to the terminal height",
836 () => {
837 const { service, stdout } = makeStatic();
838 const store = new DashStore(dashboardEntries);
839 store.setDetails("default", { state: "ready", providers: dashboardProviders, available: [] });
840 const output = formatStatic(<Dashboard store={store} initialSelected={0} />, {
841 columns: 80,
842 });
843
844 expect(output.split("\n").length).toBeLessThanOrEqual(stdout.rows);
845 expect(output).toContain("AWS");
846 expect(output).toContain("Cloudflare");
847 expect(output).toContain("switch profile");
848 expect(output).not.toContain("Vercel");
849 // The profile row holds the initial focus slot: the pointer sits on it and
850 // the provider rows keep a blank cursor column so the table stays aligned.
851 expect(output).toContain("\n ❯ default");
852 expect(output).toContain("\n AWS ");
853 },
854 { tags: ["unit", "local"] },
855 );
856
857 // The session sleeps on a real clock (loader delay, notice auto-dismiss).
858 it.live(
859 "scrolls the profile dashboard to the focused provider",
860 () =>
861 Effect.gen(function* () {
862 const stdin = new InputStream();
863 const { service, stdout } = yield* makeLive({ stdin });
864 const session = yield* runProfileDashboardSession({
865 entries: dashboardEntries,
866 selected: "default",
867 loadDetails: () => Effect.succeed({ providers: dashboardProviders, available: [] }),
868 execute: () => Effect.succeed({ ok: true, message: "", entries: dashboardEntries }),
869 runFlow: () => Effect.succeed({ ok: true, message: "" }),
870 reloadEntries: Effect.succeed(dashboardEntries),
871 }).pipe(Effect.provideService(Interaction, service), Effect.forkChild);
872
873 // "focus provider" joins the key bar once the providers have resolved;
874 // arrow keys are ignored while the pane still shows the loading spinner.
875 yield* Effect.promise(() => stdout.waitFor("focus provider"));
876 yield* Effect.promise(() => stdin.ready);
877 expect(stdout.output).not.toContain("Vercel");
878
879 // Walk the focus cursor down to the last provider; the list follows it.
880 for (const _ of dashboardProviders) {
881 yield* Effect.sync(() => stdin.write("\x1b[B"));
882 }
883 yield* Effect.promise(() => stdout.waitFor("Vercel"));
884
885 yield* Effect.sync(() => stdin.write("q"));
886 yield* Fiber.join(session);
887 }),
888 { tags: ["unit", "local"] },
889 );
890
891 it(
892 "renders input frames inline by default and keeps a stacked variant",
893 () => {
894 const { service } = makeStatic();
895 const inline = formatStatic(
896 <PromptFrame
897 message="Profile name"
898 description="Used to select stored credentials."
899 layout="inline"
900 >
901 <Text>production</Text>
902 </PromptFrame>,
903 );
904 const stacked = formatStatic(
905 <PromptFrame message="Profile name" layout="stacked">
906 <Text>production</Text>
907 </PromptFrame>,
908 );
909
910 expect(inline).toContain("Profile name: production");
911 expect(inline).toContain("Used to select stored credentials.");
912 expect(stacked).toContain("Profile name\n");
913 expect(stacked).toContain("production");
914 },
915 { tags: ["unit", "local"] },
916 );
917
918 it(
919 "renders compact informational toasts as a bare status line",
920 () => {
921 const { service } = makeStatic();
922 const output = formatStatic(<Toast variant="info">Credentials refreshed.</Toast>);
923
924 expect(output).toBe("• Credentials refreshed.");
925 },
926 { tags: ["unit", "local"] },
927 );
928
929 it(
930 "renders prompt frames with an indented body and no rail",
931 () => {
932 const { service } = makeStatic();
933 const output = formatStatic(
934 <PromptFrame message="Cloudflare authentication method">
935 <Menu
936 cursor={0}
937 choices={[
938 { value: "oauth", label: "OAuth", description: "recommended" },
939 { value: "token", label: "API Token or API Key", description: "use an API token" },
940 ]}
941 />
942 </PromptFrame>,
943 { columns: 100 },
944 );
945
946 const lines = output.split("\n");
947 expect(lines[0]).toBe("◆ Cloudflare authentication method");
948 // options sit directly under the heading; ❯ is the only chevron on screen
949 expect(lines[1]).toMatch(/^ ❯ OAuth\s+recommended$/);
950 expect(lines[2]).toMatch(/^ API Token or API Key\s+use an API token$/);
951 // descriptions share one column across rows
952 expect(lines[1]!.indexOf("recommended")).toBe(lines[2]!.indexOf("use an API token"));
953 expect(output).not.toContain("│");
954 expect(output).not.toContain("›");
955 },
956 { tags: ["unit", "local"] },
957 );
958
959 /**
960 * Scoped variant of `makeStatic` for tests that mount a persistent renderer.
961 * Disposal runs as a finalizer, so a failing test never leaks a Sigil
962 * instance.
963 */
964 const makeLive = (
965 overrides: {
966 readonly stdin?: InputStream;
967 readonly captureConsole?: boolean;
968 readonly input?: boolean;
969 readonly unicode?: boolean;
970 readonly colors?: boolean;
971 } = {},
972 ) => {
973 const input = overrides.input ?? true;
974 if (!input) {
975 const stdout = new CaptureStream();
976 const stderr = new CaptureStream();
977 const service = makeNonInteractive({
978 // SAFETY: CaptureStream implements the writable stream surface consumed here.
979 stdout: stdout as unknown as NodeJS.WriteStream,
980 colors: overrides.colors ?? false,
981 unicode: overrides.unicode ?? true,
982 });
983 return Effect.succeed({ service, stdout, stderr, dispose: async () => {} });
984 }
985 return Effect.acquireRelease(
986 Effect.sync(() => {
987 const stdout = new CaptureStream(input);
988 const stderr = new CaptureStream(input);
989 // Interactive runtimes need a raw-mode-capable stdin: with a real
990 // process.stdin pipe Sigil's useInput throws during commit, which now
991 // surfaces as a renderer error instead of being silently swallowed.
992 const stdin = overrides.stdin ?? (input ? new InputStream() : undefined);
993 stdin?.connect(stdout);
994 const runtime = makeRuntime(
995 {
996 input,
997 // SAFETY: InputStream implements the raw readable stream surface consumed by Sigil.
998 stdin: stdin as unknown as NodeJS.ReadStream | undefined,
999 // SAFETY: CaptureStream implements the writable stream surface consumed by Sigil.
1000 stdout: stdout as unknown as NodeJS.WriteStream,
1001 // SAFETY: CaptureStream implements the writable stream surface consumed by Sigil.
1002 stderr: stderr as unknown as NodeJS.WriteStream,
1003 captureConsole: overrides.captureConsole ?? false,
1004 },
1005 {
1006 input,
1007 columns: stdout.columns,
1008 rows: stdout.rows,
1009 colors: overrides.colors ?? false,
1010 unicode: overrides.unicode ?? true,
1011 alternateScreen: input,
1012 },
1013 );
1014 return { ...runtime, stdout, stderr };
1015 }),
1016 ({ dispose }) => Effect.promise(dispose),
1017 );
1018 };
1019
1020 it(
1021 "honors explicit color settings for static output",
1022 () => {
1023 const { service } = makeStatic();
1024 const view = <Text color="green">ready</Text>;
1025 const styled = formatStatic(view, { colors: true });
1026 expect(styled).toContain("\u001B[");
1027 expect(stripVTControlCharacters(styled)).toBe("ready");
1028 expect(formatStatic(view, { colors: false })).toBe("ready");
1029 },
1030 { tags: ["unit", "local"] },
1031 );
1032
1033 it.effect(
1034 "keeps stack output URLs reachable",
1035 () =>
1036 Effect.gen(function* () {
1037 const { service } = yield* makeLive({ colors: true });
1038 const url = "https://example.com/deploy";
1039 const output = formatStatic(stackOutputsView({ url }), { colors: true });
1040 expect(stripVTControlCharacters(output)).toContain(url);
1041 }),
1042 { tags: ["unit", "local"] },
1043 );
1044
1045 it.effect(
1046 "keeps the state explorer active while searching and quits cleanly",
1047 () =>
1048 Effect.gen(function* () {
1049 const stdin = new InputStream();
1050 const { service, stdout } = yield* makeLive({ stdin });
1051 const fiber = yield* service
1052 .session(service.prompt.screen(stateExplorerScreen(explorerSource)), { alternate: true })
1053 .pipe(Effect.forkChild);
1054 yield* Effect.promise(() => stdin.ready);
1055 yield* Effect.promise(() => stdout.waitFor("Loading"));
1056
1057 yield* Effect.sync(() => stdin.write("/"));
1058 yield* settleInput;
1059 yield* Effect.sync(() => stdin.write("workers.dev"));
1060 yield* settleInput;
1061 yield* Effect.sync(() => stdin.write("\r"));
1062 yield* settleInput;
1063 expect(fiber.pollUnsafe()).toBeUndefined();
1064
1065 yield* Effect.sync(() => stdin.write("q"));
1066 yield* Fiber.join(fiber);
1067 }),
1068 { tags: ["unit", "local"] },
1069 );
1070
1071 it.effect(
1072 "renders the built-in layout components without writing",
1073 () =>
1074 Effect.gen(function* () {
1075 const { service, stdout } = makeStatic();
1076 const rendered = yield* renderStatic(
1077 <>
1078 <SectionHeading annotation="active">Profile</SectionHeading>
1079 <DescriptionList
1080 items={[
1081 { label: "Name", value: "production" },
1082 { label: "Status", value: "ready" },
1083 ]}
1084 />
1085 </>,
1086 );
1087
1088 expect(rendered).toContain("Profile");
1089 expect(rendered).toContain("production");
1090 expect(rendered).toContain("ready");
1091 expect(stdout.output).toBe("");
1092 }),
1093 { tags: ["unit", "local"] },
1094 );
1095
1096 it.effect(
1097 "renders confirmations as a compact segmented choice",
1098 () =>
1099 Effect.gen(function* () {
1100 const { service } = makeStatic();
1101
1102 expect(
1103 (yield* renderStatic(
1104 <ChoiceGroup
1105 value
1106 choices={[
1107 { value: true, label: "Yes" },
1108 { value: false, label: "No" },
1109 ]}
1110 />,
1111 )).trim(),
1112 ).toBe("Yes No");
1113 expect(
1114 (yield* renderStatic(
1115 <ChoiceGroup
1116 value={false}
1117 choices={[
1118 { value: true, label: "Yes" },
1119 { value: false, label: "No" },
1120 ]}
1121 />,
1122 )).trim(),
1123 ).toBe("Yes No");
1124 expect(
1125 (yield* renderStatic(
1126 <ChoiceGroup
1127 value
1128 choices={[
1129 { value: true, label: "Destroy" },
1130 { value: false, label: "Cancel" },
1131 ]}
1132 />,
1133 )).trim(),
1134 ).toBe("Destroy Cancel");
1135 expect(
1136 (yield* renderStatic(
1137 <ChoiceGroup
1138 orientation="vertical"
1139 value="repair"
1140 choices={[
1141 { value: "repair", label: "Repair", description: "restore declared state" },
1142 { value: "cancel", label: "Cancel" },
1143 ]}
1144 />,
1145 )).trim(),
1146 ).toBe("Repair · restore declared state\n Cancel");
1147 }),
1148 { tags: ["unit", "local"] },
1149 );
1150
1151 it.effect(
1152 "preserves zero in primitive-array views",
1153 () =>
1154 Effect.gen(function* () {
1155 const { service } = makeStatic();
1156 const rendered = yield* renderStatic(["count: ", 0, false, null]);
1157
1158 expect(rendered).toBe("count: 0");
1159 }),
1160 { tags: ["unit", "local"] },
1161 );
1162
1163 it(
1164 "does not animate work before it starts",
1165 () => {
1166 expect(isInProgress("pending")).toBe(false);
1167 expect(isInProgress("creating")).toBe(true);
1168 expect(isInProgress("updating")).toBe(true);
1169 expect(isInProgress("deleting")).toBe(true);
1170 expect(isInProgress("running")).toBe(true);
1171 },
1172 { tags: ["unit", "local"] },
1173 );
1174
1175 it.effect(
1176 "prints headings and data views through one service",
1177 () =>
1178 Effect.gen(function* () {
1179 const { service, stdout } = makeStatic();
1180 yield* service.output.print(<Heading>Deployments</Heading>);
1181 yield* service.output.print(
1182 <DescriptionList
1183 items={[
1184 { label: "api", value: "ready" },
1185 { label: "worker", value: "updating" },
1186 ]}
1187 />,
1188 );
1189
1190 expect(stdout.output).toContain("Deployments");
1191 expect(stdout.output).toContain("worker");
1192 expect(stdout.output).toContain("updating");
1193 }),
1194 { tags: ["unit", "local"] },
1195 );
1196
1197 it.effect(
1198 "fails input operations when no terminal input is available",
1199 () =>
1200 Effect.gen(function* () {
1201 const { service } = makeStatic();
1202 const failure = yield* service.prompt
1203 .select({ message: "Choose", options: [{ label: "One", value: 1 }] })
1204 .pipe(Effect.flip);
1205
1206 expect(failure).toBeInstanceOf(NonInteractiveTerminal);
1207 if (failure instanceof NonInteractiveTerminal) {
1208 expect(failure.operation).toBe("selection");
1209 }
1210
1211 const cycleFailure = yield* service.prompt
1212 .screen(cycleSelectScreen({ message: "Change", options: [] }))
1213 .pipe(Effect.flip);
1214 expect(cycleFailure).toBeInstanceOf(NonInteractiveTerminal);
1215 if (cycleFailure instanceof NonInteractiveTerminal) {
1216 expect(cycleFailure.operation).toBe("cycle selection");
1217 }
1218 }),
1219 { tags: ["unit", "local"] },
1220 );
1221
1222 it.effect(
1223 "progress handles are updateable and settle only once",
1224 () =>
1225 Effect.gen(function* () {
1226 const { service, stdout } = makeStatic();
1227 const progress = yield* service.progress({ label: "Deploying" });
1228 yield* progress.update({ label: "Uploading", detail: "2/3" });
1229 yield* progress.succeed("Deployed");
1230 yield* progress.fail("must not print");
1231
1232 expect(stdout.output).toContain("Deploying");
1233 expect(stdout.output).toContain("Deployed");
1234 expect(stdout.output).not.toContain("must not print");
1235 }),
1236 { tags: ["unit", "local"] },
1237 );
1238
1239 /** Live views are immutable; dynamic content flows through caller stores. */
1240 const LiveLabel = ({ store }: { readonly store: LiveStore<string> }) => (
1241 <Text>{useLiveStore(store)}</Text>
1242 );
1243
1244 it.effect(
1245 "tears down store-driven live views idempotently",
1246 () =>
1247 Effect.gen(function* () {
1248 const { service, stdout } = yield* makeLive();
1249
1250 const store = new LiveStore("Scanning");
1251 const live = yield* service.live(<LiveLabel store={store} />);
1252 yield* Effect.sync(() => store.set("Deleting"));
1253 yield* live.close;
1254 yield* live.close;
1255
1256 expect(stdout.output).toContain("\u001B[?25h");
1257 }),
1258 { tags: ["unit", "local"] },
1259 );
1260
1261 it.effect(
1262 "does not let one closing view tear down a newer live view",
1263 () =>
1264 Effect.gen(function* () {
1265 const { service, stdout } = yield* makeLive();
1266
1267 const first = yield* service.live(<Text>first</Text>);
1268 const closing = yield* first.close.pipe(Effect.forkChild);
1269 const store = new LiveStore("second");
1270 const second = yield* service.live(<LiveLabel store={store} />, {
1271 persistOnClose: true,
1272 });
1273 yield* Fiber.join(closing);
1274 yield* Effect.sync(() => store.set("second updated"));
1275 yield* second.close;
1276
1277 expect(stdout.output).toContain("second updated");
1278 }),
1279 { tags: ["unit", "local"] },
1280 );
1281
1282 interface OrderingCase {
1283 readonly name: string;
1284 readonly captureConsole: boolean;
1285 readonly emit: (service: Interaction["Service"]) => Effect.Effect<void>;
1286 readonly verify: (output: string) => void;
1287 }
1288
1289 const orderingCases: ReadonlyArray<OrderingCase> = [
1290 {
1291 name: "commits persistent live views to the static transcript",
1292 captureConsole: false,
1293 emit: () => Effect.void,
1294 verify: (output) => {
1295 expect(output).toContain("Deployed");
1296 expect(output.slice(output.lastIndexOf("Deployed"))).not.toContain("\u001B[2K");
1297 expect(output).toContain("\u001B[?25h");
1298 },
1299 },
1300 {
1301 name: "keeps styled captured logs static and ordered before completed live views",
1302 captureConsole: true,
1303 emit: () => Effect.sync(() => console.log("\u001B[32mruntime ready\u001B[0m")),
1304 verify: (output) => {
1305 expect(output.match(/runtime ready/g)?.length).toBe(1);
1306 expect(output).toContain("\u001B[32m");
1307 expect(output.indexOf("runtime ready")).toBeLessThan(output.lastIndexOf("Deployed"));
1308 },
1309 },
1310 {
1311 name: "orders semantic output through the active renderer",
1312 captureConsole: false,
1313 emit: (service) => service.output.info("runtime ready"),
1314 verify: (output) => {
1315 expect(output.indexOf("runtime ready")).toBeLessThan(output.lastIndexOf("Deployed"));
1316 },
1317 },
1318 ];
1319
1320 it.effect.each(orderingCases)(
1321 "$name",
1322 ({ captureConsole, emit, verify }) =>
1323 Effect.gen(function* () {
1324 const { service, stdout } = yield* makeLive({ captureConsole, colors: captureConsole });
1325
1326 const store = new LiveStore("Deploying");
1327 const live = yield* service.live(<LiveLabel store={store} />, { persistOnClose: true });
1328 yield* emit(service);
1329 yield* Effect.sync(() => store.set("Deployed"));
1330 yield* live.close;
1331
1332 verify(stdout.output);
1333 }),
1334 { tags: ["unit", "local"] },
1335 );
1336
1337 it.effect(
1338 "commits stdio above active Sigil views",
1339 () =>
1340 Effect.gen(function* () {
1341 const { service, stdout, stderr } = yield* makeLive({ captureConsole: true });
1342 const store = new LiveStore("Resolving credentials");
1343 const live = yield* service.live(<LiveLabel store={store} />, { persistOnClose: true });
1344
1345 yield* Effect.sync(() => {
1346 stdout.write("floci stdout\n");
1347 stderr.write("node warning\n");
1348 store.set("Credentials resolved");
1349 });
1350 yield* live.close;
1351
1352 expect(stdout.output).toContain("floci stdout");
1353 expect(stdout.output).toContain("node warning");
1354 expect(stderr.output).not.toContain("node warning");
1355 expect(stdout.output).toContain("Credentials resolved");
1356 expect(stdout.output.lastIndexOf("node warning")).toBeLessThan(
1357 stdout.output.lastIndexOf("Credentials resolved"),
1358 );
1359 }),
1360 { tags: ["unit", "local"] },
1361 );
1362
1363 it.effect(
1364 "flushes a captured partial line without waiting for unmount",
1365 () =>
1366 Effect.gen(function* () {
1367 const { service, stdout, stderr } = yield* makeLive({ captureConsole: true });
1368 const store = new LiveStore("Deploying");
1369 const live = yield* service.live(<LiveLabel store={store} />);
1370 // A writer whose final chunk has no trailing newline (e.g. an error
1371 // block written raw to stderr): its tail must render within the
1372 // partial-flush deadline — before this, it sat buffered until the
1373 // renderer unmounted at process exit, so the last line of an error
1374 // only ever appeared on shutdown.
1375 yield* Effect.sync(() => {
1376 stderr.write("stack tail without newline");
1377 });
1378 yield* Effect.promise(() => stdout.waitFor("stack tail without newline"));
1379 yield* live.close;
1380 }),
1381 { tags: ["unit", "local"] },
1382 );
1383
1384 it.effect(
1385 "progress settles into success and failure status output",
1386 () =>
1387 Effect.gen(function* () {
1388 const { service, stdout } = makeStatic();
1389 yield* Effect.scoped(
1390 Effect.gen(function* () {
1391 const first = yield* service.progress({ label: "Resolve credentials" });
1392 yield* first.succeed();
1393 const second = yield* service.progress({ label: "Apply resource" });
1394 yield* second.fail();
1395 }),
1396 );
1397
1398 expect(stdout.output).toContain("Resolve credentials");
1399 expect(stdout.output).toContain("Apply resource");
1400 expect(stdout.output).toContain("✓");
1401 expect(stdout.output).toContain("×");
1402 }),
1403 { tags: ["unit", "local"] },
1404 );
1405
1406 it.effect(
1407 "task collapses success and failure into status output",
1408 () =>
1409 Effect.gen(function* () {
1410 const { service, stdout } = makeStatic();
1411 yield* service.task({ label: "Resolve credentials" }, Effect.succeed("credentials"));
1412 yield* service.task({ label: "Apply resource" }, Effect.fail("nope")).pipe(Effect.ignore);
1413
1414 expect(stdout.output).toContain("Resolve credentials");
1415 expect(stdout.output).toContain("Apply resource");
1416 expect(stdout.output).toContain("✓");
1417 expect(stdout.output).toContain("×");
1418 }),
1419 { tags: ["unit", "local"] },
1420 );
1421
1422 it.effect(
1423 "status output composes as a normal view",
1424 () =>
1425 Effect.gen(function* () {
1426 const { service } = makeStatic();
1427 const rendered = yield* renderStatic(
1428 <Status variant="warning" detail="retrying">
1429 API unavailable
1430 </Status>,
1431 );
1432 expect(rendered).toContain("API unavailable");
1433 expect(rendered).toContain("retrying");
1434 }),
1435 { tags: ["unit", "local"] },
1436 );
1437
1438 it.effect(
1439 "uses ASCII fallbacks when Unicode is unavailable",
1440 () =>
1441 Effect.gen(function* () {
1442 const rendered = yield* renderStatic(
1443 <>
1444 <Heading>Deploy</Heading>
1445 <Status variant="success">Complete</Status>
1446 </>,
1447 { unicode: false },
1448 );
1449 expect(rendered).toContain("@ Deploy");
1450 expect(rendered).toContain("+ Complete");
1451 expect(rendered).not.toContain("✓");
1452 }),
1453 { tags: ["unit", "local"] },
1454 );
1455
1456 it.effect(
1457 "logs chunked resource stdout and stderr as tagged records",
1458 () => {
1459 const records: Array<LogRecord> = [];
1460 const logger = Logger.make<unknown, void>((options) => {
1461 records.push(recordOf(options));
1462 });
1463 return Effect.gen(function* () {
1464 const output = yield* makeResourceOutput("www");
1465 output.stdout.push("first\nsec");
1466 output.stdout.push("ond\r");
1467 output.stderr.push("\x1b[33mfailed\x1b[39m");
1468 output.stdout.flush();
1469 output.stderr.flush();
1470 expect(
1471 records.map(({ level, kind, attributes, data }) => ({ level, kind, attributes, data })),
1472 ).toEqual([
1473 {
1474 level: "info",
1475 kind: "output",
1476 attributes: { fqn: "www" },
1477 data: { stream: "stdout", text: "first" },
1478 },
1479 {
1480 level: "info",
1481 kind: "output",
1482 attributes: { fqn: "www" },
1483 data: { stream: "stdout", text: "second" },
1484 },
1485 {
1486 level: "info",
1487 kind: "output",
1488 attributes: { fqn: "www" },
1489 data: { stream: "stderr", text: "\x1b[33mfailed\x1b[39m" },
1490 },
1491 ]);
1492 }).pipe(Effect.provide(Logger.layer([logger])));
1493 },
1494 { tags: ["unit", "local"] },
1495 );
1496
1497 it.effect(
1498 "routes effectful resource output through the configured logger",
1499 () => {
1500 const records: Array<LogRecord> = [];
1501 const logger = Logger.make<unknown, void>((options) => {
1502 records.push(recordOf(options));
1503 });
1504 const output = makeResourceLogger("www");
1505
1506 return Effect.gen(function* () {
1507 yield* output("stdout", "[MDX] generated files");
1508 yield* output("stderr", "vite diagnostic");
1509 expect(
1510 records.map((record) =>
1511 record.kind === "output" ? `${record.attributes.fqn}: ${record.data.text}` : record.kind,
1512 ),
1513 ).toEqual(["www: [MDX] generated files", "www: vite diagnostic"]);
1514 }).pipe(Effect.provide(Logger.layer([logger])));
1515 },
1516 { tags: ["unit", "local"] },
1517 );
1518
1519 it.effect(
1520 "does not decorate resource stderr as a semantic failure",
1521 () =>
1522 Effect.gen(function* () {
1523 const { service, stdout } = yield* makeLive({ captureConsole: true });
1524 const live = yield* service.live(<Text>Building</Text>);
1525
1526 const output = yield* makeResourceOutput("www");
1527 output.stderr.push("[FILE_NAME_CONFLICT] warning\n");
1528 output.stderr.flush();
1529 yield* live.close;
1530
1531 const rendered = stripVTControlCharacters(stdout.output);
1532 expect(rendered).toContain(`[www] [FILE_NAME_CONFLICT] warning`);
1533 expect(rendered).not.toContain("×");
1534 }).pipe(
1535 Effect.provide(Logger.layer([makePlainConsoleSink({ colors: false })])),
1536 // The CLI logs through the process console, which the renderer captures.
1537 Effect.provideService(Console.Console, globalThis.console),
1538 ),
1539 { tags: ["unit", "local"] },
1540 );
1541
1542 it.effect(
1543 "runs interactive components inside the owned session",
1544 () =>
1545 Effect.gen(function* () {
1546 const { service, stdout } = yield* makeLive();
1547
1548 const result = yield* service.prompt.screen(
1549 Screen.make("test screen", ({ submit }) => {
1550 queueMicrotask(() => submit("completed", <Status>Done</Status>));
1551 return <Status>Working</Status>;
1552 }),
1553 );
1554 expect(result).toBe("completed");
1555 expect(stdout.output).toContain("Done");
1556 }),
1557 { tags: ["unit", "local"] },
1558 );
1559
1560 it.effect(
1561 "restores the terminal after an alternate-screen interaction",
1562 () =>
1563 Effect.gen(function* () {
1564 const { service, stdout } = yield* makeLive();
1565
1566 yield* service.session(
1567 service.prompt.screen(
1568 Screen.make("full screen", ({ submit }) => {
1569 queueMicrotask(() => submit(undefined));
1570 return <Status>Browsing</Status>;
1571 }),
1572 ),
1573 { alternate: true },
1574 );
1575
1576 expect(stdout.output).toContain("\u001B[?1049h");
1577 expect(stdout.output).toContain("\u001B[?1049l");
1578 expect(stdout.output.indexOf("\u001B[?1049h")).toBeLessThan(
1579 stdout.output.indexOf("\u001B[?1049l"),
1580 );
1581 }),
1582 { tags: ["unit", "local"] },
1583 );
1584
1585 it.effect(
1586 "treats the terminal DEL byte as text-field backspace",
1587 () =>
1588 Effect.gen(function* () {
1589 const stdin = new InputStream();
1590 const { service } = yield* makeLive({ stdin });
1591
1592 const fiber = yield* service.prompt
1593 .screen(
1594 Screen.make("backspace", ({ submit }) => (
1595 <TextField initialValue="abc" onChange={submit} onSubmit={submit} />
1596 )),
1597 )
1598 .pipe(Effect.forkChild);
1599 yield* Effect.promise(() => stdin.ready);
1600 yield* Effect.sync(() => stdin.write("\x7f"));
1601 const result = yield* Fiber.join(fiber);
1602
1603 expect(result).toBe("ab");
1604 }),
1605 { tags: ["unit", "local"] },
1606 );
1607
1608 /** Let a written stdin chunk flow through Sigil's input pipeline. */
1609 const settleInput = Effect.yieldNow.pipe(Effect.repeat({ times: 2 }));
1610
1611 it.effect(
1612 "strips control characters from pasted text-field input",
1613 () =>
1614 Effect.gen(function* () {
1615 const stdin = new InputStream();
1616 const { service } = yield* makeLive({ stdin });
1617
1618 const fiber = yield* service.prompt
1619 .screen(Screen.make("paste", ({ submit }) => <TextField onSubmit={submit} />))
1620 .pipe(Effect.forkChild);
1621 yield* Effect.promise(() => stdin.ready);
1622 // A paste arrives as one chunk; embedded newlines/tabs must not survive.
1623 yield* Effect.sync(() => stdin.write("to\tken\r\n123"));
1624 yield* settleInput;
1625 yield* Effect.sync(() => stdin.write("\r"));
1626 const result = yield* Fiber.join(fiber);
1627
1628 expect(result).toBe("token123");
1629 }),
1630 { tags: ["unit", "local"] },
1631 );
1632
1633 it.effect(
1634 "shows the whole typed value while width remains available",
1635 () =>
1636 Effect.gen(function* () {
1637 const stdin = new InputStream();
1638 const { service, stdout } = yield* makeLive({ stdin });
1639
1640 const fiber = yield* service.prompt
1641 .text({ message: "New profile name" })
1642 .pipe(Effect.forkChild);
1643 yield* Effect.promise(() => stdin.ready);
1644 // Regression: the field's box used to shrink to its content, so the
1645 // measured "available" width collapsed to the minimum and the value
1646 // scrolled after ~4 characters despite a mostly-empty row.
1647 yield* Effect.sync(() => stdin.write("my-longer-profile-name"));
1648 yield* Effect.promise(() => stdout.waitFor("my-longer-profile-name"));
1649 expect(stdout.output).toContain("my-longer-profile-name");
1650 yield* Effect.sync(() => stdin.write("\r"));
1651 const result = yield* Fiber.join(fiber);
1652
1653 expect(result).toBe("my-longer-profile-name");
1654 }),
1655 { tags: ["unit", "local"] },
1656 );
1657
1658 it.effect(
1659 "shows a text prompt default before it is accepted",
1660 () =>
1661 Effect.gen(function* () {
1662 const stdin = new InputStream();
1663 const { service, stdout } = yield* makeLive({ stdin });
1664
1665 const fiber = yield* service.prompt
1666 .text({ message: "Emulator endpoint", defaultValue: "http://localhost:4566" })
1667 .pipe(Effect.forkChild);
1668 yield* Effect.promise(() => stdin.ready);
1669 yield* Effect.promise(() => stdout.waitFor("http://localhost:4566"));
1670 expect(stripVTControlCharacters(stdout.output)).toContain(
1671 "Emulator endpoint: http://localhost:4566",
1672 );
1673 yield* Effect.sync(() => stdin.write("\r"));
1674
1675 expect(yield* Fiber.join(fiber)).toBe("http://localhost:4566");
1676 }),
1677 { tags: ["unit", "local"] },
1678 );
1679
1680 /** A searchable picker over more accounts than one window shows. */
1681 const manyAccounts = Array.from({ length: 60 }, (_, index) => ({
1682 value: `id-${index + 1}`,
1683 label: `Account ${String(index + 1).padStart(2, "0")}`,
1684 description: `id-${index + 1}`,
1685 }));
1686
1687 const selectManyAccounts = (keys: ReadonlyArray<string>) =>
1688 Effect.gen(function* () {
1689 const stdin = new InputStream();
1690 const { service, stdout } = yield* makeLive({ stdin });
1691 const fiber = yield* service.prompt
1692 .select({ message: "Select an account", searchable: true, options: manyAccounts })
1693 .pipe(Effect.forkChild);
1694 yield* Effect.promise(() => stdin.ready);
1695 yield* Effect.promise(() => stdout.waitFor("60 choices"));
1696 for (const key of keys) {
1697 yield* Effect.sync(() => stdin.write(key));
1698 yield* Effect.sleep("5 millis");
1699 }
1700 yield* Effect.sync(() => stdin.write("\r"));
1701 return { value: yield* Fiber.join(fiber), output: stripVTControlCharacters(stdout.output) };
1702 });
1703
1704 it.live(
1705 "scrolls a long select to its last choice with the arrow keys",
1706 () =>
1707 Effect.gen(function* () {
1708 const { value, output } = yield* selectManyAccounts(Array(59).fill("\x1b[B"));
1709 expect(value).toBe("id-60");
1710 expect(output).toContain("Account 60");
1711 expect(output).toMatch(/↓ \d+ more/);
1712 expect(output).toMatch(/↑ \d+ more/);
1713 }),
1714 { tags: ["unit", "local"] },
1715 );
1716
1717 it.live(
1718 "pages and jumps through a long select",
1719 () =>
1720 Effect.gen(function* () {
1721 // A 24-row terminal shows 16 choices, so each PageDown moves 16.
1722 const paged = yield* selectManyAccounts(["\x1b[6~", "\x1b[6~", "\x1b[6~"]);
1723 expect(paged.value).toBe("id-49");
1724 // End jumps to the last choice and Home back to the first.
1725 expect((yield* selectManyAccounts(["\x1b[F"])).value).toBe("id-60");
1726 expect((yield* selectManyAccounts(["\x1b[F", "\x1b[H"])).value).toBe("id-1");
1727 // Up from the first choice wraps to the last.
1728 expect((yield* selectManyAccounts(["\x1b[A"])).value).toBe("id-60");
1729 }),
1730 { tags: ["unit", "local"] },
1731 );
1732
1733 it.live(
1734 "filters a long select to a choice outside the first window",
1735 () =>
1736 Effect.gen(function* () {
1737 const byName = yield* selectManyAccounts(["Account 47"]);
1738 expect(byName.value).toBe("id-47");
1739 expect(byName.output).toContain("1 of 60");
1740 // Descriptions (the account id) are searchable too.
1741 expect((yield* selectManyAccounts(["id-53"])).value).toBe("id-53");
1742 }),
1743 { tags: ["unit", "local"] },
1744 );
1745
1746 it.live(
1747 "tab fills a text prompt's default into the empty field",
1748 () =>
1749 Effect.gen(function* () {
1750 const stdin = new InputStream();
1751 const { service, stdout } = yield* makeLive({ stdin });
1752
1753 const fiber = yield* service.prompt
1754 .text({ message: "Token name", defaultValue: "alchemy-superuser" })
1755 .pipe(Effect.forkChild);
1756 yield* Effect.promise(() => stdin.ready);
1757 yield* Effect.promise(() => stdout.waitFor("alchemy-superuser"));
1758 yield* Effect.sync(() => stdin.write("\t"));
1759 // A separate chunk: the parser reads "\t-2" in one chunk as typed text.
1760 yield* Effect.sleep("50 millis");
1761 yield* Effect.sync(() => stdin.write("-2"));
1762 yield* Effect.promise(() => stdout.waitFor("alchemy-superuser-2"));
1763 yield* Effect.sync(() => stdin.write("\r"));
1764
1765 expect(yield* Fiber.join(fiber)).toBe("alchemy-superuser-2");
1766 }),
1767 { tags: ["unit", "local"] },
1768 );
1769
1770 it.effect(
1771 "deletes a whole emoji grapheme on backspace",
1772 () =>
1773 Effect.gen(function* () {
1774 const stdin = new InputStream();
1775 const { service } = yield* makeLive({ stdin });
1776
1777 const fiber = yield* service.prompt
1778 .screen(
1779 Screen.make("grapheme", ({ submit }) => (
1780 <TextField initialValue="a👍" onChange={submit} onSubmit={submit} />
1781 )),
1782 )
1783 .pipe(Effect.forkChild);
1784 yield* Effect.promise(() => stdin.ready);
1785 yield* Effect.sync(() => stdin.write("\x7f"));
1786 const result = yield* Fiber.join(fiber);
1787
1788 expect(result).toBe("a");
1789 }),
1790 { tags: ["unit", "local"] },
1791 );
1792
1793 it.effect(
1794 "erases the multi-select filter with the terminal DEL byte",
1795 () =>
1796 Effect.gen(function* () {
1797 const stdin = new InputStream();
1798 const { service } = yield* makeLive({ stdin });
1799
1800 const fiber = yield* service.prompt
1801 .multiSelect({
1802 message: "pick",
1803 options: [
1804 { value: "alpha", label: "alpha" },
1805 { value: "beta", label: "beta" },
1806 ],
1807 })
1808 .pipe(Effect.forkChild);
1809 yield* Effect.promise(() => stdin.ready);
1810 // Filter to nothing, erase the filter with DEL, then toggle + confirm.
1811 yield* Effect.sync(() => stdin.write("z"));
1812 yield* settleInput;
1813 yield* Effect.sync(() => stdin.write("\x7f"));
1814 yield* settleInput;
1815 yield* Effect.sync(() => stdin.write(" "));
1816 yield* settleInput;
1817 yield* Effect.sync(() => stdin.write("\r"));
1818 const result = yield* Fiber.join(fiber);
1819
1820 expect(result).toEqual(["alpha"]);
1821 }),
1822 { tags: ["unit", "local"] },
1823 );
1824
1825 it.effect(
1826 "filters searchable selects without stealing Enter",
1827 () =>
1828 Effect.gen(function* () {
1829 const stdin = new InputStream();
1830 const { service } = yield* makeLive({ stdin });
1831
1832 const fiber = yield* service.prompt
1833 .select({
1834 message: "pick",
1835 searchable: true,
1836 options: [
1837 { value: "alpha", label: "alpha" },
1838 { value: "beta", label: "beta" },
1839 ],
1840 })
1841 .pipe(Effect.forkChild);
1842 yield* Effect.promise(() => stdin.ready);
1843 yield* Effect.sync(() => stdin.write("bet"));
1844 yield* settleInput;
1845 yield* Effect.sync(() => stdin.write("\r"));
1846 const result = yield* Fiber.join(fiber);
1847
1848 expect(result).toBe("beta");
1849 }),
1850 { tags: ["unit", "local"] },
1851 );
1852
1853 it.effect(
1854 "keeps required cycle edits open until something changes",
1855 () =>
1856 Effect.gen(function* () {
1857 const stdin = new InputStream();
1858 const { service } = yield* makeLive({ stdin });
1859
1860 const fiber = yield* service.prompt
1861 .screen(
1862 cycleSelectScreen({
1863 message: "Manage accounts",
1864 requireChange: true,
1865 options: [
1866 {
1867 label: "Cloudflare",
1868 states: [
1869 { value: "keep", label: "keep" },
1870 { value: "remove", label: "remove" },
1871 ],
1872 },
1873 ],
1874 }),
1875 )
1876 .pipe(Effect.forkChild);
1877 yield* Effect.promise(() => stdin.ready);
1878 yield* Effect.sync(() => stdin.write("\r"));
1879 yield* settleInput;
1880 expect(fiber.pollUnsafe()).toBe(undefined);
1881
1882 yield* Effect.sync(() => stdin.write(" "));
1883 yield* settleInput;
1884 yield* Effect.sync(() => stdin.write("\r"));
1885 const result = yield* Fiber.join(fiber);
1886 expect(result).toEqual(["remove"]);
1887 }),
1888 { tags: ["unit", "local"] },
1889 );
1890
1891 it.effect(
1892 "reopens browser authorization from the waiting screen",
1893 () =>
1894 Effect.gen(function* () {
1895 const stdin = new InputStream();
1896 const { service } = yield* makeLive({ stdin });
1897 let opened = 0;
1898
1899 const fiber = yield* service.prompt
1900 .screen(
1901 browserLoginScreen({
1902 message: "Authorize",
1903 waitingLabel: "Waiting",
1904 url: "https://example.com/authorize",
1905 allowManualInput: true,
1906 inputLabel: "Enter code",
1907 onOpen: async () => {
1908 opened += 1;
1909 },
1910 }),
1911 )
1912 .pipe(Effect.forkChild);
1913 yield* Effect.promise(() => stdin.ready);
1914 yield* Effect.sync(() => stdin.write("o"));
1915 yield* settleInput;
1916 expect(opened).toBe(1);
1917
1918 yield* Effect.sync(() => stdin.write("\r"));
1919 yield* settleInput;
1920 yield* Effect.sync(() => stdin.write("code"));
1921 yield* settleInput;
1922 yield* Effect.sync(() => stdin.write("\r"));
1923 const result = yield* Fiber.join(fiber);
1924 expect(result).toBe("code");
1925 }),
1926 { tags: ["unit", "local"] },
1927 );
1928
1929 it.effect(
1930 "keeps browser-only authorization cancellable",
1931 () =>
1932 Effect.gen(function* () {
1933 const stdin = new InputStream();
1934 const { service, stdout } = yield* makeLive({ stdin });
1935
1936 const fiber = yield* service.prompt
1937 .screen(
1938 browserLoginScreen({
1939 message: "AWS authorization",
1940 waitingLabel: "Waiting",
1941 url: "https://example.com/authorize",
1942 allowManualInput: false,
1943 }),
1944 )
1945 .pipe(Effect.flip, Effect.forkChild);
1946 yield* Effect.promise(() => stdin.ready);
1947 yield* Effect.promise(() => stdout.waitFor("AWS authorization"));
1948 expect(stripVTControlCharacters(stdout.output)).not.toContain("enter code manually");
1949
1950 // Enter is intentionally inert for a browser-only flow.
1951 yield* Effect.sync(() => stdin.write("\r"));
1952 yield* settleInput;
1953 expect(fiber.pollUnsafe()).toBeUndefined();
1954
1955 yield* Effect.sync(() => stdin.write("\x1b"));
1956 const failure = yield* Fiber.join(fiber);
1957 expect(failure).toBeInstanceOf(TerminalCancelled);
1958 }),
1959 { tags: ["unit", "local"] },
1960 );
1961
1962 it.effect(
1963 "shows a device authorization code",
1964 () =>
1965 Effect.gen(function* () {
1966 const stdin = new InputStream();
1967 const { service, stdout } = yield* makeLive({ stdin });
1968
1969 const fiber = yield* service.prompt
1970 .screen(
1971 browserLoginScreen({
1972 message: "AWS authorization",
1973 waitingLabel: "Waiting for device authorization…",
1974 url: "https://device.sso.example.com/",
1975 code: "ABCD-EFGH",
1976 allowManualInput: false,
1977 }),
1978 )
1979 .pipe(Effect.flip, Effect.forkChild);
1980 yield* Effect.promise(() => stdin.ready);
1981 yield* Effect.promise(() => stdout.waitFor("ABCD-EFGH"));
1982
1983 const output = stripVTControlCharacters(stdout.output);
1984 expect(output).toContain("Code ABCD-EFGH");
1985 expect(output).toContain("copy URL");
1986
1987 yield* Effect.sync(() => stdin.write("\x1b"));
1988 const failure = yield* Fiber.join(fiber);
1989 expect(failure).toBeInstanceOf(TerminalCancelled);
1990 }),
1991 { tags: ["unit", "local"] },
1992 );
1993
1994 it.effect(
1995 "toggles every visible multi-select choice on ctrl+a",
1996 () =>
1997 Effect.gen(function* () {
1998 const stdin = new InputStream();
1999 const { service } = yield* makeLive({ stdin });
2000
2001 const fiber = yield* service.prompt
2002 .multiSelect({
2003 message: "pick",
2004 options: [
2005 { value: "alpha", label: "alpha" },
2006 { value: "beta", label: "beta" },
2007 { value: "gamma", label: "gamma", disabled: true },
2008 ],
2009 })
2010 .pipe(Effect.forkChild);
2011 yield* Effect.promise(() => stdin.ready);
2012 yield* Effect.sync(() => stdin.write("\x01"));
2013 yield* settleInput;
2014 yield* Effect.sync(() => stdin.write("\r"));
2015 const result = yield* Fiber.join(fiber);
2016
2017 expect(result).toEqual(["alpha", "beta"]);
2018 }),
2019 { tags: ["unit", "local"] },
2020 );
2021
2022 it.effect(
2023 "cleans up a cancelled standalone prompt",
2024 () =>
2025 Effect.gen(function* () {
2026 const { service, stdout } = yield* makeLive();
2027
2028 const failure = yield* service.prompt
2029 .screen(
2030 Screen.make("cancel test", ({ cancel }) => {
2031 queueMicrotask(cancel);
2032 return <Status>Waiting</Status>;
2033 }),
2034 )
2035 .pipe(Effect.flip);
2036
2037 expect(failure).toBeInstanceOf(TerminalCancelled);
2038 expect(stdout.output).toContain("cancel test cancelled");
2039 }),
2040 { tags: ["unit", "local"] },
2041 );
2042
2043 it.effect(
2044 "releases the renderer when a running prompt is interrupted",
2045 () =>
2046 Effect.gen(function* () {
2047 const stdin = new InputStream();
2048 const { service } = yield* makeLive({ stdin });
2049
2050 const fiber = yield* service.prompt
2051 .screen(Screen.make("interrupted", () => <Status>Waiting</Status>))
2052 .pipe(Effect.forkChild);
2053 yield* Effect.promise(() => stdin.ready);
2054 yield* Fiber.interrupt(fiber);
2055
2056 // The interrupted prompt must have released the renderer and the prompt
2057 // gate for the next interaction.
2058 const result = yield* service.prompt.screen(
2059 Screen.make("after interruption", ({ submit }) => {
2060 queueMicrotask(() => submit("ok"));
2061 return <Status>After</Status>;
2062 }),
2063 );
2064 expect(result).toBe("ok");
2065 }),
2066 { tags: ["unit", "local"] },
2067 );
2068
2069 it.effect(
2070 "closes leaked live handles when their scope closes",
2071 () =>
2072 Effect.gen(function* () {
2073 const { service, stdout } = yield* makeLive();
2074
2075 yield* Effect.scoped(
2076 Effect.gen(function* () {
2077 yield* service.live(<Text>Leaky</Text>);
2078 // Deliberately no close — the enclosing scope must release the row
2079 // and unmount the renderer.
2080 }),
2081 );
2082
2083 expect(stdout.output).toContain("[?25h");
2084 }),
2085 { tags: ["unit", "local"] },
2086 );
2087
2088 it.effect(
2089 "fails the active prompt when a screen throws during render",
2090 () =>
2091 Effect.gen(function* () {
2092 const { service } = yield* makeLive();
2093 const Broken = (): never => {
2094 throw new Error("screen render boom");
2095 };
2096
2097 // Without exit observation this would hang forever: the screen's
2098 // submit/cancel can never run once the renderer has crashed.
2099 const exit = yield* service.prompt
2100 .screen(Screen.make("broken screen", () => <Broken />))
2101 .pipe(Effect.exit);
2102
2103 expect(Exit.isFailure(exit)).toBe(true);
2104 }),
2105 { tags: ["unit", "local"] },
2106 );
2107
2108 it.effect(
2109 "cancels a screen with no cancel wiring on ctrl+c",
2110 () =>
2111 Effect.gen(function* () {
2112 const stdin = new InputStream();
2113 const { service, stdout } = yield* makeLive({ stdin });
2114
2115 // The screen never touches the controller — the centralized handler in
2116 // the runtime must still turn Ctrl+C into a cancellation.
2117 const fiber = yield* service.prompt
2118 .screen(Screen.make("no cancel wiring", () => <Status>Waiting</Status>))
2119 .pipe(Effect.flip, Effect.forkChild);
2120 yield* Effect.promise(() => stdin.ready);
2121 yield* Effect.sync(() => stdin.write("\x03"));
2122 const failure = yield* Fiber.join(fiber);
2123
2124 expect(failure).toBeInstanceOf(TerminalCancelled);
2125 expect(stdout.output).toContain("no cancel wiring cancelled");
2126 }),
2127 { tags: ["unit", "local"] },
2128 );
2129
2130 it.effect(
2131 "keeps one renderer alive for an Effect-driven application",
2132 () =>
2133 Effect.gen(function* () {
2134 const { service, stdout } = yield* makeLive();
2135
2136 const result = yield* service.session(
2137 Effect.gen(function* () {
2138 const action = yield* service.prompt.screen(
2139 Screen.make("main menu", ({ submit }) => {
2140 queueMicrotask(() => submit("add"));
2141 return <Status>Main menu</Status>;
2142 }),
2143 );
2144 const name = yield* service.session(
2145 service.prompt.screen(
2146 Screen.make("auth flow", ({ submit }) => {
2147 queueMicrotask(() => submit("cloudflare", <Status>Profile name</Status>));
2148 return <Status>Cloudflare auth</Status>;
2149 }),
2150 ),
2151 );
2152 const done = yield* service.prompt.screen(
2153 Screen.make("returned menu", ({ submit }) => {
2154 queueMicrotask(() => submit(true));
2155 return <Status>Returned menu</Status>;
2156 }),
2157 );
2158 return { action, name, done };
2159 }),
2160 );
2161
2162 expect(result).toEqual({ action: "add", name: "cloudflare", done: true });
2163 // Clearing an inline application first renders an empty frame. Its final
2164 // row must be reclaimed before teardown or the next shell prompt starts
2165 // one line too low.
2166 expect(stdout.output.slice(stdout.output.lastIndexOf("\n") + 1)).toContain("\u001B[1A");
2167 }),
2168 { tags: ["unit", "local"] },
2169 );
2170
2171 it.effect(
2172 "selects the plain renderer without terminal input",
2173 () => {
2174 const stdout = new CaptureStream();
2175 return Effect.gen(function* () {
2176 const capabilities = yield* Interaction.useSync((cli) => cli.terminal);
2177 const cli = yield* Interaction;
2178 yield* cli.output.print("Injected");
2179
2180 expect(capabilities.input).toBe(false);
2181 expect(capabilities.colors).toBe(false);
2182 expect(stdout.output).toContain("Injected");
2183 }).pipe(
2184 Effect.provide(
2185 interactionLayer({
2186 input: false,
2187 stdout: stdout as unknown as NodeJS.WriteStream,
2188 captureConsole: false,
2189 }),
2190 ),
2191 );
2192 },
2193 { tags: ["unit", "local"] },
2194 );
2195
2196 it.effect(
2197 "uses append-only progress when input is disabled on a TTY",
2198 () => {
2199 const stdout = new CaptureStream(true);
2200 return Effect.gen(function* () {
2201 const cli = yield* Interaction;
2202 const progress = yield* cli.progress({ label: "Deploying" });
2203 yield* progress.update({ label: "Uploading" });
2204 yield* progress.succeed("Deployed");
2205
2206 expect(cli.terminal.input).toBe(false);
2207 expect(stdout.output).toContain("Deploying\n");
2208 expect(stdout.output).toContain("Deployed\n");
2209 expect(stdout.output).not.toContain("\u001B[");
2210 }).pipe(
2211 Effect.provide(
2212 interactionLayer({
2213 input: false,
2214 stdout: stdout as unknown as NodeJS.WriteStream,
2215 captureConsole: false,
2216 }),
2217 ),
2218 );
2219 },
2220 { tags: ["unit", "local"] },
2221 );
2222
2223 it.effect(
2224 "renders the same semantic and component output without terminal input",
2225 () =>
2226 Effect.gen(function* () {
2227 const { service, stdout } = yield* makeLive({ input: false, unicode: false });
2228
2229 yield* service.output.info("Resolving credentials");
2230 yield* service.output.success({ message: "Authenticated", detail: "cloudflare" });
2231 yield* service.output.warning("Token expires soon");
2232 yield* service.output.error("Authentication failed");
2233 yield* service.output.print(
2234 <Alert variant="warning" title="Attention">
2235 Manual action required
2236 </Alert>,
2237 );
2238 yield* service.output.print(<Status>React output</Status>);
2239
2240 expect(stdout.output).toContain("Resolving credentials\n");
2241 expect(stdout.output).toContain("Authenticated");
2242 expect(stdout.output).toContain("cloudflare");
2243 expect(stdout.output).toContain("Token expires soon");
2244 expect(stdout.output).toContain("Authentication failed");
2245 expect(stdout.output).toContain("Attention");
2246 expect(stdout.output).toContain("Manual action required");
2247 expect(stdout.output).toContain("React output");
2248 }),
2249 { tags: ["unit", "local"] },
2250 );
2251
2252 it.effect(
2253 "renders application, transcript, live-work, and data primitives together",
2254 () =>
2255 Effect.gen(function* () {
2256 const { service } = makeStatic();
2257 const rendered = yield* renderStatic(
2258 <>
2259 <Tabs
2260 tabs={[
2261 { id: "dev", label: "dev" },
2262 { id: "prod", label: "prod", marked: true },
2263 ]}
2264 active="prod"
2265 />
2266 <AnsweredPrompt message="Account" answer="production" />
2267 <TaskRow spinning label="stack" />
2268 <TaskRow icon="+" label="worker" depth={1} />
2269 <ProgressGroup rows={[{ id: "providers", label: "providers", completed: 2, total: 4 }]} />
2270 <Status>q quit</Status>
2271 </>,
2272 );
2273
2274 expect(rendered).toContain("prod");
2275 expect(rendered).toContain("production");
2276 expect(rendered).toContain("worker");
2277 expect(rendered).toContain("2/4");
2278 }),
2279 { tags: ["unit", "local"] },
2280 );
2281
2282 it.effect(
2283 "composes widgets before and after divided key hints",
2284 () =>
2285 Effect.gen(function* () {
2286 const { service } = makeStatic();
2287 const rendered = yield* renderStatic(
2288 <KeyBar
2289 inline
2290 marginTop={0}
2291 divider
2292 before={<Text>Plan summary</Text>}
2293 keys={[["p", "show plan"]]}
2294 after={<Text>ready</Text>}
2295 />,
2296 );
2297
2298 expect(rendered.trim().split("\n")).toHaveLength(1);
2299 expect(rendered).toContain("Plan summary");
2300 expect(rendered.match(/│/g)).toHaveLength(2);
2301 expect(rendered).toContain("p show plan");
2302 expect(rendered).toContain("ready");
2303 }),
2304 { tags: ["unit", "local"] },
2305 );
2306
2307 it(
2308 "wraps individual key hints in narrow terminals",
2309 () => {
2310 const { service } = makeStatic();
2311 const rendered = formatStatic(
2312 <KeyBar
2313 inline
2314 marginTop={0}
2315 divider
2316 before={<Text>Ready</Text>}
2317 keys={[
2318 ["p", "show plan"],
2319 ["Ctrl+C", "exit"],
2320 ]}
2321 />,
2322 { columns: 20 },
2323 );
2324
2325 expect(rendered).toContain("p show plan");
2326 expect(rendered).toContain("Ctrl+C exit");
2327 expect(rendered.trimEnd().split("\n").length).toBeGreaterThan(1);
2328 },
2329 { tags: ["unit", "local"] },
2330 );
2331
2332 it.effect(
2333 "tabs scroll horizontally instead of wrapping when overflowing",
2334 () =>
2335 Effect.gen(function* () {
2336 const { service } = makeStatic();
2337 const tabs = Array.from({ length: 20 }, (_, i) => {
2338 const label = `profile-${String(i + 1).padStart(2, "0")}`;
2339 return { id: label, label, marked: i === 0 };
2340 });
2341
2342 // Active tab in the middle: window centers on it, arrows on both sides.
2343 const middle = yield* renderStatic(<Tabs tabs={tabs} active="profile-10" />);
2344 expect(middle).toContain("profile-10");
2345 expect(middle).toContain("‹");
2346 expect(middle).toContain("›");
2347 expect(middle).not.toContain("profile-01");
2348 expect(middle).not.toContain("profile-20");
2349 // every rendered tab stays on the single tab row — no wrapped chips
2350 expect(middle.trimEnd()).not.toContain("\n");
2351
2352 // Active tab at the start: no left arrow, right arrow only.
2353 const first = yield* renderStatic(<Tabs tabs={tabs} active="profile-01" />);
2354 expect(first).toContain("profile-01");
2355 expect(first).not.toContain("‹");
2356 expect(first).toContain("›");
2357
2358 // Active tab at the end: left arrow only.
2359 const last = yield* renderStatic(<Tabs tabs={tabs} active="profile-20" />);
2360 expect(last).toContain("profile-20");
2361 expect(last).toContain("‹");
2362 expect(last).not.toContain("›");
2363
2364 // Everything fits: no arrows at all.
2365 const fitting = yield* renderStatic(<Tabs tabs={tabs.slice(0, 3)} active="profile-02" />);
2366 expect(fitting).toContain("profile-01");
2367 expect(fitting).toContain("profile-03");
2368 expect(fitting).not.toContain("‹");
2369 expect(fitting).not.toContain("›");
2370 }),
2371 { tags: ["unit", "local"] },
2372 );
2373
2374 it(
2375 "tabsWindow keeps the active tab visible within the available width",
2376 () => {
2377 // 5 chips of width 12, gap 1, 74 columns → 5 fit exactly around the middle
2378 const widths = Array.from({ length: 20 }, () => 12);
2379 expect(tabsWindow(widths, 9, 74)).toEqual({ start: 7, end: 12 });
2380 // at the edges the window pins to the boundary
2381 expect(tabsWindow(widths, 0, 74)).toEqual({ start: 0, end: 5 });
2382 expect(tabsWindow(widths, 19, 74)).toEqual({ start: 15, end: 20 });
2383 // active always inside, even when nothing else fits
2384 expect(tabsWindow(widths, 3, 12)).toEqual({ start: 3, end: 4 });
2385 expect(tabsWindow(widths, 3, 5)).toEqual({ start: 3, end: 4 });
2386 // out-of-range active clamps; empty input yields an empty window
2387 expect(tabsWindow(widths, 99, 74)).toEqual({ start: 15, end: 20 });
2388 expect(tabsWindow([], 0, 74)).toEqual({ start: 0, end: 0 });
2389 },
2390 { tags: ["unit", "local"] },
2391 );
2392
2393 it.live(
2394 "state explorer confirms deletes inline and keeps its position afterwards",
2395 () =>
2396 Effect.gen(function* () {
2397 const { calls, source } = makeExplorerSource();
2398 let resources = ["Api/Worker", "Api/Queue", "Db"];
2399 const deleted: string[] = [];
2400 const mutable: StateExplorerSource = {
2401 ...source,
2402 listResources: () =>
2403 Effect.sync(() => {
2404 calls.resources++;
2405 return resources;
2406 }),
2407 deleteNodes: (nodes) =>
2408 Effect.sync(() => {
2409 for (const node of nodes) {
2410 deleted.push(node.path);
2411 const prefix = `app/prod/`;
2412 const fqn = node.path.slice(prefix.length);
2413 resources = resources.filter((r) => r !== fqn && !r.startsWith(`${fqn}/`));
2414 }
2415 }),
2416 };
2417 const stdin = new InputStream();
2418 const { service, stdout } = yield* makeLive({ stdin });
2419 const fiber = yield* service
2420 .session(service.prompt.screen(stateExplorerScreen(mutable)), { alternate: true })
2421 .pipe(Effect.forkChild);
2422 yield* Effect.promise(() => stdin.ready);
2423 const press = (key: string) =>
2424 Effect.sync(() => stdin.write(key)).pipe(Effect.andThen(settleInput));
2425 // Bounded waits that dump the last frame on expiry — a silent hang here
2426 // is otherwise undebuggable.
2427 const frame = () => stripVTControlCharacters(stdout.output.slice(-6000));
2428 const waitFrame = (text: string) =>
2429 Effect.promise(() => stdout.waitFor(text)).pipe(
2430 Effect.timeoutOrElse({
2431 duration: "3 seconds",
2432 orElse: () =>
2433 Effect.sync(() => {
2434 console.log(`=== TIMEOUT waiting for ${text} ===\n${frame()}`);
2435 throw new Error(`timeout waiting for ${text}`);
2436 }),
2437 }),
2438 );
2439 yield* waitFrame("app");
2440 // root → stages → state → into Api → Worker (select a row, then enter it)
2441 const enter = Effect.gen(function* () {
2442 yield* press("j");
2443 yield* press("\x1B[C");
2444 });
2445 yield* enter;
2446 yield* waitFrame("prod");
2447 yield* enter;
2448 yield* waitFrame("Api");
2449 yield* enter;
2450 yield* waitFrame("Worker");
2451 yield* press("j");
2452 yield* waitFrame("PREVIEW");
2453 yield* press("d");
2454 yield* waitFrame("Delete state records?");
2455 // The panel must not narrow the layout: its top border spans the
2456 // terminal, exactly like the header rule above the columns.
2457 const confirmFrame = frame();
2458 const rule = confirmFrame.split("\n").filter((line) => /^─+$/.test(line.trim()));
2459 expect(rule.at(-1)?.trim().length).toBe(stdout.columns);
2460 const before = stdout.output.length;
2461 yield* press("y");
2462 yield* waitFrame("Deleted state at");
2463 yield* settleInput;
2464 yield* Effect.promise(flushEffects);
2465 yield* settleInput;
2466 const after = stripVTControlCharacters(stdout.output.slice(before));
2467 expect(deleted).toEqual(["app/prod/Api/Queue"]);
2468 // stage listing re-read once; stacks/stages untouched
2469 expect(calls.stacks).toBe(1);
2470 expect(calls.stages).toBe(1);
2471 expect(calls.resources).toBe(2);
2472 // cursor moved to the surviving sibling in the same column
2473 expect(after).toContain("app/prod/Api/Worker");
2474 yield* press("q");
2475 yield* Fiber.join(fiber);
2476 }),
2477 { tags: ["unit", "local"] },
2478 );
2479
2480 it.effect(
2481 "renders nuke scan counts and outstanding providers",
2482 () =>
2483 Effect.gen(function* () {
2484 const { service } = makeStatic();
2485 const store = new NukeProgressStore();
2486 store.emit({ type: "nuke.scan.started", total: 2 });
2487 store.emit({ type: "nuke.scan.provider.started", provider: "Test.Fast" });
2488 store.emit({ type: "nuke.scan.provider.started", provider: "Test.Slow" });
2489 store.emit({ type: "nuke.scan.provider.completed", provider: "Test.Fast", resources: 3 });
2490 const output = yield* renderStatic(<NukeProgress store={store} />);
2491 expect(output).toContain("1/2");
2492 expect(output).toContain("3 resources found");
2493 expect(output).toContain("Scanning Test.Slow");
2494 const lines = output.split("\n");
2495 const header = lines.findIndex((line) => line.includes("1/2"));
2496 expect(lines[header]).toMatch(/^ \[[⣿⡇ ]+\] {2}\[1\/2\]\s*$/);
2497 expect(lines[header + 1]?.trim()).toBe("");
2498 expect(lines[header + 2]).toContain("Scanning providers");
2499 expect(output).not.toContain("Scanning Test.Fast");
2500 }),
2501 { tags: ["unit", "local"] },
2502 );
2503
2504 it.effect(
2505 "updates individual nuke plan rows during deletion",
2506 () =>
2507 Effect.gen(function* () {
2508 const { service } = makeStatic();
2509 const tree = new PlanTree(
2510 nukePlan(
2511 [
2512 { key: "b/0", providerId: "Test.B", displayName: "same-name" },
2513 { key: "a/1", providerId: "Test.A", displayName: "same-name" },
2514 { key: "a/2", providerId: "Test.A", displayName: "same-name" },
2515 ],
2516 { mode: "live" },
2517 ),
2518 { mode: "apply", viewport: "full", busy: true },
2519 );
2520 tree.setLabel("Deleting resources · pass 2");
2521 tree.emit({
2522 type: "apply.resource.status",
2523 fqn: "a/2",
2524 id: "Test.A",
2525 resourceType: "Test.A",
2526 status: "deleted",
2527 });
2528 tree.emit({
2529 type: "apply.resource.status",
2530 fqn: "a/1",
2531 id: "Test.A",
2532 resourceType: "Test.A",
2533 status: "fail",
2534 message: "blocked",
2535 });
2536 tree.emit({
2537 type: "apply.resource.status",
2538 fqn: "b/0",
2539 id: "Test.B",
2540 resourceType: "Test.B",
2541 status: "deleting",
2542 });
2543 expect(tree.snapshot().tasks.get("a/2")?.status).toBe("deleted");
2544 expect(tree.snapshot().tasks.get("a/1")?.status).toBe("fail");
2545 expect(tree.progress()).toEqual({ completed: 2, total: 3, failures: 1 });
2546 const output = yield* renderStatic(<Plan tree={tree} />);
2547 expect(output).toContain("pass 2");
2548 expect(output).toContain("blocked");
2549 expect(output.match(/same-name/g)).toHaveLength(3);
2550 expect(output).not.toContain("(Test.A)");
2551 }),
2552 { tags: ["unit", "local"] },
2553 );
2554
2555 it.effect(
2556 "renders nuke execution outcomes in the shared plan",
2557 () =>
2558 Effect.gen(function* () {
2559 const { service, stdout } = yield* makeLive();
2560 const provider: ProviderService = {
2561 nuke: { dependsOn: ["Test.Parent"] },
2562 list: () => Effect.succeed([]),
2563 reconcile: () => Effect.succeed({}),
2564 delete: () => Effect.void,
2565 };
2566 const resources = [
2567 {
2568 key: "t102",
2569 providerId: "Test.Parent",
2570 displayName: "parent",
2571 attributes: {},
2572 provider: { ...provider, nuke: undefined },
2573 },
2574 {
2575 key: "t103",
2576 providerId: "Test.Child",
2577 displayName: "same-name",
2578 attributes: {},
2579 provider: { ...provider, delete: () => Effect.fail("cannot delete child") },
2580 },
2581 { key: "t5", providerId: "Test.Child", displayName: "same-name", attributes: {}, provider },
2582 ];
2583 const result = yield* Alchemist.Nuke.execute({
2584 scan: { resources, mode: "live", context: Context.empty(), failures: [] },
2585 resources,
2586 strategy: { type: "coordinated" },
2587 }).pipe(renderNukeDelete(resources, "live"), Effect.provideService(Interaction, service));
2588 expect(result.deleted).toHaveLength(1);
2589 expect(result.failed).toHaveLength(1);
2590 expect(result.held).toHaveLength(1);
2591 expect(stdout.output).toContain("Nuke incomplete");
2592 expect(stdout.output).toContain("Held back by Test.Child");
2593 expect(stdout.output).toContain("cannot delete child");
2594 expect(stdout.output).toContain("same-name");
2595 expect(stdout.output).not.toContain("Test.Child 1/2");
2596 }),
2597 { tags: ["unit", "local"] },
2598 );
2599
2600 it.effect(
2601 "closes nuke live progress when the operation fails",
2602 () =>
2603 Effect.gen(function* () {
2604 const { service, stdout } = yield* makeLive();
2605 yield* Effect.gen(function* () {
2606 yield* emit({ type: "nuke.scan.started", total: 2 });
2607 yield* Effect.fail("scan failed");
2608 }).pipe(renderNukeScan(), Effect.provideService(Interaction, service), Effect.result);
2609 expect(stdout.output).toContain("\u001B[?25h");
2610 yield* service.output.info("After nuke");
2611 expect(stdout.output).toContain("After nuke");
2612 }),
2613 { tags: ["unit", "local"] },
2614 );
2615
2616 it.effect(
2617 "renders fixed-width Braille progress bars with partial cells",
2618 () =>
2619 Effect.gen(function* () {
2620 const { service } = makeStatic();
2621 for (const [value, expected] of [
2622 [-1, "[ ]"],
2623 [0, "[ ]"],
2624 [0.0625, "[ ]"],
2625 [0.25, "[⡇ ]"],
2626 [0.5, "[⣿ ]"],
2627 [0.75, "[⣿⡇]"],
2628 [1, "[⣿⣿]"],
2629 [2, "[⣿⣿]"],
2630 ] as const) {
2631 const output = yield* renderStatic(
2632 <ProgressBar value={value} width={2} showPercent={false} />,
2633 );
2634 expect(output.trim()).toBe(expected);
2635 }
2636 const labeled = yield* renderStatic(
2637 <ProgressBar value={0.5} width={2} label="Uploading" detail="2 of 4 files" />,
2638 );
2639 expect(labeled).toContain("[⣿ ]");
2640 expect(labeled).toContain("50%");
2641 expect(labeled).toContain("Uploading");
2642 expect(labeled).toContain("2 of 4 files");
2643 }),
2644 { tags: ["unit", "local"] },
2645 );
2646
2647 it.effect(
2648 "falls back to ASCII for progress bars without Unicode",
2649 () =>
2650 Effect.gen(function* () {
2651 const output = yield* renderStatic(
2652 <ProgressBar value={0.5} width={4} showPercent={false} />,
2653 { unicode: false },
2654 );
2655 expect(output.trim()).toBe("[##..]");
2656 }),
2657 { tags: ["unit", "local"] },
2658 );
2659
2660 it.effect(
2661 "renders nuke inventory with resource types as names and distinct row keys",
2662 () =>
2663 Effect.gen(function* () {
2664 const { service } = makeStatic();
2665 const targets = [
2666 { key: "t6", providerId: "Cloudflare.R2.Bucket", displayName: "same/name" },
2667 { key: "t7", providerId: "Cloudflare.R2.Bucket", displayName: "same/name" },
2668 { key: "t8", providerId: "AWS.S3.Bucket", displayName: "" },
2669 ];
2670 const plan = nukePlan(targets, { mode: "live" });
2671 const tree = new PlanTree(plan, { viewport: "full" });
2672 expect(tree.progressRows).toHaveLength(3);
2673 expect(new Set(tree.rows.map((row) => row.key)).size).toBe(3);
2674 expect(tree.rows.map((row) => row.id)).toEqual([
2675 "AWS.S3.Bucket",
2676 "Cloudflare.R2.Bucket",
2677 "Cloudflare.R2.Bucket",
2678 ]);
2679 expect(tree.rows.every((row) => row.type === "resource" && row.depth === 0)).toBe(true);
2680 const output = yield* renderStatic(<Plan tree={tree} />);
2681 expect(output).toContain("3 to delete");
2682 expect(output.match(/Cloudflare.R2.Bucket/g)).toHaveLength(2);
2683 expect(output).not.toContain("(Cloudflare.R2.Bucket)");
2684 expect(output.match(/same\/name/g)).toHaveLength(2);
2685
2686 const compact = yield* renderStatic(
2687 <Plan tree={new PlanTree(nukePlan(targets, { mode: "live" }), { viewport: "full" })} />,
2688 );
2689 expect(compact).toContain("3 to delete");
2690 expect(compact.match(/same\/name/g)).toHaveLength(2);
2691 expect(compact.match(/Cloudflare.R2.Bucket/g)).toHaveLength(2);
2692 expect(compact).not.toContain("(x2)");
2693 }),
2694 { tags: ["unit", "local"] },
2695 );
2696
2697 it.effect(
2698 "prints the shared nuke plan for dry-run and yes without prompting",
2699 () =>
2700 Effect.gen(function* () {
2701 for (const options of [
2702 { yes: false, dryRun: true },
2703 { yes: true, dryRun: false },
2704 ]) {
2705 const { service, stdout } = makeStatic();
2706 const result = yield* reviewNuke(
2707 [{ key: "t9", providerId: "AWS.S3.Bucket", displayName: "bucket" }],
2708 {
2709 ...options,
2710 mode: "local",
2711 },
2712 ).pipe(Effect.provideService(Interaction, service));
2713 expect(result).toBe(true);
2714 expect(stdout.output).toContain("1 to delete");
2715 expect(stdout.output).toContain("AWS.S3.Bucket");
2716 expect(stdout.output).toContain("bucket");
2717 }
2718 }),
2719 { tags: ["unit", "local"] },
2720 );
2721
2722 it.live(
2723 "defaults nuke plan approval to Cancel",
2724 () =>
2725 Effect.gen(function* () {
2726 const stdin = new InputStream();
2727 const { service, stdout } = yield* makeLive({ stdin });
2728 const review = yield* reviewNuke(
2729 [{ key: "t10", providerId: "AWS.S3.Bucket", displayName: "bucket" }],
2730 {
2731 mode: "local",
2732 yes: false,
2733 dryRun: false,
2734 },
2735 ).pipe(Effect.provideService(Interaction, service), Effect.forkChild);
2736 yield* Effect.promise(flushEffects);
2737 yield* Effect.raceFirst(
2738 Effect.promise(() => stdout.waitFor("Cancel")),
2739 Fiber.join(review).pipe(Effect.flatMap(() => Effect.die("review ended before prompt"))),
2740 );
2741 yield* Effect.promise(() => stdin.ready);
2742 expect(stdout.output).toContain("1 to delete");
2743 expect(stdout.output).toContain("locally emulated");
2744 yield* Effect.sync(() => stdin.write("\r"));
2745 yield* Effect.promise(flushEffects);
2746 expect(yield* Fiber.join(review)).toBe(false);
2747 }),
2748 { tags: ["unit", "local"] },
2749 );
2750
2751 it.effect(
2752 "keeps unnamed and duplicate nuke targets as individual rows",
2753 () =>
2754 Effect.gen(function* () {
2755 const { service } = makeStatic();
2756 const targets = [
2757 { key: "t11", providerId: "AWS.ApiGateway.GatewayResponse", displayName: "api-123" },
2758 { key: "t12", providerId: "AWS.ApiGateway.GatewayResponse", displayName: "api-123" },
2759 { key: "t13", providerId: "AWS.S3.Bucket", displayName: "photos" },
2760 { key: "t14", providerId: "AWS.S3.Bucket", displayName: "backups" },
2761 { key: "t15", providerId: "Test.Unknown", displayName: "unknown" },
2762 { key: "t16", providerId: "Test.Unknown", displayName: "" },
2763 ];
2764 const plan = nukePlan(targets, { mode: "live" });
2765 expect(plan.rows).toHaveLength(6);
2766 const output = yield* renderStatic(<Plan tree={new PlanTree(plan, { viewport: "full" })} />);
2767 expect(output).toContain("6 to delete");
2768 expect(output.match(/api-123/g)).toHaveLength(2);
2769 expect(output.match(/Test.Unknown/g)).toHaveLength(2);
2770 expect(output).not.toContain("(x2)");
2771 expect(output).toContain("photos");
2772 expect(output).toContain("backups");
2773 expect(output).not.toContain("· unknown");
2774 }),
2775 { tags: ["unit", "local"] },
2776 );
2777
2778 it.effect(
2779 "presents nuke errors as soon as they are emitted",
2780 () =>
2781 Effect.gen(function* () {
2782 for (const input of [true, false]) {
2783 const { service } = yield* makeLive({ input });
2784 const lines: string[] = [];
2785 // Handlers run on their own fiber, in order, as soon as it is scheduled.
2786 const presented = (count: number) =>
2787 Effect.yieldNow.pipe(Effect.repeat({ until: () => lines.length >= count, times: 100 }));
2788 const console = Object.assign(Object.create(globalThis.console), {
2789 log: (...args: unknown[]) =>
2790 lines.push(stripVTControlCharacters(args.join(" ")).replace(/^\[[\d:.]+\] /, "")),
2791 });
2792 yield* Effect.gen(function* () {
2793 yield* emit({ type: "nuke.scan.started", total: 2 });
2794 yield* emit({
2795 type: "nuke.scan.provider.completed",
2796 provider: "Test.Failed",
2797 resources: 0,
2798 error: "denied during scan",
2799 });
2800 // Check before the operation returns: errors must not wait for completion.
2801 yield* presented(1);
2802 expect(lines).toEqual(["WARN: Test.Failed: denied during scan"]);
2803 yield* emit({
2804 type: "nuke.resource.failed",
2805 provider: "Test.Resource",
2806 resource: "example",
2807 message: "denied during delete",
2808 });
2809 yield* presented(2);
2810 expect(lines[1]).toEqual("WARN: Test.Resource example: denied during delete");
2811 yield* emit({
2812 type: "nuke.scan.provider.completed",
2813 provider: "Test.Ready",
2814 resources: 1,
2815 });
2816 yield* emit({
2817 type: "nuke.resource.deleted",
2818 provider: "Test.Ready",
2819 resource: "gone",
2820 });
2821 }).pipe(
2822 renderNukeScan(),
2823 Effect.provideService(Interaction, service),
2824 Effect.provideService(Console.Console, console),
2825 );
2826 expect(lines).toHaveLength(input ? 2 : 4);
2827 if (!input) {
2828 expect(lines.slice(2)).toEqual([
2829 "INFO: scanned Test.Ready (1)",
2830 "INFO: deleted Test.Ready gone",
2831 ]);
2832 }
2833 }
2834 }),
2835 { tags: ["unit", "local"] },
2836 );