@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
tsx 178 lines 6.43 KB
Raw
1 /** @jsxRuntime automatic */
2 /** @jsxImportSource @alchemy.run/sigil */
3 import * as Clock from "effect/Clock";
4 import * as Effect from "effect/Effect";
5 import * as Exit from "effect/Exit";
6 import * as Layer from "effect/Layer";
7 import * as Scope from "effect/Scope";
8 import type { ApplyEvent } from "../../../Events.ts";
9 import { Interaction } from "../../../Interaction.ts";
10 import type { Plan } from "../../../Plan.ts";
11 import { type PlanStatusSession, Cli } from "../../../Report.ts";
12 import { formatElapsed } from "../../Format.ts";
13 import { approvePlanScreen } from "./ApprovePlan.tsx";
14 import { Plan as PlanComponent, PlanTree } from "./PlanView.tsx";
15
16 /**
17 * UI choices that outlive a single apply session. `alchemy dev` opens a new
18 * session (and a new plan widget) on every hot reload; without this the
19 * widget would reappear after the user hid it with `p`.
20 */
21 interface SessionPreferences {
22 planExpanded: boolean;
23 }
24
25 export const sigilCli = () =>
26 Layer.effect(
27 Cli,
28 Effect.map(Interaction, (cli) => {
29 const preferences: SessionPreferences = { planExpanded: true };
30 return Cli.of({
31 startPlanningSession: (label, detail, title) =>
32 startPlanningSession(cli, label, detail, title),
33 approvePlan: (plan, options) => approvePlan(cli, plan, options),
34 displayPlan: (plan, options) => displayPlan(cli, plan, options),
35 startApplySession: (plan, options) => startApplySession(cli, plan, options, preferences),
36 });
37 }),
38 );
39
40 const approvePlan = Effect.fn(function* <P extends Plan>(
41 cli: Interaction["Service"],
42 plan: P,
43 options?: import("../../../Report.ts").PlanDisplayOptions,
44 ) {
45 // A dismissed screen means "declined"; NonInteractiveTerminal propagates
46 // typed to the command-level handlers (a friendly line, not a raw cause).
47 return yield* cli.prompt
48 .screen(approvePlanScreen(plan, options?.detailed))
49 .pipe(Effect.catchTag("TerminalCancelled", () => Effect.succeed(false)));
50 });
51
52 const displayPlan = Effect.fn(function* <P extends Plan>(
53 cli: Interaction["Service"],
54 plan: P,
55 options?: import("../../../Report.ts").PlanDisplayOptions,
56 ) {
57 const tree = new PlanTree(plan, {
58 detailed: options?.detailed,
59 mode: "review",
60 label: "Plan",
61 viewport: "full",
62 });
63 yield* cli.output.print(<PlanComponent tree={tree} />);
64 });
65
66 const startPlanningSession = Effect.fn(function* (
67 cli: Interaction["Service"],
68 label: string,
69 detail?: string,
70 title?: string,
71 ) {
72 const startedAt = yield* Clock.currentTimeMillis;
73 const scope = yield* Scope.make();
74 const progress = yield* cli
75 .progress({
76 label,
77 detail,
78 title: title === undefined ? undefined : `${label} · ${title}`,
79 spinning: false,
80 })
81 .pipe(Scope.provide(scope));
82 let closed = false;
83 const finish = (effect: Effect.Effect<void>) =>
84 Effect.suspend(() => {
85 if (closed) return Effect.void;
86 closed = true;
87 return effect.pipe(Effect.ensuring(Scope.close(scope, Exit.void)));
88 });
89 // Settle messages carry the total planning duration, mirroring the plain
90 // renderer's "(1.8s)" suffix.
91 const settled = (message: string | undefined) =>
92 message === undefined
93 ? Effect.undefined
94 : Clock.currentTimeMillis.pipe(
95 Effect.map((now) => `${message} (${formatElapsed(now - startedAt)})`),
96 );
97 return {
98 update: (nextLabel: string, nextDetail?: string, options?: { readonly spinning?: boolean }) =>
99 progress.update({
100 label: nextLabel,
101 detail: nextDetail,
102 title: title === undefined ? undefined : `${nextLabel} · ${title}`,
103 spinning: options?.spinning ?? true,
104 }),
105 succeed: (message?: string) => finish(Effect.flatMap(settled(message), progress.succeed)),
106 fail: (message?: string) => finish(Effect.flatMap(settled(message), progress.fail)),
107 close: finish(progress.close),
108 };
109 });
110
111 const startApplySession = Effect.fn(function* <P extends Plan>(
112 cli: Interaction["Service"],
113 plan: P,
114 options: import("../../../Report.ts").PlanDisplayOptions | undefined,
115 preferences: SessionPreferences,
116 ) {
117 // Detailed applies render their YAML diffs inline in the progress tree.
118 // One-shot operations persist the final render; dev keeps its live block
119 // mounted so logs remain static above the collapsible plan and keybar.
120 const labels = plan.destroy
121 ? {
122 active: "Destroying stack",
123 success: "Stack destroyed",
124 failure: "Destroy failed",
125 }
126 : plan.defaultMode === "local"
127 ? {
128 active: "Starting dev stack",
129 success: "Dev stack ready",
130 failure: "Dev startup failed",
131 }
132 : {
133 active: "Deploying stack",
134 success: "Stack deployed",
135 failure: "Deploy failed",
136 };
137 const progress = new PlanTree(plan, {
138 detailed: options?.detailed,
139 mode: "apply",
140 label: labels.active,
141 titleDetail: options?.stage,
142 busy: true,
143 expanded: preferences.planExpanded,
144 });
145 // Remember the collapse toggle as it happens, so the next hot-reload
146 // generation opens the way the user left this one.
147 progress.subscribe(() => {
148 preferences.planExpanded = progress.snapshot().expanded;
149 });
150 // The session outlives this effect — the caller settles it via `done` on
151 // every exit path (Apply.ts's onExit). live.open is Scope-bound, so give
152 // it a manually managed scope. One-shot operations close it in `done`;
153 // dev retains it after `done` and tears it down through `close` when the
154 // generation is interrupted (a reload or Ctrl+C), so a replaced
155 // generation never leaves its widget behind.
156 const scope = yield* Scope.make();
157 const live = yield* cli
158 .live(<PlanComponent tree={progress} collapsible={options?.dev} />, {
159 persistOnClose: !options?.dev,
160 })
161 .pipe(Scope.provide(scope));
162 const close = live.close.pipe(Effect.ensuring(Scope.close(scope, Exit.void)));
163 return {
164 done: (outcome) =>
165 Effect.sync(() => {
166 const outputReady = progress.snapshot().output !== undefined;
167 progress.finish(
168 outcome,
169 labels[outcome],
170 options?.dev && outcome === "success" && outputReady ? "output" : "plan",
171 );
172 if (!options?.dev) progress.setViewport("full");
173 }).pipe(Effect.andThen(options?.dev ? Effect.void : close)),
174 close,
175 emit: (event: ApplyEvent) => Effect.sync(() => progress.emit(event)),
176 setOutput: (value: unknown) => Effect.sync(() => progress.setOutput(value)),
177 } satisfies PlanStatusSession;
178 });