@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 768 lines 28.9 KB
Raw
1 /** @jsxRuntime automatic */
2 /** @jsxImportSource @alchemy.run/sigil */
3 import { AnsiText, Box, render, Static, useTitle } from "@alchemy.run/sigil";
4 import { useSyncExternalStore } from "@alchemy.run/sigil/react";
5 import * as Context from "effect/Context";
6 import * as Effect from "effect/Effect";
7 import type { ChildProcessSpawner } from "effect/process/ChildProcessSpawner";
8 import type * as Scope from "effect/Scope";
9 import * as Semaphore from "effect/Semaphore";
10 import type { ReactNode } from "react";
11 import {
12 type BrowserLoginOptions,
13 type Interaction,
14 type NonInteractiveTerminal,
15 openUrl,
16 type SessionOptions,
17 TerminalCancelled,
18 taskFromProgress,
19 } from "../../../Interaction.ts";
20 import type {
21 ProgressHandle,
22 ProgressOptions,
23 Screen,
24 TerminalCapabilities,
25 TerminalOptions,
26 LiveViewHandle,
27 LiveViewOptions,
28 View,
29 } from "../types.ts";
30 import { CliEnvironment } from "../ui/Environment.tsx";
31 import { Spinner, Status } from "../ui/Feedback.tsx";
32 import { useTerminalInput } from "../ui/Interactive.tsx";
33 import { LiveStore, useLiveStore } from "../ui/Live.tsx";
34 import { CancelledPrompt } from "../ui/Transcript.tsx";
35 import { formatView, normalizeView } from "./Format.tsx";
36 import {
37 confirmScreen,
38 browserLoginScreen,
39 multiSelectScreen,
40 passwordScreen,
41 selectScreen,
42 textScreen,
43 } from "./Prompts.tsx";
44
45 const InSession = Context.Reference<boolean>("Alchemy::Interaction/InSession", {
46 defaultValue: () => false,
47 });
48
49 /**
50 * One rendered block. Views are immutable once mounted — dynamic content
51 * flows through caller-owned stores (`LiveStore` + `useLiveStore`) that the
52 * view component subscribes to, never through the runtime.
53 */
54 interface Item {
55 readonly key: number;
56 readonly view: View;
57 readonly placement?: LiveViewOptions["placement"];
58 }
59
60 interface StoreState {
61 readonly staticItems: Item[];
62 readonly transcript: ReadonlyArray<Item>;
63 readonly live: ReadonlyArray<Item>;
64 readonly active?: Item;
65 }
66
67 /**
68 * The single external store the React root syncs from. It only tracks WHICH
69 * blocks are mounted and in what region (static scrollback, in-session
70 * transcript, live region, active prompt) — block content never changes
71 * after mount, so there is no update surface here.
72 */
73 class TerminalStore {
74 private state: StoreState = { staticItems: [], transcript: [], live: [] };
75 private readonly listeners = new Set<() => void>();
76 private nextKey = 0;
77
78 readonly subscribe = (listener: () => void) => {
79 this.listeners.add(listener);
80 return () => this.listeners.delete(listener);
81 };
82 readonly snapshot = () => this.state;
83
84 private commit(state: StoreState) {
85 this.state = state;
86 for (const listener of this.listeners) listener();
87 }
88
89 alloc() {
90 return this.nextKey++;
91 }
92
93 append(view: View) {
94 this.commit({
95 ...this.state,
96 transcript: [...this.state.transcript, { key: this.alloc(), view }],
97 });
98 }
99
100 appendStatic(view: View) {
101 this.commit({
102 ...this.state,
103 staticItems: [...this.state.staticItems, { key: this.alloc(), view }],
104 });
105 }
106
107 addLive(key: number, view: View, placement: LiveViewOptions["placement"] = "afterTranscript") {
108 this.commit({ ...this.state, live: [...this.state.live, { key, view, placement }] });
109 }
110
111 removeLive(key: number) {
112 this.commit({ ...this.state, live: this.state.live.filter((entry) => entry.key !== key) });
113 }
114
115 /**
116 * Move a live block into scrollback (its component renders one final time
117 * from its store's final state). No-op when the row was already cleared.
118 */
119 completeLive(key: number, destination: "staticItems" | "transcript") {
120 const item = this.state.live.find((entry) => entry.key === key);
121 if (item === undefined) return;
122 this.commit({
123 ...this.state,
124 [destination]: [...this.state[destination], { key: this.alloc(), view: item.view }],
125 live: this.state.live.filter((entry) => entry.key !== key),
126 });
127 }
128
129 activate(view: View) {
130 this.commit({ ...this.state, active: { key: this.alloc(), view } });
131 }
132
133 deactivate() {
134 if (this.state.active !== undefined) this.commit({ ...this.state, active: undefined });
135 }
136
137 clear() {
138 this.commit({ ...this.state, transcript: [], live: [] });
139 }
140
141 clearStatic() {
142 if (this.state.staticItems.length > 0) {
143 this.commit({ ...this.state, staticItems: [] });
144 }
145 }
146
147 clearTranscript() {
148 if (this.state.transcript.length > 0) {
149 this.commit({ ...this.state, transcript: [] });
150 }
151 }
152
153 get idle() {
154 return this.state.active === undefined && this.state.live.length === 0;
155 }
156 }
157
158 /**
159 * Always-on Ctrl+C handler wrapped around every screen by `run`. Screens no
160 * longer need their own Ctrl+C wiring (a screen that forgot it used to make
161 * the CLI unkillable, since Sigil runs with `exitOnCtrlC: false` in raw mode);
162 * they only handle Escape, whose semantics differ per screen.
163 */
164 type ScreenCancelGuardProps = { readonly onCancel: () => void; readonly children?: ReactNode };
165
166 function ScreenCancelGuard({ onCancel, children }: ScreenCancelGuardProps) {
167 useTerminalInput(
168 (input, key) => {
169 if (key.ctrl && input === "c") onCancel();
170 },
171 { active: true },
172 );
173 return <>{children}</>;
174 }
175
176 type ItemViewProps = { readonly item: Item };
177
178 function ItemView({ item }: ItemViewProps) {
179 return <Box flexDirection="column">{item.view}</Box>;
180 }
181
182 type TerminalRootProps = { readonly store: TerminalStore };
183
184 function TerminalRoot({ store }: TerminalRootProps) {
185 const state = useSyncExternalStore(store.subscribe, store.snapshot);
186 useTerminalInput(
187 (input, key) => {
188 if (!key.ctrl || input !== "c") return;
189 process.kill(process.pid, "SIGINT");
190 },
191 { active: state.active === undefined },
192 );
193 const beforeTranscript = state.live.filter((item) => item.placement === "beforeTranscript");
194 const afterTranscript = state.live.filter((item) => item.placement !== "beforeTranscript");
195 return (
196 <Box flexDirection="column">
197 <Static items={state.staticItems}>{(item) => <ItemView key={item.key} item={item} />}</Static>
198 {beforeTranscript.map((item) => (
199 <ItemView key={item.key} item={item} />
200 ))}
201 {state.transcript.map((item) => (
202 <ItemView key={item.key} item={item} />
203 ))}
204 {afterTranscript.map((item) => (
205 <ItemView key={item.key} item={item} />
206 ))}
207 {state.active === undefined ? null : (
208 <Box marginTop={state.transcript.length > 0 ? 1 : 0}>
209 <ItemView key={state.active.key} item={state.active} />
210 </Box>
211 )}
212 </Box>
213 );
214 }
215
216 /** Progress rows are ordinary live views over a runtime-owned store. */
217 interface ProgressState {
218 readonly options: ProgressOptions;
219 readonly final?: { readonly variant: "success" | "error"; readonly message?: string };
220 }
221
222 type ProgressViewProps = { readonly store: LiveStore<ProgressState> };
223
224 function ProgressView({ store }: ProgressViewProps) {
225 const state = useLiveStore(store);
226 useTitle(state.options.title);
227 return state.final !== undefined ? (
228 <Status variant={state.final.variant}>{state.final.message ?? state.options.label}</Status>
229 ) : state.options.spinning === false ? (
230 <Status variant="info" detail={state.options.detail}>
231 {state.options.label}
232 </Status>
233 ) : (
234 <Spinner label={state.options.label} detail={state.options.detail} />
235 );
236 }
237
238 export interface SigilRuntime {
239 readonly service: Interaction["Service"];
240 readonly dispose: () => Promise<void>;
241 }
242
243 export const makeRuntime = (
244 options: TerminalOptions,
245 capabilities: TerminalCapabilities,
246 ): SigilRuntime => {
247 const stdin = options.stdin ?? process.stdin;
248 const stdout = options.stdout ?? process.stdout;
249 const stderr = options.stderr ?? process.stderr;
250 const store = new TerminalStore();
251 const rendererGate = Semaphore.makeUnsafe(1);
252 const promptGate = Semaphore.makeUnsafe(1);
253
254 interface Mounted {
255 readonly sigil: ReturnType<typeof render>;
256 readonly alternate: boolean;
257 /** Settles when the instance exits; render crashes are routed out, never rethrown. */
258 exit: Promise<void>;
259 /**
260 * Flush any partial captured line into the Static transcript — called at
261 * unmount so trailing output without a newline still lands. Lives on the
262 * instance because it closes over this mount's capture buffers and must
263 * die with it.
264 */
265 readonly flushDirectStdio?: () => void;
266 }
267 // Lifecycle state. `mounted` and `unmounting` deliberately overlap: during
268 // teardown the instance stays in `mounted` until re-validation passes, so
269 // prints/live views racing the drain still see a live renderer (and can
270 // abort the teardown). `sessionMounted` is an orthogonal axis — an
271 // `session()` region pins the renderer regardless of store idleness — and
272 // `disposed` is a terminal one-way latch.
273 let mounted: Mounted | undefined;
274 let unmounting: Promise<void> | undefined;
275 let sessionMounted = false;
276 let disposed = false;
277 /**
278 * Fails the active interaction when a screen component throws during
279 * render. Without this the prompt's callback would never resume and the
280 * CLI would hang with a dead renderer.
281 */
282 let failActive: ((error: unknown) => void) | undefined;
283 /**
284 * The single failure channel for renderer errors: route into the active
285 * interaction when a prompt is waiting, otherwise surface on stderr. Every
286 * async failure path (the exit promise, fire-and-forget mounts) funnels
287 * here so no rejection ever escapes unhandled.
288 */
289 const failRenderer = (error: unknown) => {
290 if (failActive !== undefined) failActive(error);
291 else stderr.write(`Sigil renderer error: ${String(error)}\n`);
292 };
293
294 const mount = async (alternateScreen = false): Promise<void> => {
295 // Never overlap a new Sigil root with one that is still tearing down —
296 // Sigil keys instances by stdout and two live roots corrupt the output.
297 while (unmounting !== undefined) await unmounting;
298 if (disposed || mounted !== undefined) return;
299 const captureDirectStdio = options.captureConsole !== false;
300 // Process output lives in the renderer's Static zone above every inline
301 // view. Adding a static row commits it to scrollback and naturally moves
302 // the live UI down, avoiding log-update's erase/restore path and its
303 // render artifacts. `patchConsole: "stdio"` captures console, Node
304 // warnings, and direct stream writes from tools such as Floci (the
305 // renderer's own frames go through passthrough facades and bypass the
306 // capture); `onCapturedOutput` takes ownership of each raw chunk so the
307 // Static transcript renders it instead of the built-in splicing. The
308 // renderer restores console and stream writes itself on unmount.
309 const buffers = { stdout: "", stderr: "" };
310 // A captured write that ends mid-line parks its tail here waiting for
311 // the rest of the line. A real terminal would display the partial
312 // immediately — so when no continuation arrives promptly, flush the
313 // tail as its own row instead of holding it until unmount. Without the
314 // deadline, a writer whose final chunk lacks a trailing newline (e.g.
315 // a pretty-printed cause written raw to stderr) has its last line
316 // appear only when the process exits. One timer PER STREAM: a chatty
317 // stdout must not keep resetting the deadline of a parked stderr tail.
318 const partialFlushTimers: {
319 [Stream in keyof typeof buffers]?: ReturnType<typeof setTimeout>;
320 } = {};
321 const clearPartialFlush = (stream: keyof typeof buffers) => {
322 const timer = partialFlushTimers[stream];
323 if (timer !== undefined) {
324 clearTimeout(timer);
325 partialFlushTimers[stream] = undefined;
326 }
327 };
328 const flushPartialLine = (stream: keyof typeof buffers) => {
329 partialFlushTimers[stream] = undefined;
330 if (buffers[stream] !== "") {
331 store.appendStatic(<AnsiText wrap="none">{buffers[stream]}</AnsiText>);
332 buffers[stream] = "";
333 }
334 };
335 const appendLines = (stream: keyof typeof buffers, data: string) => {
336 const parts = `${buffers[stream]}${data}`.split(/\r?\n/);
337 buffers[stream] = parts.pop() ?? "";
338 for (const line of parts) {
339 store.appendStatic(<AnsiText wrap="none">{line || " "}</AnsiText>);
340 }
341 clearPartialFlush(stream);
342 if (buffers[stream] !== "") {
343 const timer = setTimeout(() => flushPartialLine(stream), 50);
344 timer.unref?.();
345 partialFlushTimers[stream] = timer;
346 }
347 };
348 const sigil = render(
349 <CliEnvironment capabilities={capabilities} observeWindow>
350 <TerminalRoot store={store} />
351 </CliEnvironment>,
352 {
353 stdin,
354 stdout,
355 stderr,
356 exitOnCtrlC: false,
357 interactive: capabilities.input,
358 alternateScreen: alternateScreen,
359 colorProfile: capabilities.colors ? "truecolor" : "none",
360 ...(captureDirectStdio
361 ? {
362 patchConsole: "stdio" as const,
363 onCapturedOutput: (stream: "stdout" | "stderr", data: string) => {
364 appendLines(stream, data);
365 return true;
366 },
367 }
368 : { patchConsole: false as const }),
369 },
370 );
371 const current: Mounted = {
372 sigil,
373 alternate: alternateScreen,
374 exit: Promise.resolve(),
375 flushDirectStdio: captureDirectStdio
376 ? () => {
377 // AnsiText, matching the line and deadline paths: a trailing
378 // fragment must not render color-stripped just because teardown
379 // won the race against the 50ms deadline.
380 for (const stream of ["stdout", "stderr"] as const) {
381 clearPartialFlush(stream);
382 if (buffers[stream] !== "") {
383 store.appendStatic(<AnsiText wrap="none">{buffers[stream]}</AnsiText>);
384 buffers[stream] = "";
385 }
386 }
387 }
388 : undefined,
389 };
390 // Capture the exit promise at mount time: Sigil registers its process
391 // `beforeExit` listener on the first `waitUntilExit()` call and `unmount`
392 // only removes a listener that already exists, so waiting only after
393 // unmount leaks one process listener per mount cycle. A rejection means a
394 // component threw during render — Sigil has already unmounted itself, so
395 // drop the dead instance and surface the error instead of hanging.
396 current.exit = sigil.waitUntilExit().then(
397 () => undefined,
398 (error: unknown) => {
399 // The crashed instance is dropped without the unmount path, so
400 // disarm any pending partial-flush timer here too.
401 current.flushDirectStdio?.();
402 if (mounted === current) mounted = undefined;
403 failRenderer(error);
404 },
405 );
406 mounted = current;
407 };
408
409 const ensureMounted = () => Effect.promise(() => mount());
410
411 const waitForRender = () =>
412 mounted?.sigil.waitUntilRenderFlush().catch(() => undefined) ?? Promise.resolve();
413
414 /**
415 * Tear down the renderer. Total (never rejects) and re-validated across its
416 * awaits: output printed or live views opened while the final frame flushes
417 * abort the teardown instead of being destroyed with it. `force` skips the
418 * re-validation for dispose and presentation switches.
419 */
420 const unmount = (force = false): Promise<void> => {
421 if (unmounting !== undefined) return unmounting;
422 const current = mounted;
423 if (current === undefined) return Promise.resolve();
424 unmounting = (async () => {
425 try {
426 current.flushDirectStdio?.();
427 // Drain: keep flushing until no new static output arrives between
428 // flushes, so a `print` racing the teardown reaches the terminal.
429 // Unbounded by design — the bound is the renderer's convergence: the
430 // loop exits as soon as producers go quiet for one full flush.
431 let staticCount;
432 do {
433 staticCount = store.snapshot().staticItems.length;
434 await current.sigil.waitUntilRenderFlush();
435 } while (store.snapshot().staticItems.length !== staticCount);
436 // Re-validate: a prompt or live view may have re-armed the renderer
437 // while the frame flushed. Their output would be destroyed by the
438 // teardown, so leave the instance mounted for them instead.
439 if (!force && (sessionMounted || !store.idle)) return;
440 // A captured chunk that arrived DURING the drain may have parked a
441 // partial line and armed a flush timer. Flush and disarm now —
442 // otherwise the timer fires after `clearStatic()` below and the
443 // stale fragment replays at the top of the next mount.
444 current.flushDirectStdio?.();
445 mounted = undefined;
446 // unmount restores the patched console and stream writes.
447 current.sigil.unmount();
448 await current.exit;
449 current.sigil.cleanup();
450 // Static output has been handed off to the terminal. Do not replay
451 // it when a later live session mounts a fresh Sigil root.
452 store.clearStatic();
453 } catch {
454 // Teardown must be total: a crashed instance still ends up unmounted
455 // with console/stream patches restored — and with no armed partial
456 // flush timer left to poke the store after clearStatic.
457 if (mounted === current) mounted = undefined;
458 try {
459 current.flushDirectStdio?.();
460 current.sigil.unmount();
461 } catch {
462 // Already unmounted (or unmount itself is what threw above).
463 }
464 }
465 })().finally(() => {
466 unmounting = undefined;
467 });
468 return unmounting;
469 };
470
471 const releaseIfIdle = () =>
472 Effect.suspend(() =>
473 sessionMounted || !store.idle ? Effect.void : Effect.promise(() => unmount()),
474 );
475
476 const print = (view: View) =>
477 Effect.gen(function* () {
478 const inSession = yield* InSession;
479 view = normalizeView(view);
480 if (inSession) {
481 yield* Effect.sync(() => store.append(view));
482 } else if (mounted !== undefined) {
483 yield* Effect.sync(() => store.appendStatic(view));
484 } else {
485 const output = formatView(view, {
486 ...capabilities,
487 // Re-read the width at render time — the boot-time snapshot goes
488 // stale the moment the user resizes the terminal.
489 columns: stdout.columns ?? capabilities.columns,
490 });
491 if (output !== "") yield* Effect.sync(() => stdout.write(`${output}\n`));
492 }
493 });
494
495 const messageOptions = (message: string | { message: string; detail?: string }) =>
496 typeof message === "string" ? { message } : message;
497
498 const log =
499 (variant: "info" | "success" | "warning" | "error") =>
500 (message: string | { message: string; detail?: string }) => {
501 const options = messageOptions(message);
502 return print(
503 <Status variant={variant} detail={options.detail}>
504 {options.message}
505 </Status>,
506 );
507 };
508
509 const run = <Value,>(screen: Screen<Value>) =>
510 Effect.gen(function* () {
511 const inSession = yield* InSession;
512 const interaction = promptGate.withPermits(1)(
513 Effect.gen(function* () {
514 let completedView: View | undefined;
515 return yield* Effect.callback<Value, TerminalCancelled>((resume) => {
516 let settled = false;
517 const finish = (result: Effect.Effect<Value, TerminalCancelled>, resultView?: View) => {
518 if (settled) return;
519 settled = true;
520 failActive = undefined;
521 store.deactivate();
522 if (resultView !== undefined) {
523 if (inSession) store.append(normalizeView(resultView));
524 else completedView = resultView;
525 }
526 resume(result);
527 };
528 const cancel = () =>
529 finish(
530 Effect.fail(new TerminalCancelled()),
531 <CancelledPrompt message={screen.name} />,
532 );
533 // A screen that throws during render unmounts Sigil with the error;
534 // without this hook the callback would never resume and the CLI
535 // would hang forever on a dead renderer.
536 failActive = (error) => finish(Effect.die(error));
537 store.activate(
538 <ScreenCancelGuard onCancel={cancel}>
539 {screen.render({
540 submit: (value, summary) => finish(Effect.succeed(value), summary),
541 cancel,
542 })}
543 </ScreenCancelGuard>,
544 );
545 // Not awaited (Effect.callback's register is synchronous), but
546 // never fire-and-forget: a mount failure — e.g. a synchronous
547 // throw from Sigil's render() — routes through `failRenderer`,
548 // which fails this very interaction via the `failActive` hook
549 // installed above instead of escaping as an unhandled rejection.
550 mount().catch(failRenderer);
551 // Interruption cleanup: deactivate the screen and let the caller's
552 // finalizers release the renderer.
553 return Effect.sync(() => {
554 if (!settled) {
555 settled = true;
556 failActive = undefined;
557 store.deactivate();
558 }
559 });
560 }).pipe(
561 Effect.ensuring(
562 Effect.suspend(() =>
563 inSession
564 ? Effect.void
565 : releaseIfIdle().pipe(
566 Effect.andThen(
567 completedView === undefined ? Effect.void : print(completedView),
568 ),
569 ),
570 ),
571 ),
572 );
573 }),
574 );
575 return yield* inSession ? interaction : rendererGate.withPermits(1)(interaction);
576 });
577
578 // A session owns the renderer when invoked standalone. Nested, it reuses
579 // the outer renderer and clears the prompts it showed when it settles, so
580 // nested profile/OAuth flows suspend cleanly. Prompt serialization remains
581 // centralized in `run`.
582 const session = <A, E, R>(
583 effect: Effect.Effect<A, E, R>,
584 sessionOptions: SessionOptions = {},
585 ): Effect.Effect<A, E | NonInteractiveTerminal, R> =>
586 Effect.gen(function* () {
587 if (yield* InSession) {
588 return yield* effect.pipe(Effect.ensuring(Effect.sync(() => store.clearTranscript())));
589 }
590 const alternate = sessionOptions.alternate === true && capabilities.alternateScreen;
591 return yield* rendererGate.withPermits(1)(
592 Effect.acquireUseRelease(
593 Effect.promise(async () => {
594 sessionMounted = true;
595 store.clear();
596 // Sigil cannot change `alternateScreen` on a live instance: if
597 // an inline renderer (say an earlier progress row) is still
598 // mounted with the wrong presentation, remount with the
599 // requested one instead of silently ignoring it.
600 if (mounted !== undefined && mounted.alternate !== alternate) {
601 await unmount(true);
602 }
603 await mount(alternate);
604 }),
605 () => effect.pipe(Effect.provideService(InSession, true)),
606 () =>
607 Effect.promise(async () => {
608 sessionMounted = false;
609 store.clear();
610 // Let the empty frame replace the session, then erase
611 // that frame explicitly. Unmount can now restore terminal
612 // modes without leaving the empty frame's newline behind.
613 const current = mounted;
614 if (current !== undefined) {
615 await current.sigil.waitUntilRenderFlush();
616 current.sigil.clear();
617 }
618 await unmount();
619 }),
620 ),
621 );
622 });
623
624 const makeLive = (initial: View, options: LiveViewOptions = {}): Effect.Effect<LiveViewHandle> =>
625 Effect.gen(function* () {
626 const inSession = yield* InSession;
627 const key = store.alloc();
628 let closed = false;
629 yield* Effect.sync(() => store.addLive(key, normalizeView(initial), options.placement));
630 yield* ensureMounted();
631 return {
632 close: Effect.suspend(() => {
633 if (closed) return Effect.void;
634 closed = true;
635 // removeLive/completeLive no-op when the row was already cleared
636 // by a session boundary.
637 if (options.persistOnClose)
638 store.completeLive(key, inSession ? "transcript" : "staticItems");
639 else store.removeLive(key);
640 return Effect.promise(waitForRender).pipe(Effect.andThen(releaseIfIdle()));
641 }),
642 };
643 });
644
645 /**
646 * Scope-bound: the enclosing scope closes the view as a backstop, so an
647 * interrupted caller can never leave an orphaned row keeping the renderer
648 * mounted (and the process alive) forever.
649 */
650 const live = (
651 initial: View,
652 options: LiveViewOptions = {},
653 ): Effect.Effect<LiveViewHandle, never, Scope.Scope> =>
654 Effect.acquireRelease(makeLive(initial, options), (handle) => handle.close);
655
656 /**
657 * A progress row is just a live view over a runtime-owned store — the
658 * handle mutates the store, React re-renders. Settling swaps the store to
659 * its final state and commits the block to scrollback.
660 */
661 const makeProgress = (initial: ProgressOptions): Effect.Effect<ProgressHandle> =>
662 Effect.gen(function* () {
663 const inSession = yield* InSession;
664 const progressStore = new LiveStore<ProgressState>({ options: initial });
665 const key = store.alloc();
666 yield* Effect.sync(() => store.addLive(key, <ProgressView store={progressStore} />));
667 yield* ensureMounted();
668 let settled = false;
669 const finishRow = (persist: boolean) =>
670 Effect.suspend(() => {
671 if (settled) return Effect.void;
672 settled = true;
673 // completeLive/removeLive no-op when the row was already cleared
674 // by a session boundary.
675 if (persist) store.completeLive(key, inSession ? "transcript" : "staticItems");
676 else store.removeLive(key);
677 return Effect.promise(waitForRender).pipe(Effect.andThen(releaseIfIdle()));
678 });
679 const settle = (variant: "success" | "error", message?: string) =>
680 Effect.suspend(() => {
681 if (settled) return Effect.void;
682 progressStore.update((state) => ({ ...state, final: { variant, message } }));
683 return finishRow(true);
684 });
685 return {
686 update: (next) =>
687 Effect.sync(() => {
688 if (!settled) progressStore.set({ options: next });
689 }),
690 succeed: (message) => settle("success", message),
691 fail: (message) => settle("error", message),
692 // An unsettled close abandons the row rather than committing it.
693 close: finishRow(false),
694 } satisfies ProgressHandle;
695 });
696
697 const progress = (initial: ProgressOptions): Effect.Effect<ProgressHandle, never, Scope.Scope> =>
698 Effect.acquireRelease(makeProgress(initial), (handle) => handle.close);
699
700 /**
701 * The login screen races `waitFor`: the poll or callback normally wins,
702 * the screen only settles first when the user cancels or pastes a code.
703 */
704 const browserLogin = <A, E, R, E2 = never, R2 = never>(
705 login: BrowserLoginOptions<A, E, R, E2, R2>,
706 ) =>
707 Effect.gen(function* () {
708 const services = yield* Effect.context<ChildProcessSpawner>();
709 // Invoked later by the screen's keyboard handler, outside this fiber.
710 const reopen = () => Effect.runPromiseWith(services)(openUrl(login.url));
711 const openFailed = yield* Effect.isFailure(openUrl(login.url));
712 const manual = login.manualCode;
713 const screen = run(
714 browserLoginScreen({
715 message: `${login.provider} authorization`,
716 waitingLabel:
717 login.waitingLabel ?? "waiting for browser authorization (up to 5 minutes)…",
718 url: login.url,
719 code: login.code,
720 openFailed,
721 onOpen: reopen,
722 allowManualInput: manual !== undefined,
723 inputLabel: manual?.label ?? "Paste the authorization code or callback URL",
724 placeholder: manual?.placeholder,
725 validate: manual?.validate,
726 }),
727 ).pipe(
728 Effect.flatMap((code): Effect.Effect<A, E2, R2> =>
729 manual === undefined ? Effect.never : manual.exchange(code),
730 ),
731 );
732 return yield* Effect.raceFirst(login.waitFor, screen);
733 });
734
735 const service: Interaction["Service"] = {
736 terminal: capabilities,
737 output: {
738 print,
739 info: log("info"),
740 success: log("success"),
741 warning: log("warning"),
742 error: log("error"),
743 },
744 prompt: {
745 text: (inputOptions) => run(textScreen(inputOptions)),
746 password: (inputOptions) => run(passwordScreen(inputOptions)),
747 confirm: (confirmOptions) => run(confirmScreen(confirmOptions)),
748 select: (selectOptions) => run(selectScreen(selectOptions)),
749 multiSelect: (selectOptions) => run(multiSelectScreen(selectOptions)),
750 screen: run,
751 },
752 browserLogin,
753 live,
754 progress,
755 task: taskFromProgress(progress),
756 session,
757 };
758
759 return {
760 service,
761 dispose: async () => {
762 // After dispose the runtime must never mount again; force teardown even
763 // if stray live rows were leaked.
764 disposed = true;
765 await unmount(true);
766 },
767 };
768 };