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

main
tsx 736 lines 22.6 KB
Raw
1 /** @jsxRuntime automatic */
2 /** @jsxImportSource @alchemy.run/sigil */
3 /**
4 * THE plan renderer. Every surface that shows a plan tree — `alchemy plan`
5 * output, the approval prompt, and the live apply/dev/destroy progress —
6 * renders through this one state-driven component, so a plan always looks
7 * the same wherever it appears.
8 *
9 * - One {@link PlanTree} holds the flattened tree (namespaces,
10 * resources, bindings, actions) plus per-row runtime state (apply status
11 * and the row's latest log message), updated from engine
12 * {@link ApplyEvent}s.
13 * - Two presentation `mode`s: `review` renders action glyphs (`+ ~ - ±`),
14 * `apply` renders live statuses with spinners and per-row messages.
15 * - `virtual` viewports follow the active row and support keyboard scrolling;
16 * `full` viewports produce static terminal scrollback. This choice is
17 * independent of whether the tree will receive more events.
18 * - Property diffs (`detailed`) render in every mode, and the window is
19 * line-budget aware so multi-line rows never overflow the terminal.
20 */
21 import { useMemo, useSyncExternalStore } from "@alchemy.run/sigil/react";
22 import type { JSX, ReactNode } from "react";
23 import type { ApplyStatus } from "../../../Events.ts";
24 import type { Plan as AlchemyPlan } from "../../../Plan.ts";
25 import { theme } from "../../../Util/Theme.ts";
26 import { formatElapsed } from "../../Format.ts";
27 import { formatModeNote } from "../../ModeTag.ts";
28 import type { ActionVerb, PlanSummaryCounts } from "../../NamespaceTree.ts";
29 import { matchYamlChange, matchYamlKey } from "../../PropertyDiff.ts";
30 import {
31 Box,
32 KeyBar,
33 Row,
34 SectionHeading,
35 SpinnerGlyph,
36 TaskRow,
37 Text,
38 useBorderStyle,
39 useGlyphs,
40 useKeyGlyphs,
41 } from "../ui/index.ts";
42 import { NamespaceRow, namespaceStyle } from "./PlanRow.tsx";
43 import {
44 PlanTree,
45 initialResourceState,
46 type PlanRow,
47 type PlanTreeState,
48 type ResourceRow,
49 type RowState,
50 } from "./PlanTree.ts";
51 import { StackOutputs } from "./StackOutputs.tsx";
52 import { actionStyle, applyStatusColor, isInProgress, isTerminalStatus } from "./statusStyle.ts";
53 import { usePlanPresentation } from "./usePlanPresentation.ts";
54 import { usePlanViewport } from "./usePlanViewport.ts";
55
56 export { PlanTree } from "./PlanTree.ts";
57 export type {
58 PlanOutcome,
59 PlanProgress,
60 PlanRow,
61 PlanTreeOptions,
62 PlanTreeState,
63 PlanView,
64 PlanViewport,
65 RowState,
66 } from "./PlanTree.ts";
67 export type { PlanSummaryCounts } from "../../NamespaceTree.ts";
68
69 /**
70 * Row detail: the latest log/annotation line, painted danger when the row
71 * failed so the error reads at the row instead of only in the final dump.
72 */
73 const rowDetail = (status: ApplyStatus, message: string | undefined) =>
74 message !== undefined && status === "fail" ? (
75 <Text color={theme.color.danger}>{message}</Text>
76 ) : (
77 message
78 );
79
80 // ── Component ─────────────────────────────────────────────────────────────
81
82 export interface PlanProps {
83 /** Reactive tree containing rows, statuses, label, and presentation state. */
84 tree: PlanTree;
85 /** Allow the tree to collapse behind `p`. */
86 collapsible?: boolean;
87 /** Widget rendered before the summary block. */
88 before?: ReactNode;
89 /** Widget rendered on the summary row before the summary. */
90 summaryBefore?: ReactNode;
91 /** Widget rendered on the summary row after the summary. */
92 summaryAfter?: ReactNode;
93 /** Widget rendered below the virtualized rows. */
94 footer?: ReactNode;
95 /** Widget rendered after the complete Plan. */
96 after?: ReactNode;
97 }
98
99 const usePlanTree = (tree: PlanTree): PlanTreeState => {
100 const subscribe = useMemo(() => tree.subscribe.bind(tree), [tree]);
101 const snapshot = useMemo(() => tree.snapshot.bind(tree), [tree]);
102 return useSyncExternalStore(subscribe, snapshot);
103 };
104
105 export function Plan(props: PlanProps): JSX.Element {
106 const { tree, collapsible = false, before, summaryBefore, summaryAfter, footer, after } = props;
107 const { mode } = tree;
108 const keyGlyphs = useKeyGlyphs();
109 const borderStyle = useBorderStyle();
110 const state = usePlanTree(tree);
111 const { tasks, label, viewport, busy } = state;
112 const {
113 progress: { completed, total: workRows },
114 collapsed,
115 showControls,
116 lineBudget,
117 refs: { beforeRef, summaryRef, controlsRef, afterRef },
118 } = usePlanPresentation({
119 tree,
120 state,
121 busy,
122 collapsible,
123 hasFooter: footer !== undefined,
124 });
125 const {
126 selectedView,
127 hasOutput,
128 virtual: virtualizing,
129 budget: budgetRows,
130 offset: shownOffset,
131 hiddenBelow,
132 planLines: visibleLines,
133 } = usePlanViewport({
134 tree,
135 state,
136 lineBudget,
137 collapsible,
138 collapsed,
139 });
140
141 // ── Summary and operation bar ─────────────────────────────────────────
142 const operationProgress =
143 mode === "apply" ? (
144 <>
145 {busy ? (
146 <>
147 <SpinnerGlyph color={theme.color.brand} />
148 <Text> </Text>
149 </>
150 ) : null}
151 <SectionHeading>{label}</SectionHeading>
152 <Text tone="muted">{workRows === 0 ? "" : ` (${completed}/${workRows})`}</Text>
153 </>
154 ) : null;
155 const planSummary =
156 selectedView === "output" ? (
157 <SectionHeading>Output</SectionHeading>
158 ) : mode === "apply" ? (
159 <ApplySummary label="Plan" rows={tree.progressRows} tasks={tasks} />
160 ) : (
161 <ReviewSummary label={label} summary={tree.summary} />
162 );
163 const planKeys: ReadonlyArray<readonly [string, string]> = [
164 ...(!collapsed && viewport === "virtual"
165 ? [[keyGlyphs.upDown, `scroll ${selectedView}`] as const]
166 : []),
167 ...(!collapsed && hasOutput
168 ? [[keyGlyphs.leftRight, selectedView === "plan" ? "show output" : "show plan"] as const]
169 : []),
170 ["p", collapsed ? "show plan/output" : "hide widget"],
171 ["Ctrl+C", "exit"],
172 ];
173
174 return (
175 <Box flexDirection="column">
176 <Box ref={beforeRef} flexDirection="column">
177 {before}
178 </Box>
179 {collapsed ? null : (
180 <Box
181 ref={summaryRef}
182 marginBottom={1}
183 borderStyle={borderStyle}
184 borderTop
185 borderBottom={false}
186 borderLeft={false}
187 borderRight={false}
188 borderColor={theme.color.muted}
189 borderDimColor
190 >
191 {summaryBefore}
192 {planSummary}
193 {summaryAfter}
194 </Box>
195 )}
196 {collapsed ? null : (
197 <PlanContent
198 tree={tree}
199 state={state}
200 selectedView={selectedView}
201 virtual={virtualizing}
202 budget={budgetRows}
203 offset={shownOffset}
204 hiddenBelow={hiddenBelow}
205 lines={visibleLines}
206 />
207 )}
208 {showControls ? (
209 <Box
210 ref={controlsRef}
211 marginTop={collapsed ? 0 : 1}
212 borderStyle={borderStyle}
213 borderTop
214 borderBottom={false}
215 borderLeft={false}
216 borderRight={false}
217 borderColor={theme.color.muted}
218 borderDimColor
219 >
220 {collapsible ? (
221 <KeyBar
222 inline
223 marginTop={0}
224 before={operationProgress}
225 keys={planKeys}
226 after={footer}
227 divider={mode === "apply" || footer !== undefined}
228 />
229 ) : mode === "apply" ? (
230 <>
231 {operationProgress}
232 {footer}
233 </>
234 ) : (
235 footer
236 )}
237 </Box>
238 ) : null}
239 <Box ref={afterRef} flexDirection="column">
240 {after}
241 </Box>
242 </Box>
243 );
244 }
245
246 function PlanContent(props: {
247 readonly tree: PlanTree;
248 readonly state: PlanTreeState;
249 readonly selectedView: "plan" | "output";
250 readonly virtual: boolean;
251 readonly budget: number;
252 readonly offset: number;
253 readonly hiddenBelow: number;
254 readonly lines: ReturnType<typeof usePlanViewport>["planLines"];
255 }) {
256 const { tree, state, selectedView, virtual, budget, offset, hiddenBelow } = props;
257 const glyphs = useGlyphs();
258 const overflowUnit = virtual ? "lines" : "rows";
259 return (
260 <Box flexDirection="column">
261 {offset > 0 ? (
262 <Text tone="muted">
263 {glyphs.overflowUp} {offset} earlier {overflowUnit}
264 </Text>
265 ) : null}
266 {selectedView === "output" ? (
267 <StackOutputs value={state.output} offset={offset} limit={virtual ? budget : undefined} />
268 ) : props.lines === undefined ? (
269 tree.rows.map((row) => (
270 <PlanRowView
271 key={row.key}
272 row={row}
273 mode={tree.mode}
274 detailed={tree.detailed}
275 state={state.tasks.get(row.type === "binding" ? row.hostKey : row.key)}
276 defaultMode={tree.defaultMode}
277 />
278 ))
279 ) : (
280 props.lines.map((line) =>
281 line.kind === "row" ? (
282 <PlanRowView
283 key={line.row.key}
284 row={line.row}
285 mode={tree.mode}
286 detailed={tree.detailed}
287 includeYaml={false}
288 state={state.tasks.get(line.row.type === "binding" ? line.row.hostKey : line.row.key)}
289 defaultMode={tree.defaultMode}
290 />
291 ) : line.kind === "yaml" ? (
292 <YamlLine key={line.key} line={line.line} paddingLeft={line.paddingLeft} />
293 ) : (
294 <DetailLine key={line.key} paddingLeft={line.paddingLeft}>
295 <Text tone="muted" dimColor>
296 no declared property changes
297 </Text>
298 </DetailLine>
299 ),
300 )
301 )}
302 {hiddenBelow > 0 ? (
303 <Text tone="muted">
304 {glyphs.overflowDown} {hiddenBelow} more {overflowUnit}
305 </Text>
306 ) : null}
307 </Box>
308 );
309 }
310
311 // ── Rows ──────────────────────────────────────────────────────────────────
312
313 function PlanRowView(props: {
314 row: PlanRow;
315 mode: "review" | "apply";
316 detailed: boolean;
317 state: RowState | undefined;
318 defaultMode: AlchemyPlan["defaultMode"];
319 includeYaml?: boolean;
320 }): JSX.Element {
321 const { row, mode, detailed, state, defaultMode, includeYaml = true } = props;
322 const glyphs = useGlyphs();
323
324 if (row.type === "namespace") {
325 return <NamespaceRow id={row.id} depth={row.depth} action={row.action} />;
326 }
327
328 if (row.type === "binding") {
329 if (mode === "review") {
330 const style =
331 row.action === "delete"
332 ? { color: theme.color.muted, icon: "delete" as const }
333 : namespaceStyle(row.action);
334 return (
335 <Row gap={1} paddingLeft={row.depth * 2}>
336 <Text color={style.color}>{glyphs[style.icon]}</Text>
337 <Text color={row.action === "delete" ? theme.color.muted : theme.color.info}>
338 {row.id}
339 </Text>
340 {row.action === "delete" ? <Text tone="muted">(unbind)</Text> : null}
341 </Row>
342 );
343 }
344 // `state` is the HOST resource's row state: a binding is reconciled by
345 // the resource that carries it, so it settles exactly when the host does.
346 const hostStatus: ApplyStatus = state?.status ?? "pending";
347 const status: ApplyStatus | "no change" = row.action === "noop" ? "no change" : hostStatus;
348 const color = row.action === "delete" ? theme.color.muted : applyStatusColor(status);
349 const bindingStatus =
350 row.action !== "delete"
351 ? status
352 : hostStatus === "fail"
353 ? "fail"
354 : isTerminalStatus(hostStatus)
355 ? "unbound"
356 : isInProgress(hostStatus)
357 ? "unbinding"
358 : "unbind";
359 return (
360 <TaskRow
361 spinning={status !== "no change" && isInProgress(hostStatus)}
362 icon={
363 status === "pending" ? glyphs.bullet : status === "fail" ? glyphs.error : glyphs.success
364 }
365 iconColor={color}
366 label={
367 <Text color={row.action === "delete" ? theme.color.muted : theme.color.info}>
368 {row.id}
369 </Text>
370 }
371 depth={row.depth}
372 >
373 <Text color={color}>{bindingStatus}</Text>
374 </TaskRow>
375 );
376 }
377
378 if (row.type === "task") {
379 if (mode === "review") {
380 const style = namespaceStyle(row.action);
381 return (
382 <TaskRow icon={glyphs[style.icon]} iconColor={style.color} label={row.id} depth={row.depth}>
383 <Text color={theme.color.info}>[action]</Text>
384 </TaskRow>
385 );
386 }
387 const status: ApplyStatus = state?.status ?? (row.action === "noop" ? "ran" : "pending");
388 const color = applyStatusColor(status);
389 return (
390 <TaskRow
391 spinning={isInProgress(status)}
392 icon={taskIcon(row.action, status, glyphs)}
393 iconColor={color}
394 label={row.id}
395 detail={rowDetail(status, state?.message)}
396 depth={row.depth}
397 >
398 <Text color={color}>{taskLabel(row.action, status)}</Text>
399 <Text color={theme.color.info} dimColor>
400 [action]
401 </Text>
402 {state?.elapsedMs === undefined ? null : (
403 <Text tone="muted">({formatElapsed(state.elapsedMs)})</Text>
404 )}
405 </TaskRow>
406 );
407 }
408
409 // Resource row.
410 const modeNote = formatModeNote({
411 mode: row.providerMode,
412 priorMode: row.fromProviderMode,
413 defaultMode,
414 });
415 const showYaml = includeYaml && (detailed || row.propertyYaml?.kind === "drift");
416 const yaml = showYaml ? (
417 row.propertyYaml === undefined ? (
418 row.action === "update" || row.action === "adopted" || row.action === "replace" ? (
419 <DetailLine paddingLeft={row.depth * 2 + 2}>
420 <Text tone="muted" dimColor>
421 no declared property changes
422 </Text>
423 </DetailLine>
424 ) : null
425 ) : (
426 row.propertyYaml.lines.map((line, index) => (
427 <YamlLine key={`${index}:${line}`} line={line} paddingLeft={row.depth * 2 + 2} />
428 ))
429 )
430 ) : null;
431
432 if (mode === "review") {
433 const style = namespaceStyle(row.action);
434 return (
435 <Box flexDirection="column" marginTop={showYaml ? 1 : 0}>
436 <TaskRow
437 icon={glyphs[style.icon]}
438 iconColor={style.color}
439 label={<Text color={row.action === "noop" ? undefined : style.color}>{row.id}</Text>}
440 depth={row.depth}
441 detail={row.detail}
442 >
443 {modeNote && <Text tone="muted">({modeNote})</Text>}
444 {row.id !== row.resourceType ? <Text tone="muted">({row.resourceType})</Text> : null}
445 </TaskRow>
446 {yaml}
447 </Box>
448 );
449 }
450
451 const rowState = state ?? initialResourceState(row);
452 const displayStatus = resourceDisplayStatus(row, rowState.status);
453 const color = applyStatusColor(displayStatus);
454 return (
455 <Box flexDirection="column">
456 <TaskRow
457 spinning={isInProgress(rowState.status)}
458 icon={
459 rowState.status === "pending"
460 ? glyphs.bullet
461 : rowState.status === "fail"
462 ? glyphs.error
463 : rowState.status === "adopted"
464 ? glyphs.adopt
465 : rowState.status === "orphaned"
466 ? glyphs.orphan
467 : glyphs.success
468 }
469 iconColor={color}
470 label={
471 <>
472 {row.action === "orphaned" ? <Text tone="muted">{row.id}</Text> : row.id}
473 {row.id !== row.resourceType ? <Text tone="muted"> ({row.resourceType})</Text> : null}
474 {row.detail ? <Text tone="muted"> · {row.detail}</Text> : null}
475 </>
476 }
477 detail={rowDetail(rowState.status, rowState.message)}
478 depth={row.depth}
479 >
480 {modeNote ? <Text tone="muted">({modeNote})</Text> : null}
481 <Text color={color}>{displayStatus}</Text>
482 {rowState.elapsedMs === undefined ? null : (
483 <Text tone="muted">({formatElapsed(rowState.elapsedMs)})</Text>
484 )}
485 </TaskRow>
486 {yaml}
487 </Box>
488 );
489 }
490
491 // ── Headers ───────────────────────────────────────────────────────────────
492
493 function ReviewSummary(props: { label: string; summary: PlanSummaryCounts }): JSX.Element {
494 const { counts, taskCounts, bindingChanges } = props.summary;
495 const parts = [
496 ...(["create", "update", "adopted", "delete", "orphaned", "replace"] as const)
497 .filter((action) => counts[action] > 0)
498 .map((action) => ({
499 key: action,
500 label: `${counts[action]} to ${action}`,
501 color: namespaceStyle(action).color,
502 })),
503 ...(counts.noop > 0
504 ? [
505 {
506 key: "noop",
507 label: `${counts.noop} no change`,
508 color: theme.color.muted,
509 },
510 ]
511 : []),
512 ...(taskCounts.run > 0
513 ? [
514 {
515 key: "run",
516 label: `${taskCounts.run} to run`,
517 color: namespaceStyle("run").color,
518 },
519 ]
520 : []),
521 ...(taskCounts.delete > 0
522 ? [
523 {
524 key: "drop",
525 label: `${taskCounts.delete} to drop`,
526 color: namespaceStyle("delete").color,
527 },
528 ]
529 : []),
530 ...(taskCounts.noop > 0
531 ? [
532 {
533 key: "task-noop",
534 label: `${taskCounts.noop} tasks no change`,
535 color: theme.color.muted,
536 },
537 ]
538 : []),
539 ...(bindingChanges > 0
540 ? [
541 {
542 key: "bindings",
543 label: `${bindingChanges} binding changes`,
544 color: theme.color.info,
545 },
546 ]
547 : []),
548 ];
549 return (
550 <>
551 <SectionHeading>{props.label}</SectionHeading>
552 <Text tone="muted"> · </Text>
553 {parts.length === 0 ? (
554 <Text tone="muted">no changes</Text>
555 ) : (
556 parts.map((part, index) => (
557 <Box key={part.key}>
558 {index === 0 ? null : <Text tone="muted"> · </Text>}
559 <Text color={part.color}>{part.label}</Text>
560 </Box>
561 ))
562 )}
563 </>
564 );
565 }
566
567 const applySummaryOrder: readonly (ApplyStatus | "no change")[] = [
568 "fail",
569 "attaching",
570 "post-attach",
571 "pre-creating",
572 "creating",
573 "creating replacement",
574 "updating",
575 "adopting",
576 "deleting",
577 "orphaning",
578 "replacing",
579 "running",
580 "pending",
581 "created",
582 "updated",
583 "adopted",
584 "deleted",
585 "orphaned",
586 "replaced",
587 "ran",
588 "skipped",
589 "no change",
590 ];
591
592 function ApplySummary(props: {
593 label: string;
594 rows: readonly PlanRow[];
595 tasks: ReadonlyMap<string, RowState>;
596 }): JSX.Element {
597 const counts = new Map<ApplyStatus | "no change", number>();
598 for (const row of props.rows) {
599 const status = props.tasks.get(row.key)?.status ?? "pending";
600 const displayStatus = row.action === "noop" ? "no change" : status;
601 counts.set(displayStatus, (counts.get(displayStatus) ?? 0) + 1);
602 }
603 const parts = applySummaryOrder
604 .filter((status) => counts.has(status))
605 .map((status) => ({
606 status,
607 count: counts.get(status) ?? 0,
608 }));
609
610 return (
611 <>
612 <SectionHeading>{props.label}</SectionHeading>
613 <Text tone="muted"> · </Text>
614 {parts.length === 0 ? (
615 <Text tone="muted">no resources</Text>
616 ) : (
617 parts.map((part, index) => (
618 <Box key={part.status}>
619 {index === 0 ? null : <Text tone="muted"> · </Text>}
620 <Text color={applyStatusColor(part.status)}>
621 {part.count} {part.status}
622 </Text>
623 </Box>
624 ))
625 )}
626 </>
627 );
628 }
629
630 // ── Status helpers ────────────────────────────────────────────────────────
631
632 const resourceDisplayStatus = (row: ResourceRow, status: ApplyStatus): ApplyStatus | "no change" =>
633 row.action === "noop" && (status === "created" || status === "updated") ? "no change" : status;
634
635 const taskLabel = (action: ActionVerb, status: ApplyStatus): string =>
636 action === "delete"
637 ? status === "deleted" || status === "orphaned"
638 ? status
639 : "drop"
640 : status === "ran"
641 ? action === "noop"
642 ? "skip"
643 : "ran"
644 : status === "running"
645 ? "running"
646 : status === "fail"
647 ? "fail"
648 : action === "noop"
649 ? "skip"
650 : "run";
651
652 /** Static glyph for a task row; the running state renders a spinner instead. */
653 function taskIcon(
654 action: ActionVerb,
655 status: ApplyStatus,
656 glyphs: ReturnType<typeof useGlyphs>,
657 ): string {
658 if (status === "fail") return glyphs.error;
659 if (status === "skipped") return glyphs.bullet;
660 if (status === "ran") return action === "noop" ? glyphs.bullet : glyphs.success;
661 if (status === "deleted" || status === "orphaned") return glyphs.success;
662 if (action === "delete") return glyphs[actionStyle.delete.icon];
663 if (action === "noop") return glyphs[actionStyle.noop.icon];
664 return glyphs[actionStyle.run.icon];
665 }
666
667 function YamlLine({ line, paddingLeft }: { readonly line: string; readonly paddingLeft: number }) {
668 const change = matchYamlChange(line);
669 const content = change?.content ?? line;
670 const key = matchYamlKey(content);
671 const removed = change?.marker === "-";
672 const added = change?.marker === "+";
673 return (
674 <DetailLine
675 paddingLeft={paddingLeft}
676 backgroundColor={
677 removed
678 ? theme.color.diffRemoveBackground
679 : added
680 ? theme.color.diffAddBackground
681 : undefined
682 }
683 >
684 <Box width={2} flexShrink={0}>
685 <Text color={removed ? theme.color.danger : theme.color.success}>
686 {change?.marker ?? " "}
687 </Text>
688 </Box>
689 <Box flexGrow={1}>
690 <Text wrap="truncate-end">
691 {key === undefined ? (
692 content
693 ) : (
694 <>
695 {key.indent}
696 <Text color={change === undefined ? theme.color.info : undefined}>{key.key}</Text>
697 {key.value}
698 </>
699 )}
700 </Text>
701 </Box>
702 </DetailLine>
703 );
704 }
705
706 function DetailLine({
707 paddingLeft,
708 backgroundColor,
709 children,
710 }: {
711 readonly paddingLeft: number;
712 readonly backgroundColor?: string;
713 readonly children: ReactNode;
714 }) {
715 const borderStyle = useBorderStyle();
716 return (
717 <Box paddingLeft={paddingLeft} width="100%">
718 <Box
719 width="100%"
720 paddingLeft={1}
721 borderStyle={borderStyle}
722 borderLeft
723 borderTop={false}
724 borderRight={false}
725 borderBottom={false}
726 borderColor={theme.color.muted}
727 borderDimColor
728 backgroundColor={backgroundColor}
729 >
730 {children}
731 </Box>
732 </Box>
733 );
734 }
735
736 // ── Static convenience ────────────────────────────────────────────────────