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

main
ts 339 lines 9.63 KB
Raw
1 import type { ApplyEvent, ApplyStatus, ResourceStatusChanged } from "../../../Events.ts";
2 import type { ActionApply, ActionDelete, CRUD, Plan } from "../../../Plan.ts";
3 import type { ProviderMode } from "../../../ProviderMode.ts";
4 import {
5 buildNamespaceTree,
6 buildPlanSummary,
7 flattenTree,
8 type ActionVerb,
9 type FlattenedItem,
10 type PlanSummaryCounts,
11 } from "../../NamespaceTree.ts";
12 import type { DeclaredPropertyYaml } from "../../PropertyDiff.ts";
13 import { isInProgress, isTerminalStatus } from "./statusStyle.ts";
14
15 export type PlanRow =
16 | {
17 key: string;
18 type: "namespace";
19 id: string;
20 depth: number;
21 action: FlattenedItem["action"];
22 }
23 | {
24 key: string;
25 type: "resource";
26 id: string;
27 resourceType: string;
28 /** Secondary identity for inventories without logical resource names. */
29 detail?: string;
30 depth: number;
31 action: CRUD["action"];
32 persistedApplyStatus?: "created" | "updated";
33 providerMode?: ProviderMode;
34 fromProviderMode?: ProviderMode;
35 propertyYaml?: DeclaredPropertyYaml;
36 }
37 | {
38 key: string;
39 type: "binding";
40 id: string;
41 depth: number;
42 action: "create" | "update" | "delete" | "noop";
43 /**
44 * Row key of the resource that carries this binding. Bindings have no
45 * lifecycle of their own — the host provider reconciles them — so the
46 * row mirrors the host's apply status instead of tracking its own.
47 */
48 hostKey: string;
49 }
50 | {
51 key: string;
52 type: "task";
53 id: string;
54 depth: number;
55 action: ActionVerb;
56 };
57
58 export type ResourceRow = Extract<PlanRow, { type: "resource" }>;
59
60 /**
61 * Only resources and actions receive apply events and settle. Namespaces are
62 * grouping only, and bindings are reconciled by their host resource, so
63 * counting them would leave the progress total unreachable.
64 */
65 const isProgressRow = (row: PlanRow) => row.type === "resource" || row.type === "task";
66
67 export interface RowState extends Required<Pick<ResourceStatusChanged, "id" | "status">> {
68 key: string;
69 message?: string;
70 startedAt?: number;
71 elapsedMs?: number;
72 }
73
74 export type PlanViewport = "full" | "virtual";
75 export type PlanView = "plan" | "output";
76 export type PlanOutcome = "success" | "failure";
77
78 export interface PlanProgress {
79 readonly completed: number;
80 readonly failures: number;
81 readonly total: number;
82 }
83
84 export interface PlanTreeState {
85 readonly tasks: Map<string, RowState>;
86 readonly label: string;
87 readonly expanded: boolean;
88 readonly viewport: PlanViewport;
89 readonly busy: boolean;
90 readonly outcome: PlanOutcome | undefined;
91 readonly output: unknown;
92 readonly view: PlanView;
93 }
94
95 export interface PlanTreeOptions {
96 readonly detailed?: boolean;
97 readonly mode?: "review" | "apply";
98 readonly label?: string;
99 readonly titleDetail?: string;
100 readonly viewport?: PlanViewport;
101 readonly busy?: boolean;
102 /**
103 * Initial collapse state of a collapsible tree. Dev passes the user's
104 * last choice so a hot reload doesn't bring back a widget they hid.
105 * @default true
106 */
107 readonly expanded?: boolean;
108 }
109
110 /** Display-only plans, such as cloud inventories, need no engine state or providers. */
111 export interface PlanTreeData {
112 readonly rows: readonly PlanRow[];
113 readonly summary: PlanSummaryCounts;
114 readonly defaultMode?: ProviderMode;
115 }
116
117 const getRowKey = (item: FlattenedItem) => item.path.join("/");
118
119 const findCrudByLogicalId = (plan: Plan, id: string): CRUD | undefined =>
120 [...Object.values(plan.resources), ...Object.values(plan.deletions)].find(
121 (item): item is CRUD => item?.resource.LogicalId === id,
122 );
123
124 const buildRows = (plan: Plan, detailed: boolean): PlanRow[] => {
125 const resources = [
126 ...Object.values(plan.resources),
127 ...Object.values(plan.deletions).filter(
128 (item): item is NonNullable<Plan["deletions"][string]> => item !== undefined,
129 ),
130 ] as CRUD[];
131 const actions = [
132 ...Object.values(plan.actions ?? {}),
133 ...Object.values(plan.actionDeletions ?? {}),
134 ].filter((task): task is ActionApply | ActionDelete => task !== undefined);
135
136 return flattenTree(buildNamespaceTree(resources, actions), {
137 includePropertyYaml: detailed,
138 }).map((item) => {
139 if (item.type === "namespace") {
140 return {
141 key: getRowKey(item),
142 type: "namespace" as const,
143 id: item.id,
144 depth: item.depth,
145 action: item.action,
146 };
147 }
148 if (item.type === "binding") {
149 return {
150 key: getRowKey(item),
151 type: "binding" as const,
152 id: item.bindingSid ?? item.id,
153 depth: item.depth,
154 action: item.action as "create" | "update" | "delete" | "noop",
155 hostKey: item.path.slice(0, -1).join("/"),
156 };
157 }
158 if (item.type === "action") {
159 return {
160 key: getRowKey(item),
161 type: "task" as const,
162 id: item.id,
163 depth: item.depth,
164 action: item.action as ActionVerb,
165 };
166 }
167 return {
168 key: getRowKey(item),
169 type: "resource" as const,
170 id: item.id,
171 resourceType: item.resourceType ?? "Unknown",
172 depth: item.depth,
173 action: item.action as CRUD["action"],
174 providerMode: item.providerMode,
175 fromProviderMode: item.fromProviderMode,
176 propertyYaml: item.propertyYaml,
177 persistedApplyStatus:
178 item.action === "noop"
179 ? (() => {
180 const crud = findCrudByLogicalId(plan, item.id);
181 return crud?.action === "noop" ? crud.state.status : undefined;
182 })()
183 : undefined,
184 };
185 });
186 };
187
188 export const initialResourceState = (row: ResourceRow): RowState => ({
189 key: row.key,
190 id: row.id,
191 status: row.action === "noop" ? (row.persistedApplyStatus ?? "created") : "pending",
192 });
193
194 const buildInitialTasks = (rows: readonly PlanRow[]) =>
195 new Map(
196 rows.flatMap((row): Array<[string, RowState]> => {
197 if (row.type === "resource") return [[row.key, initialResourceState(row)]];
198 if (row.type === "task") {
199 return [
200 [
201 row.key,
202 {
203 key: row.key,
204 id: row.id,
205 status: row.action === "noop" ? "skipped" : "pending",
206 },
207 ],
208 ];
209 }
210 return [];
211 }),
212 );
213
214 export class PlanTree {
215 readonly rows: readonly PlanRow[];
216 readonly progressRows: readonly PlanRow[];
217 readonly summary: PlanSummaryCounts;
218 readonly mode: "review" | "apply";
219 readonly detailed: boolean;
220 readonly titleDetail?: string;
221 readonly defaultMode?: ProviderMode;
222 private state: PlanTreeState;
223 private readonly listeners = new Set<() => void>();
224
225 constructor(plan: Plan | PlanTreeData, options: PlanTreeOptions = {}) {
226 this.detailed = options.detailed ?? false;
227 this.mode = options.mode ?? "review";
228 this.titleDetail = options.titleDetail;
229 this.defaultMode = plan.defaultMode;
230 this.rows = "rows" in plan ? plan.rows : buildRows(plan, this.detailed);
231 this.progressRows = this.rows.filter(isProgressRow);
232 this.summary = "rows" in plan ? plan.summary : buildPlanSummary(plan);
233 this.state = {
234 tasks: buildInitialTasks(this.rows),
235 label: options.label ?? "Plan",
236 expanded: options.expanded ?? true,
237 viewport: options.viewport ?? "virtual",
238 busy: options.busy ?? false,
239 outcome: undefined,
240 output: undefined,
241 view: "plan",
242 };
243 }
244
245 subscribe(listener: () => void) {
246 this.listeners.add(listener);
247 return () => this.listeners.delete(listener);
248 }
249
250 snapshot() {
251 return this.state;
252 }
253
254 progress(): PlanProgress {
255 let completed = 0;
256 let failures = 0;
257 let total = 0;
258 for (const row of this.progressRows) {
259 const status = this.state.tasks.get(row.key)?.status;
260 if (row.action !== "noop") {
261 total++;
262 if (status !== undefined && isTerminalStatus(status)) completed++;
263 }
264 if (status === "fail") failures++;
265 }
266 return { completed, failures, total };
267 }
268
269 setExpanded(expanded: boolean) {
270 this.update({ expanded });
271 }
272
273 setLabel(label: string) {
274 this.update({ label });
275 }
276
277 setViewport(viewport: PlanViewport) {
278 this.update({ viewport });
279 }
280
281 setBusy(busy: boolean) {
282 this.update({
283 busy,
284 outcome: busy ? undefined : this.state.outcome,
285 view: busy ? "plan" : this.state.view,
286 });
287 }
288
289 finish(outcome: PlanOutcome, label: string, view: PlanView = this.state.view) {
290 this.update({ busy: false, outcome, label, view });
291 }
292
293 setOutput(output: unknown) {
294 this.update({ output });
295 }
296
297 setView(view: PlanView) {
298 this.update({ view });
299 }
300
301 emit(event: ApplyEvent) {
302 const tasks = new Map(this.state.tasks);
303 const key = event.fqn;
304 const now = Date.now();
305 const timing = (current: RowState | undefined, status: ApplyStatus) => {
306 const startedAt = current?.startedAt ?? (isInProgress(status) ? now : undefined);
307 return {
308 startedAt,
309 elapsedMs:
310 isTerminalStatus(status) && startedAt !== undefined
311 ? now - startedAt
312 : current?.elapsedMs,
313 };
314 };
315
316 if (event.type === "apply.resource.status") {
317 const current = tasks.get(key);
318 if (current) {
319 tasks.set(key, {
320 key,
321 id: event.id,
322 status: event.status,
323 message: event.message ?? current.message,
324 ...timing(current, event.status),
325 });
326 }
327 } else {
328 const current = tasks.get(key);
329 if (current) tasks.set(key, { ...current, message: event.message });
330 }
331
332 this.update({ tasks });
333 }
334
335 private update(patch: Partial<PlanTreeState>) {
336 this.state = { ...this.state, ...patch };
337 for (const listener of this.listeners) listener();
338 }
339 }