/** @jsxRuntime automatic */
/** @jsxImportSource @alchemy.run/sigil */
/**
* THE plan renderer. Every surface that shows a plan tree — `alchemy plan`
* output, the approval prompt, and the live apply/dev/destroy progress —
* renders through this one state-driven component, so a plan always looks
* the same wherever it appears.
*
* - One {@link PlanTree} holds the flattened tree (namespaces,
* resources, bindings, actions) plus per-row runtime state (apply status
* and the row's latest log message), updated from engine
* {@link ApplyEvent}s.
* - Two presentation `mode`s: `review` renders action glyphs (`+ ~ - ±`),
* `apply` renders live statuses with spinners and per-row messages.
* - `virtual` viewports follow the active row and support keyboard scrolling;
* `full` viewports produce static terminal scrollback. This choice is
* independent of whether the tree will receive more events.
* - Property diffs (`detailed`) render in every mode, and the window is
* line-budget aware so multi-line rows never overflow the terminal.
*/
import { useMemo, useSyncExternalStore } from "@alchemy.run/sigil/react";
import type { JSX, ReactNode } from "react";
import type { ApplyStatus } from "../../../Events.ts";
import type { Plan as AlchemyPlan } from "../../../Plan.ts";
import { theme } from "../../../Util/Theme.ts";
import { formatElapsed } from "../../Format.ts";
import { formatModeNote } from "../../ModeTag.ts";
import type { ActionVerb, PlanSummaryCounts } from "../../NamespaceTree.ts";
import { matchYamlChange, matchYamlKey } from "../../PropertyDiff.ts";
import {
Box,
KeyBar,
Row,
SectionHeading,
SpinnerGlyph,
TaskRow,
Text,
useBorderStyle,
useGlyphs,
useKeyGlyphs,
} from "../ui/index.ts";
import { NamespaceRow, namespaceStyle } from "./PlanRow.tsx";
import {
PlanTree,
initialResourceState,
type PlanRow,
type PlanTreeState,
type ResourceRow,
type RowState,
} from "./PlanTree.ts";
import { StackOutputs } from "./StackOutputs.tsx";
import { actionStyle, applyStatusColor, isInProgress, isTerminalStatus } from "./statusStyle.ts";
import { usePlanPresentation } from "./usePlanPresentation.ts";
import { usePlanViewport } from "./usePlanViewport.ts";
export { PlanTree } from "./PlanTree.ts";
export type {
PlanOutcome,
PlanProgress,
PlanRow,
PlanTreeOptions,
PlanTreeState,
PlanView,
PlanViewport,
RowState,
} from "./PlanTree.ts";
export type { PlanSummaryCounts } from "../../NamespaceTree.ts";
/**
* Row detail: the latest log/annotation line, painted danger when the row
* failed so the error reads at the row instead of only in the final dump.
*/
const rowDetail = (status: ApplyStatus, message: string | undefined) =>
message !== undefined && status === "fail" ? (
{message}
) : (
message
);
// ── Component ─────────────────────────────────────────────────────────────
export interface PlanProps {
/** Reactive tree containing rows, statuses, label, and presentation state. */
tree: PlanTree;
/** Allow the tree to collapse behind `p`. */
collapsible?: boolean;
/** Widget rendered before the summary block. */
before?: ReactNode;
/** Widget rendered on the summary row before the summary. */
summaryBefore?: ReactNode;
/** Widget rendered on the summary row after the summary. */
summaryAfter?: ReactNode;
/** Widget rendered below the virtualized rows. */
footer?: ReactNode;
/** Widget rendered after the complete Plan. */
after?: ReactNode;
}
const usePlanTree = (tree: PlanTree): PlanTreeState => {
const subscribe = useMemo(() => tree.subscribe.bind(tree), [tree]);
const snapshot = useMemo(() => tree.snapshot.bind(tree), [tree]);
return useSyncExternalStore(subscribe, snapshot);
};
export function Plan(props: PlanProps): JSX.Element {
const { tree, collapsible = false, before, summaryBefore, summaryAfter, footer, after } = props;
const { mode } = tree;
const keyGlyphs = useKeyGlyphs();
const borderStyle = useBorderStyle();
const state = usePlanTree(tree);
const { tasks, label, viewport, busy, elapsedMs } = state;
const {
progress: { completed, total: workRows },
collapsed,
showControls,
lineBudget,
refs: { beforeRef, summaryRef, controlsRef, afterRef },
} = usePlanPresentation({
tree,
state,
busy,
collapsible,
hasFooter: footer !== undefined,
});
const {
selectedView,
hasOutput,
virtual: virtualizing,
budget: budgetRows,
offset: shownOffset,
hiddenBelow,
planLines: visibleLines,
} = usePlanViewport({
tree,
state,
lineBudget,
collapsible,
collapsed,
});
// ── Summary and operation bar ─────────────────────────────────────────
const operationProgress =
mode === "apply" ? (
<>
{busy ? (
<>
>
) : null}
{label}
{workRows === 0 ? "" : ` (${completed}/${workRows})`}
{elapsedMs === undefined ? null : ({formatElapsed(elapsedMs)})}
>
) : null;
const planSummary =
selectedView === "output" ? (
Output
) : mode === "apply" ? (
) : (
);
const planKeys: ReadonlyArray = [
...(!collapsed && viewport === "virtual"
? [[keyGlyphs.upDown, `scroll ${selectedView}`] as const]
: []),
...(!collapsed && hasOutput
? [[keyGlyphs.leftRight, selectedView === "plan" ? "show output" : "show plan"] as const]
: []),
["p", collapsed ? "show plan/output" : "hide widget"],
["Ctrl+C", "exit"],
];
return (
{before}
{collapsed ? null : (
{summaryBefore}
{planSummary}
{summaryAfter}
)}
{collapsed ? null : (
)}
{showControls ? (
{collapsible ? (
) : mode === "apply" ? (
<>
{operationProgress}
{footer}
>
) : (
footer
)}
) : null}
{after}
);
}
function PlanContent(props: {
readonly tree: PlanTree;
readonly state: PlanTreeState;
readonly selectedView: "plan" | "output";
readonly virtual: boolean;
readonly budget: number;
readonly offset: number;
readonly hiddenBelow: number;
readonly lines: ReturnType["planLines"];
}) {
const { tree, state, selectedView, virtual, budget, offset, hiddenBelow } = props;
const glyphs = useGlyphs();
const overflowUnit = virtual ? "lines" : "rows";
return (
{offset > 0 ? (
{glyphs.overflowUp} {offset} earlier {overflowUnit}
) : null}
{selectedView === "output" ? (
) : props.lines === undefined ? (
tree.rows.map((row) => (
))
) : (
props.lines.map((line) =>
line.kind === "row" ? (
) : line.kind === "yaml" ? (
) : (
no declared property changes
),
)
)}
{hiddenBelow > 0 ? (
{glyphs.overflowDown} {hiddenBelow} more {overflowUnit}
) : null}
);
}
// ── Rows ──────────────────────────────────────────────────────────────────
function PlanRowView(props: {
row: PlanRow;
mode: "review" | "apply";
detailed: boolean;
state: RowState | undefined;
defaultMode: AlchemyPlan["defaultMode"];
includeYaml?: boolean;
}): JSX.Element {
const { row, mode, detailed, state, defaultMode, includeYaml = true } = props;
const glyphs = useGlyphs();
if (row.type === "namespace") {
return ;
}
if (row.type === "binding") {
if (mode === "review") {
const style =
row.action === "delete"
? { color: theme.color.muted, icon: "delete" as const }
: namespaceStyle(row.action);
return (
{glyphs[style.icon]}
{row.id}
{row.action === "delete" ? (unbind) : null}
);
}
// `state` is the HOST resource's row state: a binding is reconciled by
// the resource that carries it, so it settles exactly when the host does.
const hostStatus: ApplyStatus = state?.status ?? "pending";
const status: ApplyStatus | "no change" = row.action === "noop" ? "no change" : hostStatus;
const color = row.action === "delete" ? theme.color.muted : applyStatusColor(status);
const bindingStatus =
row.action !== "delete"
? status
: hostStatus === "fail"
? "fail"
: isTerminalStatus(hostStatus)
? "unbound"
: isInProgress(hostStatus)
? "unbinding"
: "unbind";
return (
{row.id}
}
depth={row.depth}
>
{bindingStatus}
);
}
if (row.type === "task") {
if (mode === "review") {
const style = namespaceStyle(row.action);
return (
[action]
);
}
const status: ApplyStatus = state?.status ?? (row.action === "noop" ? "ran" : "pending");
const color = applyStatusColor(status);
return (
{taskLabel(row.action, status)}
[action]
{state?.elapsedMs === undefined ? null : (
({formatElapsed(state.elapsedMs)})
)}
);
}
// Resource row.
const modeNote = formatModeNote({
mode: row.providerMode,
priorMode: row.fromProviderMode,
defaultMode,
});
const showYaml = includeYaml && (detailed || row.propertyYaml?.kind === "drift");
const yaml = showYaml ? (
row.propertyYaml === undefined ? (
row.action === "update" || row.action === "adopted" || row.action === "replace" ? (
no declared property changes
) : null
) : (
row.propertyYaml.lines.map((line, index) => (
))
)
) : null;
if (mode === "review") {
const style = namespaceStyle(row.action);
return (
{row.id}}
depth={row.depth}
detail={row.detail}
>
{modeNote && ({modeNote})}
{row.id !== row.resourceType ? ({row.resourceType}) : null}
{yaml}
);
}
const rowState = state ?? initialResourceState(row);
const displayStatus = resourceDisplayStatus(row, rowState.status);
const color = applyStatusColor(displayStatus);
return (
{row.action === "orphaned" ? {row.id} : row.id}
{row.id !== row.resourceType ? ({row.resourceType}) : null}
{row.detail ? · {row.detail} : null}
>
}
detail={rowDetail(rowState.status, rowState.message)}
detailOverflow={rowState.status === "fail" ? "wrap" : "truncate"}
depth={row.depth}
>
{modeNote ? ({modeNote}) : null}
{displayStatus}
{rowState.elapsedMs === undefined ? null : (
({formatElapsed(rowState.elapsedMs)})
)}
{yaml}
);
}
// ── Headers ───────────────────────────────────────────────────────────────
function ReviewSummary(props: { label: string; summary: PlanSummaryCounts }): JSX.Element {
const { counts, taskCounts, bindingChanges } = props.summary;
const parts = [
...(["create", "update", "adopted", "delete", "orphaned", "replace"] as const)
.filter((action) => counts[action] > 0)
.map((action) => ({
key: action,
label: `${counts[action]} to ${action}`,
color: namespaceStyle(action).color,
})),
...(counts.noop > 0
? [
{
key: "noop",
label: `${counts.noop} no change`,
color: theme.color.muted,
},
]
: []),
...(taskCounts.run > 0
? [
{
key: "run",
label: `${taskCounts.run} to run`,
color: namespaceStyle("run").color,
},
]
: []),
...(taskCounts.delete > 0
? [
{
key: "drop",
label: `${taskCounts.delete} to drop`,
color: namespaceStyle("delete").color,
},
]
: []),
...(taskCounts.noop > 0
? [
{
key: "task-noop",
label: `${taskCounts.noop} tasks no change`,
color: theme.color.muted,
},
]
: []),
...(bindingChanges > 0
? [
{
key: "bindings",
label: `${bindingChanges} binding changes`,
color: theme.color.info,
},
]
: []),
];
return (
<>
{props.label}
·
{parts.length === 0 ? (
no changes
) : (
parts.map((part, index) => (
{index === 0 ? null : · }
{part.label}
))
)}
>
);
}
const applySummaryOrder: readonly (ApplyStatus | "no change")[] = [
"fail",
"attaching",
"post-attach",
"pre-creating",
"creating",
"creating replacement",
"updating",
"adopting",
"deleting",
"orphaning",
"replacing",
"running",
"pending",
"created",
"updated",
"adopted",
"deleted",
"orphaned",
"replaced",
"ran",
"skipped",
"no change",
];
function ApplySummary(props: {
label: string;
rows: readonly PlanRow[];
tasks: ReadonlyMap;
}): JSX.Element {
const counts = new Map();
for (const row of props.rows) {
const status = props.tasks.get(row.key)?.status ?? "pending";
const displayStatus = row.action === "noop" ? "no change" : status;
counts.set(displayStatus, (counts.get(displayStatus) ?? 0) + 1);
}
const parts = applySummaryOrder
.filter((status) => counts.has(status))
.map((status) => ({
status,
count: counts.get(status) ?? 0,
}));
return (
<>
{props.label}
·
{parts.length === 0 ? (
no resources
) : (
parts.map((part, index) => (
{index === 0 ? null : · }
{part.count} {part.status}
))
)}
>
);
}
// ── Status helpers ────────────────────────────────────────────────────────
const resourceDisplayStatus = (row: ResourceRow, status: ApplyStatus): ApplyStatus | "no change" =>
row.action === "noop" && (status === "created" || status === "updated") ? "no change" : status;
const taskLabel = (action: ActionVerb, status: ApplyStatus): string =>
action === "delete"
? status === "deleted" || status === "orphaned"
? status
: "drop"
: status === "ran"
? action === "noop"
? "skip"
: "ran"
: status === "running"
? "running"
: status === "fail"
? "fail"
: action === "noop"
? "skip"
: "run";
/** Static glyph for a task row; the running state renders a spinner instead. */
function taskIcon(
action: ActionVerb,
status: ApplyStatus,
glyphs: ReturnType,
): string {
if (status === "fail") return glyphs.error;
if (status === "skipped") return glyphs.bullet;
if (status === "ran") return action === "noop" ? glyphs.bullet : glyphs.success;
if (status === "deleted" || status === "orphaned") return glyphs.success;
if (action === "delete") return glyphs[actionStyle.delete.icon];
if (action === "noop") return glyphs[actionStyle.noop.icon];
return glyphs[actionStyle.run.icon];
}
function YamlLine({ line, paddingLeft }: { readonly line: string; readonly paddingLeft: number }) {
const change = matchYamlChange(line);
const content = change?.content ?? line;
const key = matchYamlKey(content);
const removed = change?.marker === "-";
const added = change?.marker === "+";
return (
{change?.marker ?? " "}
{key === undefined ? (
content
) : (
<>
{key.indent}
{key.key}
{key.value}
>
)}
);
}
function DetailLine({
paddingLeft,
backgroundColor,
children,
}: {
readonly paddingLeft: number;
readonly backgroundColor?: string;
readonly children: ReactNode;
}) {
const borderStyle = useBorderStyle();
return (
{children}
);
}
// ── Static convenience ────────────────────────────────────────────────────