import { HeaderNavigation, type NavigationPage } from "./HeaderNavigation"; import { SettingsPage } from "./SettingsPage"; import { SetupScreen } from "./SetupScreen"; import { settingsApi } from "./settingsApi"; import { lazy, Suspense, useCallback, useEffect, useReducer, useRef, useState, } from "react"; import ReactMarkdown from "react-markdown"; import { blockActive, notebookIncludes, parseNotebook, renderHost, renderStep, renderText, resolveParams, scopeActive, } from "@shellbook/core"; import type { Block, HostInfo, NotebookResponse, NotebookSummary, ParamValues, ServerEvent, StartRunRequest, Step, } from "@shellbook/core"; import { NotebookList } from "./NotebookList"; import { HostKeyConfirmation } from "./HostKeyConfirmation"; import { HostsPage } from "./HostsPage"; import { HttpError } from "./api"; import type { Api } from "./api"; import { emptySession, eventReducer, stepKey } from "./events"; import { ParamsForm, type ParamGroup } from "./ParamsForm"; import { HostBlockCard } from "./HostBlockCard"; import { StepCard } from "./StepCard"; import { ChatPanel } from "./ChatPanel"; const TerminalSlot = lazy(() => import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })), ); const Editor = lazy(() => import("./Editor").then((module) => ({ default: module.Editor })), ); function steps(blocks: Block[]): Step[] { return blocks.flatMap((block) => block.type === "step" ? [block.step] : block.type === "markdown" || block.type === "host" ? [] : steps(block.blocks), ); } /** Included notebooks (`::use`, nested too) as parameter groups. */ function includedGroups(blocks: Block[]): ParamGroup[] { return blocks.flatMap((block): ParamGroup[] => block.type === "use" ? [{ scope: block.scope, title: `${block.title ?? block.path} (${block.scope})` }, ...includedGroups(block.blocks)] : block.type === "after" || block.type === "when" ? includedGroups(block.blocks) : [], ); } export function App({ api }: { api: Api }) { const [auth, setAuth] = useState<"loading" | "login" | "setup" | "ready">("loading"); const [page, setPage] = useState("Notebooks"); const [password, setPassword] = useState(""); const [list, setList] = useState([]); const [hosts, setHosts] = useState([]); const [doc, setDoc] = useState(); const [source, setSource] = useState(""); const [values, setValues] = useState({}); const [edit, setEdit] = useState(false); const [terminal, setTerminal] = useState(false); const [chat, setChat] = useState(false); const [terminalOpened, setTerminalOpened] = useState(false); const [conflict, setConflict] = useState(false); const [error, setError] = useState(""); const [connected, setConnected] = useState(false); const [session, dispatch] = useReducer(eventReducer, emptySession); const [confirm, setConfirm] = useState(); const requests = useRef(new Map()); const [pending, setPending] = useState>(new Set()); const [checkIds, setCheckIds] = useState([]); const loadSequence = useRef(0); const dirty = !!doc && source !== doc.source; const current = useRef({ doc, dirty, source }); current.current = { doc, dirty, source }; const load = useCallback( async (path: string) => { const sequence = ++loadSequence.current; const sourceAtRequest = current.current.source; try { const next = await api.notebook(path); if (sequence !== loadSequence.current) return; const same = current.current.doc?.path === path; if ( current.current.dirty && current.current.source !== sourceAtRequest ) { setConflict(true); return; } setDoc(next); setSource(next.source); setConflict(false); setError(""); if (!same) { setValues({}); setEdit(false); setCheckIds([]); } } catch (e) { setError(String(e)); } }, [api], ); useEffect(() => { void api .me() .then(() => setAuth("ready")) .catch((e) => { if (e instanceof HttpError && e.status === 401) { setAuth("login"); void settingsApi.setupStatus() .then(status => { if (status.required) setAuth("setup"); }) .catch(() => {}); } else setError(String(e)); }); }, [api]); useEffect(() => { if (auth !== "ready") return; let active = true; void Promise.all([api.list(), api.hosts()]) .then(([notebooks, inventory]) => { if (!active) return; setList(notebooks.notebooks); setHosts(inventory.hosts); if (notebooks.notebooks[0]) void load(notebooks.notebooks[0].path); }) .catch((e) => setError(String(e))); const close = api.events((event: ServerEvent) => { if ((event.type === "file.changed" || event.type === "file.deleted") && event.path === "hosts.yaml") { void api.hosts().then(result => setHosts(result.hosts)).catch(e => setError(String(e))); window.dispatchEvent(new Event("shellbook:hosts-changed")); return; } const open = current.current; if (event.type === "file.changed" || event.type === "file.deleted") { void api .list() .then((result) => { if (active) setList(result.notebooks); }) .catch((e) => setError(String(e))); } // A changed included notebook changes the composed one; a draft keeps its own copy. if (event.type === "file.changed" && event.path !== open.doc?.path && open.doc?.includes.includes(event.path)) { if (!open.dirty) void load(open.doc.path); } else if (event.type === "file.changed" && event.path === open.doc?.path) { if (open.dirty) setConflict(true); else void load(event.path); } else if ( event.type === "file.deleted" && event.path === open.doc?.path ) { setConflict(true); setError("This notebook was deleted on disk. Your draft is retained."); } else dispatch(event); }, setConnected); return () => { active = false; close(); }; }, [api, auth, load]); useEffect(() => { const guard = (e: BeforeUnloadEvent) => { if (dirty) { e.preventDefault(); e.returnValue = ""; } }; window.addEventListener("beforeunload", guard); return () => window.removeEventListener("beforeunload", guard); }, [dirty]); // The saved notebook comes composed from the server; a draft shows its includes after saving. const notebook = doc ? edit && source !== doc.source ? parseNotebook(source) : doc.notebook : undefined; const path = doc?.path ?? ""; const hostNames = hosts.map((h) => h.name); const sessionRuntime = session.runtime[path] ?? {}; // Builtins ({{shellbook.public_key}}) come from the server, which also sets them on runs. const runtime = { ...sessionRuntime, ...doc?.builtins }; const resolved = notebook ? resolveParams(notebook, values, hostNames, runtime) : { values: {}, errors: {} }; const active = (id: string) => !!notebook && blockActive(notebook, id, resolved.values); const groups = notebook ? includedGroups(notebook.blocks).filter((group) => scopeActive(notebook, group.scope, resolved.values)) : []; const activeChecks = notebook ? steps(notebook.blocks).filter((s) => s.kind === "check" && active(s.attrs.id)) : []; const runnable = (step: Step) => { const rendered = renderStep(notebook!, step, resolved.values, runtime, hostNames); return !rendered.missing.length && !Object.keys(rendered.invalid).length; }; const runFor = (id: string) => session.runs[session.latest[stepKey(path, id)] ?? ""]; async function start(request: StartRunRequest) { const key = stepKey(request.notebookPath, request.stepId); setPending((previous) => new Set(previous).add(key)); try { const { runId } = await api.run(request); requests.current.set(runId, request); dispatch({ type: "requested", runId, request }); } catch (e) { setError(String(e)); } finally { setPending((previous) => { const next = new Set(previous); next.delete(key); return next; }); } } function requestRun(step: Step) { if (!notebook || !doc || dirty || !active(step.attrs.id)) return; const rendered = renderStep( notebook, step, resolved.values, runtime, hostNames, ); if ( rendered.missing.length || Object.keys(rendered.invalid).length || pending.has(stepKey(path, step.attrs.id)) ) return; const request: StartRunRequest = { notebookPath: path, stepId: step.attrs.id, params: { ...resolved.values }, runtime: { ...sessionRuntime }, artifactSources: { ...session.artifactSources[path] }, }; const host = hosts.find((h) => h.name === rendered.host); if ( step.kind === "run" && (step.attrs.confirm || host?.tags.includes("prod")) ) setConfirm(request); else void start(request); } function blocks(items: Block[]): React.ReactNode { if (!notebook) return null; return items.map((block, i) => { if (block.type === "markdown") return (
{renderText( block.text, { ...runtime, ...resolved.values }, notebook, )}
); if (block.type === "when") return block.values.includes(resolved.values[block.param] ?? "") ? (
{blocks(block.blocks)}
) : null; if (block.type === "use") return (
{block.title ?? block.path} {block.path} · as {block.scope} {block.blocks.length ? ( blocks(block.blocks) ) : (

Save the notebook to load {block.path}.

)}
); if (block.type === "host") { const rendered = renderHost(notebook, block, resolved.values, runtime, hostNames); const capture = (name: string) => { if (block.capture) dispatch({ type: "runtime.set", notebookPath: path, name: block.capture, value: name }); }; return ( h.name === rendered.name)} captured={block.capture ? runtime[block.capture] : undefined} onUse={capture} onAdd={async (host) => { await api.addHost(host); setHosts((await api.hosts()).hosts); window.dispatchEvent(new Event("shellbook:hosts-changed")); capture(host.name); }} /> ); } if (block.type === "after") { const run = runFor(block.stepId); return run && run.status === (block.onFailure ? "failure" : "success") ? (
{blocks(block.blocks)}
) : null; } const rendered = renderStep( notebook, block.step, resolved.values, runtime, hostNames, ); return ( h.name === rendered.host)} run={runFor(block.step.attrs.id)} artifact={api.artifact} onArtifactState={(runId, name, state) => dispatch({ type: "artifact.download", runId, name, state }) } connected={ connected && !dirty && !pending.has(stepKey(path, block.step.attrs.id)) } onRun={() => requestRun(block.step)} /> ); }); } async function save() { if (!doc) return; try { const saved = await api.save(path, source, doc.version); const parsed = parseNotebook(source); setDoc({ ...doc, source, notebook: parsed, version: saved.version, }); setConflict(false); // Includes are composed on the server: reload to show them. if (notebookIncludes(parsed).length || doc.includes.length) await load(path); } catch (e) { if (e instanceof HttpError && e.status === 409) setConflict(true); else setError(String(e)); } } const keyPrompt = Object.values(session.runs).find( (run) => run.status === "hostKey" && requests.current.has(run.runId), ); if (auth === "setup") return setAuth("ready")} />; if (auth === "login") return (

ShellBook

Sign in to your workspace

{ e.preventDefault(); void api .login(password) .then(() => { setPassword(""); setError(""); setAuth("ready"); }) .catch(() => { setPassword(""); setError("Login failed"); }); }} >
{error &&

{error}

}
); return (
{page === "Settings" && { setTerminalOpened(true); setTerminal(true); }} />} {page === "Hosts" && { void api.hosts().then(result => setHosts(result.hosts)).catch(e => setError(String(e))); }} />}
{chat && { if (!dirty || window.confirm("Discard unsaved edits?")) void load(path); }} openTerminal={() => { setChat(false); setTerminalOpened(true); setTerminal(true); }} />} {terminalOpened && ( Loading terminal...

}>
)} {confirm && (

Confirm execution

Run “{confirm.stepId}” with the displayed parameters? This step can change the target host.

)} {keyPrompt?.hostKey && dispatch({ type: "run.error", runId: keyPrompt.runId, message: "Host key rejected" })} onTrust={() => { const request = requests.current.get(keyPrompt.runId)!; dispatch({ type: "run.error", runId: keyPrompt.runId, message: "Retrying with accepted host key" }); void start({ ...request, acceptHostKey: keyPrompt.hostKey!.fingerprint }); }} />}
); }