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.
This commit is contained in:
Florian Schmidt
2026-11-16 11:42:12 +01:00
parent 28e806d641
commit 845d6c828e
24 changed files with 1407 additions and 136 deletions
+98 -24
View File
@@ -13,10 +13,14 @@ import {
} from "react";
import ReactMarkdown from "react-markdown";
import {
blockActive,
notebookIncludes,
parseNotebook,
renderHost,
renderStep,
renderText,
resolveParams,
scopeActive,
} from "@shellbook/core";
import type {
Block,
@@ -34,7 +38,8 @@ import { HostsPage } from "./HostsPage";
import { HttpError } from "./api";
import type { Api } from "./api";
import { emptySession, eventReducer, stepKey } from "./events";
import { ParamsForm } from "./ParamsForm";
import { ParamsForm, type ParamGroup } from "./ParamsForm";
import { HostBlockCard } from "./HostBlockCard";
import { StepCard } from "./StepCard";
import { ChatPanel } from "./ChatPanel";
const TerminalSlot = lazy(() =>
@@ -48,8 +53,18 @@ function steps(blocks: Block[]): Step[] {
return blocks.flatMap((block) =>
block.type === "step"
? [block.step]
: block.type === "after"
? steps(block.blocks)
: 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)
: [],
);
}
@@ -146,7 +161,10 @@ export function App({ api }: { api: Api }) {
})
.catch((e) => setError(String(e)));
}
if (event.type === "file.changed" && event.path === open.doc?.path) {
// 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 (
@@ -173,20 +191,31 @@ export function App({ api }: { api: Api }) {
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
? edit && source !== doc.source
? parseNotebook(source)
: doc.notebook
: undefined;
const resolved = notebook
? resolveParams(
notebook,
values,
hosts.map((h) => h.name),
)
: { values: {}, errors: {} };
const path = doc?.path ?? "";
const runtime = session.runtime[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) {
@@ -207,13 +236,13 @@ export function App({ api }: { api: Api }) {
}
}
function requestRun(step: Step) {
if (!notebook || !doc || dirty) return;
if (!notebook || !doc || dirty || !active(step.attrs.id)) return;
const rendered = renderStep(
notebook,
step,
resolved.values,
runtime,
hosts.map((h) => h.name),
hostNames,
);
if (
rendered.missing.length ||
@@ -225,7 +254,7 @@ export function App({ api }: { api: Api }) {
notebookPath: path,
stepId: step.attrs.id,
params: { ...resolved.values },
runtime: { ...runtime },
runtime: { ...sessionRuntime },
artifactSources: { ...session.artifactSources[path] },
};
const host = hosts.find((h) => h.name === rendered.host);
@@ -251,6 +280,49 @@ export function App({ api }: { api: Api }) {
</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 &&
@@ -265,7 +337,7 @@ export function App({ api }: { api: Api }) {
block.step,
resolved.values,
runtime,
hosts.map((h) => h.name),
hostNames,
);
return (
<StepCard
@@ -292,13 +364,16 @@ export function App({ api }: { api: Api }) {
if (!doc) return;
try {
const saved = await api.save(path, source, doc.version);
const parsed = parseNotebook(source);
setDoc({
...doc,
source,
notebook: parseNotebook(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));
@@ -428,6 +503,7 @@ export function App({ api }: { api: Api }) {
values={resolved.values}
errors={resolved.errors}
hosts={hosts}
groups={groups}
onChange={(name, value) =>
setValues((previous) => ({ ...previous, [name]: value }))
}
@@ -472,7 +548,8 @@ export function App({ api }: { api: Api }) {
disabled={
!connected ||
dirty ||
Object.keys(resolved.errors).length > 0 ||
activeChecks.length === 0 ||
!activeChecks.every(runnable) ||
steps(notebook.blocks).some(
(s) =>
runFor(s.attrs.id)?.status === "running" ||
@@ -480,11 +557,8 @@ export function App({ api }: { api: Api }) {
)
}
onClick={() => {
const checks = steps(notebook.blocks).filter(
(s) => s.kind === "check",
);
setCheckIds(checks.map((s) => s.attrs.id));
checks.forEach(requestRun);
setCheckIds(activeChecks.map((s) => s.attrs.id));
activeChecks.forEach(requestRun);
}}
>
Run all checks
+67
View File
@@ -3,8 +3,11 @@ import { parseNotebook, type ParamDef } from "@shellbook/core";
import {
addParameter,
afterSnippet,
hostSnippet,
notebookSteps,
stepSnippet,
useSnippet,
whenSnippet,
type InsertKind,
} from "./authoring";
export function AuthoringToolbar({
@@ -23,7 +26,13 @@ export function AuthoringToolbar({
const [error, setError] = useState("");
const [type, setType] = useState<ParamDef["type"]>("string");
const [after, setAfter] = useState("");
const [when, setWhen] = useState("");
const [include, setInclude] = useState(false);
const steps = notebookSteps(notebook.blocks);
const choices = notebook.params.flatMap((p) =>
p.type === "choice" ? (p.options ?? []).map((o) => ({ param: p.name, option: o })) : [],
);
const selected = choices.find((c) => JSON.stringify([c.param, c.option]) === when);
return (
<div className="authoring">
<label>
@@ -77,6 +86,56 @@ export function AuthoringToolbar({
>
Insert after note
</button>
<label>
Show when
<select value={when} onChange={(e) => setWhen(e.target.value)}>
<option value="">Choose an option</option>
{choices.map((c) => (
<option key={JSON.stringify([c.param, c.option])} value={JSON.stringify([c.param, c.option])}>
{c.param} = {c.option}
</option>
))}
</select>
</label>
<button
type="button"
disabled={!selected}
onClick={() => selected && insert(whenSnippet(selected.param, selected.option))}
>
Insert when section
</button>
<button type="button" onClick={() => setInclude(!include)}>
Use notebook
</button>
<button type="button" onClick={() => insert(hostSnippet())}>
Add host
</button>
{include && (
<form
aria-label="Use notebook"
onSubmit={(e) => {
e.preventDefault();
const data = new FormData(e.currentTarget);
try {
insert(useSnippet(String(data.get("path")), String(data.get("alias"))));
setInclude(false);
setError("");
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
}}
>
<label>
Notebook path
<input name="path" required placeholder="infra/lxc-container.md" />
</label>
<label>
Alias
<input name="alias" required pattern="[A-Za-z_][A-Za-z0-9_]*" placeholder="ct" />
</label>
<button>Insert include</button>
</form>
)}
{param && (
<form
onSubmit={(e) => {
@@ -160,6 +219,14 @@ export function AuthoringToolbar({
upload="file.txt:/tmp/file.txt". After notes appear when their
selected step succeeds.
</p>
<p>
Chaining: {'::use{notebook="infra/lxc-container.md" as=ct with="hostname={{name}}"}'}{" "}
includes another notebook; its parameters appear as ct.name and its
captures as {"{{ct.address}}"}. {":::when{target=lxc}"} … {":::"} shows a
section only for that choice. {'::host{name="{{hostname}}" address="{{address}}" capture=host}'}{" "}
adds a created machine to Hosts. {"{{shellbook.public_key}}"} is
ShellBook's SSH public key.
</p>
<p>
Artifact and upload snippets are examples: choose files and commands
appropriate to your runbook before running.
+99
View File
@@ -0,0 +1,99 @@
import { useState } from "react";
import type { HostInfo, RenderedHost } from "@shellbook/core";
/**
* A notebook's `::host` block: adds the machine a notebook created (e.g. an LXC container)
* to Hosts, so later steps can target it. Never overwrites a different existing host.
*/
export function HostBlockCard({
rendered,
existing,
captured,
onAdd,
onUse,
}: {
rendered: RenderedHost;
/** Host with the same name already in Hosts. */
existing?: HostInfo;
/** Runtime value of the block's capture, if any. */
captured?: string;
onAdd(host: HostInfo): Promise<void>;
onUse(name: string): void;
}) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const problems = Object.entries(rendered.invalid);
const ready = !rendered.missing.length && !problems.length;
const same =
!!existing &&
existing.address === rendered.address &&
existing.user === rendered.user &&
existing.port === rendered.port;
async function add() {
setBusy(true);
setError("");
try {
await onAdd({
name: rendered.name,
address: rendered.address,
user: rendered.user,
port: rendered.port,
tags: [],
});
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
}
return (
<article className="step host-block" aria-label={`Add host ${rendered.name}`}>
<header>
<strong>Add to Hosts</strong>
<code>
{rendered.user}@{rendered.address}:{rendered.port}
</code>
<span>as {rendered.name}</span>
</header>
{rendered.missing.length > 0 && (
<p className="muted">
Available after: {rendered.missing.join(", ")}
</p>
)}
{problems.map(([field, message]) => (
<p className="error" key={field}>
{message}
</p>
))}
{ready &&
(existing ? (
same ? (
captured === existing.name ? (
<p role="status">✓ {existing.name} is in Hosts</p>
) : (
<button onClick={() => onUse(existing.name)}>
Use existing host {existing.name}
</button>
)
) : (
<p className="error" role="alert">
A different host named {rendered.name} already exists. Choose
another name or change it under Hosts.
</p>
)
) : (
<button className="primary" disabled={busy} onClick={() => void add()}>
{busy ? "Adding…" : "Add to Hosts"}
</button>
))}
{error && (
<p className="error" role="alert">
{error}
</p>
)}
<p className="muted">
The first connection asks you to confirm the new server's host key.
</p>
</article>
);
}
+65 -45
View File
@@ -1,68 +1,88 @@
import type { HostInfo, Notebook, ParamValues } from "@shellbook/core";
import type { HostInfo, Notebook, ParamDef, ParamValues } from "@shellbook/core";
/** An included notebook (`::use`) whose parameters the form shows as a group. */
export interface ParamGroup {
scope: string;
title: string;
}
export function ParamsForm({
notebook,
values,
errors,
hosts,
groups = [],
onChange,
}: {
notebook: Notebook;
values: ParamValues;
errors: Record<string, string>;
hosts: HostInfo[];
/** Active included notebooks; parameters of inactive ones are hidden. */
groups?: ParamGroup[];
onChange(name: string, value: string): void;
}) {
const field = (param: ParamDef) => {
const id = `param-${param.name}`;
const local = param.scope ? param.name.slice(param.scope.length + 1) : param.name;
const common = {
id,
required: param.required,
value: values[param.name] ?? "",
"aria-labelledby": `${id}-label`,
"aria-invalid": !!errors[param.name],
"aria-describedby": errors[param.name] ? `${id}-error` : undefined,
onChange: (
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
) => onChange(param.name, e.target.value),
};
return (
<label key={param.name} htmlFor={id}>
<span id={`${id}-label`}>
{param.label ?? local}
{param.required && <b title="Required"> *</b>}
</span>
{param.type === "host" || param.type === "choice" ? (
<select {...common}>
<option value="">Select…</option>
{(param.type === "host"
? hosts.map((h) => h.name)
: (param.options ?? [])
).map((option) => (
<option key={option}>{option}</option>
))}
</select>
) : (
<input
{...common}
type={param.type === "secret" ? "password" : "text"}
autoComplete={param.type === "secret" ? "new-password" : "off"}
spellCheck={false}
/>
)}
{errors[param.name] && (
<small id={`${id}-error`} className="error">
{errors[param.name]}
</small>
)}
</label>
);
};
return (
<form
className="params"
aria-label="Notebook parameters"
onSubmit={(e) => e.preventDefault()}
>
{notebook.params.map((param) => {
const id = `param-${param.name}`;
const common = {
id,
required: param.required,
value: values[param.name] ?? "",
"aria-labelledby": `${id}-label`,
"aria-invalid": !!errors[param.name],
"aria-describedby": errors[param.name] ? `${id}-error` : undefined,
onChange: (
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
) => onChange(param.name, e.target.value),
};
return (
<label key={param.name} htmlFor={id}>
<span id={`${id}-label`}>
{param.label ?? param.name}
{param.required && <b title="Required"> *</b>}
</span>
{param.type === "host" || param.type === "choice" ? (
<select {...common}>
<option value="">Select…</option>
{(param.type === "host"
? hosts.map((h) => h.name)
: (param.options ?? [])
).map((option) => (
<option key={option}>{option}</option>
))}
</select>
) : (
<input
{...common}
type={param.type === "secret" ? "password" : "text"}
autoComplete={param.type === "secret" ? "new-password" : "off"}
spellCheck={false}
/>
)}
{errors[param.name] && (
<small id={`${id}-error`} className="error">
{errors[param.name]}
</small>
)}
</label>
);
{notebook.params.filter((param) => !param.scope).map(field)}
{groups.map((group) => {
const params = notebook.params.filter((param) => param.scope === group.scope);
return params.length ? (
<fieldset key={group.scope}>
<legend>{group.title}</legend>
{params.map(field)}
</fieldset>
) : null;
})}
</form>
);
+10
View File
@@ -1,4 +1,7 @@
import type {
HostInfo,
HostInventoryResponse,
SaveHostRequest,
NotebookListResponse,
HostsResponse,
NotebookResponse,
@@ -66,6 +69,8 @@ export interface Api {
baseVersion: string,
): Promise<SaveNotebookResponse>;
run(request: StartRunRequest): Promise<StartRunResponse>;
/** Add a host to the inventory (a notebook's `::host` block); 409 if the name is taken. */
addHost(host: HostInfo): Promise<void>;
events(
receive: (event: ServerEvent) => void,
connection: (connected: boolean) => void,
@@ -93,6 +98,11 @@ export const liveApi: Api = {
baseVersion,
}),
run: (request) => json("/runs", "POST", request),
async addHost(host) {
const { version } = await json<HostInventoryResponse>("/host-management");
const request: SaveHostRequest = { host, baseVersion: version };
await json("/host-management", "POST", request);
},
artifact: (id, name) =>
`/api/runs/${encodeURIComponent(id)}/artifacts/${encodeURIComponent(name)}`,
events(receive, connection) {
+19 -3
View File
@@ -1,5 +1,6 @@
import { isMap, parseDocument } from "yaml";
import {
includePath,
parseNotebook,
type Block,
type ParamDef,
@@ -9,9 +10,9 @@ export function notebookSteps(blocks: Block[]): Step[] {
return blocks.flatMap((b) =>
b.type === "step"
? [b.step]
: b.type === "after"
? notebookSteps(b.blocks)
: [],
: b.type === "markdown" || b.type === "host"
? []
: notebookSteps(b.blocks),
);
}
const attr = (value: string) =>
@@ -60,6 +61,21 @@ export function stepSnippet(
export function afterSnippet(id: string): string {
return `\n\n:::after{step=${attr(id)}}\nAdd follow-up instructions here.\n:::\n`;
}
/** A section shown (and runnable) only while a choice parameter has this value. */
export function whenSnippet(param: string, value: string): string {
return `\n\n:::when{${param}=${attr(value)}}\nShown only when ${param} is ${value.replace(/[\r\n]/g, " ")}.\n:::\n`;
}
/** Include another notebook; its parameters and steps are namespaced as alias.name. */
export function useSnippet(path: string, alias: string): string {
if (!includePath(path)) throw new Error("Notebook path must be dir/name.md relative to notebooks/");
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(alias) || alias === "shellbook")
throw new Error("Alias must use letters, digits or _ (not shellbook)");
return `\n\n::use{notebook=${attr(path)} as=${alias}}\n`;
}
/** Add the machine a notebook created to Hosts; replace the example templates. */
export function hostSnippet(): string {
return '\n\n::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}\n';
}
export function addParameter(source: string, def: ParamDef): string {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(def.name))
throw new Error("Invalid parameter name");
+14 -1
View File
@@ -41,10 +41,23 @@ export type Action =
state: DownloadState;
}
| ServerEvent
| { type: "requested"; runId: string; request: StartRunRequest };
| { type: "requested"; runId: string; request: StartRunRequest }
/** A runtime value set in the browser, e.g. by a `::host` block's capture. */
| { type: "runtime.set"; notebookPath: string; name: string; value: string };
export function eventReducer(state: Session, event: Action): Session {
if (event.type === "file.changed" || event.type === "file.deleted")
return state;
if (event.type === "runtime.set")
return {
...state,
runtime: {
...state.runtime,
[event.notebookPath]: {
...state.runtime[event.notebookPath],
[event.name]: event.value,
},
},
};
if (event.type === "requested" || event.type === "run.started") {
const info = event.type === "requested" ? event.request : event;
const previous = state.runs[event.runId];
+12 -8
View File
@@ -1,7 +1,7 @@
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
import type { Api } from "../api";
import { HttpError } from "../api";
import { parseNotebook, renderStep } from "@shellbook/core";
import { findStep, parseNotebook, renderStep } from "@shellbook/core";
import initial from "./ssh-key.md?raw";
let source = initial;
let version = 1;
@@ -50,8 +50,14 @@ export const mockApi: Api = {
path,
source,
notebook: parseNotebook(source),
includes: [],
builtins: { "shellbook.public_key": "ssh-ed25519 AAAADEMO shellbook" },
version: String(version),
}),
addHost: async (host) => {
if (hosts.some((h) => h.name === host.name)) throw new HttpError(409, "Host already exists");
hosts.push({ ...host });
},
save: async (_path, next, base) => {
if (base !== String(version)) throw new HttpError(409);
source = next;
@@ -68,13 +74,11 @@ export const mockApi: Api = {
artifact: () => artifactUrl,
run: async (request: StartRunRequest) => {
const notebook = parseNotebook(source);
const block = notebook.blocks.find(
(b) => b.type === "step" && b.step.attrs.id === request.stepId,
);
if (!block || block.type !== "step") throw new Error("Unknown demo step");
const step = findStep(notebook.blocks, request.stepId);
if (!step) throw new Error("Unknown demo step");
const rendered = renderStep(
notebook,
block.step,
step,
request.params,
request.runtime,
hosts.map((h) => h.name),
@@ -125,8 +129,8 @@ export const mockApi: Api = {
request.stepId === "keygen"
? rendered.artifacts.filter((name) => !name.endsWith(".pub"))
: [],
captured: block.step.attrs.capture
? { name: block.step.attrs.capture, value: "demo-value" }
captured: step.attrs.capture
? { name: step.attrs.capture, value: "demo-value" }
: undefined,
});
}, 850);
+42
View File
@@ -152,6 +152,25 @@ main {
.params b {
color: var(--accent);
}
.params {
max-height: 40vh;
overflow-y: auto;
}
.params fieldset {
flex-basis: 100%;
display: flex;
flex-wrap: wrap;
gap: 12px;
margin: 0;
border: 1px solid var(--line);
border-radius: 6px;
padding: 8px 12px 12px;
}
.params legend {
font-size: 12px;
color: var(--muted);
padding: 0 4px;
}
.notebook {
max-width: 1100px;
margin: auto;
@@ -279,6 +298,29 @@ a {
border-left: 3px solid var(--accent);
padding-left: 18px;
}
/* Chained notebooks (::use): the included notebook, collapsible. */
.included {
border: 1px dashed var(--line);
border-radius: 7px;
padding: 4px 18px;
margin: 20px 0;
}
.included > summary {
cursor: pointer;
padding: 10px 0;
font-weight: 600;
}
.included > summary small {
font-weight: normal;
color: var(--muted);
margin-left: 8px;
}
.host-block > p {
margin: 10px 16px;
}
.host-block > button {
margin: 10px 16px;
}
.banner {
padding: 14px 24px;
background: var(--panel);
+7
View File
@@ -62,9 +62,12 @@ function harness() {
path: "ssh-key.md",
source,
notebook: parseNotebook(source),
includes: [],
builtins: {},
version: "1",
}),
save: vi.fn().mockResolvedValue({ version: "2" }),
addHost: vi.fn().mockResolvedValue(undefined),
run: vi.fn(async (_request: StartRunRequest) => ({ runId: String(++id) })),
events: (callback, connected) => {
receive = callback;
@@ -215,6 +218,8 @@ it("retains edits made while a file reload is in flight", async () => {
path: "ssh-key.md",
source,
notebook: parseNotebook(source),
includes: [],
builtins: {},
version: "2",
}),
);
@@ -247,6 +252,8 @@ Key generation failed. Retry safely.
path: "ssh-key.md",
source: captureSource,
notebook: parseNotebook(captureSource),
includes: [],
builtins: {},
version: "1",
});
await ready(api);
+11
View File
@@ -78,3 +78,14 @@ it("adds frontmatter when absent and rejects invalid YAML or secret defaults", (
}),
).toThrow();
});
it("generates valid chaining snippets", async () => {
const { whenSnippet, useSnippet, hostSnippet } = await import("../authoring");
const base = "---\nparams:\n target: {type: choice, options: [existing, lxc]}\n hostname: {type: name}\n address: {type: string}\n---\n";
const source = base + whenSnippet("target", "lxc") + useSnippet("infra/lxc-container.md", "ct") + hostSnippet();
const notebook = parseNotebook(source);
expect(notebook.diagnostics).toEqual([]);
expect(notebook.blocks.map((b) => b.type).filter((t) => t !== "markdown")).toEqual(["when", "use", "host"]);
expect(() => useSnippet("../x.md", "ct")).toThrow("dir/name.md");
expect(() => useSnippet("x.md", "shellbook")).toThrow("Alias");
});
+106
View File
@@ -0,0 +1,106 @@
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { expect, it, vi } from "vitest";
vi.mock("../Editor", () => ({ Editor: () => null }));
import { App } from "../App";
import type { Api } from "../api";
import type { HostInfo, ServerEvent, StartRunRequest } from "@shellbook/core";
import { composeNotebook, parseNotebook } from "@shellbook/core";
const lxc = `---
title: LXC container
params:
proxmox: {type: host, required: true}
hostname: {type: name, required: true}
---
\`\`\`sh {run host="{{proxmox}}" id=create title="Create container" capture=address}
pct create --hostname {{hostname}} --key {{shellbook.public_key}}
\`\`\`
::host{name="{{hostname}}" address="{{address}}" capture=host}
`;
const service = `---
title: Web server
params:
target: {type: choice, options: [existing, lxc], default: existing}
host: {type: host, required: true, default: "{{ct.host}}"}
---
:::when{target=lxc}
::use{notebook="infra/lxc.md" as=ct with="hostname=web-ct"}
:::
\`\`\`sh {check host="{{host}}" id=installed title="Is nginx installed"}
command -v nginx
\`\`\`
`;
const files: Record<string, string> = { "infra/lxc.md": lxc };
const composed = composeNotebook("web.md", parseNotebook(service), p => files[p] === undefined ? undefined : parseNotebook(files[p]!));
function harness() {
let receive: (event: ServerEvent) => void = () => {};
const hosts: HostInfo[] = [{ name: "pve", address: "10.0.0.2", user: "root", port: 22, tags: [] }];
const api: Api = {
create: vi.fn(), move: vi.fn(), deleteNotebook: vi.fn(),
me: vi.fn().mockResolvedValue({}),
login: vi.fn(),
list: vi.fn().mockResolvedValue({ notebooks: [{ path: "web.md", title: "Web server" }] }),
hosts: vi.fn(async () => ({ hosts: [...hosts] })),
notebook: vi.fn().mockResolvedValue({
path: "web.md", source: service, notebook: composed, includes: ["infra/lxc.md"],
builtins: { "shellbook.public_key": "ssh-ed25519 AAAA shellbook" }, version: "1",
}),
save: vi.fn(),
run: vi.fn(async (_request: StartRunRequest) => ({ runId: "1" })),
addHost: vi.fn(async (host: HostInfo) => { hosts.push(host); }),
events: (callback, connected) => { receive = callback; connected(true); return () => {}; },
artifact: () => "/download",
};
return { api, emit: (event: ServerEvent) => act(() => receive(event)) };
}
it("shows the included notebook and its parameters only for the selected option", async () => {
const { api } = harness();
render(<App api={api} />);
const target = await screen.findByLabelText("target");
expect(screen.queryByRole("article", { name: "Create container" })).not.toBeInTheDocument();
expect(screen.queryByRole("group", { name: "LXC container (ct)" })).not.toBeInTheDocument();
fireEvent.change(target, { target: { value: "lxc" } });
const group = screen.getByRole("group", { name: "LXC container (ct)" });
expect(within(group).getByLabelText("hostname *")).toHaveValue("web-ct");
fireEvent.change(within(group).getByLabelText("proxmox *"), { target: { value: "pve" } });
const create = screen.getByRole("article", { name: "Create container" });
expect(create).toHaveTextContent("pct create --hostname web-ct --key 'ssh-ed25519 AAAA shellbook'");
// The parent's host waits for the container; the parent's checks cannot run yet.
expect(screen.getByText("Available after the step that sets ct.host")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Run all checks" })).toBeDisabled();
});
it("adds the created container to Hosts and feeds it into the parent's steps", async () => {
const { api, emit } = harness();
render(<App api={api} />);
fireEvent.change(await screen.findByLabelText("target"), { target: { value: "lxc" } });
fireEvent.change(screen.getByLabelText("proxmox *"), { target: { value: "pve" } });
const card = screen.getByRole("article", { name: "Add host web-ct" });
expect(card).toHaveTextContent("Available after: ct.address");
fireEvent.click(within(screen.getByRole("article", { name: "Create container" })).getByRole("button", { name: "Run" }));
await waitFor(() => expect(api.run).toHaveBeenCalledTimes(1));
const request = vi.mocked(api.run).mock.calls[0]![0];
expect(request).toMatchObject({ stepId: "ct.create", params: { target: "lxc", "ct.proxmox": "pve", "ct.hostname": "web-ct" } });
// Builtins are the server's; the client never sends them.
expect(request.runtime).toEqual({});
emit({ type: "run.finished", runId: "1", exitCode: 0, durationMs: 5, artifacts: [], captured: { name: "ct.address", value: "10.0.30.160" } });
fireEvent.click(within(card).getByRole("button", { name: "Add to Hosts" }));
await waitFor(() => expect(api.addHost).toHaveBeenCalledWith({ name: "web-ct", address: "10.0.30.160", user: "root", port: 22, tags: [] }));
expect(await within(card).findByRole("status")).toHaveTextContent("web-ct is in Hosts");
expect(screen.getByLabelText("host *")).toHaveValue("web-ct");
expect(screen.getByRole("article", { name: "Is nginx installed" })).toHaveTextContent("web-ct");
expect(screen.getByRole("button", { name: "Run all checks" })).toBeEnabled();
});
it("reloads when an included notebook changes", async () => {
const { api, emit } = harness();
render(<App api={api} />);
await screen.findByLabelText("target");
expect(api.notebook).toHaveBeenCalledTimes(1);
emit({ type: "file.changed", path: "infra/lxc.md" });
await waitFor(() => expect(api.notebook).toHaveBeenCalledTimes(2));
});