diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index b6da778..69f0627 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -1,5 +1,5 @@ import { registerSettings } from "./settings"; -import { hostsPlugin } from "./hosts"; +import { builtinValues, hostsPlugin } from "./hosts"; import Fastify, { type FastifyInstance } from "fastify"; import websocket from "@fastify/websocket"; import { loadConfig, type ServerConfig } from "./config"; @@ -42,9 +42,10 @@ export async function buildApp(options: AppOptions = {}): Promise builtinValues(config); + await app.register(workspacePlugin, { config, builtins }); await app.register(hostsPlugin, { config }); - await app.register(runsPlugin, { config, hub }); + await app.register(runsPlugin, { config, hub, builtins }); await app.register(terminalPlugin, { ...options.terminal, workspaceDir: config.workspaceDir }); await app.register(chatPlugin, { config }); diff --git a/apps/server/src/hosts/index.ts b/apps/server/src/hosts/index.ts index 448015d..e5a3974 100644 --- a/apps/server/src/hosts/index.ts +++ b/apps/server/src/hosts/index.ts @@ -43,6 +43,11 @@ export async function shellbookPublicKey(config: ServerConfig) { throw httpError(503, "ShellBook key unavailable"); return `${parsed.type} ${parsed.getPublicSSH().toString("base64")}`; } +/** Runtime values every notebook can reference ({{shellbook.public_key}}); empty when the key is unavailable. */ +export async function builtinValues(config: ServerConfig): Promise> { + try { return { "shellbook.public_key": await shellbookPublicKey(config) }; } + catch { return {}; } +} export async function hostsPlugin( app: FastifyInstance, { config }: { config: ServerConfig }, diff --git a/apps/server/src/runs/index.ts b/apps/server/src/runs/index.ts index d430d42..19894b9 100644 --- a/apps/server/src/runs/index.ts +++ b/apps/server/src/runs/index.ts @@ -3,38 +3,41 @@ import { randomUUID } from "node:crypto"; import { appendFile, mkdir, copyFile, stat, rm } from "node:fs/promises"; import path from "node:path"; import { createReadStream } from "node:fs"; -import { parseNotebook, resolveParams, renderStep, secretEnv, shellQuote, type Block, type Step, type Notebook, type RenderedStep, type StartRunRequest, type HostInfo } from "@shellbook/core"; +import { blockActive, findStep, isBuiltin, resolveParams, renderStep, secretEnv, shellQuote, type Step, type Notebook, type ParamValues, type RenderedStep, type StartRunRequest, type HostInfo } from "@shellbook/core"; import type { FastifyInstance } from "fastify"; import type { Client } from "ssh2"; import type { ServerConfig } from "../config"; -import { readHosts, readNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace"; +import { readHosts, loadNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace"; import { connect, exec, localExec, scriptInput, sftp, sftpRequest, transfer, HostKeyError, sshFailure, type Output } from "../ssh"; import { EventsHub } from "./events"; import { runRoot, artifactFile, persistArtifacts, isSensitive, claimArtifact, sweepRuns } from "./artifacts"; export { EventsHub } from "./events"; -export function findStep(blocks: Block[], id: string): Step | undefined { - for (const block of blocks) { - if (block.type === "step" && block.step.attrs.id === id) return block.step; - if (block.type === "after") { const found = findStep(block.blocks, id); if (found) return found; } - } -} - -export function prepareRun(notebook: Notebook, req: StartRunRequest, hosts: HostInfo[]) { +/** `notebook` is the composed notebook (see loadNotebook); builtins come from the server only. */ +export function prepareRun(notebook: Notebook, req: StartRunRequest, hosts: HostInfo[], builtins: ParamValues = {}) { if (notebook.diagnostics.some(d => d.severity === "error")) throw httpError(400, "Notebook has errors"); const step = findStep(notebook.blocks, req.stepId); if (!step) throw httpError(404, "Step not found"); const names = hosts.map(h => h.name); - const resolved = resolveParams(notebook, req.params, names); - if (Object.keys(resolved.errors).length) throw httpError(400, "Parameters are missing or invalid"); - const rendered = renderStep(notebook, step, resolved.values, req.runtime, names); + // A client cannot supply or override builtins. + const runtime: ParamValues = Object.assign(Object.create(null) as ParamValues, + Object.fromEntries(Object.entries(req.runtime).filter(([name]) => !isBuiltin(name))), builtins); + 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). + // Same rule as core's renderStep: required params and secrets of the step's scope gate it; + // other params only matter when the step references them (checked by renderStep below). + 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"); + 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"); const host = hosts.find(h => h.name === rendered.host); if (!rendered.local && !host) throw httpError(400, "Unknown target host"); for (const name of rendered.artifacts) safeRelative(name); if (rendered.kind === "check" && (rendered.uploads.length || rendered.artifacts.length)) throw httpError(400, "Checks cannot upload or collect artifacts"); if (!Number.isFinite(step.attrs.timeoutSec) || step.attrs.timeoutSec <= 0) throw httpError(400, "Invalid timeout"); - return { step, rendered, host, env: secretEnv(notebook, resolved.values) }; + return { step, rendered, host, env: secretEnv(notebook, resolved.values, step.attrs.scope) }; } /** Streaming redaction retains possible secret prefixes across chunks. */ @@ -179,7 +182,7 @@ export async function executeRun({ config, hub, runId, request, step, rendered, function stringMap(value: unknown): value is Record { return !!value && typeof value === "object" && !Array.isArray(value) && Object.values(value).every(v => typeof v === "string"); } -export async function runsPlugin(app: FastifyInstance, { config, hub }: { config: ServerConfig; hub: EventsHub }) { +export async function runsPlugin(app: FastifyInstance, { config, hub, builtins = async () => ({}) }: { config: ServerConfig; hub: EventsHub; builtins?: () => Promise }) { const queue = new SerialQueue(); const active = new Set(); const downloads = new Set>(); @@ -197,8 +200,8 @@ export async function runsPlugin(app: FastifyInstance, { config, hub }: { config app.post<{ Body: StartRunRequest }>("/api/runs", async (req, reply) => { const body = req.body; if (!body || typeof body.notebookPath !== "string" || typeof body.stepId !== "string" || !stringMap(body.params) || !stringMap(body.runtime) || !stringMap(body.artifactSources) || (body.acceptHostKey !== undefined && typeof body.acceptHostKey !== "string")) throw httpError(400, "Invalid run request"); - const { source } = await readNotebook(config, body.notebookPath); - const prepared = prepareRun(parseNotebook(source), body, await readHosts(config)); + const { notebook } = await loadNotebook(config, body.notebookPath); + const prepared = prepareRun(notebook, body, await readHosts(config), await builtins()); const runId = randomUUID(); active.add(runId); // Queue immediately; defer the work to allow the HTTP response to reach the subscriber. diff --git a/apps/server/src/workspace/index.ts b/apps/server/src/workspace/index.ts index e445532..dd83cff 100644 --- a/apps/server/src/workspace/index.ts +++ b/apps/server/src/workspace/index.ts @@ -4,7 +4,7 @@ import { readFile, readdir, realpath, lstat } from "node:fs/promises"; import path from "node:path"; import { parse } from "yaml"; import { validateHost } from "../hosts/validation"; -import { parseNotebook, type HostInfo } from "@shellbook/core"; +import { composeNotebook, notebookIncludes, parseNotebook, type HostInfo, type Notebook, type ParamValues } from "@shellbook/core"; import type { FastifyInstance } from "fastify"; import type { ServerConfig } from "../config"; @@ -43,6 +43,29 @@ export async function readNotebook(config: ServerConfig, name: string) { return { file, source: await readFile(file, "utf8") }; } +/** Upper bound on notebook files read for one composition (includes of includes). */ +const MAX_INCLUDE_FILES = 32; + +/** + * Read a notebook and compose its `::use` includes. Included files go through the same + * workspace path rules; unreadable ones become "not found" diagnostics on the use line. + */ +export async function loadNotebook(config: ServerConfig, name: string) { + const { file, source } = await readNotebook(config, name); + const root = parseNotebook(source); + const parsed = new Map([[name, root]]); + const queue = notebookIncludes(root); + while (queue.length && parsed.size < MAX_INCLUDE_FILES) { + const next = queue.shift()!; + if (parsed.has(next)) continue; + const included = await readNotebook(config, next).then(r => parseNotebook(r.source), () => undefined); + parsed.set(next, included); + if (included) queue.push(...notebookIncludes(included)); + } + const notebook = composeNotebook(name, root, include => parsed.get(include)); + return { file, source, notebook, includes: [...parsed.keys()].filter(include => include !== name) }; +} + export async function readHosts(config: ServerConfig): Promise { return parseHosts(await readFile(path.join(config.workspaceDir, "hosts.yaml"), "utf8")); } @@ -72,7 +95,13 @@ export class SerialQueue { async idle() { await Promise.allSettled(this.tails.values()); } } -export async function workspacePlugin(app: FastifyInstance, { config }: { config: ServerConfig }) { +export interface WorkspaceOptions { + config: ServerConfig; + /** Server-provided runtime values such as shellbook.public_key. */ + builtins?: () => Promise; +} + +export async function workspacePlugin(app: FastifyInstance, { config, builtins = async () => ({}) }: WorkspaceOptions) { const saves = new SerialQueue(); notebookManagement(app, config, saves); app.get("/api/hosts", async () => ({ hosts: await readHosts(config) })); @@ -93,8 +122,8 @@ export async function workspacePlugin(app: FastifyInstance, { config }: { config return { notebooks: notebooks.sort((a, b) => a.path.localeCompare(b.path)) }; }); app.get<{ Params: { path: string } }>("/api/notebooks/:path", async req => { - const { source } = await readNotebook(config, req.params.path); - return { path: req.params.path, source, notebook: parseNotebook(source), version: version(source) }; + const { source, notebook, includes } = await loadNotebook(config, req.params.path); + return { path: req.params.path, source, notebook, includes, builtins: await builtins(), version: version(source) }; }); app.put<{ Params: { path: string }; Body: { source: string; baseVersion: string } }>("/api/notebooks/:path", async req => { if (!req.body || typeof req.body.source !== "string" || typeof req.body.baseVersion !== "string") throw httpError(400, "Invalid save request"); diff --git a/apps/server/test/chained.test.ts b/apps/server/test/chained.test.ts new file mode 100644 index 0000000..ee447cc --- /dev/null +++ b/apps/server/test/chained.test.ts @@ -0,0 +1,159 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { cp, mkdtemp, mkdir, writeFile, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { generateKeyPairSync } from "node:crypto"; +import type { HostInfo, NotebookResponse, StartRunRequest } from "@shellbook/core"; +import { findStep } from "@shellbook/core"; +import { buildApp } from "../src/app"; +import { loadConfig, type ServerConfig } from "../src/config"; +import { prepareRun } from "../src/runs"; +import { loadNotebook } from "../src/workspace"; + +const lxc = `--- +title: LXC container +params: + proxmox: {type: host, required: true} + hostname: {type: name, required: true} + ROOTPW: {type: secret} +--- +\`\`\`sh {run host="{{proxmox}}" id=create capture=address} +pct create --hostname {{hostname}} --key {{shellbook.public_key}} --pw "$ROOTPW" +\`\`\` + +::host{name="{{hostname}}" address="{{address}}" capture=host} +`; +const service = `--- +title: Web server +params: + target: {type: choice, options: [existing, lxc], default: lxc} + host: {type: host, required: true, default: "{{ct.host}}"} + TOKEN: {type: secret} +--- +:::when{target=lxc} +::use{notebook="infra/lxc.md" as=ct with="hostname=web-ct"} +::: + +\`\`\`sh {run host="{{host}}" id=install} +apt-get install -y nginx +\`\`\` +`; +const hosts: HostInfo[] = ["pve", "web-ct", "existing"].map(name => ({ name, address: "127.0.0.1", user: "root", port: 22, tags: [] })); + +const cleanup: (() => Promise)[] = []; +afterEach(async () => { for (const fn of cleanup.splice(0).reverse()) await fn(); }); +async function fixture(files: Record = { "infra/lxc.md": lxc, "services/web.md": service }) { + const dir = await mkdtemp(path.join(os.tmpdir(), "shellbook-chain-")); + cleanup.push(() => rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })); + const config = loadConfig({ workspaceDir: path.join(dir, "workspace"), dataDir: path.join(dir, "data"), sshKeyPath: path.join(dir, "key") }); + await mkdir(path.join(config.workspaceDir, "notebooks"), { recursive: true }); + for (const [name, source] of Object.entries(files)) { + await mkdir(path.dirname(path.join(config.workspaceDir, "notebooks", name)), { recursive: true }); + await writeFile(path.join(config.workspaceDir, "notebooks", name), source); + } + await writeFile(path.join(config.workspaceDir, "hosts.yaml"), "- name: pve\n address: 127.0.0.1\n user: root\n"); + await writeFile(config.sshKeyPath, generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }).toString()); + return config; +} +async function app(config: ServerConfig) { + const instance = await buildApp({ config, auth: false }); + cleanup.push(() => instance.close()); + return instance; +} +const request = (stepId: string, params: Record, runtime: Record = {}): StartRunRequest => + ({ notebookPath: "services/web.md", stepId, params, runtime, artifactSources: {} }); + +describe("chained notebooks on the server", () => { + it("returns the composed notebook with its includes and builtins", async () => { + const config = await fixture(); + const res = await (await app(config)).inject("/api/notebooks/services%2Fweb.md"); + expect(res.statusCode).toBe(200); + const body = res.json() as NotebookResponse; + expect(body.source).toBe(service); + expect(body.includes).toEqual(["infra/lxc.md"]); + expect(body.builtins["shellbook.public_key"]).toMatch(/^ssh-rsa AAAA/); + expect(body.notebook.diagnostics).toEqual([]); + expect(body.notebook.params.map(p => p.name)).toContain("ct.hostname"); + expect(findStep(body.notebook.blocks, "ct.create")?.attrs.scope).toBe("ct"); + }); + + it("reports a missing or unreadable include on the use line and refuses runs", async () => { + const config = await fixture({ "web.md": '::use{notebook="../escape.md" as=x}\n::use{notebook="gone.md" as=y}\n' }); + const { notebook, includes } = await loadNotebook(config, "web.md"); + expect(includes).toEqual(["gone.md"]); + expect(notebook.diagnostics.map(d => [d.line, d.message])).toEqual([ + [1, 'use requires notebook="dir/name.md" (relative to notebooks/)'], + [2, "Included notebook not found: gone.md"], + ]); + const res = await (await app(config)).inject({ method: "POST", url: "/api/runs", payload: { ...request("x", {}), notebookPath: "web.md" } }); + expect(res.statusCode).toBe(400); + expect(res.json().message).toBe("Notebook has errors"); + }); + + it("gates by scope, refuses inactive when sections and injects server builtins only", async () => { + const config = await fixture(); + const { notebook } = await loadNotebook(config, "services/web.md"); + const builtins = { "shellbook.public_key": "ssh-ed25519 SERVER" }; + const values = { target: "lxc", "ct.proxmox": "pve", "ct.ROOTPW": "root-pw", TOKEN: "token" }; + // The parent's host is still pending (captured later), which must not block the container step. + const prepared = prepareRun(notebook, request("ct.create", values, { "shellbook.public_key": "ssh-ed25519 CLIENT" }), hosts, builtins); + 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.env).toEqual({ ROOTPW: "root-pw" }); + expect(() => prepareRun(notebook, request("install", values), hosts, builtins)).toThrow("Parameters are missing or invalid"); + const parent = prepareRun(notebook, request("install", values, { "ct.host": "web-ct" }), hosts, builtins); + expect(parent.host?.name).toBe("web-ct"); + expect(parent.env).toEqual({ TOKEN: "token" }); + // 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", { target: "lxc" }), hosts, builtins)).toThrow("Parameters are missing or invalid"); + // 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"); + }); + + it("lets an optional parameter wait for a capture without blocking the step that captures it", async () => { + const config = await fixture({ "next.md": `--- +params: + proxmox: {type: host, required: true} + ctid: {type: name, default: "{{nextid}}"} +--- +\`\`\`sh {check host="{{proxmox}}" id=next capture=nextid} +pvesh get /cluster/nextid +\`\`\` + +\`\`\`sh {run host="{{proxmox}}" id=create} +pct create {{ctid}} +\`\`\` +` }); + const { notebook } = await loadNotebook(config, "next.md"); + const run = (stepId: string, runtime: Record = {}) => + prepareRun(notebook, { notebookPath: "next.md", stepId, params: { proxmox: "pve" }, runtime, artifactSources: {} }, hosts); + expect(run("next").rendered.script).toBe("pvesh get /cluster/nextid\n"); + expect(() => run("create")).toThrow("Step parameters are missing or invalid"); + expect(run("create", { nextid: "105" }).rendered.script).toBe("pct create 105\n"); + }); + + it("ships template notebooks that compose without diagnostics", async () => { + const config = await fixture({}); + await cp(path.resolve(__dirname, "../../../templates/workspace/notebooks"), path.join(config.workspaceDir, "notebooks"), { recursive: true }); + const names = ["base-hardening-checks.md", "install-package.md", "ssh-key.md", "infra/lxc-container.md", "services/web-server.md"]; + for (const name of names) expect((await loadNotebook(config, name)).notebook.diagnostics, name).toEqual([]); + const { notebook, includes } = await loadNotebook(config, "services/web-server.md"); + expect(includes).toEqual(["infra/lxc-container.md"]); + const values = { target: "lxc", server_name: "web", "ct.proxmox": "pve", "ct.net": "ip=10.0.30.160/24,gw=10.0.30.1" }; + const runtime = { "ct.nextid": "105", "ct.template": "local:vztmpl/debian-12-standard_12.7-1_amd64.tar.zst" }; + const prepared = prepareRun(notebook, request("ct.create", values, runtime), hosts, { "shellbook.public_key": "ssh-ed25519 AAAAKEY shellbook" }); + 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("--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", { target: "existing", host: "existing" }), hosts, {}).host?.name).toBe("existing"); + }); + + it("refuses an inactive step over HTTP", async () => { + const config = await fixture(); + const res = await (await app(config)).inject({ method: "POST", url: "/api/runs", payload: request("ct.create", { target: "existing", "ct.proxmox": "pve" }) }); + expect(res.statusCode).toBe(400); + expect(res.json().message).toBe("Step is not part of the selected options"); + }); +}); diff --git a/apps/server/test/m2.test.ts b/apps/server/test/m2.test.ts index 29c8a94..be29121 100644 --- a/apps/server/test/m2.test.ts +++ b/apps/server/test/m2.test.ts @@ -13,7 +13,9 @@ import { SerialQueue, safeRelative } from "../src/workspace"; import { connect, exec, fingerprint, HostKeyError, localExec, scriptInput } from "../src/ssh"; import { executeRun, EventsHub, prepareRun, redactor } from "../src/runs"; -vi.mock("@shellbook/core", () => ({ +vi.mock("@shellbook/core", async importOriginal => ({ + // Composition helpers stay real; parsing and rendering are stubbed per test. + ...pick(await importOriginal(), "composeNotebook", "notebookIncludes", "findStep", "blockActive", "isBuiltin"), parseNotebook: vi.fn((source: string) => ({ title: source.split("\n")[0], params: [], blocks: [], diagnostics: [] })), shellQuote: (value: string) => /^[A-Za-z0-9._/@:=+-]+$/.test(value) ? value : "'" + value.replaceAll("'", "'\\''") + "'", resolveParams: vi.fn((_notebook: Notebook, values: Record) => ({ values, errors: {} })), @@ -21,6 +23,9 @@ vi.mock("@shellbook/core", () => ({ secretEnv: vi.fn(() => ({})), })); +function pick(object: T, ...keys: K[]) { + return Object.fromEntries(keys.map(key => [key, object[key]])) as Pick; +} const cleanup: (() => Promise)[] = []; afterEach(async () => { for (const fn of cleanup.splice(0).reverse()) await fn(); vi.clearAllMocks(); }); async function fixture() { @@ -175,7 +180,7 @@ describe("pipeline helpers", () => { expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: -1 }); }); it("refuses missing or invalid parameters before execution", () => { - const notebook: Notebook = { title: "Test", params: [], 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"] }); diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index c541459..8e14693 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -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 }) { ); + if (block.type === "when") + return block.values.includes(resolved.values[block.param] ?? "") ? ( +
+ {blocks(block.blocks)} +
+ ) : null; + if (block.type === "use") + return ( +
+ + {block.title ?? block.path} + + {block.path} · as {block.scope} + + + {block.blocks.length ? ( + blocks(block.blocks) + ) : ( +

Save the notebook to load {block.path}.

+ )} +
+ ); + if (block.type === "host") { + const rendered = renderHost(notebook, block, resolved.values, runtime, hostNames); + const capture = (name: string) => { + if (block.capture) dispatch({ type: "runtime.set", notebookPath: path, name: block.capture, value: name }); + }; + return ( + h.name === rendered.name)} + captured={block.capture ? runtime[block.capture] : undefined} + onUse={capture} + onAdd={async (host) => { + await api.addHost(host); + setHosts((await api.hosts()).hosts); + window.dispatchEvent(new Event("shellbook:hosts-changed")); + capture(host.name); + }} + /> + ); + } if (block.type === "after") { const run = runFor(block.stepId); return run && @@ -265,7 +337,7 @@ export function App({ api }: { api: Api }) { block.step, resolved.values, runtime, - hosts.map((h) => h.name), + hostNames, ); return ( 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 diff --git a/apps/web/src/AuthoringToolbar.tsx b/apps/web/src/AuthoringToolbar.tsx index 1111972..d78a2e9 100644 --- a/apps/web/src/AuthoringToolbar.tsx +++ b/apps/web/src/AuthoringToolbar.tsx @@ -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("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 (