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

main
tsx 266 lines 8.28 KB
Raw
1 /** @jsxRuntime automatic */
2 /** @jsxImportSource @alchemy.run/sigil */
3 import * as Effect from "effect/Effect";
4 import * as Exit from "effect/Exit";
5 import * as LogLevel from "effect/LogLevel";
6 import * as Match from "effect/Match";
7 import { onEvent, type Event } from "../../../Events.ts";
8 import { Interaction } from "../../../Interaction.ts";
9 import type { Result as NukeResult, Target } from "../../../Nuke.ts";
10 import type { ProviderMode } from "../../../ProviderMode.ts";
11 import { currentConsoleSettings } from "../../GlobalLog.ts";
12 import { present } from "../../Present.ts";
13 import {
14 LiveStore,
15 ProgressBar,
16 Row,
17 SpinnerGlyph,
18 Stack,
19 Text,
20 useLiveStore,
21 } from "../ui/index.ts";
22 import { planDecisionScreen } from "./PlanDecision.tsx";
23 import type { PlanTreeData } from "./PlanTree.ts";
24 import { Plan, PlanTree } from "./PlanView.tsx";
25
26 interface NukeProgressState {
27 readonly total: number;
28 readonly completed: number;
29 readonly resources: number;
30 readonly inFlight: ReadonlyArray<string>;
31 }
32
33 export class NukeProgressStore extends LiveStore<NukeProgressState> {
34 constructor() {
35 super({ total: 0, completed: 0, resources: 0, inFlight: [] });
36 }
37
38 emit(event: Event) {
39 this.update((state) =>
40 Match.value(event).pipe(
41 Match.discriminators("type")({
42 "nuke.scan.started": (event) => ({ ...state, total: event.total }),
43 "nuke.scan.provider.started": (event) => ({
44 ...state,
45 inFlight: [...state.inFlight, event.provider],
46 }),
47 "nuke.scan.provider.completed": (event) => ({
48 ...state,
49 completed: state.completed + 1,
50 resources: state.resources + event.resources,
51 inFlight: state.inFlight.filter((id) => id !== event.provider),
52 }),
53 }),
54 Match.orElse(() => state),
55 ),
56 );
57 }
58 }
59
60 export function NukeProgress({ store }: { store: NukeProgressStore }) {
61 const state = useLiveStore(store);
62 return (
63 <Stack paddingX={2} paddingY={1} gap={1}>
64 <Row gap={2}>
65 <ProgressBar
66 value={state.total === 0 ? 0 : state.completed / state.total}
67 width={32}
68 showPercent={false}
69 variant="info"
70 />
71 <Text bold>
72 [{state.completed}/{state.total}]
73 </Text>
74 </Row>
75 <Stack>
76 <Text tone="muted">
77 Scanning providers · {state.resources} resource
78 {state.resources === 1 ? "" : "s"} found
79 </Text>
80 {state.inFlight.slice(0, 10).map((id) => (
81 <Row key={id} gap={1}>
82 <SpinnerGlyph />
83 <Text>Scanning {id}</Text>
84 </Row>
85 ))}
86 {state.inFlight.length > 10 ? (
87 <Text tone="muted">…and {state.inFlight.length - 10} more</Text>
88 ) : null}
89 {state.total === 0 ? (
90 <Row gap={1}>
91 <SpinnerGlyph />
92 <Text>Discovering providers</Text>
93 </Row>
94 ) : null}
95 </Stack>
96 </Stack>
97 );
98 }
99
100 const logNukeEvent = (event: Event, interactive: boolean) =>
101 Match.value(event).pipe(
102 Match.discriminators("type")({
103 "nuke.scan.provider.completed": (event) =>
104 event.error !== undefined
105 ? present(`${event.provider}: ${event.error}`, { level: "Warn" })
106 : interactive
107 ? Effect.void
108 : present(`scanned ${event.provider} (${event.resources})`),
109 "nuke.resource.failed": (event) =>
110 present(`${event.provider} ${event.resource}: ${event.message}`, { level: "Warn" }),
111 "nuke.resource.deleted": (event) =>
112 interactive ? Effect.void : present(`deleted ${event.provider} ${event.resource}`),
113 }),
114 Match.orElse(() => Effect.void),
115 );
116
117 /** Scan progress stays separate until the inventory is ready to review. */
118 /**
119 * `--log-level debug` (or lower) streams debug records to the console; the
120 * live progress view would repaint over them, so it falls back to plain lines.
121 */
122 const debugConsole = Effect.map(currentConsoleSettings, ({ floor }) =>
123 LogLevel.isLessThan(floor, "Info"),
124 );
125
126 export const renderNukeScan =
127 () =>
128 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
129 Effect.gen(function* () {
130 const cli = yield* Interaction;
131 const store = new NukeProgressStore();
132 const live =
133 cli.terminal.input && !(yield* debugConsole)
134 ? yield* cli.live(<NukeProgress store={store} />)
135 : undefined;
136 return yield* effect.pipe(
137 onEvent((event) =>
138 Effect.gen(function* () {
139 if (live) store.emit(event);
140 yield* logNukeEvent(event, live !== undefined);
141 }),
142 ),
143 Effect.ensuring(live?.close ?? Effect.void),
144 );
145 });
146
147 /** Drive the same resource rows used by the preview through their deletion lifecycle. */
148 export const renderNukeDelete =
149 (
150 targets: ReadonlyArray<Pick<Target, "key" | "providerId" | "displayName">>,
151 mode: ProviderMode,
152 ) =>
153 <A extends NukeResult, E, R>(effect: Effect.Effect<A, E, R>) =>
154 Effect.gen(function* () {
155 const cli = yield* Interaction;
156 const tree = new PlanTree(nukePlan(targets, { mode }), {
157 mode: "apply",
158 label: "Deleting resources",
159 busy: true,
160 });
161 const live =
162 cli.terminal.input && !(yield* debugConsole)
163 ? yield* cli.live(<Plan tree={tree} />, { persistOnClose: true })
164 : undefined;
165 return yield* effect.pipe(
166 onEvent((event) =>
167 Effect.sync(() =>
168 Match.value(event).pipe(
169 Match.discriminators("type")({
170 "apply.resource.status": (event) => tree.emit(event),
171 "apply.resource.note": (event) => tree.emit(event),
172 "nuke.pass.started": (event) =>
173 tree.setLabel(`Deleting resources · pass ${event.pass}`),
174 }),
175 Match.orElse(() => undefined),
176 ),
177 ).pipe(Effect.andThen(logNukeEvent(event, live !== undefined))),
178 ),
179 Effect.onExit((exit) =>
180 Effect.sync(() => {
181 const success =
182 Exit.isSuccess(exit) &&
183 exit.value.failed.length === 0 &&
184 exit.value.held.length === 0;
185 tree.finish(
186 success ? "success" : "failure",
187 success ? "Nuke complete" : "Nuke incomplete",
188 );
189 tree.setViewport("full");
190 }),
191 ),
192 Effect.ensuring(live?.close ?? Effect.void),
193 );
194 });
195
196 /** Cloud inventory rows carry display identity only, never fabricated stack state. */
197 export const nukePlan = (
198 targets: ReadonlyArray<Pick<Target, "key" | "providerId" | "displayName">>,
199 options: { mode: ProviderMode },
200 ): PlanTreeData => ({
201 defaultMode: options.mode,
202 rows: targets
203 .map((target) => ({
204 key: target.key,
205 type: "resource" as const,
206 id: target.providerId,
207 resourceType: target.providerId,
208 detail:
209 target.displayName && target.displayName !== "unknown" ? target.displayName : undefined,
210 depth: 0,
211 action: "delete" as const,
212 providerMode: options.mode,
213 }))
214 .sort((a, b) => a.id.localeCompare(b.id) || (a.detail ?? "").localeCompare(b.detail ?? "")),
215 summary: {
216 counts: {
217 create: 0,
218 update: 0,
219 adopted: 0,
220 delete: targets.length,
221 orphaned: 0,
222 replace: 0,
223 noop: 0,
224 },
225 taskCounts: { run: 0, delete: 0, noop: 0 },
226 bindingChanges: 0,
227 },
228 });
229
230 export const reviewNuke = Effect.fn(function* (
231 targets: ReadonlyArray<Pick<Target, "key" | "providerId" | "displayName">>,
232 options: {
233 mode: ProviderMode;
234 yes: boolean;
235 dryRun: boolean;
236 },
237 ) {
238 const cli = yield* Interaction;
239 const plan = nukePlan(targets, options);
240 if (options.yes || options.dryRun) {
241 yield* cli.output.print(
242 <Plan
243 tree={
244 new PlanTree(plan, {
245 mode: "review",
246 label: "Nuke",
247 viewport: "full",
248 })
249 }
250 />,
251 );
252 return true;
253 }
254 return yield* cli.prompt.screen(
255 planDecisionScreen({
256 plan,
257 label: "Nuke",
258 message: `Permanently DELETE ${targets.length} ${options.mode === "local" ? "locally emulated " : ""}resource(s)? This cannot be undone.`,
259 choices: [
260 { value: true, label: "Delete" },
261 { value: false, label: "Cancel" },
262 ],
263 initialValue: false,
264 }),
265 );
266 });