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

main
tsx 866 lines 29.1 KB
Raw
1 /** @jsxRuntime automatic */
2 /** @jsxImportSource @alchemy.run/sigil */
3 /**
4 * GUI-style dashboard behind bare `alchemy profile`. One Sigil app stays
5 * mounted for the whole session and screens replace each other in place:
6 *
7 * overview — chip tabs (default profile first), selected profile's
8 * provider details with an up/down focus cursor, keybind bar,
9 * inline rename/new/delete/remove
10 * edit — replaces the overview: per-provider cycle rows
11 * (keep / reconfigure / remove, add for unconnected)
12 *
13 * Pure store actions (create/rename/delete) round-trip through
14 * the hub via a request bridge WITHOUT unmounting — results come back as
15 * in-app notices. Only flows that must prompt in the transcript (provider
16 * configuration, credential refresh) resolve the session. The built-in
17 * `default` profile is pinned first and can be neither renamed nor deleted.
18 */
19 import { useEffect, useState } from "@alchemy.run/sigil/react";
20 import * as Effect from "effect/Effect";
21 import * as Fiber from "effect/Fiber";
22 import * as Scheduler from "effect/Scheduler";
23 import type { JSX } from "react";
24 import { Interaction, type NonInteractiveTerminal } from "../../../Interaction.ts";
25 import { theme } from "../../../Util/Theme.ts";
26 import {
27 Alert,
28 Box,
29 CycleList,
30 Gutter,
31 InlineConfirm,
32 KeyBar,
33 LiveStore,
34 Pointer,
35 PromptFrame,
36 Spinner,
37 Stack,
38 Status,
39 Tabs,
40 Text,
41 TextField,
42 Toast,
43 useCycleNavigation,
44 useGlyphs,
45 useKeyGlyphs,
46 useLiveStore,
47 useTerminalInput,
48 useTerminalSize,
49 VirtualList,
50 } from "../ui/index.ts";
51 import {
52 type EditState,
53 editStateStyle,
54 ProviderBlock,
55 providerBlockHeight,
56 providerColumnWidths,
57 type ProfileProviderDisplay,
58 } from "./Profile.tsx";
59
60 // --- data contracts ---------------------------------------------------------
61
62 export interface DashboardEntry {
63 readonly name: string;
64 readonly isActive: boolean;
65 readonly isDefault: boolean;
66 }
67
68 export interface ProfileDetailsPayload {
69 readonly providers: ReadonlyArray<ProfileProviderDisplay>;
70 /** Registry providers not yet connected to this profile. */
71 readonly available: ReadonlyArray<string>;
72 }
73
74 export type PureAction =
75 | { kind: "create"; name: string }
76 | { kind: "rename"; name: string; newName: string }
77 | { kind: "delete"; name: string };
78
79 export type FlowAction =
80 | {
81 kind: "edit-apply";
82 name: string;
83 add: string[];
84 reconfigure: string[];
85 remove: string[];
86 }
87 | { kind: "refresh"; name: string; provider?: string };
88
89 export type ExternalAction = FlowAction | { kind: "exit" };
90
91 export interface ExecuteResult {
92 readonly ok: boolean;
93 readonly message: string;
94 readonly entries: ReadonlyArray<DashboardEntry>;
95 /** Profile to focus after the action (e.g. the new name of a rename). */
96 readonly selected?: string;
97 }
98
99 // --- store ------------------------------------------------------------------
100
101 export type Details =
102 | { state: "loading" }
103 | ({ state: "ready" } & ProfileDetailsPayload)
104 | { state: "failed"; message: string };
105
106 interface Notice {
107 readonly ok: boolean;
108 readonly message: string;
109 }
110
111 interface Flow {
112 readonly kind: FlowAction["kind"];
113 readonly name: string;
114 readonly provider?: string;
115 /** Inline flows render within the overview (refresh spinner). */
116 readonly inline: boolean;
117 }
118
119 interface DashState {
120 readonly entries: ReadonlyArray<DashboardEntry>;
121 readonly details: ReadonlyMap<string, Details>;
122 readonly notice: Notice | undefined;
123 readonly busy: boolean;
124 /** One-shot tab focus request (e.g. follow a rename to its new name). */
125 readonly focus: string | undefined;
126 /** Active in-app flow; `inline` flows render within the overview. */
127 readonly flow: Flow | undefined;
128 }
129
130 /**
131 * Immutable-snapshot store on top of `LiveStore`, so every mutation notifies
132 * the mounted dashboard. The resolver bridge and the notice auto-dismiss
133 * timer live outside the snapshot — they carry no visual state.
134 */
135 export class DashStore extends LiveStore<DashState> {
136 private resolver: ((action: PureAction | ExternalAction) => void) | null = null;
137
138 constructor(entries: ReadonlyArray<DashboardEntry>) {
139 super({
140 entries,
141 details: new Map(),
142 notice: undefined,
143 busy: false,
144 focus: undefined,
145 flow: undefined,
146 });
147 }
148
149 detailsFor(name: string): Details {
150 return this.snapshot().details.get(name) ?? { state: "loading" };
151 }
152 detailNames(): ReadonlySet<string> {
153 return new Set(this.snapshot().details.keys());
154 }
155 setDetails(name: string, details: Details) {
156 this.update((state) => ({
157 ...state,
158 details: new Map(state.details).set(name, details),
159 }));
160 }
161 setFlow(flow: Flow | undefined) {
162 this.update((state) => ({ ...state, flow }));
163 }
164 clearFocus() {
165 this.update((state) => ({ ...state, focus: undefined }));
166 }
167 dispose() {
168 this.resolver = null;
169 }
170 clearNotice() {
171 this.update((state) => ({ ...state, notice: undefined }));
172 }
173 applyResult(result: ExecuteResult) {
174 this.update((state) => ({
175 ...state,
176 entries: result.entries,
177 notice: { ok: result.ok, message: result.message },
178 focus: result.ok ? result.selected : undefined,
179 busy: false,
180 }));
181 }
182 bindResolver(resolve: (action: PureAction | ExternalAction) => void) {
183 this.resolver = resolve;
184 }
185 readonly dispatch = (action: PureAction | ExternalAction) => {
186 if (this.snapshot().busy || this.resolver === null) return;
187 const resolve = this.resolver;
188 this.resolver = null;
189 this.update((state) => ({ ...state, busy: true, notice: undefined }));
190 resolve(action);
191 };
192 }
193
194 // --- building blocks --------------------------------------------------------
195
196 type DetailsPaneProps = {
197 details: Details;
198 refreshingProvider?: string;
199 /** Index into `details.providers` the up/down cursor rests on. */
200 focusedIndex: number;
201 };
202
203 function DetailsPane({ details, refreshingProvider, focusedIndex }: DetailsPaneProps): JSX.Element {
204 if (details.state === "loading") {
205 return <Spinner label="resolving credentials…" />;
206 }
207 if (details.state === "failed") {
208 return <Status variant="error">{details.message}</Status>;
209 }
210 if (details.providers.length === 0) {
211 return <Text tone="muted">No accounts connected — press e to add one.</Text>;
212 }
213 const { providers } = details;
214 const { nameWidth, methodWidth } = providerColumnWidths(providers);
215 const focusedProvider = providers[focusedIndex]?.name;
216 const reauthHint = "press r to re-login";
217 // The same blocks `profile show` prints, windowed to the rows the terminal
218 // leaves the pane: the list shrinks to fit (see the root layout in
219 // `Dashboard`) and scrolls just enough to keep the focused provider in view.
220 // The profile-level slot (no focused provider) shows the list from the top.
221 return (
222 <Box flexDirection="column" minHeight={0}>
223 <VirtualList
224 items={providers}
225 getKey={(provider) => provider.name}
226 itemHeight={(provider, index) => providerBlockHeight(provider, index === 0)}
227 focusedIndex={Math.max(0, focusedIndex)}
228 renderItem={(provider, index) => (
229 <ProviderBlock
230 provider={provider}
231 first={index === 0}
232 nameWidth={nameWidth}
233 methodWidth={methodWidth}
234 reauthHint={reauthHint}
235 refreshingProvider={refreshingProvider}
236 focusedProvider={focusedProvider}
237 focusColumn
238 />
239 )}
240 />
241 </Box>
242 );
243 }
244
245 // --- edit screen ------------------------------------------------------------
246
247 interface EditRow {
248 readonly provider: string;
249 readonly method: string | undefined; // undefined = not connected
250 readonly states: ReadonlyArray<EditState>;
251 }
252
253 type EditScreenProps = {
254 profile: string;
255 rows: ReadonlyArray<EditRow>;
256 onApply: (choices: ReadonlyArray<EditState>) => void;
257 onBack: () => void;
258 };
259
260 function EditScreen({ profile, rows, onApply, onBack }: EditScreenProps): JSX.Element {
261 const { cursor, indices, move, cycle } = useCycleNavigation(rows.map((row) => row.states.length));
262 const keys = useKeyGlyphs();
263 const glyphs = useGlyphs();
264 const [unchanged, setUnchanged] = useState(false);
265 useTerminalInput((input, key) => {
266 const plain = !key.ctrl && !key.meta;
267 if (key.escape) return onBack();
268 if (key.up || (plain && input === "k")) move(-1);
269 else if (key.down || (plain && input === "j")) move(1);
270 else if ((plain && input === " ") || key.right) {
271 cycle(1);
272 setUnchanged(false);
273 } else if (key.left) {
274 cycle(-1);
275 setUnchanged(false);
276 } else if (key.enter) {
277 if (indices.every((index) => index === 0)) setUnchanged(true);
278 else onApply(rows.map((row, i) => row.states[indices[i]]!));
279 }
280 });
281 if (rows.length === 0) {
282 return (
283 <Stack>
284 <Text>
285 <Text bold color={theme.color.accent}>
286 edit accounts
287 </Text>
288 <Text tone="muted"> · {profile}</Text>
289 </Text>
290 <Status>No providers are available for this profile.</Status>
291 <KeyBar keys={[[keys.escape, "back"]]} />
292 </Stack>
293 );
294 }
295 const choices = rows.map((row) => ({
296 label: row.provider,
297 description: row.method ?? "not connected",
298 states: row.states.map((state) => ({
299 value: state,
300 label: editStateStyle[state].label,
301 icon: glyphs[editStateStyle[state].icon],
302 variant: editStateStyle[state].variant,
303 })),
304 }));
305 return (
306 <Stack gap={1}>
307 <Text>
308 <Text bold color={theme.color.accent}>
309 edit accounts
310 </Text>
311 <Text tone="muted"> · {profile}</Text>
312 </Text>
313 <CycleList choices={choices} cursor={cursor} indices={indices} />
314 {unchanged ? (
315 <Alert variant="warning" title="No changes to apply">
316 Press Space to change an account, or Esc to go back.
317 </Alert>
318 ) : null}
319 <KeyBar
320 keys={[
321 [keys.upDown, "navigate"],
322 [keys.space, "change"],
323 [keys.enter, "apply"],
324 [keys.escape, "back"],
325 ]}
326 />
327 </Stack>
328 );
329 }
330
331 // --- main component ---------------------------------------------------------
332
333 type Mode = "normal" | "rename" | "create" | "delete" | "remove";
334
335 type DashboardControlsProps = {
336 readonly mode: Mode;
337 readonly busy: boolean;
338 readonly flow: Flow | undefined;
339 readonly entry: DashboardEntry | undefined;
340 readonly provider: ProfileProviderDisplay | undefined;
341 readonly keybinds: ReadonlyArray<readonly [string, string]>;
342 readonly keyGlyphs: ReturnType<typeof useKeyGlyphs>;
343 readonly store: DashStore;
344 readonly setMode: (mode: Mode) => void;
345 };
346
347 function DashboardControls({
348 mode,
349 busy,
350 flow,
351 entry,
352 provider,
353 keybinds,
354 keyGlyphs,
355 store,
356 setMode,
357 }: DashboardControlsProps) {
358 if (flow?.inline !== true && (busy || flow !== undefined)) return null;
359 if (mode === "normal") return <KeyBar keys={keybinds} marginTop={0} />;
360 if (mode === "delete" && entry !== undefined) {
361 return (
362 <InlineConfirm
363 message={`Delete '${entry.name}' and all its stored credentials?`}
364 confirmLabel="Delete"
365 cancelLabel="Cancel"
366 onSubmit={(confirmed) => {
367 setMode("normal");
368 if (confirmed) store.dispatch({ kind: "delete", name: entry.name });
369 }}
370 onCancel={() => setMode("normal")}
371 />
372 );
373 }
374 if (mode === "remove" && entry !== undefined && provider !== undefined) {
375 return (
376 <InlineConfirm
377 message={`Remove '${provider.name}' from profile '${entry.name}'?`}
378 confirmLabel="Remove"
379 cancelLabel="Cancel"
380 onSubmit={(confirmed) => {
381 setMode("normal");
382 if (confirmed) {
383 store.dispatch({
384 kind: "edit-apply",
385 name: entry.name,
386 add: [],
387 reconfigure: [],
388 remove: [provider.name],
389 });
390 }
391 }}
392 onCancel={() => setMode("normal")}
393 />
394 );
395 }
396
397 const renaming = mode === "rename" && entry !== undefined;
398 return (
399 <PromptFrame
400 message={renaming ? `rename '${entry.name}' to` : "new profile name"}
401 layout="inline"
402 keys={[
403 [keyGlyphs.enter, "confirm"],
404 [keyGlyphs.escape, "cancel"],
405 ]}
406 >
407 <TextField
408 key={`${mode}-${entry?.name ?? ""}`}
409 placeholder={renaming ? `${entry.name}-new` : "my-profile"}
410 onSubmit={(value) => {
411 const name = value.trim();
412 if (name.length === 0) return;
413 setMode("normal");
414 store.dispatch(
415 renaming
416 ? { kind: "rename", name: entry.name, newName: name }
417 : { kind: "create", name },
418 );
419 }}
420 onCancel={() => setMode("normal")}
421 />
422 </PromptFrame>
423 );
424 }
425
426 type DashboardProps = {
427 store: DashStore;
428 initialSelected: number;
429 };
430
431 export function Dashboard({ store, initialSelected }: DashboardProps): JSX.Element {
432 const state = useLiveStore(store);
433 const keyGlyphs = useKeyGlyphs();
434 const { rows } = useTerminalSize();
435 const [selected, setSelected] = useState(initialSelected);
436 // -1 is the profile-level slot: no provider is focused and profile actions
437 // are shown. Up/down cycles through this slot and every connected provider.
438 const [focusedProvider, setFocusedProvider] = useState(-1);
439 const [mode, setMode] = useState<Mode>("normal");
440 const [screen, setScreen] = useState<"overview" | "edit">("overview");
441 const { entries, focus: requestedFocus, flow, busy, notice } = state;
442 useEffect(() => {
443 if (requestedFocus === undefined) return;
444 const focusIndex = entries.findIndex((entry) => entry.name === requestedFocus);
445 store.clearFocus();
446 if (focusIndex >= 0) {
447 setSelected(focusIndex);
448 }
449 }, [entries, requestedFocus, store]);
450 const index = Math.min(Math.max(selected, 0), entries.length - 1);
451 const entry = entries[index];
452 const details = entry === undefined ? undefined : store.detailsFor(entry.name);
453 const providers = details?.state === "ready" ? details.providers : [];
454 const provider = providers[focusedProvider];
455 const moveProviderFocus = (delta: -1 | 1) =>
456 setFocusedProvider((current) => {
457 const slotCount = providers.length + 1;
458 const position = current + 1;
459 return ((position + delta + slotCount) % slotCount) - 1;
460 });
461 useEffect(() => setFocusedProvider(-1), [entry?.name]);
462
463 useTerminalInput((input, key) => {
464 // flow prompts, the edit screen, and the inline TextField/InlineConfirm
465 // modes own the keyboard
466 if (flow !== undefined || screen === "edit" || busy) return;
467 if (mode !== "normal") return;
468 if (input === "q" || key.escape || (key.ctrl && input === "c")) {
469 store.dispatch({ kind: "exit" });
470 } else if (key.ctrl || key.meta) {
471 return;
472 } else if (entry === undefined) {
473 if (input === "n") setMode("create");
474 } else if (key.left) {
475 setSelected((s) => (s + entries.length - 1) % entries.length);
476 setFocusedProvider(-1);
477 } else if (key.right) {
478 setSelected((s) => (s + 1) % entries.length);
479 setFocusedProvider(-1);
480 } else if (key.up && providers.length > 0) {
481 moveProviderFocus(-1);
482 } else if (key.down && providers.length > 0) {
483 moveProviderFocus(1);
484 } else if (provider === undefined && input === "R" && !entry.isDefault) {
485 setMode("rename");
486 } else if (provider === undefined && input === "d" && !entry.isDefault) {
487 setMode("delete");
488 } else if (provider === undefined && input === "e" && details?.state === "ready") {
489 setScreen("edit");
490 } else if (provider === undefined && input === "r") {
491 store.dispatch({ kind: "refresh", name: entry.name });
492 } else if (provider === undefined && input === "n") {
493 setMode("create");
494 } else if (input === "e" && provider !== undefined) {
495 store.dispatch({
496 kind: "edit-apply",
497 name: entry.name,
498 add: [],
499 reconfigure: [provider.name],
500 remove: [],
501 });
502 } else if (input === "r" && provider !== undefined) {
503 store.dispatch({
504 kind: "refresh",
505 name: entry.name,
506 provider: provider.name,
507 });
508 } else if (input === "d" && provider !== undefined) {
509 setMode("remove");
510 }
511 });
512
513 if (flow !== undefined && !flow.inline) {
514 return (
515 <Text>
516 <Text bold color={theme.color.accent}>
517 {flow.kind === "refresh" ? "refresh" : "edit accounts"}
518 </Text>
519 <Text tone="muted"> · {flow.name}</Text>
520 </Text>
521 );
522 }
523
524 if (
525 screen === "edit" &&
526 entry !== undefined &&
527 details !== undefined &&
528 details.state === "ready"
529 ) {
530 const rows: EditRow[] = [
531 ...details.providers.map((provider) => ({
532 provider: provider.name,
533 method: provider.method,
534 states: ["keep", "reconfigure", "remove"] as const,
535 })),
536 ...details.available.map((name) => ({
537 provider: name,
538 method: undefined,
539 states: ["skip", "add"] as const,
540 })),
541 ];
542 return (
543 <EditScreen
544 profile={entry.name}
545 rows={rows}
546 onBack={() => setScreen("overview")}
547 onApply={(choices) => {
548 const pick = (state: EditState) =>
549 rows.flatMap((row, i) => (choices[i] === state ? [row.provider] : []));
550 const action: ExternalAction = {
551 kind: "edit-apply",
552 name: entry.name,
553 add: pick("add"),
554 reconfigure: pick("reconfigure"),
555 remove: pick("remove"),
556 };
557 setScreen("overview");
558 if (action.add.length + action.reconfigure.length + action.remove.length === 0) {
559 return;
560 }
561 store.dispatch(action);
562 }}
563 />
564 );
565 }
566
567 const annotation = entry !== undefined && entry.isActive ? "active" : "";
568
569 const keybinds: ReadonlyArray<readonly [string, string]> =
570 entry === undefined
571 ? [
572 ["n", "new"],
573 ["q", "quit"],
574 ]
575 : [
576 [keyGlyphs.leftRight, "switch profile"],
577 ...(providers.length === 0 ? [] : ([[keyGlyphs.upDown, "focus provider"]] as const)),
578 ...(provider !== undefined
579 ? ([
580 ["e", "reconfigure"],
581 ["r", "refresh"],
582 ["d", "remove"],
583 ] as const)
584 : ([
585 ...(details?.state === "ready"
586 ? ([
587 ["e", "edit"],
588 ["r", "refresh"],
589 ] as const)
590 : []),
591 ["n", "new"],
592 ...(entry.isDefault
593 ? []
594 : ([
595 ["R", "rename"],
596 ["d", "delete"],
597 ] as const)),
598 ] as ReadonlyArray<readonly [string, string]>)),
599 ["q", "quit"],
600 ];
601
602 // The frame never exceeds the terminal: the provider list is the only part
603 // allowed to shrink (a `VirtualList` windows it to whatever rows are left),
604 // so every other row of chrome opts out of shrinking. Short lists keep the
605 // compact layout because the cap is a maximum, not a fixed height.
606 return (
607 <Stack maxHeight={rows}>
608 <Stack flexShrink={0}>
609 <Tabs
610 tabs={entries.map((e) => ({
611 id: e.name,
612 label: e.name,
613 marked: e.isActive,
614 }))}
615 active={entry?.name ?? ""}
616 />
617 </Stack>
618 <Stack gap={1} minHeight={0}>
619 {entry === undefined ? (
620 <Text tone="muted">No profiles yet — press n to create one.</Text>
621 ) : (
622 <>
623 {/* The profile row is the first focus slot. It sits in the same
624 gutter as the provider rows and shares their cursor column, so
625 the pointer moves in a straight line as focus travels. */}
626 <Box flexShrink={0}>
627 <Gutter>
628 <Box flexDirection="row">
629 <Pointer focused={provider === undefined} />
630 <Text> </Text>
631 <Text bold color={provider === undefined ? theme.paint.focus : undefined}>
632 {entry.name}
633 </Text>
634 {annotation === "" ? null : <Text tone="muted"> · {annotation}</Text>}
635 </Box>
636 </Gutter>
637 </Box>
638 <Box flexDirection="column" minHeight={0}>
639 <DetailsPane
640 details={details ?? { state: "loading" }}
641 focusedIndex={focusedProvider}
642 refreshingProvider={flow?.kind === "refresh" ? flow.provider : undefined}
643 />
644 </Box>
645 </>
646 )}
647 </Stack>
648 {/* Keep one stable status row so notices do not push the controls around.
649 It shares the gutter with the profile/provider rows above it. */}
650 <Box minHeight={1} flexShrink={0} paddingLeft={theme.space.indent}>
651 {busy && flow === undefined ? (
652 <Spinner label="working…" />
653 ) : notice !== undefined ? (
654 <Toast variant={notice.ok ? "info" : "error"}>{notice.message}</Toast>
655 ) : null}
656 </Box>
657 <Stack flexShrink={0}>
658 <DashboardControls
659 mode={mode}
660 busy={busy}
661 flow={flow}
662 entry={entry}
663 provider={provider}
664 keybinds={keybinds}
665 keyGlyphs={keyGlyphs}
666 store={store}
667 setMode={setMode}
668 />
669 </Stack>
670 </Stack>
671 );
672 }
673
674 // --- session driver ---------------------------------------------------------
675
676 export interface DashboardSessionOptions<R> {
677 readonly entries: ReadonlyArray<DashboardEntry>;
678 readonly selected: string | undefined;
679 /**
680 * Resolves a profile's provider details. A typed failure renders as the
681 * detail pane's `failed` state, showing the error's message.
682 */
683 readonly loadDetails: (
684 name: string,
685 ) => Effect.Effect<ProfileDetailsPayload, { readonly message: string }, R>;
686 /** Executes a pure store action and returns the refreshed state. */
687 readonly execute: (action: PureAction) => Effect.Effect<ExecuteResult, never, R>;
688 /**
689 * Runs an edit/refresh flow. Its prompts render inside the dashboard via
690 * the embedded session; resolves with a toast outcome — `ok: false`
691 * renders as a persistent error notice instead of an auto-dismissing
692 * success toast.
693 */
694 readonly runFlow: (
695 action: FlowAction,
696 events: {
697 readonly onProviderStart: (provider: string) => Effect.Effect<void>;
698 },
699 ) => Effect.Effect<{ ok: boolean; message: string }, never, R>;
700 /** Re-reads entries after a flow (the active profile may have changed). */
701 readonly reloadEntries: Effect.Effect<ReadonlyArray<DashboardEntry>, never, R>;
702 }
703
704 /**
705 * Runs the dashboard inside one Interaction session. Pure actions and
706 * edit/refresh flows share the same frame, and the session clears it on
707 * exit.
708 */
709 export const runProfileDashboardSession = <R,>(
710 options: DashboardSessionOptions<R>,
711 ): Effect.Effect<void, NonInteractiveTerminal, R | Interaction> =>
712 Effect.flatMap(Interaction, (cli) =>
713 cli.session(
714 // live is Scope-bound; the session scope is its release backstop
715 // (the ensuring(live.close) below settles it on the normal path).
716 Effect.scoped(
717 Effect.gen(function* () {
718 const store = new DashStore(options.entries);
719 let noticeFiber: Fiber.Fiber<void, never> | undefined;
720
721 const applyResult = Effect.fn(function* (result: ExecuteResult) {
722 if (noticeFiber !== undefined) yield* Fiber.interrupt(noticeFiber);
723 store.applyResult(result);
724 if (result.ok) {
725 noticeFiber = yield* Effect.sleep("4 seconds").pipe(
726 Effect.andThen(Effect.sync(() => store.clearNotice())),
727 Effect.forkChild,
728 );
729 }
730 });
731
732 const loadInto = (name: string) =>
733 options.loadDetails(name).pipe(
734 Effect.flatMap((payload) =>
735 Effect.sync(() => store.setDetails(name, { state: "ready", ...payload })),
736 ),
737 Effect.catch((error) =>
738 Effect.sync(() =>
739 store.setDetails(name, {
740 state: "failed",
741 message: error.message,
742 }),
743 ),
744 ),
745 Effect.catchDefect((defect) =>
746 Effect.sync(() =>
747 store.setDetails(name, {
748 state: "failed",
749 message: String(defect),
750 }),
751 ),
752 ),
753 // Provider discovery can build very large Layers. Yield often
754 // enough for Sigil's 80ms animation clock to keep painting while
755 // that CPU-heavy Effect graph is evaluated.
756 Effect.provideService(Scheduler.MaxOpsBeforeYield, 64),
757 );
758
759 const initialSelected = Math.max(
760 0,
761 options.entries.findIndex((entry) => entry.name === options.selected),
762 );
763
764 const live = yield* cli.live(
765 <Dashboard store={store} initialSelected={initialSelected} />,
766 { placement: "beforeTranscript" },
767 );
768
769 // Mount the spinner before starting stack import/provider builds.
770 // Forking the loader first allowed synchronous module evaluation to
771 // delay the dashboard's first frame, making it look fully hung.
772 const loader = yield* Effect.forEach(options.entries, (entry) => loadInto(entry.name), {
773 concurrency: 2,
774 discard: true,
775 }).pipe(Effect.delay("1 millis"), Effect.forkChild);
776
777 yield* Effect.gen(function* () {
778 while (true) {
779 const action = yield* Effect.callback<PureAction | ExternalAction>((resume) => {
780 store.bindResolver((action) => resume(Effect.succeed(action)));
781 });
782 switch (action.kind) {
783 case "exit":
784 return;
785 case "refresh":
786 case "edit-apply": {
787 store.setFlow({
788 kind: action.kind,
789 name: action.name,
790 provider: action.kind === "refresh" ? action.provider : undefined,
791 // refresh keeps the overview on screen with a spinner; only
792 // account editing takes over the whole view
793 inline: action.kind === "refresh",
794 });
795 const flowEffect = options.runFlow(action, {
796 onProviderStart: (provider) =>
797 Effect.sync(() =>
798 store.setFlow({
799 kind: "refresh",
800 name: action.name,
801 provider,
802 inline: true,
803 }),
804 ),
805 });
806 // Provider login implementations emit useful progress in
807 // standalone commands. Inside the dashboard that progress
808 // belongs in the provider pane, not the transcript.
809 const quietRefreshCli = {
810 ...cli,
811 output: {
812 ...cli.output,
813 info: () => Effect.void,
814 success: () => Effect.void,
815 },
816 } satisfies Interaction["Service"];
817 const result = yield* cli.session(
818 action.kind === "refresh"
819 ? flowEffect.pipe(Effect.provideService(Interaction, quietRefreshCli))
820 : flowEffect,
821 );
822 const entries = yield* options.reloadEntries;
823 if (action.kind === "refresh") {
824 // Keep the provider-level spinner visible until the new
825 // expiry/token details have replaced the old ones.
826 yield* loadInto(action.name);
827 } else {
828 store.setDetails(action.name, { state: "loading" });
829 yield* loadInto(action.name).pipe(Effect.forkChild);
830 }
831 store.setFlow(undefined);
832 yield* applyResult({
833 ok: result.ok,
834 message: result.message,
835 entries,
836 selected: action.name,
837 });
838 break;
839 }
840 default: {
841 const result = yield* options.execute(action);
842 // a renamed/created profile needs its details (re)resolved
843 const names = store.detailNames();
844 yield* applyResult(result);
845 yield* Effect.forEach(
846 result.entries.filter((e) => !names.has(e.name)),
847 (e) => loadInto(e.name),
848 { concurrency: 2, discard: true },
849 ).pipe(Effect.forkChild);
850 }
851 }
852 }
853 }).pipe(
854 Effect.ensuring(Effect.sync(() => store.dispose())),
855 Effect.ensuring(
856 Effect.suspend(() =>
857 noticeFiber === undefined ? Effect.void : Fiber.interrupt(noticeFiber),
858 ),
859 ),
860 Effect.ensuring(live.close),
861 Effect.ensuring(Fiber.interrupt(loader)),
862 );
863 }),
864 ),
865 ),
866 );