Compare commits

..
4 Commits
Author SHA1 Message Date
Florian Schmidt 04771b74a1 docs(mind): record guided groups and step gating (#16) 2026-11-16 16:49:47 +01:00
Florian Schmidt 381c7f555e feat(web): parameter fields in the text and collapsible groups (#16)
Inline fields share the value with the parameter panel. Groups and
included notebooks render as collapsible sections whose outline shows
the input status (orange missing, green complete, grey optional) and
remember their open state. The panel groups use the same colors. The
authoring toolbar inserts groups and fields; the demo serves the guided
example.
2026-11-16 16:49:47 +01:00
Florian Schmidt eb31de7120 feat(server): refuse runs only for values the step uses (#16)
Drop the scope-wide required-parameter check in prepareRun; renderStep's
missing and invalid lists are the single gate, matching the UI.
2026-11-16 16:49:47 +01:00
Florian Schmidt bdbcd2dcd5 feat(core): parameter fields in text, groups and gating by used values (#16)
- `::param{name=x}` places a parameter's input inside the text.
- `:::group{title="…" collapsed}` is a collapsible container for anything;
  groups are presentational and never gate steps. Included notebooks
  namespace field names and group titles.
- `groupInputs` reports a container's input status (missing, filled,
  optional, none) from its fields, the parameters its steps use and, for
  `::use`, the included notebook's parameters.
- A step is gated only by the values it uses: referenced parameters, the
  required secrets its script reads and valid set secrets of its scope.
  Unused required parameters no longer block early steps of a guided
  runbook.
- Spec §3.2/§3.6/§3.7, workspace format guide and a guided admin-user
  example notebook.
2026-11-16 16:49:47 +01:00
25 changed files with 1023 additions and 165 deletions
+2
View File
@@ -18,5 +18,7 @@
- [2026-11-16] **Collapsible parameters (#13):** the form and each included group collapse (remembered via `uiPrefs.ts`). Collapsed, only missing required values and values changed from their default are listed as chips; untouched defaults are just counted, so the bar stays one line. - [2026-11-16] **Collapsible parameters (#13):** the form and each included group collapse (remembered via `uiPrefs.ts`). Collapsed, only missing required values and values changed from their default are listed as chips; untouched defaults are just counted, so the bar stays one line.
- [2026-11-16] **Icon (#14):** `apps/web/public/shellbook.svg` (mint notebook with `>_` on a dark tile) is the single source for favicon, top bar, sign-in, setup and README. The PNGs (192, 512, 180 apple-touch on a full dark square) are rendered from it with headless Edge; give the SVG fixed px sizes, since headless Edge enforces a minimum viewport width and `100vw` overshoots. - [2026-11-16] **Icon (#14):** `apps/web/public/shellbook.svg` (mint notebook with `>_` on a dark tile) is the single source for favicon, top bar, sign-in, setup and README. The PNGs (192, 512, 180 apple-touch on a full dark square) are rendered from it with headless Edge; give the SVG fixed px sizes, since headless Edge enforces a minimum viewport width and `100vw` overshoots.
- [2026-11-16] **Self-update from Settings (#15):** the unprivileged service only writes `<data>/update-request`; root-owned `shellbook-update.path` (PathChanged) starts oneshot `shellbook-update.service` → fixed `/usr/local/sbin/shellbook-update`, output to `/var/log/shellbook-update.log`. Server reads `systemctl show --timestamp=unix` + log tail; UI polls through the restart and ignores runs that started before the request. Installs predating #15 need one CLI `shellbook-update` to get the units. - [2026-11-16] **Self-update from Settings (#15):** the unprivileged service only writes `<data>/update-request`; root-owned `shellbook-update.path` (PathChanged) starts oneshot `shellbook-update.service` → fixed `/usr/local/sbin/shellbook-update`, output to `/var/log/shellbook-update.log`. Server reads `systemctl show --timestamp=unix` + log tail; UI polls through the restart and ignores runs that started before the request. Installs predating #15 need one CLI `shellbook-update` to get the units.
- [2026-11-16] **Guided text and groups (#16):** `::param{name=x}` places a parameter's input in the text (same value as the panel); `:::group{title collapsed}` is a presentational container that never gates. Core `groupInputs` gives its outline status (missing=orange, filled=green, optional/none=grey) from its fields, the params its steps/hosts reference and, for `::use` sections, the included params. Collapse state is per `path:title` in localStorage.
- [2026-11-16] **Step gating = values used (#16):** a step needs only its referenced params/runtime values, the required secrets its script reads (`$NAME`/`${NAME}`) and valid set secrets of its scope (all go to env). Unused required params no longer block it, so guided notebooks run step 1 before later values exist. `renderStep` is the only gate; server `prepareRun` dropped its scope-wide check.
## Archive ## Archive
+1 -1
View File
@@ -15,7 +15,7 @@
- [2026-11-16] **Watcher timing tests:** full parallel test run on Windows delays fs events >100 ms; keep watcher test debounce/quiet windows generous. - [2026-11-16] **Watcher timing tests:** full parallel test run on Windows delays fs events >100 ms; keep watcher test debounce/quiet windows generous.
- [2026-11-16] **HTTP errors:** server httpError messages (4xx/502/503) are user-facing and shown by the web client; 500 messages are not. Keep 4xx/502 messages free of secrets. - [2026-11-16] **HTTP errors:** server httpError messages (4xx/502/503) are user-facing and shown by the web client; 500 messages are not. Keep 4xx/502 messages free of secrets.
- [2026-11-16] **CJS named imports in the bundle:** `import { utils } from "ssh2"` passes Vitest but crashes `node dist/main.js`; import CommonJS packages via default export. `test/bundle.test.ts` starts the real bundle. - [2026-11-16] **CJS named imports in the bundle:** `import { utils } from "ssh2"` passes Vitest but crashes `node dist/main.js`; import CommonJS packages via default export. `test/bundle.test.ts` starts the real bundle.
- [2026-11-16] **Capture defaults deadlock if required in the same scope:** a required param whose default waits for a capture of its own notebook blocks the step producing it. Make such params optional (e.g. `ctid: default "{{nextid}}"`). - [2026-11-16] **Capture defaults (resolved by #16):** a required param waiting for a capture of its own notebook used to block the step producing it. Since steps are gated only by values they use, this only bites if the producing step references that param.
- [2026-11-16] **Bash tool heredocs with apostrophes fail** in this harness ("unexpected EOF"); write scripts to the scratchpad and run them instead. - [2026-11-16] **Bash tool heredocs with apostrophes fail** in this harness ("unexpected EOF"); write scripts to the scratchpad and run them instead.
- [2026-11-16] **Commas in YAML flow-mapping labels:** `{ label: Key (optional, else x) }` splits at the comma into a valueless key; quote such values. The parser now says so at the parameter line. - [2026-11-16] **Commas in YAML flow-mapping labels:** `{ label: Key (optional, else x) }` splits at the comma into a valueless key; quote such values. The parser now says so at the parameter line.
- [2026-11-16] **Stopping a background dev server task leaves its Node child running** on Windows (ports 8080/5173 stay taken); reuse it or kill the process. - [2026-11-16] **Stopping a background dev server task leaves its Node child running** on Windows (ports 8080/5173 stay taken); reuse it or kill the process.
+3 -3
View File
@@ -2,7 +2,7 @@
> Always-loaded. Everything else is on-demand. Update TOC when files change. > Always-loaded. Everything else is on-demand. Update TOC when files change.
## Current Focus ## Current Focus
- [2026-11-16] M0–M3 (#1–#4), UI-first follow-ups (#7–#10) and chained notebooks (#11: when/use/host, LXC + web-server templates) the UI/UX overhaul (#12) and collapsible parameters (#13) the app icon (#14) and self-update from Settings (#15) closed. - [2026-11-16] M0–M3 (#1–#4), UI-first follow-ups (#7–#10) and chained notebooks (#11: when/use/host, LXC + web-server templates) the UI/UX overhaul (#12) and collapsible parameters (#13) the app icon (#14) self-update from Settings (#15) and guided text with groups (#16) closed.
- [2026-11-16] Open: #5/#6 need a real CT 501 deploy (bootstrap.sh one-liner, setup token, real SSH run, tmux terminal). Not yet verified in a real browser or against real OpenSSH. - [2026-11-16] Open: #5/#6 need a real CT 501 deploy (bootstrap.sh one-liner, setup token, real SSH run, tmux terminal). Not yet verified in a real browser or against real OpenSSH.
## Invariants ## Invariants
@@ -15,7 +15,7 @@
- Everything doable from the web UI; files are storage, not the only way in. - Everything doable from the web UI; files are storage, not the only way in.
## Table of Contents ## Table of Contents
- `architecture.md` — 17 entries — why custom app, stack, AI integration, workspace split, deploy/update, chained notebooks, template delivery, web UI shell, collapsible params, app icon, UI self-update - `architecture.md` — 19 entries — why custom app, stack, AI integration, workspace split, deploy/update, chained notebooks, template delivery, web UI shell, collapsible params, app icon, UI self-update, groups/inline fields, step gating by used values
- `attempts.md` — 4 entries — marimo + marimo-pair trial and why it was dropped - `attempts.md` — 4 entries — marimo + marimo-pair trial and why it was dropped
- `open.md` — 2 entries — open design questions (sudo password, chat history) - `open.md` — 2 entries — open design questions (sudo password, chat history)
- `gotchas.md` — 17 entries — integration foot-guns (CRLF, host-key events, tmux/systemd, env names, pct exec PATH, TUN, chat paths, watcher timing, capture-default deadlock, heredocs, YAML flow commas, orphaned dev servers) - `gotchas.md` — 17 entries — integration foot-guns (CRLF, host-key events, tmux/systemd, env names, pct exec PATH, TUN, chat paths, watcher timing, capture defaults, heredocs, YAML flow commas, orphaned dev servers)
+3 -6
View File
@@ -23,12 +23,9 @@ export function prepareRun(notebook: Notebook, req: StartRunRequest, hosts: Host
const runtime: ParamValues = Object.assign(Object.create(null) as ParamValues, const runtime: ParamValues = Object.assign(Object.create(null) as ParamValues,
Object.fromEntries(Object.entries(req.runtime).filter(([name]) => !isBuiltin(name))), builtins); Object.fromEntries(Object.entries(req.runtime).filter(([name]) => !isBuiltin(name))), builtins);
const resolved = resolveParams(notebook, req.params, names, runtime); const resolved = resolveParams(notebook, req.params, names, runtime);
// Only parameters of the step's own scope gate it (an included notebook's form does not block the parent). // A step needs exactly the values it uses (core renderStep, spec §3.6): referenced params,
// Same rule as core's renderStep: required params and secrets of the step's scope gate it; // required secrets its script reads and every set secret of its scope (passed as env).
// other params only matter when the step references them (checked by renderStep below). // Unused required params never block it, so guided notebooks run early steps first.
const scope = step.attrs.scope ?? "";
const gating = notebook.params.filter(def => (def.scope ?? "") === scope && (def.required || def.type === "secret"));
if (gating.some(def => Object.hasOwn(resolved.errors, def.name))) throw httpError(400, "Parameters are missing or invalid");
if (!blockActive(notebook, step.attrs.id, resolved.values)) throw httpError(400, "Step is not part of the selected options"); if (!blockActive(notebook, step.attrs.id, resolved.values)) throw httpError(400, "Step is not part of the selected options");
const rendered = renderStep(notebook, step, resolved.values, runtime, names); const rendered = renderStep(notebook, step, resolved.values, runtime, names);
if (rendered.missing.length || Object.keys(rendered.invalid).length) throw httpError(400, "Step parameters are missing or invalid"); if (rendered.missing.length || Object.keys(rendered.invalid).length) throw httpError(400, "Step parameters are missing or invalid");
+35 -4
View File
@@ -4,7 +4,7 @@ import os from "node:os";
import path from "node:path"; import path from "node:path";
import { generateKeyPairSync } from "node:crypto"; import { generateKeyPairSync } from "node:crypto";
import type { HostInfo, NotebookResponse, StartRunRequest } from "@shellbook/core"; import type { HostInfo, NotebookResponse, StartRunRequest } from "@shellbook/core";
import { findStep } from "@shellbook/core"; import { findStep, parseNotebook } from "@shellbook/core";
import { buildApp } from "../src/app"; import { buildApp } from "../src/app";
import { loadConfig, type ServerConfig } from "../src/config"; import { loadConfig, type ServerConfig } from "../src/config";
import { prepareRun } from "../src/runs"; import { prepareRun } from "../src/runs";
@@ -100,13 +100,13 @@ describe("chained notebooks on the server", () => {
expect(prepared.rendered.script).toBe("pct create --hostname web-ct --key 'ssh-ed25519 SERVER' --pw \"$ROOTPW\"\n"); expect(prepared.rendered.script).toBe("pct create --hostname web-ct --key 'ssh-ed25519 SERVER' --pw \"$ROOTPW\"\n");
expect(prepared.host?.name).toBe("pve"); expect(prepared.host?.name).toBe("pve");
expect(prepared.env).toEqual({ ROOTPW: "root-pw" }); expect(prepared.env).toEqual({ ROOTPW: "root-pw" });
expect(() => prepareRun(notebook, request("install", values), hosts, builtins)).toThrow("Parameters are missing or invalid"); expect(() => prepareRun(notebook, request("install", values), hosts, builtins)).toThrow("Step parameters are missing or invalid");
const parent = prepareRun(notebook, request("install", values, { "ct.host": "web-ct" }), hosts, builtins); const parent = prepareRun(notebook, request("install", values, { "ct.host": "web-ct" }), hosts, builtins);
expect(parent.host?.name).toBe("web-ct"); expect(parent.host?.name).toBe("web-ct");
expect(parent.env).toEqual({ TOKEN: "token" }); expect(parent.env).toEqual({ TOKEN: "token" });
// Container steps are refused when "existing host" is selected; the included form gates its own steps. // Container steps are refused when "existing host" is selected; the included form gates its own steps.
expect(() => prepareRun(notebook, request("ct.create", { ...values, target: "existing" }), hosts, builtins)).toThrow("Step is not part of the selected options"); expect(() => prepareRun(notebook, request("ct.create", { ...values, target: "existing" }), hosts, builtins)).toThrow("Step is not part of the selected options");
expect(() => prepareRun(notebook, request("ct.create", { target: "lxc" }), hosts, builtins)).toThrow("Parameters are missing or invalid"); expect(() => prepareRun(notebook, request("ct.create", { target: "lxc" }), hosts, builtins)).toThrow("Step parameters are missing or invalid");
// Without a server key the builtin stays missing even if a client sends one. // Without a server key the builtin stays missing even if a client sends one.
expect(() => prepareRun(notebook, request("ct.create", values, { "shellbook.public_key": "ssh-ed25519 CLIENT" }), hosts, {})).toThrow("Step parameters are missing or invalid"); expect(() => prepareRun(notebook, request("ct.create", values, { "shellbook.public_key": "ssh-ed25519 CLIENT" }), hosts, {})).toThrow("Step parameters are missing or invalid");
}); });
@@ -146,7 +146,7 @@ pct create {{ctid}}
expect(prepared.rendered.script).toContain("printf '%s\\n' 'ssh-ed25519 AAAAKEY shellbook' > \"$keys\""); expect(prepared.rendered.script).toContain("printf '%s\\n' 'ssh-ed25519 AAAAKEY shellbook' > \"$keys\"");
expect(prepared.rendered.script).toContain("pct create 105 local:vztmpl/debian-12-standard_12.7-1_amd64.tar.zst \\\n --hostname web \\"); expect(prepared.rendered.script).toContain("pct create 105 local:vztmpl/debian-12-standard_12.7-1_amd64.tar.zst \\\n --hostname web \\");
expect(prepared.rendered.script).toContain("--net0 name=eth0,bridge=vmbr0,'ip=10.0.30.160/24,gw=10.0.30.1'"); expect(prepared.rendered.script).toContain("--net0 name=eth0,bridge=vmbr0,'ip=10.0.30.160/24,gw=10.0.30.1'");
expect(() => prepareRun(notebook, request("install", { ...values, target: "existing" }), hosts, {})).toThrow("Parameters are missing or invalid"); expect(() => prepareRun(notebook, request("install", { ...values, target: "existing" }), hosts, {})).toThrow("Step parameters are missing or invalid");
expect(prepareRun(notebook, request("install", { target: "existing", host: "existing" }), hosts, {}).host?.name).toBe("existing"); expect(prepareRun(notebook, request("install", { target: "existing", host: "existing" }), hosts, {}).host?.name).toBe("existing");
}); });
@@ -157,3 +157,34 @@ pct create {{ctid}}
expect(res.json().message).toBe("Step is not part of the selected options"); expect(res.json().message).toBe("Step is not part of the selected options");
}); });
}); });
describe("guided notebooks (#16)", () => {
const guided = parseNotebook(`---
params:
host: {type: host, required: true}
user: {type: name, required: true}
TOKEN: {type: secret, required: true}
---
:::group{title="1. Server"}
::param{name=host}
\`\`\`sh {check host="{{host}}" id=first}
true
\`\`\`
:::
\`\`\`sh {run host="{{host}}" id=later}
useradd {{user}} && curl -H "Authorization: $TOKEN" https://example.invalid
\`\`\`
`);
it("runs an early step before later required values are filled", () => {
expect(guided.diagnostics).toEqual([]);
expect(prepareRun(guided, request("first", { host: "pve" }), hosts).rendered.script).toBe("true\n");
expect(() => prepareRun(guided, request("later", { host: "pve", TOKEN: "t" }), hosts)).toThrow("Step parameters are missing or invalid");
expect(() => prepareRun(guided, request("later", { host: "pve", user: "ops" }), hosts)).toThrow("Step parameters are missing or invalid");
expect(prepareRun(guided, request("later", { host: "pve", user: "ops", TOKEN: "t" }), hosts).env).toEqual({ TOKEN: "t" });
});
it("still refuses an invalid secret even when the step does not read it", () => {
expect(() => prepareRun(guided, request("first", { host: "pve", TOKEN: "a\0b" }), hosts)).toThrow("Step parameters are missing or invalid");
});
});
-2
View File
@@ -181,8 +181,6 @@ describe("pipeline helpers", () => {
}); });
it("refuses missing or invalid parameters before execution", () => { it("refuses missing or invalid parameters before execution", () => {
const notebook: Notebook = { title: "Test", params: [{ name: "required", type: "string", required: true }], blocks: [{ type: "step", step: step() }], diagnostics: [] }; const notebook: Notebook = { title: "Test", params: [{ name: "required", type: "string", required: true }], blocks: [{ type: "step", step: step() }], diagnostics: [] };
vi.mocked(resolveParams).mockReturnValueOnce({ values: {}, errors: { required: "missing" } });
expect(() => prepareRun(notebook, request(), [])).toThrow("Parameters are missing or invalid");
vi.mocked(renderStep).mockReturnValueOnce({ ...rendered(), missing: ["required"] }); vi.mocked(renderStep).mockReturnValueOnce({ ...rendered(), missing: ["required"] });
expect(() => prepareRun(notebook, request(), [])).toThrow("Step parameters are missing or invalid"); expect(() => prepareRun(notebook, request(), [])).toThrow("Step parameters are missing or invalid");
}); });
+60 -32
View File
@@ -14,6 +14,7 @@ import {
import ReactMarkdown from "react-markdown"; import ReactMarkdown from "react-markdown";
import { import {
blockActive, blockActive,
groupInputs,
notebookIncludes, notebookIncludes,
parseNotebook, parseNotebook,
renderHost, renderHost,
@@ -38,7 +39,8 @@ import { HostsPage } from "./HostsPage";
import { HttpError } from "./api"; import { HttpError } from "./api";
import type { Api } from "./api"; import type { Api } from "./api";
import { emptySession, eventReducer, stepKey } from "./events"; import { emptySession, eventReducer, stepKey } from "./events";
import { ParamsForm, type ParamGroup } from "./ParamsForm"; import { ParamField, ParamsForm, type ParamGroup } from "./ParamsForm";
import { GroupSection } from "./GroupSection";
import { HostBlockCard } from "./HostBlockCard"; import { HostBlockCard } from "./HostBlockCard";
import { StepCard } from "./StepCard"; import { StepCard } from "./StepCard";
import { ChatPanel } from "./ChatPanel"; import { ChatPanel } from "./ChatPanel";
@@ -55,21 +57,14 @@ const Editor = lazy(() =>
function steps(blocks: Block[]): Step[] { function steps(blocks: Block[]): Step[] {
return blocks.flatMap((block) => return blocks.flatMap((block) =>
block.type === "step" block.type === "step" ? [block.step] : "blocks" in block ? steps(block.blocks) : [],
? [block.step]
: block.type === "markdown" || block.type === "host"
? []
: steps(block.blocks),
); );
} }
/** Included notebooks (`::use`, nested too) as parameter groups. */ type UseBlock = Extract<Block, { type: "use" }>;
function includedGroups(blocks: Block[]): ParamGroup[] { /** Included notebooks (`::use`, nested too), whose parameters the form shows as groups. */
return blocks.flatMap((block): ParamGroup[] => function includes(blocks: Block[]): UseBlock[] {
block.type === "use" return blocks.flatMap((block): UseBlock[] =>
? [{ scope: block.scope, title: `${block.title ?? block.path} (${block.scope})` }, ...includedGroups(block.blocks)] block.type === "use" ? [block, ...includes(block.blocks)] : "blocks" in block ? includes(block.blocks) : [],
: block.type === "after" || block.type === "when"
? includedGroups(block.blocks)
: [],
); );
} }
/** Values that are set; unset ones stay visible as `{{name}}` in prose. */ /** Values that are set; unset ones stay visible as `{{name}}` in prose. */
@@ -239,8 +234,14 @@ export function App({ api }: { api: Api }) {
? resolveParams(notebook, values, hostNames, runtime) ? resolveParams(notebook, values, hostNames, runtime)
: { values: {}, errors: {} }; : { values: {}, errors: {} };
const active = (id: string) => !!notebook && blockActive(notebook, id, resolved.values); const active = (id: string) => !!notebook && blockActive(notebook, id, resolved.values);
const groups = notebook const groups: ParamGroup[] = notebook
? includedGroups(notebook.blocks).filter((group) => scopeActive(notebook, group.scope, resolved.values)) ? includes(notebook.blocks)
.filter((block) => scopeActive(notebook, block.scope, resolved.values))
.map((block) => ({
scope: block.scope,
title: `${block.title ?? block.path} (${block.scope})`,
status: groupInputs(notebook, block, values, hostNames, runtime).status,
}))
: []; : [];
const activeChecks = notebook const activeChecks = notebook
? steps(notebook.blocks).filter((s) => s.kind === "check" && active(s.attrs.id)) ? steps(notebook.blocks).filter((s) => s.kind === "check" && active(s.attrs.id))
@@ -302,21 +303,46 @@ export function App({ api }: { api: Api }) {
setConfirm(request); setConfirm(request);
else void start(request); else void start(request);
} }
const changeValue = (name: string, value: string) => changeValues({ ...values, [name]: value });
function blocks(items: Block[]): React.ReactNode { function blocks(items: Block[]): React.ReactNode {
if (!notebook) return null; if (!notebook) return null;
const prose = (text: string) => renderText(text, setValuesOnly({ ...runtime, ...resolved.values }), notebook);
return items.map((block, i) => { return items.map((block, i) => {
if (block.type === "markdown") if (block.type === "markdown")
return ( return (
<div className="prose" key={i}> <div className="prose" key={i}>
<ReactMarkdown> <ReactMarkdown>{prose(block.text)}</ReactMarkdown>
{renderText(
block.text,
setValuesOnly({ ...runtime, ...resolved.values }),
notebook,
)}
</ReactMarkdown>
</div> </div>
); );
if (block.type === "param") {
const def = notebook.params.find((param) => param.name === block.name);
// The parser reports unknown names; the panel still lists every parameter.
return def ? (
<div className="inline-param" key={i}>
<ParamField
param={def}
value={resolved.values[def.name]}
error={resolved.errors[def.name]}
hosts={hosts}
idPrefix={`inline-${i}-${block.range.startLine}`}
onChange={changeValue}
/>
</div>
) : null;
}
if (block.type === "group")
return (
<GroupSection
key={`${path}:${block.range.startLine}`}
title={prose(block.title)}
inputs={groupInputs(notebook, block, values, hostNames, runtime)}
params={notebook.params}
storageKey={`${path}:${block.title}`}
defaultOpen={!block.collapsed}
>
{blocks(block.blocks)}
</GroupSection>
);
if (block.type === "when") if (block.type === "when")
return block.values.includes(resolved.values[block.param] ?? "") ? ( return block.values.includes(resolved.values[block.param] ?? "") ? (
<div className="when" key={i}> <div className="when" key={i}>
@@ -325,19 +351,21 @@ export function App({ api }: { api: Api }) {
) : null; ) : null;
if (block.type === "use") if (block.type === "use")
return ( return (
<details className="included" open key={i}> <GroupSection
<summary> key={`${path}:use:${block.scope}`}
{block.title ?? block.path} className="included"
<small> title={block.title ?? block.path}
{block.path} · as {block.scope} subtitle={`${block.path} · as ${block.scope}`}
</small> inputs={groupInputs(notebook, block, values, hostNames, runtime)}
</summary> params={notebook.params}
storageKey={`${path}:use:${block.scope}`}
>
{block.blocks.length ? ( {block.blocks.length ? (
blocks(block.blocks) blocks(block.blocks)
) : ( ) : (
<p className="muted">Save the notebook to load {block.path}.</p> <p className="muted">Save the notebook to load {block.path}.</p>
)} )}
</details> </GroupSection>
); );
if (block.type === "host") { if (block.type === "host") {
const rendered = renderHost(notebook, block, resolved.values, runtime, hostNames); const rendered = renderHost(notebook, block, resolved.values, runtime, hostNames);
@@ -599,7 +627,7 @@ export function App({ api }: { api: Api }) {
writeFlag("params-open", next); writeFlag("params-open", next);
setParamsOpen(next); setParamsOpen(next);
}} }}
onChange={(name, value) => changeValues({ ...values, [name]: value })} onChange={changeValue}
onReset={() => changeValues({})} onReset={() => changeValues({})}
/> />
<article className="notebook"> <article className="notebook">
+32
View File
@@ -3,7 +3,9 @@ import { parseNotebook, type ParamDef } from "@shellbook/core";
import { import {
addParameter, addParameter,
afterSnippet, afterSnippet,
groupSnippet,
hostSnippet, hostSnippet,
paramFieldSnippet,
notebookSteps, notebookSteps,
stepSnippet, stepSnippet,
useSnippet, useSnippet,
@@ -28,6 +30,7 @@ export function AuthoringToolbar({
const [after, setAfter] = useState(""); const [after, setAfter] = useState("");
const [when, setWhen] = useState(""); const [when, setWhen] = useState("");
const [include, setInclude] = useState(false); const [include, setInclude] = useState(false);
const [field, setField] = useState("");
const steps = notebookSteps(notebook.blocks); const steps = notebookSteps(notebook.blocks);
const choices = notebook.params.flatMap((p) => const choices = notebook.params.flatMap((p) =>
p.type === "choice" ? (p.options ?? []).map((o) => ({ param: p.name, option: o })) : [], p.type === "choice" ? (p.options ?? []).map((o) => ({ param: p.name, option: o })) : [],
@@ -104,6 +107,27 @@ export function AuthoringToolbar({
> >
Insert when section Insert when section
</button> </button>
<button type="button" onClick={() => insert(groupSnippet())}>
Group
</button>
<label>
Field in text
<select value={field} onChange={(e) => setField(e.target.value)}>
<option value="">Choose a parameter</option>
{notebook.params.map((p) => (
<option key={p.name} value={p.name}>
{p.name}
</option>
))}
</select>
</label>
<button
type="button"
disabled={!notebook.params.some((p) => p.name === field)}
onClick={() => insert(paramFieldSnippet(field))}
>
Insert field
</button>
<button type="button" onClick={() => setInclude(!include)}> <button type="button" onClick={() => setInclude(!include)}>
Use notebook Use notebook
</button> </button>
@@ -227,6 +251,14 @@ export function AuthoringToolbar({
adds a created machine to Hosts. {"{{shellbook.public_key}}"} is adds a created machine to Hosts. {"{{shellbook.public_key}}"} is
ShellBook's SSH public key. ShellBook's SSH public key.
</p> </p>
<p>
Guided text: {"::param{name=host}"} on its own line shows that
parameter&apos;s input there (same value as the panel).{" "}
{':::group{title="Network" collapsed}'} … {":::"} is a collapsible
section for anything; its outline is orange while needed values are
missing, green when all are filled, grey when only optional ones remain.
{" collapsed"} starts it closed. Groups never block steps.
</p>
<p> <p>
Artifact and upload snippets are examples: choose files and commands Artifact and upload snippets are examples: choose files and commands
appropriate to your runbook before running. appropriate to your runbook before running.
+76
View File
@@ -0,0 +1,76 @@
import { useState, type ReactNode } from "react";
import type { GroupInputs, ParamDef } from "@shellbook/core";
import { paramLabel } from "./ParamsForm";
import { readFlag, writeFlag } from "./uiPrefs";
/** What the outline color means, in words (color is never the only signal). */
function statusText(inputs: GroupInputs, labelOf: (name: string) => string): string {
if (inputs.status === "missing") {
const names = [...inputs.missing, ...inputs.invalid];
const shown = names.slice(0, 3).map(labelOf).join(", ");
const more = names.length > 3 ? ` +${names.length - 3}` : "";
return inputs.missing.length ? `needs ${shown}${more}` : `check ${shown}${more}`;
}
if (inputs.status === "filled") return "complete";
if (inputs.status === "optional") return "optional";
return "";
}
/**
* A titled, collapsible container (`:::group`, and `::use` sections). The outline shows
* whether its inputs are filled in: orange — needed values missing, green — complete,
* grey — optional or no inputs. The open state is remembered per `storageKey`.
*/
export function GroupSection({
title,
subtitle,
inputs,
params,
storageKey,
defaultOpen = true,
className = "",
children,
}: {
title: string;
subtitle?: string;
inputs: GroupInputs;
/** The notebook's parameters, for labels in the status text. */
params: ParamDef[];
storageKey: string;
defaultOpen?: boolean;
className?: string;
children: ReactNode;
}) {
const flag = `group:${storageKey}`;
const [open, setOpen] = useState(() => readFlag(flag, defaultOpen));
const labelOf = (name: string) => {
const def = params.find((param) => param.name === name);
return def ? paramLabel(def) : name;
};
const status = statusText(inputs, labelOf);
return (
<section className={`group status-${inputs.status} ${className}`.trim()} aria-label={title}>
<header>
<button
type="button"
className="group-toggle"
aria-expanded={open}
onClick={() => {
writeFlag(flag, !open);
setOpen(!open);
}}
>
<span className="caret" aria-hidden="true">
{open ? "▾" : "▸"}
</span>
<span className="group-title">{title}</span>
</button>
{subtitle && <small className="muted">{subtitle}</small>}
{status && <small className="group-status">{status}</small>}
</header>
<div className="group-body" hidden={!open}>
{children}
</div>
</section>
);
}
+84 -50
View File
@@ -1,15 +1,84 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import type { HostInfo, Notebook, ParamDef, ParamValues } from "@shellbook/core"; import type { HostInfo, InputStatus, Notebook, ParamDef, ParamValues } from "@shellbook/core";
import { readFlag, writeFlag } from "./uiPrefs"; import { readFlag, writeFlag } from "./uiPrefs";
/** An included notebook (`::use`) whose parameters the form shows as a group. */ /** An included notebook (`::use`) whose parameters the form shows as a group. */
export interface ParamGroup { export interface ParamGroup {
scope: string; scope: string;
title: string; title: string;
/** Input status of the included notebook (core groupInputs), shown as the outline color. */
status?: InputStatus;
} }
const groupFlag = (title: string) => `params-group:${title}`; const groupFlag = (title: string) => `params-group:${title}`;
/** The label a parameter is shown with; included ones without a label use their local name. */
export const paramLabel = (param: ParamDef) =>
param.label ?? (param.scope ? param.name.slice(param.scope.length + 1) : param.name);
/**
* One parameter input, used by the parameter panel and by `::param` fields in the text.
* `idPrefix` keeps element ids unique when the same parameter appears in both places.
*/
export function ParamField({
param,
value,
error,
hosts,
idPrefix = "param",
onChange,
}: {
param: ParamDef;
value: string | undefined;
error: string | undefined;
hosts: HostInfo[];
idPrefix?: string;
onChange(name: string, value: string): void;
}) {
const id = `${idPrefix}-${param.name}`;
const label = paramLabel(param);
const common = {
id,
required: param.required,
value: value ?? "",
"aria-labelledby": `${id}-label`,
"aria-invalid": !!error,
// Red only for a wrong value; an empty field just still needs one.
className: error && value ? "invalid" : undefined,
"aria-describedby": error ? `${id}-error` : undefined,
onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => onChange(param.name, e.target.value),
};
return (
<label htmlFor={id}>
<span id={`${id}-label`} title={label}>
{label}
{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}
/>
)}
{error && (
// An empty field only needs a value: say so quietly; a wrong value is an error.
<small id={`${id}-error`} className={value ? "error" : "muted"}>
{error}
</small>
)}
</label>
);
}
export function ParamsForm({ export function ParamsForm({
notebook, notebook,
values, values,
@@ -58,8 +127,7 @@ export function ParamsForm({
const missingOf = (params: ParamDef[]) => const missingOf = (params: ParamDef[]) =>
params.filter((param) => param.required && !values[param.name]).length; params.filter((param) => param.required && !values[param.name]).length;
const missing = missingOf(shown); const missing = missingOf(shown);
const labelOf = (param: ParamDef) => const labelOf = paramLabel;
param.label ?? (param.scope ? param.name.slice(param.scope.length + 1) : param.name);
const reveal = (param: ParamDef) => { const reveal = (param: ParamDef) => {
if (!open) onToggle?.(true); if (!open) onToggle?.(true);
@@ -107,54 +175,16 @@ export function ParamsForm({
); );
}; };
const field = (param: ParamDef) => { const field = (param: ParamDef) => (
const id = `param-${param.name}`; <ParamField
const common = { key={param.name}
id, param={param}
required: param.required, value={values[param.name]}
value: values[param.name] ?? "", error={errors[param.name]}
"aria-labelledby": `${id}-label`, hosts={hosts}
"aria-invalid": !!errors[param.name], onChange={onChange}
// Red only for a wrong value; an empty field just still needs one.
className: errors[param.name] && values[param.name] ? "invalid" : undefined,
"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`} title={labelOf(param)}>
{labelOf(param)}
{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] && (
// An empty field only needs a value: say so quietly; a wrong value is an error.
<small id={`${id}-error`} className={values[param.name] ? "error" : "muted"}>
{errors[param.name]}
</small>
)}
</label>
); );
};
return ( return (
<form <form
@@ -191,7 +221,11 @@ export function ParamsForm({
const expanded = isGroupOpen(group.title); const expanded = isGroupOpen(group.title);
const groupMissing = missingOf(params); const groupMissing = missingOf(params);
return ( return (
<fieldset key={group.scope} className={expanded ? "" : "collapsed"} aria-label={group.title}> <fieldset
key={group.scope}
className={`status-${group.status ?? "none"}${expanded ? "" : " collapsed"}`}
aria-label={group.title}
>
<legend> <legend>
<button <button
type="button" type="button"
+18 -5
View File
@@ -8,11 +8,7 @@ import {
} from "@shellbook/core"; } from "@shellbook/core";
export function notebookSteps(blocks: Block[]): Step[] { export function notebookSteps(blocks: Block[]): Step[] {
return blocks.flatMap((b) => return blocks.flatMap((b) =>
b.type === "step" b.type === "step" ? [b.step] : "blocks" in b ? notebookSteps(b.blocks) : [],
? [b.step]
: b.type === "markdown" || b.type === "host"
? []
: notebookSteps(b.blocks),
); );
} }
const attr = (value: string) => const attr = (value: string) =>
@@ -72,6 +68,23 @@ export function useSnippet(path: string, alias: string): string {
throw new Error("Alias must use letters, digits or _ (not shellbook)"); throw new Error("Alias must use letters, digits or _ (not shellbook)");
return `\n\n::use{notebook=${attr(path)} as=${alias}}\n`; return `\n\n::use{notebook=${attr(path)} as=${alias}}\n`;
} }
/** A titled, collapsible container; its outline shows whether its inputs are filled in. */
export function groupSnippet(title = "Group title"): string {
return `
:::group{title=${attr(title)}}
Explain this part here.
:::
`;
}
/** The parameter's input field at this point of the text. */
export function paramFieldSnippet(name: string): string {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error("Invalid parameter name");
return `
::param{name=${name}}
`;
}
/** Add the machine a notebook created to Hosts; replace the example templates. */ /** Add the machine a notebook created to Hosts; replace the example templates. */
export function hostSnippet(): string { export function hostSnippet(): string {
return '\n\n::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}\n'; return '\n\n::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}\n';
+25 -12
View File
@@ -2,9 +2,18 @@ import type { ServerEvent, StartRunRequest } from "@shellbook/core";
import type { Api } from "../api"; import type { Api } from "../api";
import { HttpError } from "../api"; import { HttpError } from "../api";
import { findStep, parseNotebook, renderStep } from "@shellbook/core"; import { findStep, parseNotebook, renderStep } from "@shellbook/core";
import initial from "./ssh-key.md?raw"; import sshKey from "./ssh-key.md?raw";
let source = initial; import adminUser from "../../../../templates/workspace/notebooks/admin-user.md?raw";
let version = 1; // Demo notebooks, editable in this browser session only.
const files: Record<string, { title: string; source: string; version: number }> = {
"ssh-key.md": { title: "New server SSH key", source: sshKey, version: 1 },
"admin-user.md": { title: "Create an admin user", source: adminUser, version: 1 },
};
const file = (path: string) => {
const entry = files[path];
if (!entry) throw new HttpError(404);
return entry;
};
let counter = 0; let counter = 0;
const listeners = new Set<(event: ServerEvent) => void>(); const listeners = new Set<(event: ServerEvent) => void>();
const emit = (event: ServerEvent) => const emit = (event: ServerEvent) =>
@@ -43,26 +52,30 @@ export const mockApi: Api = {
me: async () => ({ authenticated: true }), me: async () => ({ authenticated: true }),
login: async () => undefined, login: async () => undefined,
list: async () => ({ list: async () => ({
notebooks: [{ path: "ssh-key.md", title: "New server SSH key" }], notebooks: Object.entries(files).map(([path, entry]) => ({ path, title: entry.title })),
}), }),
hosts: async () => ({ hosts }), hosts: async () => ({ hosts }),
notebook: async (path) => ({ notebook: async (path) => {
const { source, version } = file(path);
return {
path, path,
source, source,
notebook: parseNotebook(source), notebook: parseNotebook(source),
includes: [], includes: [],
builtins: { "shellbook.public_key": "ssh-ed25519 AAAADEMO shellbook" }, builtins: { "shellbook.public_key": "ssh-ed25519 AAAADEMO shellbook" },
version: String(version), version: String(version),
}), };
},
addHost: async (host) => { addHost: async (host) => {
if (hosts.some((h) => h.name === host.name)) throw new HttpError(409, "Host already exists"); if (hosts.some((h) => h.name === host.name)) throw new HttpError(409, "Host already exists");
hosts.push({ ...host }); hosts.push({ ...host });
}, },
save: async (_path, next, base) => { save: async (path, next, base) => {
if (base !== String(version)) throw new HttpError(409); const entry = file(path);
source = next; if (base !== String(entry.version)) throw new HttpError(409);
version++; entry.source = next;
return { version: String(version) }; entry.version++;
return { version: String(entry.version) };
}, },
events: (receive, connected) => { events: (receive, connected) => {
listeners.add(receive); listeners.add(receive);
@@ -73,7 +86,7 @@ export const mockApi: Api = {
}, },
artifact: () => artifactUrl, artifact: () => artifactUrl,
run: async (request: StartRunRequest) => { run: async (request: StartRunRequest) => {
const notebook = parseNotebook(source); const notebook = parseNotebook(file(request.notebookPath).source);
const step = findStep(notebook.blocks, request.stepId); const step = findStep(notebook.blocks, request.stepId);
if (!step) throw new Error("Unknown demo step"); if (!step) throw new Error("Unknown demo step");
const rendered = renderStep( const rendered = renderStep(
+91 -11
View File
@@ -615,6 +615,12 @@ nav[aria-label="Main navigation"] button[aria-current="page"] {
.params fieldset.collapsed { .params fieldset.collapsed {
padding-bottom: 8px; padding-bottom: 8px;
} }
.params fieldset.status-missing {
border-color: var(--warn);
}
.params fieldset.status-filled {
border-color: var(--ok);
}
.params legend { .params legend {
font-size: 12px; font-size: 12px;
font-weight: 600; font-weight: 600;
@@ -805,22 +811,96 @@ pre.script {
border-left: 3px solid var(--accent); border-left: 3px solid var(--accent);
padding-left: 18px; padding-left: 18px;
} }
/* Chained notebooks (::use): the included notebook, collapsible. */ /*
.included { * Groups (:::group) and included notebooks (::use): collapsible containers whose outline
border: 1px dashed var(--line); * shows their input status — orange: needed values missing, green: complete, grey: optional.
*/
.group {
--group-line: var(--line);
border: 1px solid var(--group-line);
border-left-width: 4px;
border-radius: 8px; border-radius: 8px;
padding: 4px 18px; padding: 0 18px;
margin: 20px 0; margin: 20px 0;
} }
.included > summary { .group.status-missing {
cursor: pointer; --group-line: var(--warn);
padding: 10px 0;
font-weight: 600;
} }
.included > summary small { .group.status-filled {
font-weight: normal; --group-line: var(--ok);
}
.group.included {
border-style: dashed;
border-left-style: solid;
}
.group > header {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 4px 10px;
padding: 10px 0;
}
.group-toggle {
display: inline-flex;
align-items: baseline;
gap: 8px;
border: none;
background: none;
padding: 0;
color: var(--text);
font: inherit;
font-size: 15px;
font-weight: 600;
text-align: left;
}
.group-toggle:hover {
color: var(--accent);
}
.group-toggle .caret {
width: 10px;
color: var(--muted); color: var(--muted);
margin-left: 8px; }
.group > header > small {
font-size: 12px;
}
.group-status {
margin-left: auto;
color: var(--muted);
}
.group.status-missing > header > .group-status {
color: var(--warn);
}
.group.status-filled > header > .group-status {
color: var(--ok);
}
.group.status-filled > header > .group-status::before {
content: "✓ ";
}
.group-body {
padding-bottom: 6px;
}
.group-body > .prose:first-child > :first-child {
margin-top: 0;
}
/* ::param — a parameter's input inside the text, bound to the same value as the panel. */
.inline-param {
max-width: 420px;
margin: 12px 0;
}
.inline-param label {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 12.5px;
}
.inline-param label > span {
color: var(--muted);
}
.inline-param b {
color: var(--accent);
}
.inline-param + .inline-param {
margin-top: -2px;
} }
.host-block > p { .host-block > p {
margin: 10px 14px; margin: 10px 14px;
+11
View File
@@ -89,3 +89,14 @@ it("generates valid chaining snippets", async () => {
expect(() => useSnippet("../x.md", "ct")).toThrow("dir/name.md"); expect(() => useSnippet("../x.md", "ct")).toThrow("dir/name.md");
expect(() => useSnippet("x.md", "shellbook")).toThrow("Alias"); expect(() => useSnippet("x.md", "shellbook")).toThrow("Alias");
}); });
it("generates valid group and parameter field snippets", async () => {
const { groupSnippet, paramFieldSnippet } = await import("../authoring");
const base = "---\nparams:\n hostname: {type: name}\n---\n";
const notebook = parseNotebook(base + groupSnippet('Say "hi"') + paramFieldSnippet("hostname"));
expect(notebook.diagnostics).toEqual([]);
expect(notebook.blocks.filter((b) => b.type !== "markdown")).toEqual([
expect.objectContaining({ type: "group", title: 'Say "hi"', collapsed: false }),
expect.objectContaining({ type: "param", name: "hostname" }),
]);
expect(() => paramFieldSnippet("a b")).toThrow("Invalid parameter name");
});
+99
View File
@@ -0,0 +1,99 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { beforeEach, expect, it, vi } from "vitest";
vi.mock("../Editor", () => ({ Editor: () => null }));
import { App } from "../App";
import type { Api } from "../api";
import { parseNotebook } from "@shellbook/core";
const source = `---
title: Guided setup
params:
host: {type: host, required: true, label: Target server}
user: {type: name, label: Login user}
note: {type: string}
---
# Guided setup
:::group{title="1. Connect"}
Pick the server first:
::param{name=host}
\`\`\`sh {check host="{{host}}" id=whoami title="Who am I"}
id {{user}}
\`\`\`
:::
:::group{title="2. Notes" collapsed}
::param{name=note}
:::
`;
function api(): Api {
return {
create: vi.fn(), move: vi.fn(), deleteNotebook: vi.fn(),
me: vi.fn().mockResolvedValue({}),
login: vi.fn(),
list: vi.fn().mockResolvedValue({ notebooks: [{ path: "guide.md", title: "Guided setup" }] }),
hosts: vi.fn().mockResolvedValue({ hosts: [{ name: "pve", address: "10.0.0.2", user: "root", port: 22, tags: [] }] }),
notebook: vi.fn().mockResolvedValue({
path: "guide.md", source, notebook: parseNotebook(source), includes: [], builtins: {}, version: "1",
}),
save: vi.fn(),
run: vi.fn(),
addHost: vi.fn(),
events: (_callback, connected) => { connected(true); return () => {}; },
artifact: () => "/download",
};
}
beforeEach(() => localStorage.clear());
it("shows parameter fields in the text, bound to the same value as the panel", async () => {
render(<App api={api()} />);
const connect = await screen.findByRole("region", { name: "1. Connect" });
const inline = within(connect).getByLabelText(/Target server/);
const panel = within(screen.getByRole("form", { name: "Notebook parameters" })).getByLabelText(/Target server/);
expect(inline).not.toBe(panel);
fireEvent.change(inline, { target: { value: "pve" } });
expect(panel).toHaveValue("pve");
fireEvent.change(panel, { target: { value: "" } });
expect(inline).toHaveValue("");
});
it("colors a group by the state of its inputs and says so in text", async () => {
render(<App api={api()} />);
const connect = await screen.findByRole("region", { name: "1. Connect" });
// The check needs host (required) and user (referenced by the script).
expect(connect).toHaveClass("status-missing");
expect(within(connect).getByText("needs Target server, Login user")).toBeInTheDocument();
fireEvent.change(within(connect).getByLabelText(/Target server/), { target: { value: "pve" } });
expect(connect).toHaveTextContent("needs Login user");
fireEvent.change(within(screen.getByRole("form", { name: "Notebook parameters" })).getByLabelText(/Login user/), {
target: { value: "admin" },
});
expect(connect).toHaveClass("status-filled");
expect(within(connect).getByText("complete")).toBeInTheDocument();
// Only optional inputs: grey.
expect(screen.getByRole("region", { name: "2. Notes" })).toHaveClass("status-optional");
});
it("collapses groups, starts collapsed ones closed and remembers the choice", async () => {
const { unmount } = render(<App api={api()} />);
const notes = await screen.findByRole("region", { name: "2. Notes" });
const toggle = within(notes).getByRole("button", { name: "2. Notes" });
expect(toggle).toHaveAttribute("aria-expanded", "false");
expect(within(notes).getByLabelText("note", { selector: "input" })).not.toBeVisible();
fireEvent.click(toggle);
expect(within(notes).getByLabelText("note", { selector: "input" })).toBeVisible();
const connect = screen.getByRole("region", { name: "1. Connect" });
fireEvent.click(within(connect).getByRole("button", { name: "1. Connect" }));
expect(within(connect).getByText("Who am I")).not.toBeVisible();
unmount();
render(<App api={api()} />);
const again = await screen.findByRole("region", { name: "1. Connect" });
expect(within(again).getByRole("button", { name: "1. Connect" })).toHaveAttribute("aria-expanded", "false");
expect(within(screen.getByRole("region", { name: "2. Notes" })).getByRole("button", { name: "2. Notes" }))
.toHaveAttribute("aria-expanded", "true");
});
+38 -6
View File
@@ -93,7 +93,11 @@ Download the private key above, then save it:
- **Substitution in scripts is shell-safe**: the value is inserted shell-quoted when it - **Substitution in scripts is shell-safe**: the value is inserted shell-quoted when it
contains anything outside `[A-Za-z0-9._/@:=+-]`. The displayed script and the executed contains anything outside `[A-Za-z0-9._/@:=+-]`. The displayed script and the executed
script are the same string. One function does this (`core/shellQuote`), nowhere else. script are the same string. One function does this (`core/shellQuote`), nowhere else.
- A step with a missing required param shows the script with `{{name}}` highlighted and a disabled Run button. - A step needs exactly the values it uses: every param and runtime value it references, and
the required secrets its script reads as `$NAME`/`${NAME}`. While one is missing the script
shows `{{name}}` highlighted and Run is disabled. Required params the step does not use never
block it, so a guided notebook (§3.7) runs its first steps before later values are entered.
Set secrets of the step's notebook are always validated, because all are passed as env vars.
### 3.3 Step attributes ### 3.3 Step attributes
@@ -149,12 +153,11 @@ notebook that first creates an LXC container:
- `with` sets defaults of the included params, written in the including notebook's - `with` sets defaults of the included params, written in the including notebook's
namespace. Secrets cannot be bound; they are entered in the form and passed only to namespace. Secrets cannot be bound; they are entered in the form and passed only to
steps of their own notebook, under their local name (`$ROOTPW`). steps of their own notebook, under their local name (`$ROOTPW`).
- Required params gate only steps of their own notebook (scope); a step also needs every - Steps are gated only by the values they use (§3.2); an included notebook's empty form
value it references. never blocks the parent's steps unless they reference its values.
- Non-secret defaults may reference captures and builtins (`default: "{{ct.host}}"`). Until - Non-secret defaults may reference captures and builtins (`default: "{{ct.host}}"`). Until
the value exists the field shows "Available after the step that sets ct.host". A the value exists the field shows "Available after the step that sets ct.host". Only
required param that waits for a capture of its own notebook would block the step steps that reference such a param wait for it.
producing it; make such params optional.
- `::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}` adds - `::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}` adds
the machine to Hosts (same validation as the Hosts page; never overwrites a different the machine to Hosts (same validation as the Hosts page; never overwrites a different
host with that name). `capture` stores the host name as a runtime value so later host with that name). `capture` stores the host name as a runtime value so later
@@ -163,6 +166,35 @@ notebook that first creates an LXC container:
`{{shellbook.public_key}}` is ShellBook's SSH public key. The server sets them on every `{{shellbook.public_key}}` is ShellBook's SSH public key. The server sets them on every
run; client-sent values are ignored. run; client-sent values are ignored.
### 3.7 Guided text: parameter fields and groups
Authors can ask for each value where the text explains it:
```markdown
:::group{title="1. Network" collapsed}
Pick the bridge the container joins:
::param{name=bridge}
:::
```
- `::param{name=x}` on its own line shows the input of the declared parameter `x` at that
point. It is bound to the same value as the parameter panel, which still lists every
parameter. Inside an included notebook the name is namespaced like everything else.
- `:::group{title="…" collapsed}` … `:::` is a titled, collapsible container for any
blocks, including nested groups. `collapsed` starts it closed; the user's choice is
remembered per notebook. The title may use `{{name}}` like prose. Groups are purely
presentational: unlike `:::when` they never hide or block steps.
- A group's **inputs** are its `::param` fields, the parameters its steps and `::host`
blocks reference (those are needed: the step cannot run without them) and, for a
`::use` section, the included notebook's parameters. Inactive `:::when` sections and
runtime values are ignored. Core `groupInputs` computes the status, shown as the outline
color and in words: orange (missing) while a required or needed input is empty or a
value is invalid, green (filled) when every input has a value, grey (optional) when
only optional inputs are empty or there are none.
- Included notebooks (`::use`) are shown as groups with the same status, so a reusable
group is a notebook included where it is needed.
## 4. Execution ## 4. Execution
- Scripts run as `bash -euo pipefail -s` with the script on stdin; no TTY. - Scripts run as `bash -euo pipefail -s` with the script on stdin; no TTY.
+10 -8
View File
@@ -15,7 +15,7 @@ export function notebookIncludes(notebook: Notebook): string[] {
const walk = (blocks: Block[]) => { const walk = (blocks: Block[]) => {
for (const block of blocks) { for (const block of blocks) {
if (block.type === "use" && !block.blocks.length) { if (includePath(block.path)) paths.push(block.path); } if (block.type === "use" && !block.blocks.length) { if (includePath(block.path)) paths.push(block.path); }
else if (block.type === "after" || block.type === "when" || block.type === "use") walk(block.blocks); else if (block.type === "after" || block.type === "when" || block.type === "use" || block.type === "group") walk(block.blocks);
} }
}; };
walk(notebook.blocks); walk(notebook.blocks);
@@ -53,6 +53,8 @@ function prefixBlocks(blocks: Block[], alias: string): Block[] {
case "after": return { ...block, stepId: qualify(alias, block.stepId), blocks: prefixBlocks(block.blocks, alias) }; case "after": return { ...block, stepId: qualify(alias, block.stepId), blocks: prefixBlocks(block.blocks, alias) };
case "when": return { ...block, param: qualify(alias, block.param), blocks: prefixBlocks(block.blocks, alias) }; case "when": return { ...block, param: qualify(alias, block.param), blocks: prefixBlocks(block.blocks, alias) };
case "use": return { ...block, scope: qualify(alias, block.scope), bindings: {}, blocks: prefixBlocks(block.blocks, alias) }; case "use": return { ...block, scope: qualify(alias, block.scope), bindings: {}, blocks: prefixBlocks(block.blocks, alias) };
case "group": return { ...block, title: rewrite(block.title, alias), blocks: prefixBlocks(block.blocks, alias) };
case "param": return { ...block, name: qualify(alias, block.name) };
case "host": return { case "host": return {
...block, id: qualify(alias, block.id), scope: scoped(alias, block.scope), ...block, id: qualify(alias, block.id), scope: scoped(alias, block.scope),
name: rewrite(block.name, alias), address: rewrite(block.address, alias), name: rewrite(block.name, alias), address: rewrite(block.address, alias),
@@ -77,7 +79,7 @@ function blockIds(blocks: Block[], into: string[] = []): string[] {
for (const block of blocks) { for (const block of blocks) {
if (block.type === "step") into.push(block.step.attrs.id); if (block.type === "step") into.push(block.step.attrs.id);
else if (block.type === "host") into.push(block.id); else if (block.type === "host") into.push(block.id);
else if (block.type !== "markdown") blockIds(block.blocks, into); else if ("blocks" in block) blockIds(block.blocks, into);
} }
return into; return into;
} }
@@ -98,7 +100,7 @@ function compose(path: string, notebook: Notebook, load: (path: string) => Noteb
const params: ParamDef[] = [...notebook.params]; const params: ParamDef[] = [...notebook.params];
const fail = (message: string, line: number) => diagnostics.push({ severity: "error", message, line }); const fail = (message: string, line: number) => diagnostics.push({ severity: "error", message, line });
const resolve = (blocks: Block[]): Block[] => blocks.map((block): Block => { const resolve = (blocks: Block[]): Block[] => blocks.map((block): Block => {
if (block.type === "after" || block.type === "when") return { ...block, blocks: resolve(block.blocks) }; if (block.type === "after" || block.type === "when" || block.type === "group") return { ...block, blocks: resolve(block.blocks) };
if (block.type !== "use") return block; if (block.type !== "use") return block;
const line = block.range.startLine; const line = block.range.startLine;
// The parser already reported an invalid path; never hand it to the loader. // The parser already reported an invalid path; never hand it to the loader.
@@ -132,11 +134,11 @@ function compose(path: string, notebook: Notebook, load: (path: string) => Noteb
return { ...notebook, params, blocks, diagnostics }; return { ...notebook, params, blocks, diagnostics };
} }
/** Find a step anywhere in the block tree (after, when and use containers). */ /** Find a step anywhere in the block tree (after, when, use and group containers). */
export function findStep(blocks: Block[], id: string): Step | undefined { export function findStep(blocks: Block[], id: string): Step | undefined {
for (const block of blocks) { for (const block of blocks) {
if (block.type === "step" && block.step.attrs.id === id) return block.step; if (block.type === "step" && block.step.attrs.id === id) return block.step;
if (block.type === "after" || block.type === "when" || block.type === "use") { if ("blocks" in block) {
const found = findStep(block.blocks, id); const found = findStep(block.blocks, id);
if (found) return found; if (found) return found;
} }
@@ -155,7 +157,7 @@ export function blockActive(notebook: Notebook, id: string, values: ParamValues)
if (block.type === "when") { if (block.type === "when") {
const found = walk(block.blocks, active && block.values.includes(values[block.param] ?? "")); const found = walk(block.blocks, active && block.values.includes(values[block.param] ?? ""));
if (found !== undefined) return found; if (found !== undefined) return found;
} else if (block.type === "after" || block.type === "use") { } else if (block.type === "after" || block.type === "use" || block.type === "group") {
const found = walk(block.blocks, active); const found = walk(block.blocks, active);
if (found !== undefined) return found; if (found !== undefined) return found;
} }
@@ -171,7 +173,7 @@ export function scopeActive(notebook: Notebook, scope: string, values: ParamValu
const walk = (blocks: Block[], active: boolean): boolean | undefined => { const walk = (blocks: Block[], active: boolean): boolean | undefined => {
for (const block of blocks) { for (const block of blocks) {
if (block.type === "use" && block.scope === scope) return active; if (block.type === "use" && block.scope === scope) return active;
if (block.type === "markdown" || block.type === "step" || block.type === "host") continue; if (!("blocks" in block)) continue;
const found = walk(block.blocks, active && (block.type !== "when" || block.values.includes(values[block.param] ?? ""))); const found = walk(block.blocks, active && (block.type !== "when" || block.values.includes(values[block.param] ?? "")));
if (found !== undefined) return found; if (found !== undefined) return found;
} }
@@ -185,7 +187,7 @@ export function captureNames(blocks: Block[], into = new Set<string>()): Set<str
for (const block of blocks) { for (const block of blocks) {
if (block.type === "step" && block.step.attrs.capture) into.add(block.step.attrs.capture); if (block.type === "step" && block.step.attrs.capture) into.add(block.step.attrs.capture);
else if (block.type === "host" && block.capture) into.add(block.capture); else if (block.type === "host" && block.capture) into.add(block.capture);
else if (block.type !== "markdown" && block.type !== "step" && block.type !== "host") captureNames(block.blocks, into); else if ("blocks" in block) captureNames(block.blocks, into);
} }
return into; return into;
} }
+76 -10
View File
@@ -1,5 +1,5 @@
// Public API of @shellbook/core. Pure functions, no I/O. // Public API of @shellbook/core. Pure functions, no I/O.
import type { Block, Notebook, ParamValues, RenderedHost, RenderedStep, Step } from "./types"; import type { Block, GroupInputs, Notebook, ParamValues, RenderedHost, RenderedStep, Step } from "./types";
import { captureNames, isBuiltin } from "./compose"; import { captureNames, isBuiltin } from "./compose";
export type * from "./types"; export type * from "./types";
export type * from "./protocol"; export type * from "./protocol";
@@ -78,8 +78,10 @@ export function resolveParams(
} }
/** /**
* Shared template substitution for steps and host blocks. Required params gate only * Shared template substitution for steps and host blocks. A block needs exactly the values
* blocks of their own scope: an included notebook's form does not block the parent. * it uses (spec §3.6): referenced parameters and runtime values, and for scripts the
* required secrets of its scope that the script reads. Required parameters it does not
* use never block it, so guided notebooks can run early steps before later values exist.
*/ */
function substitution(notebook: Notebook, scope: string | undefined, values: ParamValues, runtime: ParamValues, hostNames: readonly string[]) { function substitution(notebook: Notebook, scope: string | undefined, values: ParamValues, runtime: ParamValues, hostNames: readonly string[]) {
const resolved = resolveParams(notebook, values, hostNames, runtime); const resolved = resolveParams(notebook, values, hostNames, runtime);
@@ -87,12 +89,18 @@ function substitution(notebook: Notebook, scope: string | undefined, values: Par
const defs = new Map(notebook.params.map(def => [def.name, def])); const defs = new Map(notebook.params.map(def => [def.name, def]));
const invalid = dictionary(); const invalid = dictionary();
const missing = new Set<string>(); const missing = new Set<string>();
for (const def of notebook.params) { const ownSecrets = notebook.params.filter(def => def.type === "secret" && (def.scope ?? "") === (scope ?? ""));
if ((def.scope ?? "") !== (scope ?? "")) continue; // Every set secret of the scope is passed as an env var (secretEnv), so it must be valid.
if (def.required && !resolved.values[def.name]) missing.add(def.name); for (const def of ownSecrets)
if ((def.required || def.type === "secret") && resolved.values[def.name] if (resolved.values[def.name] && own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!;
&& own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!; /** A required secret the script reads as $NAME or ${NAME} (its local name) must be set. */
const readsSecrets = (script: string) => {
for (const def of ownSecrets) {
const local = def.scope ? def.name.slice(def.scope.length + 1) : def.name;
if (def.required && !resolved.values[def.name] && new RegExp("\\$\\{?" + local + "(?![A-Za-z0-9_])").test(script))
missing.add(def.name);
} }
};
const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => { const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => {
const def = defs.get(name); const def = defs.get(name);
if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; } if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; }
@@ -110,7 +118,7 @@ function substitution(notebook: Notebook, scope: string | undefined, values: Par
if (own(invalid, name)) return match; if (own(invalid, name)) return match;
return script ? shellQuote(value) : value; return script ? shellQuote(value) : value;
}); });
return { substitute, invalid, missing }; return { substitute, readsSecrets, invalid, missing };
} }
/** /**
@@ -124,8 +132,9 @@ export function renderStep(
runtime: ParamValues, runtime: ParamValues,
hostNames: readonly string[], hostNames: readonly string[],
): RenderedStep { ): RenderedStep {
const { substitute, invalid, missing } = substitution(notebook, step.attrs.scope, values, runtime, hostNames); const { substitute, readsSecrets, invalid, missing } = substitution(notebook, step.attrs.scope, values, runtime, hostNames);
const script = substitute(step.script, true); const script = substitute(step.script, true);
readsSecrets(step.script);
const host = step.attrs.local || step.attrs.host === undefined ? undefined : substitute(step.attrs.host, false); const host = step.attrs.local || step.attrs.host === undefined ? undefined : substitute(step.attrs.host, false);
if (!step.attrs.local && (!host || !hostNames.includes(host))) invalid.host ??= "Unknown or missing target host"; if (!step.attrs.local && (!host || !hostNames.includes(host))) invalid.host ??= "Unknown or missing target host";
const plainFile = (name: string) => !!name && !/[\\/\0\r\n]/.test(name) && !name.includes(".."); const plainFile = (name: string) => !!name && !/[\\/\0\r\n]/.test(name) && !name.includes("..");
@@ -162,6 +171,63 @@ export function renderHost(
return { id: block.id, name, address, user, port, missing: [...missing], invalid }; return { id: block.id, name, address, user, port, missing: [...missing], invalid };
} }
/**
* Input status of a container block (`:::group`, `::use`; spec §3.7). Its inputs are its
* `::param` fields, the parameters its steps and host blocks reference (those are needed:
* the step cannot run without them) and, for `::use`, the included notebook's parameters.
* Sections of inactive `:::when` blocks are ignored; runtime values are not inputs.
*/
export function groupInputs(
notebook: Notebook,
block: Block,
values: ParamValues,
hostNames: readonly string[],
runtime: ParamValues = {},
): GroupInputs {
const resolved = resolveParams(notebook, values, hostNames, runtime);
const defs = new Map(notebook.params.map(def => [def.name, def]));
const params: string[] = [];
const needed = new Set<string>();
const add = (name: string, need: boolean) => {
const def = defs.get(name);
if (!def) return;
if (!params.includes(name)) params.push(name);
if (need || def.required) needed.add(name);
};
const references = (text: string) => { for (const match of text.matchAll(template)) add(match[1]!, true); };
const walk = (items: Block[]) => {
for (const item of items) {
switch (item.type) {
case "param": add(item.name, false); break;
case "step": {
const attrs = item.step.attrs;
// In display order: the target first, then the script.
if (attrs.host !== undefined) references(attrs.host);
references(item.step.script);
attrs.artifacts.forEach(references);
for (const upload of attrs.uploads) { references(upload.src); references(upload.dst); }
break;
}
case "host": [item.name, item.address, item.user, item.port].forEach(references); break;
case "when": if (item.values.includes(resolved.values[item.param] ?? "")) walk(item.blocks); break;
case "use":
for (const def of notebook.params) if (def.scope === item.scope) add(def.name, false);
walk(item.blocks); break;
case "after": case "group": walk(item.blocks); break;
case "markdown": break;
}
}
};
walk([block]);
const filled = (name: string) => !!resolved.values[name];
const missing = params.filter(name => needed.has(name) && !filled(name));
const invalid = params.filter(name => filled(name) && own(resolved.errors, name));
const status = missing.length || invalid.length ? "missing"
: !params.length ? "none"
: params.every(filled) ? "filled" : "optional";
return { status, params, missing, invalid };
}
/** Substitute prose without quoting; secrets always appear masked. */ /** Substitute prose without quoting; secrets always appear masked. */
export function renderText(text: string, values: ParamValues, notebook: Notebook): string { export function renderText(text: string, values: ParamValues, notebook: Notebook): string {
const secrets = new Set(notebook.params.filter(def => def.type === "secret").map(def => def.name)); const secrets = new Set(notebook.params.filter(def => def.type === "secret").map(def => def.name));
+26 -3
View File
@@ -156,7 +156,24 @@ export function parseNotebook(source: string): Notebook {
blocks.push({ type: "when", param: param ?? "", values, blocks: children, range: { startLine: begin + 1, endLine: i } }); blocks.push({ type: "when", param: param ?? "", values, blocks: children, range: { startLine: begin + 1, endLine: i } });
markdownStart = i; continue; markdownStart = i; continue;
} }
const leaf = /^\s{0,3}::(use|host)\{(.*)\}\s*$/.exec(line); const group = /^\s{0,3}:::group\{(.*)\}\s*$/.exec(line);
if (group && depth < 100) {
flush(); const begin = i++;
const attrs = attributes(group[1]!, m => error(m, begin + 1));
for (const key of attrs.keys()) if (!["title", "collapsed"].includes(key)) error(`Unknown group attribute: ${key}`, begin + 1);
const title = attrs.get("title");
if (title?.length !== 1 || typeof title[0] !== "string" || !title[0].trim()) error('group requires title="…"', begin + 1);
if (attrs.has("collapsed") && attrs.get("collapsed")![0] !== true) error("collapsed must be a flag", begin + 1);
const children = parseBlocks(true, depth + 1);
if (i === lines.length) error("Unclosed group container", begin + 1);
else i++;
blocks.push({
type: "group", title: typeof title?.[0] === "string" ? title[0] : "", collapsed: attrs.has("collapsed"),
blocks: children, range: { startLine: begin + 1, endLine: i },
});
markdownStart = i; continue;
}
const leaf = /^\s{0,3}::(use|host|param)\{(.*)\}\s*$/.exec(line);
if (leaf) { if (leaf) {
flush(); flush();
const lineNo = i + 1; const lineNo = i + 1;
@@ -167,7 +184,13 @@ export function parseNotebook(source: string): Notebook {
return typeof v?.[0] === "string" ? v[0] : undefined; return typeof v?.[0] === "string" ? v[0] : undefined;
}; };
const range = { startLine: lineNo, endLine: lineNo }; const range = { startLine: lineNo, endLine: lineNo };
if (leaf[1] === "use") { if (leaf[1] === "param") {
for (const key of attrs.keys()) if (key !== "name") error(`Unknown param attribute: ${key}`, lineNo);
const name = get("name") ?? "";
if (!name) error("param requires name=parameter", lineNo);
else if (!notebook.params.some(def => def.name === name)) error(`param references unknown parameter: ${name}`, lineNo);
blocks.push({ type: "param", name, range });
} else if (leaf[1] === "use") {
for (const key of attrs.keys()) if (!["notebook", "as", "with"].includes(key)) error(`Unknown use attribute: ${key}`, lineNo); for (const key of attrs.keys()) if (!["notebook", "as", "with"].includes(key)) error(`Unknown use attribute: ${key}`, lineNo);
const path = get("notebook") ?? ""; const path = get("notebook") ?? "";
const alias = get("as") ?? ""; const alias = get("as") ?? "";
@@ -270,7 +293,7 @@ export function parseNotebook(source: string): Notebook {
i = end < lines.length ? end + 1 : end; markdownStart = i; continue; i = end < lines.length ? end + 1 : end; markdownStart = i; continue;
} }
heading ??= /^ {0,3}#\s+(.+?)\s*#*\s*$/.exec(line)?.[1]; heading ??= /^ {0,3}#\s+(.+?)\s*#*\s*$/.exec(line)?.[1];
if (/^\s*:::/.test(line) || /^\s{0,3}::(use|host)\b/.test(line)) error("Malformed or unexpected directive", i + 1); if (/^\s*:::/.test(line) || /^\s{0,3}::(use|host|param)\b/.test(line)) error("Malformed or unexpected directive", i + 1);
i++; i++;
} }
flush(); return blocks; flush(); return blocks;
+37
View File
@@ -105,6 +105,26 @@ export type Block =
blocks: Block[]; blocks: Block[];
range: SourceRange; range: SourceRange;
} }
| {
/** `::param{name=x}` — the parameter's input field at this point of the text. */
type: "param";
/** Parameter name (namespaced like `ct.hostname` inside an included notebook). */
name: string;
range: SourceRange;
}
| {
/**
* `:::group{title="…" collapsed}` — a titled, collapsible container for any blocks.
* Purely presentational: it never gates display or execution.
*/
type: "group";
/** Template; `{{name}}` is substituted like prose. */
title: string;
/** `collapsed` flag: starts closed until the user opens it. */
collapsed: boolean;
blocks: Block[];
range: SourceRange;
}
| { | {
/** `::host{name= address= user= port= capture=}` — add a machine to Hosts from the notebook. */ /** `::host{name= address= user= port= capture=}` — add a machine to Hosts from the notebook. */
type: "host"; type: "host";
@@ -120,6 +140,23 @@ export type Block =
range: SourceRange; range: SourceRange;
}; };
/**
* How far the inputs of a group (or included notebook) are filled in:
* "missing" — a needed value is empty or a value is invalid; "filled" — every input has a
* value; "optional" — only optional inputs are empty; "none" — the group has no inputs.
*/
export type InputStatus = "none" | "optional" | "filled" | "missing";
export interface GroupInputs {
status: InputStatus;
/** Parameters the group asks for or uses, in document order. */
params: string[];
/** Needed (required, or referenced by a step or host block) but empty. */
missing: string[];
/** Filled but invalid. */
invalid: string[];
}
/** A `::host` block with all templates resolved. */ /** A `::host` block with all templates resolved. */
export interface RenderedHost { export interface RenderedHost {
id: string; id: string;
+1 -1
View File
@@ -46,7 +46,7 @@ const files: Record<string, string> = { "infra/lxc.md": lxc, "services/web.md":
const load = (path: string) => files[path] === undefined ? undefined : parseNotebook(files[path]!); const load = (path: string) => files[path] === undefined ? undefined : parseNotebook(files[path]!);
const composed = () => composeNotebook("services/web.md", parseNotebook(service), load); const composed = () => composeNotebook("services/web.md", parseNotebook(service), load);
function all(blocks: Block[]): Block[] { function all(blocks: Block[]): Block[] {
return blocks.flatMap(b => b.type === "markdown" || b.type === "step" || b.type === "host" ? [b] : [b, ...all(b.blocks)]); return blocks.flatMap(b => "blocks" in b ? [b, ...all(b.blocks)] : [b]);
} }
const hosts = ["pve", "web-ct", "existing"]; const hosts = ["pve", "web-ct", "existing"];
+2 -1
View File
@@ -132,7 +132,8 @@ describe("rendering and secrets", () => {
it("blocks missing and invalid used params, unknown variables and invalid hosts", () => { it("blocks missing and invalid used params, unknown variables and invalid hosts", () => {
const n = book(" x: {type: name}\n required: {type: string, required: true}\n unused: {type: name}", "{{x}} {{unknown}} {{empty}}", "host=missing"); const n = book(" x: {type: name}\n required: {type: string, required: true}\n unused: {type: name}", "{{x}} {{unknown}} {{empty}}", "host=missing");
const r = render(n, { x: "bad value", unused: "bad value" }, { empty: "" }); const r = render(n, { x: "bad value", unused: "bad value" }, { empty: "" });
expect(r.missing).toEqual(["required", "empty"]); // An unused required param does not block the step (guided notebooks, spec §3.6).
expect(r.missing).toEqual(["empty"]);
expect(Object.keys(r.invalid).sort()).toEqual(["host", "unknown", "x"]); expect(Object.keys(r.invalid).sort()).toEqual(["host", "unknown", "x"]);
expect(r.script).toBe("{{x}} {{unknown}} {{empty}}\n"); expect(r.script).toBe("{{x}} {{unknown}} {{empty}}\n");
}); });
+202
View File
@@ -0,0 +1,202 @@
import { describe, expect, it } from "vitest";
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { blockActive, composeNotebook, findStep, groupInputs, parseNotebook, renderStep } from "../src/index";
import type { Block, Notebook } from "../src/index";
const fence = "```";
const source = `---
title: Groups
params:
host: { type: host, required: true }
user: { type: name, default: admin }
port: { type: string }
note: { type: string }
mode: { type: choice, options: [a, b] }
---
# Groups
:::group{title="Connect to {{host}}"}
First pick the server:
::param{name=host}
${fence}sh {check host="{{host}}" id=ping}
id {{user}}
${fence}
:::group{title="Optional details" collapsed}
::param{name=note}
:::
:::
:::group{title="Prose only"}
Nothing to fill in here.
:::
`;
const groups = (blocks: Block[]): Extract<Block, { type: "group" }>[] =>
blocks.flatMap(b => (b.type === "group" ? [b, ...groups(b.blocks)] : "blocks" in b ? groups(b.blocks) : []));
const hosts = ["web"];
describe("group and param directives", () => {
it("parses nested groups, the collapsed flag and parameter fields", () => {
const n = parseNotebook(source);
expect(n.diagnostics).toEqual([]);
const [connect, details, prose] = groups(n.blocks);
expect(connect).toMatchObject({ title: "Connect to {{host}}", collapsed: false, range: { startLine: 13 } });
expect(connect!.blocks.map(b => b.type)).toEqual(["markdown", "param", "markdown", "step", "markdown", "group"]);
expect(connect!.blocks[1]).toMatchObject({ type: "param", name: "host", range: { startLine: 16, endLine: 16 } });
expect(details).toMatchObject({ title: "Optional details", collapsed: true });
expect(details!.blocks).toEqual([expect.objectContaining({ type: "param", name: "note" })]);
expect(prose!.blocks).toEqual([expect.objectContaining({ type: "markdown" })]);
});
it("does not gate steps inside groups", () => {
const n = parseNotebook(source);
expect(findStep(n.blocks, "ping")?.attrs.host).toBe("{{host}}");
expect(blockActive(n, "ping", {})).toBe(true);
expect(renderStep(n, findStep(n.blocks, "ping")!, { host: "web" }, {}, hosts).script).toBe("id admin\n");
});
it.each([
[":::group{}\n:::", 'group requires title="…"'],
[':::group{title="x" open}\n:::', "Unknown group attribute: open"],
[':::group{title="x" collapsed=yes}\n:::', "collapsed must be a flag"],
[':::group{title="x"}\ntext', "Unclosed group container"],
["::param{name=nope}", "param references unknown parameter: nope"],
["::param{}", "param requires name=parameter"],
["::param{name=user label=x}", "Unknown param attribute: label"],
["::param name=user", "Malformed or unexpected directive"],
])("reports %j", (body, message) => {
const n = parseNotebook(`---\nparams:\n user: { type: name }\n---\n${body}\n`);
expect(n.diagnostics).toContainEqual(expect.objectContaining({ severity: "error", message, line: 5 }));
});
it("namespaces fields and group titles of included notebooks", () => {
const child = `---\ntitle: Child\nparams:\n name: { type: name, required: true }\n---\n:::group{title="Name {{name}}"}\n::param{name=name}\n:::\n`;
const root = `::use{notebook="lib/child.md" as=c}\n`;
const composed = composeNotebook("root.md", parseNotebook(root), path => (path === "lib/child.md" ? parseNotebook(child) : undefined));
expect(composed.diagnostics).toEqual([]);
const [group] = groups(composed.blocks);
expect(group).toMatchObject({ title: "Name {{c.name}}", blocks: [{ type: "param", name: "c.name" }] });
});
});
describe("groupInputs", () => {
const notebook = parseNotebook(source);
const [connect, details, prose] = groups(notebook.blocks);
const status = (block: Block, values: Record<string, string>, n: Notebook = notebook) =>
groupInputs(n, block, values, hosts);
it("is missing while a required field is empty, filled when every input has a value", () => {
expect(status(connect!, {})).toEqual({ status: "missing", params: ["host", "user", "note"], missing: ["host"], invalid: [] });
// user has a default; the optional note in the nested group still counts for the outer one.
expect(status(connect!, { host: "web" }).status).toBe("optional");
expect(status(connect!, { host: "web", note: "x" })).toMatchObject({ status: "filled", missing: [] });
});
it("treats a parameter a step references as needed and reports invalid values", () => {
expect(status(connect!, { host: "web", user: "" }).status).toBe("optional"); // default fills it
const n = parseNotebook(source.replace("user: { type: name, default: admin }", "user: { type: name }"));
const [group] = groups(n.blocks);
expect(status(group!, { host: "web" }, n)).toMatchObject({ status: "missing", missing: ["user"] });
expect(status(group!, { host: "nope", user: "root" }, n)).toMatchObject({ status: "missing", missing: [], invalid: ["host"] });
});
it("is optional with only optional fields and none without inputs", () => {
expect(status(details!, {})).toEqual({ status: "optional", params: ["note"], missing: [], invalid: [] });
expect(status(details!, { note: "x" }).status).toBe("filled");
expect(status(prose!, {})).toEqual({ status: "none", params: [], missing: [], invalid: [] });
});
it("ignores inactive when sections and runtime values", () => {
const n = parseNotebook(`---
params:
mode: { type: choice, options: [a, b], default: a }
x: { type: string, required: true }
---
:::group{title="G"}
:::when{mode=b}
::param{name=x}
:::
${fence}sh {run on=local id=r capture=out}
echo {{mode}}
${fence}
${fence}sh {run on=local id=s}
echo {{out}}
${fence}
:::
`);
expect(n.diagnostics).toEqual([]);
const [group] = groups(n.blocks);
expect(status(group!, {}, n)).toEqual({ status: "filled", params: ["mode"], missing: [], invalid: [] });
expect(status(group!, { mode: "b" }, n)).toMatchObject({ status: "missing", missing: ["x"] });
});
it("counts an included notebook's own parameters for its ::use section", () => {
const child = `---\ntitle: Child\nparams:\n name: { type: name, required: true }\n size: { type: string }\n---\ntext\n`;
const composed = composeNotebook("root.md", parseNotebook(`::use{notebook="lib/child.md" as=c}\n`), () => parseNotebook(child));
const use = composed.blocks.find(b => b.type === "use")!;
expect(status(use, {}, composed)).toEqual({ status: "missing", params: ["c.name", "c.size"], missing: ["c.name"], invalid: [] });
expect(status(use, { "c.name": "x" }, composed).status).toBe("optional");
});
});
describe("shipped templates", () => {
const root = fileURLToPath(new URL("../../../templates/workspace/notebooks/", import.meta.url));
const files = readdirSync(root, { recursive: true, encoding: "utf8" }).filter(f => f.endsWith(".md"));
it.each(files)("%s parses without errors", file => {
const n = parseNotebook(readFileSync(join(root, file), "utf8"));
// Included notebooks are resolved by the server; parsing alone must be clean.
expect(n.diagnostics).toEqual([]);
});
it("guides the admin-user example with fields in each group", () => {
const n = parseNotebook(readFileSync(join(root, "admin-user.md"), "utf8"));
const all = groups(n.blocks);
expect(all.map(g => g.title)).toEqual(["1. Pick the server", "2. Describe the user", "3. Create the user", "4. Verify"]);
expect(groupInputs(n, all[2]!, {}, hosts)).toMatchObject({ status: "missing", missing: ["host", "user", "pubkey"] });
const values = { host: "web", user: "ops", pubkey: "ssh-ed25519 AAAA ops" };
expect(all.map(g => groupInputs(n, g, values, hosts).status)).toEqual(["filled", "filled", "filled", "filled"]);
expect(renderStep(n, findStep(n.blocks, "create")!, values, {}, hosts).script)
.toContain(String.raw`printf '%s\n' 'ssh-ed25519 AAAA ops' > /home/ops/.ssh/authorized_keys`);
});
});
describe("step gating for guided notebooks", () => {
const n = parseNotebook(`---
params:
host: { type: host, required: true }
user: { type: name, required: true }
TOKEN: { type: secret, required: true }
OTHER: { type: secret, required: true }
---
${fence}sh {check host="{{host}}" id=first}
true
${fence}
${fence}sh {run host="{{host}}" id=later}
useradd {{user}}
${fence}
${fence}sh {run host="{{host}}" id=token}
curl -H "Authorization: Bearer \${TOKEN}" https://example.invalid
${fence}
`);
const step = (id: string) => findStep(n.blocks, id)!;
const render = (id: string, values: Record<string, string>) => renderStep(n, step(id), values, {}, hosts);
it("blocks a step only on the values it uses", () => {
// Required, but unused by this step: an earlier step runs before later values are known.
expect(render("first", { host: "web" })).toMatchObject({ missing: [], invalid: {} });
expect(render("later", { host: "web" }).missing).toEqual(["user"]);
});
it("treats a required secret the script reads as $NAME or \${NAME} as used", () => {
expect(render("token", { host: "web" }).missing).toEqual(["TOKEN"]);
expect(render("token", { host: "web", TOKEN: "t" })).toMatchObject({ missing: [], invalid: {} });
// A $TOKENX or OTHER mention is not TOKEN.
expect(render("first", { host: "web" }).missing).not.toContain("OTHER");
});
});
+24 -1
View File
@@ -48,7 +48,9 @@ Non-secret defaults may reference other parameters.
Use `{{name}}` in prose, attributes and scripts. Script substitution is already Use `{{name}}` in prose, attributes and scripts. Script substitution is already
shell-quoted by ShellBook's core: write `id {{user}}`, not `id '{{user}}'`. shell-quoted by ShellBook's core: write `id {{user}}`, not `id '{{user}}'`.
Do not invent escaping rules or assume templates expand like shell variables. Do not invent escaping rules or assume templates expand like shell variables.
Missing required parameters disable execution. In shell strings use ordinary A step runs once every value it uses is set: its `{{…}}` references and the required
secrets its script reads as `$NAME`. Unused required parameters do not block it, so
early steps can run before later values are known. In shell strings use ordinary
shell variables where needed, e.g. `destination={{destination}}` then `"$destination"`. shell variables where needed, e.g. `destination={{destination}}` then `"$destination"`.
## Step syntax and every attribute ## Step syntax and every attribute
@@ -135,5 +137,26 @@ apt-get install -y nginx
offers to add a created machine to Hosts and stores its name in `{{host}}`. offers to add a created machine to Hosts and stores its name in `{{host}}`.
- `{{shellbook.public_key}}` is ShellBook's SSH public key, e.g. for `pct create --ssh-public-keys`. - `{{shellbook.public_key}}` is ShellBook's SSH public key, e.g. for `pct create --ssh-public-keys`.
## Guided text: fields and groups
````markdown
:::group{title="1. Network" collapsed}
Pick the bridge the container joins:
::param{name=bridge}
```sh {check host="{{host}}" id=bridge-exists}
ip link show {{bridge}}
```
:::
````
- `::param{name=x}` on its own line shows parameter `x`'s input at that point (same
value as the parameter panel). Use it to ask for each value where it is explained.
- `:::group{title="…"}` … `:::` is a collapsible section for anything (text, fields,
steps, nested groups); `collapsed` starts it closed. Its outline is orange while a
required field or a parameter its steps use is empty, green when all its inputs are
filled, grey otherwise. Groups never hide or block steps; use `:::when` for that.
See the notebooks for complete SSH-key, read-only hardening, Debian package, LXC See the notebooks for complete SSH-key, read-only hardening, Debian package, LXC
container (`infra/lxc-container.md`) and chained service (`services/web-server.md`) examples. container (`infra/lxc-container.md`) and chained service (`services/web-server.md`) examples.
@@ -0,0 +1,58 @@
---
title: Create an admin user
params:
host: { type: host, required: true, label: Target server }
user: { type: name, required: true, label: User name }
pubkey: { type: string, required: true, label: Public SSH key }
shell: { type: path, default: /bin/bash, label: Login shell }
---
# Create an admin user
A guided runbook: each section asks for what it needs where it is explained. A
section's outline turns green once its values are filled in. For Debian hosts;
runs need passwordless sudo and ask for confirmation.
:::group{title="1. Pick the server"}
Choose the machine from Hosts. This check only reads state.
::param{name=host}
```sh {check host="{{host}}" id=can-sudo title="Passwordless sudo works" sudo}
true
```
:::
:::group{title="2. Describe the user"}
Pick a login name (letters, digits, `.`, `_`, `-`) and paste the public key the
user logs in with, e.g. the content of their `~/.ssh/id_ed25519.pub`.
::param{name=user}
::param{name=pubkey}
::param{name=shell}
```sh {check host="{{host}}" id=user-free title="User does not exist yet"}
! id {{user}}
```
:::
:::group{title="3. Create the user"}
Creates **{{user}}** in the `sudo` group and authorizes the key.
```sh {run host="{{host}}" id=create title="Create user and authorize key" sudo confirm}
useradd --create-home --shell {{shell}} --groups sudo {{user}}
install -d -m 700 -o {{user}} -g {{user}} /home/{{user}}/.ssh
printf '%s\n' {{pubkey}} > /home/{{user}}/.ssh/authorized_keys
chown {{user}}:{{user}} /home/{{user}}/.ssh/authorized_keys
chmod 600 /home/{{user}}/.ssh/authorized_keys
```
:::
:::group{title="4. Verify" collapsed}
```sh {check host="{{host}}" id=verify title="User is in sudo and has the key" sudo}
id -nG {{user}} | grep -qw sudo
test -s /home/{{user}}/.ssh/authorized_keys
```
:::