Files
ShellBook/apps/web/src/App.tsx
T
Florian Schmidt 845d6c828e feat: chained notebooks with when sections and host blocks (#11)
A notebook can include another one and continue with what it produced:

- core: parse :::when{param=a,b}, ::use{notebook= as= with=} and
  ::host{name= address= user= port= capture=}; composeNotebook namespaces
  an included notebook's params, steps, captures and templates by alias
  (cycles, missing files, depth > 4 and child errors are reported on the
  use line). Defaults may reference captures and builtins
  ({{shellbook.public_key}}); required params and secrets gate only steps
  of their own scope; secretEnv passes a scope's secrets under local names.
- protocol: NotebookResponse gains includes and builtins.
- server: compose includes on load, inject builtins (client values are
  ignored), refuse steps in inactive when sections.
- web: render when/use/host blocks, group included params in the form,
  add a created machine to Hosts and capture its name, reload when an
  included notebook changes, run all checks only for active steps,
  authoring snippets for when, use and host.
2026-11-16 11:42:12 +01:00

632 lines
21 KiB
TypeScript

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<NavigationPage>("Notebooks");
const [password, setPassword] = useState("");
const [list, setList] = useState<NotebookSummary[]>([]);
const [hosts, setHosts] = useState<HostInfo[]>([]);
const [doc, setDoc] = useState<NotebookResponse>();
const [source, setSource] = useState("");
const [values, setValues] = useState<ParamValues>({});
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<StartRunRequest>();
const requests = useRef(new Map<string, StartRunRequest>());
const [pending, setPending] = useState<Set<string>>(new Set());
const [checkIds, setCheckIds] = useState<string[]>([]);
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 (
<div className="prose" key={i}>
<ReactMarkdown>
{renderText(
block.text,
{ ...runtime, ...resolved.values },
notebook,
)}
</ReactMarkdown>
</div>
);
if (block.type === "when")
return block.values.includes(resolved.values[block.param] ?? "") ? (
<div className="when" key={i}>
{blocks(block.blocks)}
</div>
) : null;
if (block.type === "use")
return (
<details className="included" open key={i}>
<summary>
{block.title ?? block.path}
<small>
{block.path} · as {block.scope}
</small>
</summary>
{block.blocks.length ? (
blocks(block.blocks)
) : (
<p className="muted">Save the notebook to load {block.path}.</p>
)}
</details>
);
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 (
<HostBlockCard
key={block.id}
rendered={rendered}
existing={hosts.find((h) => 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") ? (
<section className="after" key={i}>
{blocks(block.blocks)}
</section>
) : null;
}
const rendered = renderStep(
notebook,
block.step,
resolved.values,
runtime,
hostNames,
);
return (
<StepCard
key={block.step.attrs.id}
step={block.step}
rendered={rendered}
host={hosts.find((h) => 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 <SetupScreen onComplete={() => setAuth("ready")} />;
if (auth === "login")
return (
<main className="login">
<h1>ShellBook</h1>
<p>Sign in to your workspace</p>
<form
onSubmit={(e) => {
e.preventDefault();
void api
.login(password)
.then(() => {
setPassword("");
setError("");
setAuth("ready");
})
.catch(() => {
setPassword("");
setError("Login failed");
});
}}
>
<label>
Password
<input
autoFocus
type="password"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</label>
<button className="primary">Sign in</button>
</form>
{error && <p role="alert">{error}</p>}
</main>
);
return (
<div className={`app ${terminal || chat ? "with-terminal" : ""}`}>
<aside className="sidebar">
<h1>
ShellBook<span>RUNBOOKS</span>
</h1>
<NotebookList
api={api}
list={list}
path={path}
version={doc?.version}
canLeave={() => !dirty || window.confirm("Discard unsaved edits?")}
onSelect={(next) => {
if (!dirty || window.confirm("Discard unsaved edits?"))
void load(next);
}}
onChanged={async (next) => {
const result = await api.list();
setList(result.notebooks);
if (next) await load(next);
else {
++loadSequence.current;
setDoc(undefined);
setSource("");
setConflict(false);
}
}}
/>
<small className="connection">
{import.meta.env.VITE_MOCK === "1" ? "DEMO · " : ""}
{connected
? "● Events connected"
: "○ Events disconnected · reload to reconnect"}
</small>
</aside>
<main>
<HeaderNavigation page={page} onChange={setPage} />
{page === "Settings" && <SettingsPage openTerminal={() => { setTerminalOpened(true); setTerminal(true); }} />}
{page === "Hosts" && <HostsPage onChange={() => { void api.hosts().then(result => setHosts(result.hosts)).catch(e => setError(String(e))); }} />}
<div hidden={page !== "Notebooks"}>
<div className="toolbar">
<button aria-expanded={chat} onClick={() => { setChat(!chat); setTerminal(false); }}>Chat</button>
<span>{doc?.notebook.title ?? "Loading workspace…"}</span>
<button onClick={() => setEdit(!edit)}>
{edit ? "Close editor" : "Edit Markdown"}
</button>
<button
aria-expanded={terminal}
onClick={() => {
setTerminalOpened(true);
setChat(false);
setTerminal(!terminal);
}}
>
Terminal {terminal ? "→" : "←"}
</button>
</div>
{error && (
<p className="banner error" role="alert">
{error}
<button onClick={() => location.reload()}>Retry</button>
</p>
)}
{conflict && (
<div className="banner error" role="alert">
The file changed on disk. Your draft has been retained.
<button
onClick={() => {
if (!dirty || window.confirm("Discard your draft and reload?"))
void load(path);
}}
>
Reload from disk
</button>
</div>
)}
{notebook && (
<>
<ParamsForm
notebook={notebook}
values={resolved.values}
errors={resolved.errors}
hosts={hosts}
groups={groups}
onChange={(name, value) =>
setValues((previous) => ({ ...previous, [name]: value }))
}
/>
<div className="notebook">
{edit && (
<section>
<div className="actions">
<strong>Markdown editor {dirty ? "· unsaved" : ""}</strong>
<button
className="primary"
disabled={
!dirty ||
conflict ||
notebook.diagnostics.some((d) => d.severity === "error")
}
onClick={() => void save()}
>
Save
</button>
</div>
<Suspense fallback={<p>Loading editor…</p>}>
<Editor
key={`${path}:${doc?.version}`}
source={source}
onChange={setSource}
/>
</Suspense>
<p className="muted">
Live preview below. Save changes before running steps.
</p>
</section>
)}
{notebook.diagnostics.map((d, i) => (
<p role="alert" className="error" key={i}>
{d.line && `Line ${d.line}: `}
{d.message}
</p>
))}
<div className="actions">
<button
disabled={
!connected ||
dirty ||
activeChecks.length === 0 ||
!activeChecks.every(runnable) ||
steps(notebook.blocks).some(
(s) =>
runFor(s.attrs.id)?.status === "running" ||
pending.has(stepKey(path, s.attrs.id)),
)
}
onClick={() => {
setCheckIds(activeChecks.map((s) => s.attrs.id));
activeChecks.forEach(requestRun);
}}
>
Run all checks
</button>
{checkIds.length > 0 && (
<span role="status">
✅{" "}
{
checkIds.filter((id) => runFor(id)?.status === "success")
.length
}{" "}
/ {checkIds.length} · ❌{" "}
{
checkIds.filter((id) => runFor(id)?.status === "failure")
.length
}
</span>
)}
</div>
{blocks(notebook.blocks)}
</div>
</>
)}
</div>
</main>
{chat && <ChatPanel notebookPath={doc?.path} openNotebook={path => {
if (!dirty || window.confirm("Discard unsaved edits?")) void load(path);
}} openTerminal={() => { setChat(false); setTerminalOpened(true); setTerminal(true); }} />}
{terminalOpened && (
<Suspense fallback={<p>Loading terminal...</p>}>
<TerminalSlot collapsed={!terminal} />
</Suspense>
)}
{confirm && (
<div className="modal-backdrop">
<section
role="dialog"
aria-modal="true"
aria-labelledby="confirm-title"
>
<h2 id="confirm-title">Confirm execution</h2>
<p>
Run “{confirm.stepId}” with the displayed parameters? This step
can change the target host.
</p>
<button onClick={() => setConfirm(undefined)}>Cancel</button>
<button
className="primary"
onClick={() => {
void start(confirm);
setConfirm(undefined);
}}
>
Confirm and run
</button>
</section>
</div>
)}
{keyPrompt?.hostKey && <HostKeyConfirmation
{...keyPrompt.hostKey}
onReject={() => 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 });
}}
/>}
</div>
);
}