Compare commits

...
21 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
Florian Schmidt cae72c7f28 docs(mind): record self-update from Settings (#15) 2026-11-16 15:31:01 +01:00
Florian Schmidt 2025185489 feat(web): update button in Settings (#15)
Shows the installed commit, checks for new commits, starts the update after
a confirmation and follows its output through the service restart.
2026-11-16 15:31:01 +01:00
Florian Schmidt 936abbef9d feat(deploy): install the update trigger units (#15)
shellbook-update.path starts the oneshot shellbook-update.service, which
runs the fixed root-owned updater and logs to /var/log/shellbook-update.log.
2026-11-16 15:31:01 +01:00
Florian Schmidt 2fc5f99f59 feat(server): request updates through a systemd trigger (#15)
The service stays unprivileged: POST /api/settings/update only writes the
update-request file in the data directory, which a root-owned path unit
watches. Status comes from systemctl show and the root-owned update log;
the check fetches the tracked branch into FETCH_HEAD and lists new commits.
2026-11-16 15:31:00 +01:00
Florian Schmidt ebf8649ab6 docs(mind): record app icon (#14) 2026-11-16 15:21:07 +01:00
Florian Schmidt 6350f1e6f4 feat(web): app icon and logo (#14)
A notebook with a shell prompt on a dark tile, as one SVG used for the
favicon, the top bar, sign-in, setup and the README. PNG renders (192,
512, apple-touch) and a web manifest let browsers and phones show it
when the app is added to the home screen.
2026-11-16 15:21:07 +01:00
Florian Schmidt bcf392e95a docs(mind): record collapsible parameters (#13) 2026-11-16 14:45:54 +01:00
Florian Schmidt 57305a2dc6 feat(web): collapsible parameter form and groups (#13)
The parameter form and each included notebook group collapse; the choice
is remembered in the browser. Collapsed, the form lists only missing
required values and values changed from their default as chips that open
their field, and counts untouched defaults, so it stays one line.
2026-11-16 14:45:54 +01:00
Florian Schmidt 6bfcc9d70d fix(core): report parameter errors at their line with a quoting hint (#13)
An unquoted comma in a flow-mapping label splits it into a valueless key.
Parameter diagnostics now point at the parameter's own frontmatter line,
and a valueless unknown field says that the value needs quotes.
2026-11-16 14:45:53 +01:00
Florian Schmidt dd0af5d580 docs(mind): record web UI shell (#12) 2026-11-16 12:32:01 +01:00
Florian Schmidt e38f9c453c feat(web): rework layout and quality of life (#12)
- App shell: top bar with connection state and Chat/Terminal toggles,
  per-column scrolling, sidebar only on the Notebooks page.
- Hash routes (#/notebooks/<path>, #/hosts, #/settings) so reloads and
  links keep the open notebook and page.
- Parameters sit beside the notebook on wide screens, collapsible, with
  missing-count summary and Reset; non-secret values are remembered per
  notebook in localStorage (secrets and undeclared names never stored).
- Sticky notebook header with breadcrumbs, check summary and run-all;
  Ctrl/Cmd+S saves the Markdown draft.
- Step cards show target, one deduplicated hint for missing values and
  copy feedback.
- Shared Dialog, Menu and CopyButton components; notebook and host
  actions move into menus and modal dialogs.
- Hosts page as a compact list; Settings split into cards with sign out
  for this browser.
2026-11-16 12:32:01 +01:00
Florian Schmidt 16cfcd36ea fix(templates): avoid template syntax in LXC prose (#12)
The literal {{ct.host}} in prose was composed into {{ct.ct.host}} when the
notebook is included; describe the capture in words instead.
2026-11-16 12:31:54 +01:00
Florian Schmidt 382da1736f fix(core): keep unset values visible in prose (#12)
renderText now leaves {{name}} in place when the value is empty, so prose
shows which parameter is still missing instead of a blank.
2026-11-16 12:31:54 +01:00
Florian Schmidt 276d6ef3ca docs(mind): record chained notebook decisions (#11) 2026-11-16 11:42:50 +01:00
Florian Schmidt 54115289cc feat(deploy): bring new notebook templates into existing workspaces (#11)
Each shipped template is offered once (recorded in
/etc/shellbook/templates-offered) and copied as the service user only
when the file does not exist, so updates add new templates without
overwriting files or restoring deleted ones.
2026-11-16 11:42:13 +01:00
Florian Schmidt 85afd105f7 feat(templates): LXC container and chained web server notebooks (#11)
infra/lxc-container.md creates an unprivileged container on a Proxmox
host with ShellBook's key, waits for its address and adds it to Hosts.
services/web-server.md installs nginx on an existing host or on a new
container through ::use. Document chaining in the spec (3.6) and in the
workspace format guide.
2026-11-16 11:42:12 +01:00
Florian Schmidt 845d6c828e feat: chained notebooks with when sections and host blocks (#11)
A notebook can include another one and continue with what it produced:

- core: parse :::when{param=a,b}, ::use{notebook= as= with=} and
  ::host{name= address= user= port= capture=}; composeNotebook namespaces
  an included notebook's params, steps, captures and templates by alias
  (cycles, missing files, depth > 4 and child errors are reported on the
  use line). Defaults may reference captures and builtins
  ({{shellbook.public_key}}); required params and secrets gate only steps
  of their own scope; secretEnv passes a scope's secrets under local names.
- protocol: NotebookResponse gains includes and builtins.
- server: compose includes on load, inject builtins (client values are
  ignored), refuse steps in inactive when sections.
- web: render when/use/host blocks, group included params in the form,
  add a created machine to Hosts and capture its name, reload when an
  included notebook changes, run all checks only for active steps,
  authoring snippets for when, use and host.
2026-11-16 11:42:12 +01:00
70 changed files with 5938 additions and 1267 deletions
+8
View File
@@ -12,5 +12,13 @@
- [2026-11-16] **Notebook management (#9):** a shared mutation queue serializes saves/create/move/duplicate/delete. Exclusive hard-link publication prevents target replacement; saves use temp+rename. The recursive watcher updates lists; deleted open drafts are retained. Frontmatter helpers use YAML document nodes.
- [2026-11-16] **Host credentials (#7):** write-only AES-256-GCM files under dataDir, host-name AAD; shared SSH connect selects per-host password/key. ssh2 1.17.0 has no client user-certificate pairing API. Hosts plugin owns management routes and preserves inventory comments/version checks.
- [2026-11-16] **Deploy/update:** host one-liner `bootstrap.sh` (temp dir, nothing left on host); `install.sh` is install-or-update; root-owned `shellbook-update` fetches the installer over HTTPS because root must never run code from the service-user-writable `/opt/shellbook`.
- [2026-11-16] **Chained notebooks (#11):** `::use` is flattened in core (`composeNotebook`): alias-prefixed params/ids/captures with `scope`, so render/run keep one notebook model and one substitution path. Server loads files and injects builtins (`shellbook.*`, server-only); `:::when` gates display and execution; `::host` adds to Hosts via the host-management API. Required params/secrets gate only their own scope, identically in core render and server `prepareRun`.
- [2026-11-16] **Template delivery:** `install.sh` offers each shipped notebook template once (`/etc/shellbook/templates-offered`), copied as the service user, never overwriting or restoring deleted files.
- [2026-11-16] **Web UI shell (#12):** top bar (tabs, live state, Chat/Terminal), notebook sidebar only on Notebooks, parameter panel beside the notebook via a container query (above it when narrow), dialogs/menus from `ui.tsx`. Page and notebook live in the URL hash (`route.ts`); typed non-secret values are remembered per notebook in localStorage (`paramMemory.ts`, secrets and undeclared names are dropped on read and write).
- [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] **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
+4
View File
@@ -15,5 +15,9 @@
- [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] **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 (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] **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.
## Archive
+3 -3
View File
@@ -2,7 +2,7 @@
> Always-loaded. Everything else is on-demand. Update TOC when files change.
## Current Focus
- [2026-11-16] M0–M3 (#1–#4) and the UI-first follow-ups (#7 hosts/credentials, #8 chat, #9 notebook management, #10 settings/setup) 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.
## Invariants
@@ -15,7 +15,7 @@
- Everything doable from the web UI; files are storage, not the only way in.
## Table of Contents
- `architecture.md` — 11 entries — why custom app, stack, AI integration, workspace split, deploy/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
- `open.md` — 2 entries — open design questions (sudo password, chat history)
- `gotchas.md` — 13 entries — integration foot-guns (CRLF, host-key events, tmux/systemd, env names, pct exec PATH, TUN, chat paths, watcher timing)
- `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)
+2
View File
@@ -1,3 +1,5 @@
<img src="apps/web/public/shellbook.svg" alt="" width="72" height="72">
# ShellBook
Notebook-style runbooks for Linux servers.
+9 -4
View File
@@ -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";
@@ -10,6 +10,7 @@ import { createNotebookWatcher } from "./watch";
import { registerAuth, type AuthOptions } from "./auth";
import { registerStatic } from "./static";
import { chatPlugin } from "./chat";
import { defaultUpdateOptions, registerUpdate, type UpdateOptions } from "./update";
export interface AppOptions {
logger?: boolean;
@@ -26,6 +27,8 @@ export interface AppOptions {
/** Watch workspace notebooks and publish file.changed/file.deleted on /api/events. */
watchNotebooks?: boolean;
terminal?: Omit<TerminalOptions, "workspaceDir">;
/** Overrides for the self-update trigger (tests). */
update?: Partial<UpdateOptions>;
}
/**
@@ -33,7 +36,7 @@ export interface AppOptions {
* src/auth/ login, persistent session secret (registered first: its hook guards every /api route)
* src/workspace/ notebooks, hosts.yaml; src/ssh/, src/runs/ queue, audit, artifacts, /api/events
* src/terminal/ node-pty + tmux, /api/terminal; src/watch/ file.changed events into the events hub
* src/static/ built web app with SPA fallback
* src/static/ built web app with SPA fallback; src/update/ self-update trigger (root runs it via systemd)
*/
export async function buildApp(options: AppOptions = {}): Promise<FastifyInstance> {
const config = loadConfig(options.config);
@@ -41,10 +44,12 @@ export async function buildApp(options: AppOptions = {}): Promise<FastifyInstanc
const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false });
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
await registerSettings(app, config);
await registerUpdate(app, { ...defaultUpdateOptions(config.dataDir), ...options.update });
await app.register(websocket);
await app.register(workspacePlugin, { config });
const builtins = () => 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 });
+5
View File
@@ -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<Record<string, string>> {
try { return { "shellbook.public_key": await shellbookPublicKey(config) }; }
catch { return {}; }
}
export async function hostsPlugin(
app: FastifyInstance,
{ config }: { config: ServerConfig },
+17 -17
View File
@@ -3,38 +3,38 @@ 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);
// A step needs exactly the values it uses (core renderStep, spec §3.6): referenced params,
// required secrets its script reads and every set secret of its scope (passed as env).
// Unused required params never block it, so guided notebooks run early steps first.
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 +179,7 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
function stringMap(value: unknown): value is Record<string, string> {
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<ParamValues> }) {
const queue = new SerialQueue();
const active = new Set<string>();
const downloads = new Set<Promise<void>>();
@@ -197,8 +197,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.
+180
View File
@@ -0,0 +1,180 @@
import { execFile } from "node:child_process";
import { access, mkdir, open, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import type { FastifyInstance } from "fastify";
import type {
UpdateCheckResponse,
UpdateStartResponse,
UpdateState,
UpdateStatusResponse,
} from "@shellbook/core";
/**
* Self-update from the web UI (#15). The service never gains privileges: it only writes
* a request file. A root-owned systemd path unit (deploy/install.sh) watches that file
* and starts `shellbook-update.service`, which runs the fixed root-owned updater and
* writes its output to a root-owned log. Here we only read that state back.
*/
export interface UpdateOptions {
/** Written to request an update; watched by shellbook-update.path. */
requestFile: string;
/** Present when the trigger units are installed. */
triggerUnit: string;
/** Output of the last update run (StandardOutput of the update unit). */
logFile: string;
/** The git checkout the server runs from. */
repoDir: string;
/** Runs a program with argv (no shell) and returns stdout; rejects on failure. */
run(file: string, args: string[], timeoutMs: number): Promise<string>;
}
const UNIT = "shellbook-update.service";
const LOG_BYTES = 64 * 1024;
const LOG_LINES = 200;
function run(file: string, args: string[], timeoutMs: number): Promise<string> {
return new Promise((resolve, reject) => {
execFile(
file,
args,
// Never wait for credentials on a terminal that is not there.
{ timeout: timeoutMs, maxBuffer: 1024 * 1024, windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } },
(error, stdout) => (error ? reject(error) : resolve(stdout)),
);
});
}
export function defaultUpdateOptions(dataDir: string): UpdateOptions {
return {
requestFile: join(dataDir, "update-request"),
triggerUnit: "/etc/systemd/system/shellbook-update.path",
logFile: "/var/log/shellbook-update.log",
// systemd starts the service in the checkout (WorkingDirectory=/opt/shellbook).
repoDir: process.cwd(),
run,
};
}
/** `--timestamp=unix` prints `@<seconds>`; empty or `n/a` means never. */
function timestamp(value: string | undefined): string | null {
const match = value?.match(/^@(\d+)$/);
return match ? new Date(Number(match[1]) * 1000).toISOString() : null;
}
/** The last lines of the log, reading at most LOG_BYTES from its end. */
async function logTail(path: string): Promise<string> {
let file;
try {
file = await open(path, "r");
} catch {
return "";
}
try {
const { size } = await file.stat();
const length = Math.min(size, LOG_BYTES);
const buffer = Buffer.alloc(length);
await file.read(buffer, 0, length, size - length);
const lines = buffer.toString("utf8").split("\n");
// Drop a partial first line when the read started mid-file.
if (length < size) lines.shift();
if (lines.at(-1) === "") lines.pop();
return lines.slice(-LOG_LINES).join("\n");
} finally {
await file.close();
}
}
export function createUpdater(options: UpdateOptions) {
const git = (args: string[], timeoutMs = 5000) =>
options.run("git", ["-C", options.repoDir, ...args], timeoutMs).then((out) => out.trim());
const current = () => git(["rev-parse", "--short", "HEAD"]).catch(() => null);
const available = () => access(options.triggerUnit).then(() => true, () => false);
async function unitState(): Promise<Pick<UpdateStatusResponse, "state" | "startedAt" | "finishedAt">> {
let output: string;
try {
output = await options.run(
"systemctl",
["show", UNIT, "--timestamp=unix", "--property=ActiveState,Result,ExecMainStartTimestamp,ExecMainExitTimestamp"],
5000,
);
} catch {
return { state: "unknown", startedAt: null, finishedAt: null };
}
const props: Record<string, string> = Object.fromEntries(
output.split("\n").filter((line) => line.includes("=")).map((line) => {
const at = line.indexOf("=");
return [line.slice(0, at), line.slice(at + 1).trim()];
}),
);
const startedAt = timestamp(props.ExecMainStartTimestamp);
const finishedAt = timestamp(props.ExecMainExitTimestamp);
let state: UpdateState;
if (["activating", "active", "reloading", "deactivating"].includes(props.ActiveState ?? "")) state = "running";
else if (props.ActiveState === "failed" || (startedAt && props.Result !== "success")) state = "failed";
else state = startedAt ? "succeeded" : "idle";
return { state, startedAt, finishedAt: state === "running" ? null : finishedAt };
}
return {
async status(): Promise<UpdateStatusResponse> {
const [isAvailable, commit] = await Promise.all([available(), current()]);
if (!isAvailable)
return { available: false, state: "idle", current: commit, startedAt: null, finishedAt: null, log: "" };
return { available: true, current: commit, ...(await unitState()), log: await logTail(options.logFile) };
},
/** Fetches the tracked branch (FETCH_HEAD only) and lists the commits an update would bring. */
async check(): Promise<UpdateCheckResponse> {
const commit = await current();
const branch = await git(["symbolic-ref", "-q", "--short", "HEAD"]).catch(() => null);
// A detached HEAD is a pinned SHELLBOOK_REF: the installer never pulls it.
if (!branch) return { current: commit, latest: null, pinned: true, changes: [] };
const upstream = await git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
const slash = upstream.indexOf("/");
if (slash <= 0) throw new Error(`Unexpected upstream: ${upstream}`);
await git(["fetch", "--quiet", "--no-tags", "--", upstream.slice(0, slash), upstream.slice(slash + 1)], 30_000);
const latest = await git(["rev-parse", "--short", "FETCH_HEAD"]);
const log = await git(["log", "--format=%h%x09%s", "-n", "50", "HEAD..FETCH_HEAD"]);
const changes = log
? log.split("\n").map((line) => {
const tab = line.indexOf("\t");
return { commit: line.slice(0, tab), subject: line.slice(tab + 1) };
})
: [];
return { current: commit, latest, pinned: false, changes };
},
/** Requests an update; systemd runs it as root. Returns null when it cannot start. */
async start(): Promise<{ ok: true; response: UpdateStartResponse } | { ok: false; error: string }> {
if (!(await available())) return { ok: false, error: "Updating from the web UI is not installed here. Run shellbook-update as root." };
if ((await unitState()).state === "running") return { ok: false, error: "An update is already running." };
const requestedAt = new Date().toISOString();
await mkdir(dirname(options.requestFile), { recursive: true });
// Closing the written file is what triggers the path unit (PathChanged=).
await writeFile(options.requestFile, requestedAt + "\n", { mode: 0o600 });
return { ok: true, response: { requestedAt } };
},
};
}
export async function registerUpdate(app: FastifyInstance, options: UpdateOptions): Promise<void> {
const updater = createUpdater(options);
app.get("/api/settings/update", async (_request, reply) =>
reply.header("Cache-Control", "no-store").send(await updater.status()),
);
app.post("/api/settings/update/check", async (_request, reply) => {
if ((await updater.status()).state === "running")
return reply.code(409).send({ error: "An update is running." });
try {
return reply.header("Cache-Control", "no-store").send(await updater.check());
} catch (error) {
app.log.warn({ err: error }, "update check failed");
return reply.code(502).send({ error: "Could not check the repository for updates." });
}
});
app.post("/api/settings/update", async (_request, reply) => {
const result = await updater.start();
return result.ok ? reply.code(202).send(result.response) : reply.code(409).send({ error: result.error });
});
}
+33 -4
View File
@@ -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<string, Notebook | undefined>([[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<HostInfo[]> {
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<ParamValues>;
}
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");
+190
View File
@@ -0,0 +1,190 @@
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, parseNotebook } 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<unknown>)[] = [];
afterEach(async () => { for (const fn of cleanup.splice(0).reverse()) await fn(); });
async function fixture(files: Record<string, string> = { "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<string, string>, runtime: Record<string, string> = {}): 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("Step 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("Step 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<string, string> = {}) =>
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("Step 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");
});
});
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");
});
});
+7 -4
View File
@@ -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<typeof import("@shellbook/core")>(), "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<string, string>) => ({ values, errors: {} })),
@@ -21,6 +23,9 @@ vi.mock("@shellbook/core", () => ({
secretEnv: vi.fn(() => ({})),
}));
function pick<T extends object, K extends keyof T>(object: T, ...keys: K[]) {
return Object.fromEntries(keys.map(key => [key, object[key]])) as Pick<T, K>;
}
const cleanup: (() => Promise<unknown>)[] = [];
afterEach(async () => { for (const fn of cleanup.splice(0).reverse()) await fn(); vi.clearAllMocks(); });
async function fixture() {
@@ -175,9 +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: [] };
vi.mocked(resolveParams).mockReturnValueOnce({ values: {}, errors: { required: "missing" } });
expect(() => prepareRun(notebook, request(), [])).toThrow("Parameters are missing or invalid");
const notebook: Notebook = { title: "Test", params: [{ name: "required", type: "string", required: true }], blocks: [{ type: "step", step: step() }], diagnostics: [] };
vi.mocked(renderStep).mockReturnValueOnce({ ...rendered(), missing: ["required"] });
expect(() => prepareRun(notebook, request(), [])).toThrow("Step parameters are missing or invalid");
});
+168
View File
@@ -0,0 +1,168 @@
import { afterEach, expect, it } from "vitest";
import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { FastifyInstance } from "fastify";
import { buildApp } from "../src/app";
import type { UpdateOptions } from "../src/update";
const dirs: string[] = [];
const apps: FastifyInstance[] = [];
afterEach(async () => {
for (const app of apps.splice(0)) await app.close();
for (const path of dirs.splice(0)) await rm(path, { recursive: true, force: true });
});
type Reply = string | Error;
/** Fake for `git`/`systemctl`: answers by "file arg arg…" prefix and records every call. */
function fakeRun(answers: Record<string, Reply>) {
const calls: string[][] = [];
const run: UpdateOptions["run"] = async (file, args) => {
calls.push([file, ...args]);
const line = [file, ...args].join(" ");
const key = Object.keys(answers).sort((a, b) => b.length - a.length).find((k) => line.startsWith(k));
if (key === undefined) throw new Error(`unexpected command: ${line}`);
const answer = answers[key]!;
if (answer instanceof Error) throw answer;
return answer;
};
return { run, calls };
}
const show = (state: string, result = "success", start = "@1763300000", exit = "@1763300090") =>
`ActiveState=${state}\nResult=${result}\nExecMainStartTimestamp=${start}\nExecMainExitTimestamp=${exit}\n`;
const git = (repo: string) => `git -C ${repo}`;
async function setup(answers: Record<string, Reply>, installed = true, withAuth = false) {
const root = await mkdtemp(join(tmpdir(), "update-"));
dirs.push(root);
const triggerUnit = join(root, "shellbook-update.path");
if (installed) await writeFile(triggerUnit, "[Path]\n");
const fake = fakeRun(answers);
const options: Partial<UpdateOptions> = {
triggerUnit,
logFile: join(root, "update.log"),
repoDir: join(root, "repo"),
run: fake.run,
};
const app = await buildApp({ config: { dataDir: join(root, "data") }, auth: withAuth ? undefined : false, update: options });
apps.push(app);
return { app, root, repo: options.repoDir!, calls: fake.calls, requestFile: join(root, "data", "update-request"), logFile: options.logFile! };
}
it("reports the installed commit, the last run and the end of its log", async () => {
const { app, logFile, calls } = await setup({
"git -C": "abc1234\n",
"systemctl show shellbook-update.service": show("inactive"),
});
const lines = Array.from({ length: 400 }, (_, i) => `line ${i}`);
await writeFile(logFile, lines.join("\n") + "\n");
const status = (await app.inject("/api/settings/update")).json();
expect(status).toMatchObject({
available: true,
state: "succeeded",
current: "abc1234",
startedAt: new Date(1763300000 * 1000).toISOString(),
finishedAt: new Date(1763300090 * 1000).toISOString(),
});
// Only the end of a long log is returned.
expect(status.log.split("\n")[0]).toBe("line 200");
expect(status.log).toContain("line 399");
// Read-only queries only, with argv (no shell).
expect(calls.map((c) => c[0])).toEqual(expect.arrayContaining(["git", "systemctl"]));
expect(calls.find((c) => c[0] === "systemctl")).toEqual([
"systemctl", "show", "shellbook-update.service", "--timestamp=unix",
"--property=ActiveState,Result,ExecMainStartTimestamp,ExecMainExitTimestamp",
]);
});
it.each([
[show("activating", "success", "@1763300000", ""), "running"],
[show("failed", "exit-code"), "failed"],
[show("inactive", "success", "", ""), "idle"],
])("maps unit state %#", async (output, state) => {
const { app } = await setup({ "git -C": "abc1234\n", "systemctl show": output });
expect((await app.inject("/api/settings/update")).json().state).toBe(state);
});
it("says so when systemd cannot be asked, and is unavailable without the trigger unit", async () => {
const broken = await setup({ "git -C": new Error("no git"), "systemctl show": new Error("no systemd") });
expect((await broken.app.inject("/api/settings/update")).json()).toMatchObject({ available: true, state: "unknown", current: null });
const missing = await setup({ "git -C": "abc1234\n" }, false);
expect((await missing.app.inject("/api/settings/update")).json()).toMatchObject({ available: false, state: "idle", current: "abc1234" });
// Never asks systemd or writes a request without the units.
expect(missing.calls.some((c) => c[0] === "systemctl")).toBe(false);
expect((await missing.app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(409);
await expect(stat(missing.requestFile)).rejects.toMatchObject({ code: "ENOENT" });
});
it("starts an update only by writing the request file, and never twice at once", async () => {
const idle = await setup({ "git -C": "abc1234\n", "systemctl show": show("inactive") });
const started = await idle.app.inject({ method: "POST", url: "/api/settings/update", payload: {} });
expect(started.statusCode).toBe(202);
const { requestedAt } = started.json();
expect(Date.parse(requestedAt)).not.toBeNaN();
expect((await readFile(idle.requestFile, "utf8")).trim()).toBe(requestedAt);
// The server itself never starts units or runs the updater.
expect(idle.calls.filter((c) => c[0] === "systemctl").every((c) => c[1] === "show")).toBe(true);
const busy = await setup({ "git -C": "abc1234\n", "systemctl show": show("active", "success", "@1763300000", "") });
expect((await busy.app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(409);
});
it("checks the tracked branch and lists the commits an update would bring", async () => {
const answers: Record<string, Reply> = {};
const target = await setup(answers);
Object.assign(answers, {
[`${git(target.repo)} rev-parse --short HEAD`]: "abc1234\n",
[`${git(target.repo)} symbolic-ref -q --short HEAD`]: "main\n",
[`${git(target.repo)} rev-parse --abbrev-ref --symbolic-full-name @{u}`]: "origin/main\n",
[`${git(target.repo)} fetch --quiet --no-tags -- origin main`]: "",
[`${git(target.repo)} rev-parse --short FETCH_HEAD`]: "def5678\n",
[`${git(target.repo)} log --format=%h%x09%s -n 50 HEAD..FETCH_HEAD`]: "def5678\tfeat(web): b\nbbb0000\tfix: a\ttab\n",
"systemctl show": show("inactive"),
});
const result = await target.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} });
expect(result.statusCode).toBe(200);
expect(result.json()).toEqual({
current: "abc1234",
latest: "def5678",
pinned: false,
changes: [
{ commit: "def5678", subject: "feat(web): b" },
{ commit: "bbb0000", subject: "fix: a\ttab" },
],
});
});
it("reports a pinned checkout without fetching, and a failed fetch as 502", async () => {
const pinnedAnswers: Record<string, Reply> = {};
const pinned = await setup(pinnedAnswers);
Object.assign(pinnedAnswers, {
[`${git(pinned.repo)} rev-parse --short HEAD`]: "abc1234\n",
[`${git(pinned.repo)} symbolic-ref -q --short HEAD`]: new Error("detached"),
"systemctl show": show("inactive"),
});
const result = await pinned.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} });
expect(result.json()).toEqual({ current: "abc1234", latest: null, pinned: true, changes: [] });
expect(pinned.calls.some((c) => c.includes("fetch"))).toBe(false);
const offlineAnswers: Record<string, Reply> = {};
const offline = await setup(offlineAnswers);
Object.assign(offlineAnswers, {
[`${git(offline.repo)} rev-parse --short HEAD`]: "abc1234\n",
[`${git(offline.repo)} symbolic-ref -q --short HEAD`]: "main\n",
[`${git(offline.repo)} rev-parse --abbrev-ref --symbolic-full-name @{u}`]: "origin/main\n",
[`${git(offline.repo)} fetch`]: new Error("Could not resolve host"),
"systemctl show": show("inactive"),
});
const failed = await offline.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} });
expect(failed.statusCode).toBe(502);
// The git error text stays in the server log, not in the response.
expect(failed.body).not.toContain("resolve host");
});
it("requires a session", async () => {
const { app } = await setup({ "git -C": "abc1234\n", "systemctl show": show("inactive") }, true, true);
expect((await app.inject("/api/settings/update")).statusCode).toBe(401);
expect((await app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(401);
});
+5
View File
@@ -4,6 +4,11 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="dark light" />
<meta name="theme-color" content="#141a22" />
<link rel="icon" href="/shellbook.svg" type="image/svg+xml" />
<link rel="icon" href="/icon-192.png" type="image/png" sizes="192x192" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="manifest" href="/manifest.webmanifest" />
<title>ShellBook</title>
</head>
<body>
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+14
View File
@@ -0,0 +1,14 @@
{
"name": "ShellBook",
"short_name": "ShellBook",
"description": "Notebook-style server runbooks",
"start_url": "/",
"display": "standalone",
"background_color": "#11151b",
"theme_color": "#141a22",
"icons": [
{ "src": "/shellbook.svg", "type": "image/svg+xml", "sizes": "any" },
{ "src": "/icon-192.png", "type": "image/png", "sizes": "192x192" },
{ "src": "/icon-512.png", "type": "image/png", "sizes": "512x512" }
]
}
+12
View File
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="ShellBook">
<!-- Dark tile so the mark reads on light and dark tabs alike. -->
<rect width="64" height="64" rx="14" fill="#141a22"/>
<!-- Notebook: mint cover with a darker spine. -->
<rect x="11" y="7" width="42" height="50" rx="6" fill="#86dab9"/>
<path d="M17 7h5v50h-5a6 6 0 0 1-6-6V13a6 6 0 0 1 6-6z" fill="#4fa985"/>
<!-- Bookmark ribbon. -->
<path d="M41 7h7v16l-3.5-3-3.5 3z" fill="#f2c56b"/>
<!-- Shell prompt: >_ -->
<path d="M28.5 25.5l8 6.5-8 6.5" fill="none" stroke="#141a22" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M39.5 41.5h8" fill="none" stroke="#141a22" stroke-width="5" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 759 B

+431 -210
View File
@@ -13,10 +13,15 @@ import {
} from "react";
import ReactMarkdown from "react-markdown";
import {
blockActive,
groupInputs,
notebookIncludes,
parseNotebook,
renderHost,
renderStep,
renderText,
resolveParams,
scopeActive,
} from "@shellbook/core";
import type {
Block,
@@ -34,9 +39,15 @@ import { HostsPage } from "./HostsPage";
import { HttpError } from "./api";
import type { Api } from "./api";
import { emptySession, eventReducer, stepKey } from "./events";
import { ParamsForm } from "./ParamsForm";
import { ParamField, ParamsForm, type ParamGroup } from "./ParamsForm";
import { GroupSection } from "./GroupSection";
import { HostBlockCard } from "./HostBlockCard";
import { StepCard } from "./StepCard";
import { ChatPanel } from "./ChatPanel";
import { parseRoute, routeHash } from "./route";
import { recallValues, rememberValues } from "./paramMemory";
import { Dialog, Logo } from "./ui";
import { readFlag, writeFlag } from "./uiPrefs";
const TerminalSlot = lazy(() =>
import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })),
);
@@ -46,18 +57,26 @@ const Editor = lazy(() =>
function steps(blocks: Block[]): Step[] {
return blocks.flatMap((block) =>
block.type === "step"
? [block.step]
: block.type === "after"
? steps(block.blocks)
: [],
block.type === "step" ? [block.step] : "blocks" in block ? steps(block.blocks) : [],
);
}
type UseBlock = Extract<Block, { type: "use" }>;
/** Included notebooks (`::use`, nested too), whose parameters the form shows as groups. */
function includes(blocks: Block[]): UseBlock[] {
return blocks.flatMap((block): UseBlock[] =>
block.type === "use" ? [block, ...includes(block.blocks)] : "blocks" in block ? includes(block.blocks) : [],
);
}
/** Values that are set; unset ones stay visible as `{{name}}` in prose. */
function setValuesOnly(values: ParamValues): ParamValues {
return Object.fromEntries(Object.entries(values).filter(([, value]) => value));
}
export function App({ api }: { api: Api }) {
const initialRoute = useRef(parseRoute(location.hash));
const [auth, setAuth] = useState<"loading" | "login" | "setup" | "ready">("loading");
const [page, setPage] = useState<NavigationPage>("Notebooks");
const [page, setPage] = useState<NavigationPage>(initialRoute.current.page);
const [password, setPassword] = useState("");
const [list, setList] = useState<NotebookSummary[]>([]);
const [list, setList] = useState<NotebookSummary[]>();
const [hosts, setHosts] = useState<HostInfo[]>([]);
const [doc, setDoc] = useState<NotebookResponse>();
const [source, setSource] = useState("");
@@ -65,6 +84,7 @@ export function App({ api }: { api: Api }) {
const [edit, setEdit] = useState(false);
const [terminal, setTerminal] = useState(false);
const [chat, setChat] = useState(false);
const [paramsOpen, setParamsOpen] = useState(() => readFlag("params-open", true));
const [terminalOpened, setTerminalOpened] = useState(false);
const [conflict, setConflict] = useState(false);
const [error, setError] = useState("");
@@ -98,7 +118,7 @@ export function App({ api }: { api: Api }) {
setConflict(false);
setError("");
if (!same) {
setValues({});
setValues(recallValues(path, next.notebook));
setEdit(false);
setCheckIds([]);
}
@@ -108,6 +128,7 @@ export function App({ api }: { api: Api }) {
},
[api],
);
const leave = () => !current.current.dirty || window.confirm("Discard unsaved edits?");
useEffect(() => {
void api
.me()
@@ -129,7 +150,10 @@ export function App({ api }: { api: Api }) {
if (!active) return;
setList(notebooks.notebooks);
setHosts(inventory.hosts);
if (notebooks.notebooks[0]) void load(notebooks.notebooks[0].path);
// Open the notebook from the URL, else the first one.
const wanted = initialRoute.current.notebook;
const first = notebooks.notebooks.find((n) => n.path === wanted) ?? notebooks.notebooks[0];
if (first) void load(first.path);
})
.catch((e) => setError(String(e)));
const close = api.events((event: ServerEvent) => {
@@ -146,7 +170,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 (
@@ -172,23 +199,63 @@ export function App({ api }: { api: Api }) {
window.addEventListener("beforeunload", guard);
return () => window.removeEventListener("beforeunload", guard);
}, [dirty]);
// Keep the page and notebook in the URL; back/forward navigate between them.
useEffect(() => {
if (auth !== "ready") return;
// Until the first notebook is open, keep the requested one in the URL.
if (page === "Notebooks" && !doc && list === undefined) return;
const hash = routeHash({ page, notebook: doc?.path });
if (location.hash === hash) return;
if (location.hash) history.pushState(null, "", hash);
else history.replaceState(null, "", hash);
}, [auth, page, doc, list]);
useEffect(() => {
const follow = () => {
const route = parseRoute(location.hash);
setPage(route.page);
if (route.notebook && route.notebook !== current.current.doc?.path && leave()) void load(route.notebook);
};
window.addEventListener("hashchange", follow);
return () => window.removeEventListener("hashchange", follow);
}, [load]);
// 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: ParamGroup[] = notebook
? 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
? 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)] ?? ""];
function changeValues(next: ParamValues) {
setValues(next);
if (doc) rememberValues(doc.path, doc.notebook, next);
}
async function start(request: StartRunRequest) {
const key = stepKey(request.notebookPath, request.stepId);
setPending((previous) => new Set(previous).add(key));
@@ -207,13 +274,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 +292,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);
@@ -236,21 +303,91 @@ export function App({ api }: { api: Api }) {
setConfirm(request);
else void start(request);
}
const changeValue = (name: string, value: string) => changeValues({ ...values, [name]: value });
function blocks(items: Block[]): React.ReactNode {
if (!notebook) return null;
const prose = (text: string) => renderText(text, setValuesOnly({ ...runtime, ...resolved.values }), notebook);
return items.map((block, i) => {
if (block.type === "markdown")
return (
<div className="prose" key={i}>
<ReactMarkdown>
{renderText(
block.text,
{ ...runtime, ...resolved.values },
notebook,
)}
</ReactMarkdown>
<ReactMarkdown>{prose(block.text)}</ReactMarkdown>
</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")
return block.values.includes(resolved.values[block.param] ?? "") ? (
<div className="when" key={i}>
{blocks(block.blocks)}
</div>
) : null;
if (block.type === "use")
return (
<GroupSection
key={`${path}:use:${block.scope}`}
className="included"
title={block.title ?? block.path}
subtitle={`${block.path} · as ${block.scope}`}
inputs={groupInputs(notebook, block, values, hostNames, runtime)}
params={notebook.params}
storageKey={`${path}:use:${block.scope}`}
>
{block.blocks.length ? (
blocks(block.blocks)
) : (
<p className="muted">Save the notebook to load {block.path}.</p>
)}
</GroupSection>
);
if (block.type === "host") {
const rendered = renderHost(notebook, block, resolved.values, runtime, hostNames);
const capture = (name: string) => {
if (block.capture) dispatch({ type: "runtime.set", notebookPath: path, name: block.capture, value: name });
};
return (
<HostBlockCard
key={block.id}
rendered={rendered}
existing={hosts.find((h) => h.name === rendered.name)}
captured={block.capture ? runtime[block.capture] : undefined}
onUse={capture}
onAdd={async (host) => {
await api.addHost(host);
setHosts((await api.hosts()).hosts);
window.dispatchEvent(new Event("shellbook:hosts-changed"));
capture(host.name);
}}
/>
);
}
if (block.type === "after") {
const run = runFor(block.stepId);
return run &&
@@ -265,7 +402,7 @@ export function App({ api }: { api: Api }) {
block.step,
resolved.values,
runtime,
hosts.map((h) => h.name),
hostNames,
);
return (
<StepCard
@@ -288,31 +425,66 @@ export function App({ api }: { api: Api }) {
);
});
}
const canSave =
dirty && !conflict && !notebook?.diagnostics.some((d) => d.severity === "error");
async function save() {
if (!doc) return;
try {
const saved = await api.save(path, source, doc.version);
const parsed = parseNotebook(source);
setDoc({
...doc,
source,
notebook: parseNotebook(source),
notebook: parsed,
version: saved.version,
});
setConflict(false);
// Includes are composed on the server: reload to show them.
if (notebookIncludes(parsed).length || doc.includes.length) await load(path);
} catch (e) {
if (e instanceof HttpError && e.status === 409) setConflict(true);
else setError(String(e));
}
}
// Ctrl/Cmd+S saves the open draft.
const saveRef = useRef(save);
saveRef.current = save;
const canSaveRef = useRef(canSave);
canSaveRef.current = canSave && edit;
useEffect(() => {
const key = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "s" && canSaveRef.current) {
e.preventDefault();
void saveRef.current();
}
};
window.addEventListener("keydown", key);
return () => window.removeEventListener("keydown", key);
}, []);
const keyPrompt = Object.values(session.runs).find(
(run) => run.status === "hostKey" && requests.current.has(run.runId),
);
const checksBusy = notebook
? steps(notebook.blocks).some(
(s) =>
runFor(s.attrs.id)?.status === "running" ||
pending.has(stepKey(path, s.attrs.id)),
)
: false;
const openTerminal = () => {
setTerminalOpened(true);
setChat(false);
setTerminal(true);
};
if (auth === "setup") return <SetupScreen onComplete={() => setAuth("ready")} />;
if (auth === "login")
return (
<main className="login">
<h1>ShellBook</h1>
<p>Sign in to your workspace</p>
<h1>
<Logo size={48} />
ShellBook<span>RUNBOOKS</span>
</h1>
<p className="muted">Sign in to your workspace</p>
<form
onSubmit={(e) => {
e.preventDefault();
@@ -342,194 +514,243 @@ export function App({ api }: { api: Api }) {
</label>
<button className="primary">Sign in</button>
</form>
{error && <p role="alert">{error}</p>}
{error && <p role="alert" className="error">{error}</p>}
</main>
);
return (
<div className={`app ${terminal || chat ? "with-terminal" : ""}`}>
<aside className="sidebar">
<h1>
ShellBook<span>RUNBOOKS</span>
</h1>
<NotebookList
api={api}
list={list}
path={path}
version={doc?.version}
canLeave={() => !dirty || window.confirm("Discard unsaved edits?")}
onSelect={(next) => {
if (!dirty || window.confirm("Discard unsaved edits?"))
void load(next);
}}
onChanged={async (next) => {
const result = await api.list();
setList(result.notebooks);
if (next) await load(next);
else {
++loadSequence.current;
setDoc(undefined);
setSource("");
setConflict(false);
}
}}
/>
<small className="connection">
{import.meta.env.VITE_MOCK === "1" ? "DEMO · " : ""}
{connected
? "● Events connected"
: "○ Events disconnected · reload to reconnect"}
</small>
</aside>
<main>
<div className="app">
<header className="topbar">
<span className="brand">
<Logo />
ShellBook
{import.meta.env.VITE_MOCK === "1" && <span className="chip">demo</span>}
</span>
<HeaderNavigation page={page} onChange={setPage} />
{page === "Settings" && <SettingsPage openTerminal={() => { setTerminalOpened(true); setTerminal(true); }} />}
{page === "Hosts" && <HostsPage onChange={() => { void api.hosts().then(result => setHosts(result.hosts)).catch(e => setError(String(e))); }} />}
<div hidden={page !== "Notebooks"}>
<div className="toolbar">
<button aria-expanded={chat} onClick={() => { setChat(!chat); setTerminal(false); }}>Chat</button>
<span>{doc?.notebook.title ?? "Loading workspace…"}</span>
<button onClick={() => setEdit(!edit)}>
{edit ? "Close editor" : "Edit Markdown"}
</button>
<button
aria-expanded={terminal}
onClick={() => {
setTerminalOpened(true);
setChat(false);
setTerminal(!terminal);
}}
>
Terminal {terminal ? "→" : "←"}
</button>
</div>
{error && (
<p className="banner error" role="alert">
{error}
<button onClick={() => location.reload()}>Retry</button>
</p>
)}
{conflict && (
<div className="banner error" role="alert">
The file changed on disk. Your draft has been retained.
<button
onClick={() => {
if (!dirty || window.confirm("Discard your draft and reload?"))
void load(path);
<span className="spacer" />
<span
className={`connection ${connected ? "ok" : "bad"}`}
title={connected ? "Live updates connected" : "Live updates disconnected; reload to reconnect"}
>
{connected ? "Live" : "Offline · reload"}
</span>
<button
aria-expanded={chat}
className={chat ? "toggled" : ""}
onClick={() => {
setChat(!chat);
setTerminal(false);
}}
>
Chat
</button>
<button
aria-expanded={terminal}
className={terminal ? "toggled" : ""}
onClick={() => {
if (terminal) setTerminal(false);
else openTerminal();
}}
>
Terminal
</button>
</header>
<div className="workspace">
{page === "Notebooks" && (
<aside className="sidebar" aria-label="Notebook list">
<NotebookList
api={api}
list={list ?? []}
path={path}
version={doc?.version}
canLeave={leave}
onSelect={(next) => {
if (next !== path && leave()) void load(next);
}}
onChanged={async (next) => {
const result = await api.list();
setList(result.notebooks);
if (next) await load(next);
else {
++loadSequence.current;
setDoc(undefined);
setSource("");
setConflict(false);
}
}}
>
Reload from disk
</button>
</div>
)}
{notebook && (
<>
<ParamsForm
notebook={notebook}
values={resolved.values}
errors={resolved.errors}
hosts={hosts}
onChange={(name, value) =>
setValues((previous) => ({ ...previous, [name]: value }))
}
/>
<div className="notebook">
{edit && (
<section>
<div className="actions">
<strong>Markdown editor {dirty ? "· unsaved" : ""}</strong>
<button
className="primary"
disabled={
!dirty ||
conflict ||
notebook.diagnostics.some((d) => d.severity === "error")
}
onClick={() => void save()}
>
Save
</button>
</div>
<Suspense fallback={<p>Loading editor…</p>}>
<Editor
key={`${path}:${doc?.version}`}
source={source}
onChange={setSource}
/>
</Suspense>
<p className="muted">
Live preview below. Save changes before running steps.
</p>
</section>
)}
{notebook.diagnostics.map((d, i) => (
<p role="alert" className="error" key={i}>
{d.line && `Line ${d.line}: `}
{d.message}
</p>
))}
<div className="actions">
</aside>
)}
<main className="main">
{error && (
<p className="banner error" role="alert">
{error}
<button onClick={() => location.reload()}>Retry</button>
</p>
)}
{page === "Settings" && (
<SettingsPage openTerminal={openTerminal} onSignOut={() => setAuth("login")} />
)}
{page === "Hosts" && <HostsPage onChange={() => { void api.hosts().then(result => setHosts(result.hosts)).catch(e => setError(String(e))); }} />}
<div className="notebook-page" hidden={page !== "Notebooks"}>
{conflict && (
<div className="banner error" role="alert">
The file changed on disk. Your draft has been retained.
<button
disabled={
!connected ||
dirty ||
Object.keys(resolved.errors).length > 0 ||
steps(notebook.blocks).some(
(s) =>
runFor(s.attrs.id)?.status === "running" ||
pending.has(stepKey(path, s.attrs.id)),
)
}
onClick={() => {
const checks = steps(notebook.blocks).filter(
(s) => s.kind === "check",
);
setCheckIds(checks.map((s) => s.attrs.id));
checks.forEach(requestRun);
if (!dirty || window.confirm("Discard your draft and reload?"))
void load(path);
}}
>
Run all checks
Reload from disk
</button>
{checkIds.length > 0 && (
<span role="status">
✅{" "}
{
checkIds.filter((id) => runFor(id)?.status === "success")
.length
}{" "}
/ {checkIds.length} · ❌{" "}
{
checkIds.filter((id) => runFor(id)?.status === "failure")
.length
}
</span>
)}
</div>
{blocks(notebook.blocks)}
</div>
</>
)}
{!notebook && (
<div className="empty">
{list === undefined
? "Loading workspace…"
: list.length
? "Select a notebook."
: "No notebooks yet. Create one with + in the sidebar, or ask Claude in Chat."}
</div>
)}
{notebook && (
<div className={`notebook-layout${paramsOpen ? "" : " params-collapsed"}`}>
<ParamsForm
notebook={notebook}
values={resolved.values}
errors={resolved.errors}
hosts={hosts}
groups={groups}
open={paramsOpen}
onToggle={(next) => {
writeFlag("params-open", next);
setParamsOpen(next);
}}
onChange={changeValue}
onReset={() => changeValues({})}
/>
<article className="notebook">
<header className="notebook-header">
<span className="crumbs" title={path}>
{path.split("/").map((part, i, parts) => (
<span key={i} className={i === parts.length - 1 ? "file" : ""}>
{part}
</span>
))}
{dirty && <span className="chip warn">unsaved</span>}
</span>
<span className="spacer" />
{checkIds.length > 0 && (
<span role="status" className="check-summary">
✅{" "}
{checkIds.filter((id) => runFor(id)?.status === "success").length}{" "}
/ {checkIds.length} · ❌{" "}
{checkIds.filter((id) => runFor(id)?.status === "failure").length}
</span>
)}
<button
title={
activeChecks.length
? "Runs every check step; checks never change hosts"
: "This notebook has no check steps"
}
disabled={
!connected ||
dirty ||
activeChecks.length === 0 ||
!activeChecks.every(runnable) ||
checksBusy
}
onClick={() => {
setCheckIds(activeChecks.map((s) => s.attrs.id));
activeChecks.forEach(requestRun);
}}
>
Run all checks
</button>
<button
className={edit ? "toggled" : ""}
onClick={() => setEdit(!edit)}
>
{edit ? "Close editor" : "Edit Markdown"}
</button>
</header>
{edit && (
<section className="editor-panel">
<div className="actions">
<strong>Markdown</strong>
<span className="muted">
{dirty ? "Unsaved changes · Ctrl+S saves" : "Saved"}
</span>
<span className="spacer" />
{dirty && (
<button
onClick={() => {
if (window.confirm("Discard your unsaved changes?") && doc) setSource(doc.source);
}}
>
Discard
</button>
)}
<button
className="primary"
disabled={!canSave}
onClick={() => void save()}
>
Save
</button>
</div>
<Suspense fallback={<p>Loading editor…</p>}>
<Editor
key={`${path}:${doc?.version}`}
source={source}
onChange={setSource}
/>
</Suspense>
<p className="muted">
Live preview below. Save changes before running steps.
</p>
</section>
)}
{notebook.diagnostics.map((d, i) => (
<p role="alert" className="banner error" key={i}>
{d.line && `Line ${d.line}: `}
{d.message}
</p>
))}
{blocks(notebook.blocks)}
</article>
</div>
)}
</div>
</main>
{chat && (
<ChatPanel
notebookPath={doc?.path}
openNotebook={(next) => {
if (leave()) {
setPage("Notebooks");
void load(next);
}
}}
openTerminal={openTerminal}
onClose={() => setChat(false)}
/>
)}
</div>
</main>
{chat && <ChatPanel notebookPath={doc?.path} openNotebook={path => {
if (!dirty || window.confirm("Discard unsaved edits?")) void load(path);
}} openTerminal={() => { setChat(false); setTerminalOpened(true); setTerminal(true); }} />}
{terminalOpened && (
<Suspense fallback={<p>Loading terminal...</p>}>
<TerminalSlot collapsed={!terminal} />
</Suspense>
)}
{terminalOpened && (
<Suspense fallback={<p>Loading terminal…</p>}>
<TerminalSlot collapsed={!terminal} onClose={() => setTerminal(false)} />
</Suspense>
)}
</div>
{confirm && (
<div className="modal-backdrop">
<section
role="dialog"
aria-modal="true"
aria-labelledby="confirm-title"
>
<h2 id="confirm-title">Confirm execution</h2>
<p>
Run “{confirm.stepId}” with the displayed parameters? This step
can change the target host.
</p>
<Dialog title="Confirm execution" onClose={() => setConfirm(undefined)}>
<p>
Run “{confirm.stepId}” with the displayed parameters? This step
can change the target host.
</p>
<div className="dialog-actions">
<button onClick={() => setConfirm(undefined)}>Cancel</button>
<button
className="primary"
@@ -540,8 +761,8 @@ export function App({ api }: { api: Api }) {
>
Confirm and run
</button>
</section>
</div>
</div>
</Dialog>
)}
{keyPrompt?.hostKey && <HostKeyConfirmation
{...keyPrompt.hostKey}
+99
View File
@@ -3,8 +3,13 @@ import { parseNotebook, type ParamDef } from "@shellbook/core";
import {
addParameter,
afterSnippet,
groupSnippet,
hostSnippet,
paramFieldSnippet,
notebookSteps,
stepSnippet,
useSnippet,
whenSnippet,
type InsertKind,
} from "./authoring";
export function AuthoringToolbar({
@@ -23,7 +28,14 @@ export function AuthoringToolbar({
const [error, setError] = useState("");
const [type, setType] = useState<ParamDef["type"]>("string");
const [after, setAfter] = useState("");
const [when, setWhen] = useState("");
const [include, setInclude] = useState(false);
const [field, setField] = useState("");
const steps = notebookSteps(notebook.blocks);
const choices = notebook.params.flatMap((p) =>
p.type === "choice" ? (p.options ?? []).map((o) => ({ param: p.name, option: o })) : [],
);
const selected = choices.find((c) => JSON.stringify([c.param, c.option]) === when);
return (
<div className="authoring">
<label>
@@ -77,6 +89,77 @@ export function AuthoringToolbar({
>
Insert after note
</button>
<label>
Show when
<select value={when} onChange={(e) => setWhen(e.target.value)}>
<option value="">Choose an option</option>
{choices.map((c) => (
<option key={JSON.stringify([c.param, c.option])} value={JSON.stringify([c.param, c.option])}>
{c.param} = {c.option}
</option>
))}
</select>
</label>
<button
type="button"
disabled={!selected}
onClick={() => selected && insert(whenSnippet(selected.param, selected.option))}
>
Insert when section
</button>
<button type="button" onClick={() => 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)}>
Use notebook
</button>
<button type="button" onClick={() => insert(hostSnippet())}>
Add host
</button>
{include && (
<form
aria-label="Use notebook"
onSubmit={(e) => {
e.preventDefault();
const data = new FormData(e.currentTarget);
try {
insert(useSnippet(String(data.get("path")), String(data.get("alias"))));
setInclude(false);
setError("");
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
}}
>
<label>
Notebook path
<input name="path" required placeholder="infra/lxc-container.md" />
</label>
<label>
Alias
<input name="alias" required pattern="[A-Za-z_][A-Za-z0-9_]*" placeholder="ct" />
</label>
<button>Insert include</button>
</form>
)}
{param && (
<form
onSubmit={(e) => {
@@ -160,6 +243,22 @@ export function AuthoringToolbar({
upload="file.txt:/tmp/file.txt". After notes appear when their
selected step succeeds.
</p>
<p>
Chaining: {'::use{notebook="infra/lxc-container.md" as=ct with="hostname={{name}}"}'}{" "}
includes another notebook; its parameters appear as ct.name and its
captures as {"{{ct.address}}"}. {":::when{target=lxc}"} … {":::"} shows a
section only for that choice. {'::host{name="{{hostname}}" address="{{address}}" capture=host}'}{" "}
adds a created machine to Hosts. {"{{shellbook.public_key}}"} is
ShellBook's SSH public key.
</p>
<p>
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>
Artifact and upload snippets are examples: choose files and commands
appropriate to your runbook before running.
+11 -6
View File
@@ -12,8 +12,8 @@ const connectChat = (): ChatSocket => new WebSocket(`${location.protocol === "ht
type Message = { role: "user" | "assistant" | "tool"; text: string; path?: string };
/** notebookPath and openNotebook use app paths (relative to notebooks/); the chat wire uses workspace paths. */
export function ChatPanel({ notebookPath, openNotebook, openTerminal, connect = connectChat }: {
notebookPath?: string; openNotebook(path: string): void; openTerminal(): void; connect?: () => ChatSocket;
export function ChatPanel({ notebookPath, openNotebook, openTerminal, onClose, connect = connectChat }: {
notebookPath?: string; openNotebook(path: string): void; openTerminal(): void; onClose?(): void; connect?: () => ChatSocket;
}) {
const [history, setHistory] = useState<ChatConversation[]>([]);
const [selected, setSelected] = useState("");
@@ -68,10 +68,15 @@ export function ChatPanel({ notebookPath, openNotebook, openTerminal, connect =
setError(""); setLogin(false); setSummary(""); setAllowShell(false);
}
function send(message: ChatClientMessage) { try { socket.current?.send(JSON.stringify(message)); } catch { setBusy(false); setError("Cannot send chat message. Reconnect to continue."); } }
return <aside className="chat-panel" aria-label="Chat panel">
<h2>Chat with Claude</h2>
<div className="actions"><button disabled={busy} onClick={() => choose("")}>New conversation</button>
{!ready && <button onClick={() => setAttempt(n => n + 1)}>Reconnect chat</button>}</div>
return <aside className="chat-panel side-panel" aria-label="Chat panel">
<header className="panel-header">
<h2>Chat with Claude</h2>
<span className="spacer" />
{!ready && <button onClick={() => setAttempt(n => n + 1)}>Reconnect chat</button>}
<button disabled={busy} onClick={() => choose("")}>New conversation</button>
{onClose && <button className="icon" aria-label="Close chat" onClick={onClose}>×</button>}
</header>
{notebookPath && <p className="muted">About: <code>{notebookPath}</code></p>}
<label>Conversation history<select aria-label="Conversation history" disabled={busy} value={selected} onChange={e => choose(e.target.value)}>
<option value="">New conversation</option>{[...history].reverse().map(c => <option key={c.id} value={c.id}>{c.title}</option>)}
</select></label>
+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>
);
}
+99
View File
@@ -0,0 +1,99 @@
import { useState } from "react";
import type { HostInfo, RenderedHost } from "@shellbook/core";
/**
* A notebook's `::host` block: adds the machine a notebook created (e.g. an LXC container)
* to Hosts, so later steps can target it. Never overwrites a different existing host.
*/
export function HostBlockCard({
rendered,
existing,
captured,
onAdd,
onUse,
}: {
rendered: RenderedHost;
/** Host with the same name already in Hosts. */
existing?: HostInfo;
/** Runtime value of the block's capture, if any. */
captured?: string;
onAdd(host: HostInfo): Promise<void>;
onUse(name: string): void;
}) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const problems = Object.entries(rendered.invalid);
const ready = !rendered.missing.length && !problems.length;
const same =
!!existing &&
existing.address === rendered.address &&
existing.user === rendered.user &&
existing.port === rendered.port;
async function add() {
setBusy(true);
setError("");
try {
await onAdd({
name: rendered.name,
address: rendered.address,
user: rendered.user,
port: rendered.port,
tags: [],
});
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
}
return (
<article className="step host-block" aria-label={`Add host ${rendered.name}`}>
<header>
<strong>Add to Hosts</strong>
<code>
{rendered.user}@{rendered.address}:{rendered.port}
</code>
<span>as {rendered.name}</span>
</header>
{rendered.missing.length > 0 && (
<p className="muted">
Available after: {rendered.missing.join(", ")}
</p>
)}
{problems.map(([field, message]) => (
<p className="error" key={field}>
{message}
</p>
))}
{ready &&
(existing ? (
same ? (
captured === existing.name ? (
<p role="status">✓ {existing.name} is in Hosts</p>
) : (
<button onClick={() => onUse(existing.name)}>
Use existing host {existing.name}
</button>
)
) : (
<p className="error" role="alert">
A different host named {rendered.name} already exists. Choose
another name or change it under Hosts.
</p>
)
) : (
<button className="primary" disabled={busy} onClick={() => void add()}>
{busy ? "Adding…" : "Add to Hosts"}
</button>
))}
{error && (
<p className="error" role="alert">
{error}
</p>
)}
<p className="muted">
The first connection asks you to confirm the new server's host key.
</p>
</article>
);
}
+320 -224
View File
@@ -9,8 +9,15 @@ import type {
import { json } from "./api";
import "./hosts.css";
import { HostKeyConfirmation } from "./HostKeyConfirmation";
import { CopyButton, Dialog, Menu } from "./ui";
const base = "/host-management";
const url = (name: string) => `${base}/${encodeURIComponent(name)}`;
const credentialNames: Record<string, string> = {
shellbook: "ShellBook key",
password: "Password",
privateKey: "Private key",
certificate: "Certificate",
};
const empty: HostInfo = {
name: "",
address: "",
@@ -23,6 +30,8 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
const [draft, setDraft] = useState<HostInfo>({ ...empty });
const [editVersion, setEditVersion] = useState("");
const [editing, setEditing] = useState<string>();
/** The add/edit server dialog is open. */
const [form, setForm] = useState(false);
const [credentialHost, setCredentialHost] = useState<string>();
const [type, setType] = useState<HostCredentialInput["type"]>("shellbook");
const [password, setPassword] = useState("");
@@ -84,54 +93,101 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
);
}
}
const closeForm = () => {
setForm(false);
setEditing(undefined);
setDraft({ ...empty });
};
const closeCredentials = () => {
setCredentialHost(undefined);
setPassword("");
setPrivateKey("");
setPassphrase("");
};
return (
<section className="hosts-page" aria-label="Server management">
<h1>Servers and SSH credentials</h1>
{error && <p role="alert">{error}</p>}
{status && <p role="status">{status}</p>}
<button
disabled={busy}
onClick={() =>
void perform(async () => {
await load();
<section className="page hosts-page" aria-label="Server management">
<header className="page-header">
<div>
<h1>Hosts</h1>
<p className="muted">
Servers ShellBook connects to over SSH, and how it signs in.
</p>
</div>
<span className="spacer" />
<button disabled={busy} onClick={() => void perform(load)}>
Reload
</button>
<button
className="primary"
disabled={!inventory}
onClick={() => {
setEditing(undefined);
setDraft({ ...empty });
})
}
>
Reload hosts
</button>
setForm(true);
}}
>
Add server
</button>
</header>
{error && !form && !credentialHost && (
<p role="alert" className="banner error">
{error}
</p>
)}
{status && (
<p role="status" className="banner ok">
{status}
</p>
)}
{inventory && (
<>
<h2>ShellBook public key</h2>
<pre>{inventory.publicKey}</pre>
<button
onClick={() =>
void perform(async () => {
await navigator.clipboard.writeText(inventory.publicKey);
setStatus("Public key copied");
})
}
>
Copy public key
</button>
<p>{inventory.certificateSupport.reason}</p>
<div className="host-list">
{!inventory.hosts.length && (
<p className="empty">
No servers yet. Add one, or run a notebook such as
infra/lxc-container.md that adds the machine it creates.
</p>
)}
{inventory.hosts.map((host) => (
<article key={host.name}>
<h2>{host.name}</h2>
<p>
{host.user}@{host.address}:{host.port}
</p>
<p>{host.tags.join(", ")}</p>
<p>
Authentication: {host.credential.type}{" "}
{host.credential.fingerprint}{" "}
{host.credential.setAt && `set ${host.credential.setAt}`}
</p>
<article key={host.name} className="host-row" aria-label={host.name}>
<div className="host-main">
<h2>{host.name}</h2>
<code>
{host.user}@{host.address}
{host.port === 22 ? "" : `:${host.port}`}
</code>
</div>
<div className="host-meta">
{host.tags.map((tag) => (
<span key={tag} className={`chip ${tag === "prod" ? "warn" : ""}`}>
{tag}
</span>
))}
<span
className="chip"
title={[
host.credential.fingerprint,
host.credential.setAt && `set ${host.credential.setAt}`,
]
.filter(Boolean)
.join(" · ")}
>
{credentialNames[host.credential.type] ?? host.credential.type}
</span>
</div>
<div className="actions">
<button
disabled={busy}
aria-label={`Test connection to ${host.name}`}
onClick={() =>
void perform(() => action(host.name, { action: "test" }))
}
>
Test
</button>
<button
disabled={busy}
aria-label={`Edit ${host.name}`}
onClick={() => {
setEditing(host.name);
setEditVersion(inventory.version);
@@ -142,12 +198,15 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
port: host.port,
tags: host.tags,
});
setError("");
setForm(true);
}}
>
Edit {host.name}
Edit
</button>
<button
disabled={busy}
aria-label={`SSH credentials for ${host.name}`}
onClick={() => {
setCredentialHost(host.name);
setType("shellbook");
@@ -156,168 +215,201 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
setPassphrase("");
}}
>
SSH credentials for {host.name}
</button>
<button
disabled={busy}
onClick={() =>
void perform(() => action(host.name, { action: "test" }))
}
>
Test connection to {host.name}
</button>
<button
disabled={busy || host.credential.type !== "password"}
onClick={() =>
void perform(async () => {
const { script } = await json<{ script: string }>(
`${url(host.name)}/install-key`,
);
setInstall({ host: host.name, script });
})
}
>
Install ShellBook key on {host.name}
</button>
<button
disabled={busy}
onClick={() => {
if (
window.confirm(
`Forget trusted SSH host key for ${host.name}? The next connection requires verification.`,
)
)
void perform(async () => {
await json(`${url(host.name)}/known-key`, "DELETE");
setStatus("Host key forgotten");
});
}}
>
Forget host key for {host.name}
</button>
<button
disabled={busy}
onClick={() => {
if (
window.confirm(
`Delete ${host.name} and its stored credential?`,
)
)
void perform(async () => {
await json(url(host.name), "DELETE", {
baseVersion: inventory.version,
});
await load();
onChange?.();
});
}}
>
Delete {host.name}
Credentials
</button>
<Menu label={`More actions for ${host.name}`}>
{(close) => (
<>
<button
role="menuitem"
disabled={busy || host.credential.type !== "password"}
title={
host.credential.type === "password"
? undefined
: "Needs a saved password"
}
onClick={() => {
close();
void perform(async () => {
const { script } = await json<{ script: string }>(
`${url(host.name)}/install-key`,
);
setInstall({ host: host.name, script });
});
}}
>
Install ShellBook key on {host.name}
</button>
<button
role="menuitem"
disabled={busy}
onClick={() => {
close();
if (
window.confirm(
`Forget trusted SSH host key for ${host.name}? The next connection requires verification.`,
)
)
void perform(async () => {
await json(`${url(host.name)}/known-key`, "DELETE");
setStatus("Host key forgotten");
});
}}
>
Forget host key
</button>
<button
role="menuitem"
className="danger"
disabled={busy}
onClick={() => {
close();
if (
window.confirm(
`Delete ${host.name} and its stored credential?`,
)
)
void perform(async () => {
await json(url(host.name), "DELETE", {
baseVersion: inventory.version,
});
await load();
onChange?.();
});
}}
>
Delete {host.name}
</button>
</>
)}
</Menu>
</div>
</article>
))}
</div>
<h2>{editing ? `Edit ${editing}` : "Add server"}</h2>
<form
onSubmit={(e) => {
e.preventDefault();
void perform(async () => {
await json(
editing ? url(editing) : base,
editing ? "PUT" : "POST",
{
host: draft,
baseVersion: editing ? editVersion : inventory.version,
},
);
setEditing(undefined);
setDraft({ ...empty });
await load();
onChange?.();
});
}}
>
<label>
Name
<input
required
pattern="[A-Za-z0-9._-]+"
value={draft.name}
onChange={(e) => setDraft({ ...draft, name: e.target.value })}
/>
</label>
<label>
Address
<input
required
value={draft.address}
onChange={(e) =>
setDraft({ ...draft, address: e.target.value })
}
/>
</label>
<label>
SSH user
<input
required
value={draft.user}
onChange={(e) => setDraft({ ...draft, user: e.target.value })}
/>
</label>
<label>
Port
<input
required
type="number"
min="1"
max="65535"
value={draft.port}
onChange={(e) =>
setDraft({ ...draft, port: Number(e.target.value) })
}
/>
</label>
<label>
Tags (comma separated)
<input
value={draft.tags.join(",")}
onChange={(e) =>
setDraft({
...draft,
tags: e.target.value
.split(",")
.map((t) => t.trim())
.filter(Boolean),
})
}
/>
</label>
<button disabled={busy}>Save server</button>
<button
type="button"
onClick={() => {
setEditing(undefined);
setDraft({ ...empty });
}}
<details className="card public-key">
<summary>ShellBook public key</summary>
<p className="muted">
Add it to <code>~/.ssh/authorized_keys</code> on a server, or save
the server&apos;s password under Credentials and use “Install
ShellBook key” from its ⋯ menu.
</p>
<pre>{inventory.publicKey}</pre>
<div className="actions">
<CopyButton label="Copy public key" text={() => inventory.publicKey} />
</div>
<p className="muted">{inventory.certificateSupport.reason}</p>
</details>
{form && (
<Dialog
title={editing ? `Edit ${editing}` : "Add server"}
onClose={closeForm}
>
New server
</button>
</form>
<form
className="grid-form"
onSubmit={(e) => {
e.preventDefault();
void perform(async () => {
await json(
editing ? url(editing) : base,
editing ? "PUT" : "POST",
{
host: draft,
baseVersion: editing ? editVersion : inventory.version,
},
);
closeForm();
await load();
onChange?.();
});
}}
>
<label>
Name
<input
required
pattern="[A-Za-z0-9._-]+"
placeholder="web-1"
value={draft.name}
onChange={(e) => setDraft({ ...draft, name: e.target.value })}
/>
</label>
<label>
Address
<input
required
placeholder="10.0.0.5 or host.example.org"
value={draft.address}
onChange={(e) =>
setDraft({ ...draft, address: e.target.value })
}
/>
</label>
<label>
SSH user
<input
required
value={draft.user}
onChange={(e) => setDraft({ ...draft, user: e.target.value })}
/>
</label>
<label>
Port
<input
required
type="number"
min="1"
max="65535"
value={draft.port}
onChange={(e) =>
setDraft({ ...draft, port: Number(e.target.value) })
}
/>
</label>
<label className="full">
Tags (comma separated; “prod” asks before every run)
<input
value={draft.tags.join(",")}
onChange={(e) =>
setDraft({
...draft,
tags: e.target.value
.split(",")
.map((t) => t.trim())
.filter(Boolean),
})
}
/>
</label>
{error && (
<p role="alert" className="error full">
{error}
</p>
)}
<div className="dialog-actions full">
<button type="button" onClick={closeForm}>
Cancel
</button>
<button className="primary" disabled={busy}>
Save server
</button>
</div>
</form>
</Dialog>
)}
</>
)}
{credentialHost && (
<section
role="dialog"
aria-modal="true"
aria-label={`SSH credentials for ${credentialHost}`}
<Dialog
title={`SSH credentials for ${credentialHost}`}
onClose={closeCredentials}
>
<h2>SSH credentials for {credentialHost}</h2>
<p>
<p className="muted">
Saved secrets cannot be read back. Blank fields do not represent the
existing credential.
</p>
<form
className="stack"
onSubmit={(e) => {
e.preventDefault();
const credential: HostCredentialInput =
@@ -372,6 +464,7 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
Private key
<textarea
required
rows={6}
value={privateKey}
onChange={(e) => setPrivateKey(e.target.value)}
/>
@@ -402,51 +495,54 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
</label>
</>
)}
<button disabled={busy}>Save authentication</button>
<button
type="button"
onClick={() => {
setCredentialHost(undefined);
setPassword("");
setPrivateKey("");
setPassphrase("");
}}
>
Cancel
</button>
{error && (
<p role="alert" className="error">
{error}
</p>
)}
<div className="dialog-actions">
<button type="button" onClick={closeCredentials}>
Cancel
</button>
<button className="primary" disabled={busy}>
Save authentication
</button>
</div>
</form>
</section>
</Dialog>
)}
{install && (
<section
role="dialog"
aria-modal="true"
aria-label="Install ShellBook key"
<Dialog
wide
title={`Install ShellBook key on ${install.host}`}
onClose={() => setInstall(undefined)}
>
<h2>Install ShellBook key on {install.host}</h2>
<p>
<p className="muted">
This exact script runs using the stored password. After success,
select ShellBook key in SSH credentials to remove the saved
password.
</p>
<pre>{install.script}</pre>
<button
disabled={busy}
onClick={() =>
void perform(() =>
action(install.host, {
action: "install-key",
script: install.script,
}),
)
}
>
Run displayed script
</button>
<button onClick={() => setInstall(undefined)}>
Cancel installation
</button>
</section>
<pre className="script">{install.script}</pre>
<div className="dialog-actions">
<button onClick={() => setInstall(undefined)}>
Cancel installation
</button>
<button
className="primary"
disabled={busy}
onClick={() =>
void perform(() =>
action(install.host, {
action: "install-key",
script: install.script,
}),
)
}
>
Run displayed script
</button>
</div>
</Dialog>
)}
{trust && (
<HostKeyConfirmation
+109 -63
View File
@@ -3,6 +3,7 @@ import { useState } from "react";
import type { NotebookSummary } from "@shellbook/core";
import type { Api } from "./api";
import { newNotebook } from "./authoring";
import { Dialog, Menu } from "./ui";
type Node = { folders: Map<string, Node>; files: NotebookSummary[] };
function tree(list: NotebookSummary[]): Node {
const root: Node = { folders: new Map(), files: [] };
@@ -40,6 +41,10 @@ export function NotebookList({
>();
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const choose = (op: "rename" | "duplicate" | "delete") => {
setAction(op);
setError("");
};
const render = (node: Node) => (
<>
{[...node.folders]
@@ -51,67 +56,94 @@ export function NotebookList({
</details>
))}
{node.files.map((item) => (
<button
className={item.path === path ? "selected" : ""}
<div
className={`notebook-item ${item.path === path ? "selected" : ""}`}
key={item.path}
onClick={() => onSelect(item.path)}
>
{item.title}
<small>{item.path}</small>
</button>
<button
aria-current={item.path === path ? "page" : undefined}
title={item.path}
onClick={() => onSelect(item.path)}
>
{item.title}
</button>
{item.path === path && (
<Menu label={`Actions for ${item.title}`}>
{(close) =>
(["rename", "duplicate", "delete"] as const).map((op) => (
<button
key={op}
role="menuitem"
className={op === "delete" ? "danger" : ""}
onClick={() => {
close();
choose(op);
}}
>
{op === "rename"
? "Rename / move"
: op === "duplicate"
? "Duplicate"
: "Delete"}
</button>
))
}
</Menu>
)}
</div>
))}
</>
);
const shown = list.filter((n) =>
`${n.path} ${n.title}`.toLowerCase().includes(search.toLowerCase()),
);
return (
<>
<label>
Search notebooks
<div className="sidebar-tools">
<input
type="search"
aria-label="Search notebooks"
placeholder="Search notebooks"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</label>
<button
onClick={() => {
setAction("new");
setError("");
}}
>
New notebook
</button>
<button
className="icon"
aria-label="New notebook"
title="New notebook"
onClick={() => {
setAction("new");
setError("");
}}
>
+
</button>
</div>
<nav aria-label="Notebooks">
{render(
tree(
list.filter((n) =>
`${n.path} ${n.title}`
.toLowerCase()
.includes(search.toLowerCase()),
),
),
{render(tree(shown))}
{!shown.length && (
<p className="muted">
{list.length ? "No notebook matches." : "No notebooks yet."}
</p>
)}
</nav>
{path && (
<div className="actions">
{(["rename", "duplicate", "delete"] as const).map((op) => (
<button
key={op}
onClick={() => {
setAction(op);
setError("");
}}
>
{op === "rename"
? "Rename / move"
: op === "duplicate"
? "Duplicate"
: "Delete"}
</button>
))}
</div>
)}
{action && (
<Dialog
title={
action === "new"
? "New notebook"
: action === "rename"
? "Rename or move notebook"
: action === "duplicate"
? "Duplicate notebook"
: "Delete notebook"
}
onClose={() => {
if (!busy) setAction(undefined);
}}
>
<form
className="stack"
key={`${action}:${path}`}
aria-label="Manage notebook"
onSubmit={async (e) => {
@@ -158,18 +190,22 @@ export function NotebookList({
}
}}
>
<strong>
{action === "delete"
? `Delete ${path}? This cannot be undone.`
: action === "new"
? "New notebook"
: `${action} ${path}`}
</strong>
{action === "delete" ? (
<p>
Delete <code>{path}</code>? This cannot be undone.
</p>
) : (
action !== "new" && (
<p className="muted">
From <code>{path}</code>
</p>
)
)}
{action === "new" ? (
<>
<label>
Name
<input name="name" required />
<input name="name" required placeholder="debian-upgrade" />
</label>
<label>
Folder (optional)
@@ -196,18 +232,28 @@ export function NotebookList({
</label>
)
)}
<button disabled={busy}>
{action === "delete" ? "Confirm delete" : "Apply"}
</button>
<button
type="button"
disabled={busy}
onClick={() => setAction(undefined)}
>
Cancel
</button>
{error && <p role="alert">{error}</p>}
{error && (
<p role="alert" className="error">
{error}
</p>
)}
<div className="dialog-actions">
<button
type="button"
disabled={busy}
onClick={() => setAction(undefined)}
>
Cancel
</button>
<button
className={action === "delete" ? "danger" : "primary"}
disabled={busy}
>
{action === "delete" ? "Confirm delete" : "Apply"}
</button>
</div>
</form>
</Dialog>
)}
</>
);
+225 -47
View File
@@ -1,69 +1,247 @@
import type { HostInfo, Notebook, ParamValues } from "@shellbook/core";
import { useEffect, useState } from "react";
import type { HostInfo, InputStatus, Notebook, ParamDef, ParamValues } from "@shellbook/core";
import { readFlag, writeFlag } from "./uiPrefs";
/** An included notebook (`::use`) whose parameters the form shows as a group. */
export interface ParamGroup {
scope: 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}`;
/** 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({
notebook,
values,
errors,
hosts,
groups = [],
open = true,
onToggle,
onChange,
onReset,
}: {
notebook: Notebook;
values: ParamValues;
errors: Record<string, string>;
hosts: HostInfo[];
/** Active included notebooks; parameters of inactive ones are hidden. */
groups?: ParamGroup[];
/** Collapsed, the form shows a one-line summary of the values instead of the fields. */
open?: boolean;
onToggle?(open: boolean): void;
onChange(name: string, value: string): void;
/** Clears the values typed for this notebook. */
onReset?(): void;
}) {
// Group collapse choices are remembered per included notebook title.
const [groupOpen, setGroupOpen] = useState<Record<string, boolean>>({});
const isGroupOpen = (title: string) => groupOpen[title] ?? readFlag(groupFlag(title), true);
const toggleGroup = (title: string, next: boolean) => {
writeFlag(groupFlag(title), next);
setGroupOpen((current) => ({ ...current, [title]: next }));
};
// A summary chip opens its field and moves focus there once it is rendered.
const [focus, setFocus] = useState<string>();
useEffect(() => {
if (!focus) return;
document.getElementById(`param-${focus}`)?.focus();
setFocus(undefined);
}, [focus]);
const top = notebook.params.filter((param) => !param.scope);
const grouped = groups
.map((group) => ({ group, params: notebook.params.filter((param) => param.scope === group.scope) }))
.filter((entry) => entry.params.length);
const shown = [...top, ...grouped.flatMap((entry) => entry.params)];
if (!shown.length) return null;
const missingOf = (params: ParamDef[]) =>
params.filter((param) => param.required && !values[param.name]).length;
const missing = missingOf(shown);
const labelOf = paramLabel;
const reveal = (param: ParamDef) => {
if (!open) onToggle?.(true);
const group = grouped.find((entry) => entry.group.scope === param.scope);
if (group && !isGroupOpen(group.group.title)) toggleGroup(group.group.title, true);
setFocus(param.name);
};
/**
* What needs attention: missing required values and values changed from their default,
* each a button that opens its field. Untouched defaults are only counted.
*/
const summary = (params: ParamDef[], expand: () => void) => {
const listed = params.filter((param) =>
values[param.name] ? values[param.name] !== param.default : param.required,
);
const defaults = params.filter((param) => values[param.name] && values[param.name] === param.default).length;
if (!listed.length && !defaults) return null;
return (
<span className="param-summary">
{listed.map((param) => {
const value = values[param.name];
const label = labelOf(param);
return (
<button
key={param.name}
type="button"
className={`param-chip${value ? "" : " pending"}${errors[param.name] && value ? " invalid" : ""}`}
title={`${label}: ${errors[param.name] ?? "edit"}`}
onClick={() => reveal(param)}
>
<span className="param-chip-label">{label}</span>
<span className="param-chip-value">
{!value ? "missing" : param.type === "secret" ? "••••" : value}
</span>
</button>
);
})}
{defaults > 0 && (
<button type="button" className="link param-defaults" onClick={expand}>
{listed.length ? "+ " : ""}
{defaults} at default
</button>
)}
</span>
);
};
const field = (param: ParamDef) => (
<ParamField
key={param.name}
param={param}
value={values[param.name]}
error={errors[param.name]}
hosts={hosts}
onChange={onChange}
/>
);
return (
<form
className="params"
className={`params${open ? "" : " collapsed"}`}
aria-label="Notebook parameters"
onSubmit={(e) => e.preventDefault()}
>
{notebook.params.map((param) => {
const id = `param-${param.name}`;
const common = {
id,
required: param.required,
value: values[param.name] ?? "",
"aria-labelledby": `${id}-label`,
"aria-invalid": !!errors[param.name],
"aria-describedby": errors[param.name] ? `${id}-error` : undefined,
onChange: (
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
) => onChange(param.name, e.target.value),
};
return (
<label key={param.name} htmlFor={id}>
<span id={`${id}-label`}>
{param.label ?? param.name}
{param.required && <b title="Required"> *</b>}
</span>
{param.type === "host" || param.type === "choice" ? (
<select {...common}>
<option value="">Select…</option>
{(param.type === "host"
? hosts.map((h) => h.name)
: (param.options ?? [])
).map((option) => (
<option key={option}>{option}</option>
))}
</select>
) : (
<input
{...common}
type={param.type === "secret" ? "password" : "text"}
autoComplete={param.type === "secret" ? "new-password" : "off"}
spellCheck={false}
/>
)}
{errors[param.name] && (
<small id={`${id}-error`} className="error">
{errors[param.name]}
</small>
)}
</label>
);
})}
<header>
<h2>
<button
type="button"
className="params-toggle"
aria-expanded={open}
title={open ? "Collapse parameters" : "Expand parameters"}
onClick={() => onToggle?.(!open)}
>
<span className="caret" aria-hidden="true">{open ? "▾" : "▸"}</span>
Parameters
</button>
</h2>
<small className={missing ? "pending" : "ok"}>
{missing ? `${missing} required missing` : "All required set"}
</small>
{!open && summary(shown, () => onToggle?.(true))}
{onReset && open && (
<button type="button" className="link" onClick={onReset}>
Reset
</button>
)}
</header>
{open && top.map(field)}
{open &&
grouped.map(({ group, params }) => {
const expanded = isGroupOpen(group.title);
const groupMissing = missingOf(params);
return (
<fieldset
key={group.scope}
className={`status-${group.status ?? "none"}${expanded ? "" : " collapsed"}`}
aria-label={group.title}
>
<legend>
<button
type="button"
className="params-toggle"
aria-expanded={expanded}
onClick={() => toggleGroup(group.title, !expanded)}
>
<span className="caret" aria-hidden="true">{expanded ? "▾" : "▸"}</span>
{group.title}
{groupMissing > 0 && <small className="pending"> · {groupMissing} missing</small>}
</button>
</legend>
{expanded ? params.map(field) : summary(params, () => toggleGroup(group.title, true))}
</fieldset>
);
})}
</form>
);
}
+111 -63
View File
@@ -6,105 +6,153 @@ import type {
} from "@shellbook/core";
import { settingsApi } from "./settingsApi";
import { PasswordForm } from "./PasswordForm";
export function SettingsPage({ openTerminal }: { openTerminal: () => void }) {
import { UpdatePanel } from "./UpdatePanel";
function duration(seconds: number): string {
const days = seconds / 86400;
return days >= 1
? `${Number.isInteger(days) ? days : days.toFixed(1)} day${days === 1 ? "" : "s"}`
: `${Math.round(seconds / 3600)} hours`;
}
export function SettingsPage({
openTerminal,
onSignOut,
}: {
openTerminal: () => void;
/** Called after this browser signed out. */
onSignOut?: () => void;
}) {
const [info, setInfo] = useState<SystemInfoResponse>();
const [claude, setClaude] = useState<ClaudeStatusResponse>();
const [claude, setClaude] = useState<ClaudeStatusResponse | "error">();
const [session, setSession] = useState<SessionSettingsResponse>();
const [message, setMessage] = useState("");
const [busy, setBusy] = useState(false);
useEffect(() => {
let active = true;
Promise.all([
settingsApi.system(),
settingsApi.claude(),
settingsApi.session(),
])
.then(([i, c, s]) => {
if (active) {
setInfo(i);
setClaude(c);
setSession(s);
}
})
.catch(() => {
if (active)
setMessage("Unable to load settings. Sign in again or retry.");
});
const failed = () => {
if (active) setMessage("Unable to load settings. Sign in again or retry.");
};
// Independent requests: the slower Claude check must not hold back the rest.
settingsApi.system().then((i) => active && setInfo(i), failed);
settingsApi.session().then((s) => active && setSession(s), failed);
settingsApi.claude().then(
(c) => active && setClaude(c),
() => active && setClaude("error"),
);
return () => {
active = false;
};
}, []);
return (
<div className="notebook">
<h1>Settings</h1>
<section>
<div className="page settings-page">
<header className="page-header">
<div>
<h1>Settings</h1>
<p className="muted">Sign-in, the Claude CLI and this installation.</p>
</div>
</header>
{message && (
<p role="status" className="banner">
{message}
</p>
)}
<section className="card">
<h2>Password and sessions</h2>
<PasswordForm submit={settingsApi.password} />
<hr />
{session && (
<p>
Session lifetime: {session.lifetimeSeconds} seconds (
{session.lifetimeSeconds / 86400} days).
<p className="muted">
Sessions last {duration(session.lifetimeSeconds)} (
{session.lifetimeSeconds} seconds).
</p>
)}
<button
disabled={busy}
onClick={async () => {
setBusy(true);
try {
await settingsApi.revoke();
setMessage(
"Other sessions signed out. This browser remains signed in.",
);
} catch {
setMessage("Unable to sign out sessions. Try again.");
} finally {
setBusy(false);
}
}}
>
Sign out all sessions
</button>
<div className="actions">
<button
disabled={busy}
onClick={async () => {
setBusy(true);
try {
await settingsApi.revoke();
setMessage(
"Other sessions signed out. This browser remains signed in.",
);
} catch {
setMessage("Unable to sign out sessions. Try again.");
} finally {
setBusy(false);
}
}}
>
Sign out all sessions
</button>
{onSignOut && (
<button
disabled={busy}
onClick={async () => {
try {
await settingsApi.logout();
onSignOut();
} catch {
setMessage("Unable to sign out. Try again.");
}
}}
>
Sign out this browser
</button>
)}
</div>
</section>
<section>
<section className="card">
<h2>Claude CLI</h2>
{claude ? (
<>
<p>
{claude === undefined ? (
<p className="muted">Checking the Claude CLI…</p>
) : claude === "error" ? (
<p className="error">Unable to check the Claude CLI.</p>
) : (
<ul className="checklist">
<li className={claude.available ? "ok" : "bad"}>
{claude.available
? `Available: ${claude.version}`
: "Claude is unavailable on PATH or did not respond."}
</p>
<p>
</li>
<li className={claude.loginAppearsPresent ? "ok" : "bad"}>
{claude.loginAppearsPresent
? "Credentials file exists; login may be available."
: "No credentials file found."}
</p>
</>
) : (
<p>Checking CLI...</p>
</li>
</ul>
)}
<button onClick={openTerminal}>Open terminal to log in</button>
<p>
Run <code>claude</code>, then <code>/login</code>. Credentials are
checked for existence only.
<p className="muted">
Run <code>claude</code> in the terminal, then <code>/login</code>.
Credentials are checked for existence only.
</p>
<div className="actions">
<button onClick={openTerminal}>Open terminal to log in</button>
</div>
</section>
<section>
<h2>About/System</h2>
{info && (
<dl>
<section className="card">
<h2>About this installation</h2>
{info ? (
<dl className="facts">
<dt>ShellBook version</dt>
<dd>{info.version}</dd>
<dt>Workspace</dt>
<dd>{info.workspacePath}</dd>
<dd>
<code>{info.workspacePath}</code>
</dd>
<dt>Data directory</dt>
<dd>{info.dataDirPath}</dd>
<dd>
<code>{info.dataDirPath}</code>
</dd>
<dt>Node version</dt>
<dd>{info.nodeVersion}</dd>
</dl>
) : (
<p className="muted">Loading…</p>
)}
</section>
{message && <p role="status">{message}</p>}
<UpdatePanel />
</div>
);
}
+5 -1
View File
@@ -1,9 +1,13 @@
import { PasswordForm } from "./PasswordForm";
import { settingsApi } from "./settingsApi";
import { Logo } from "./ui";
export function SetupScreen({ onComplete }: { onComplete: () => void }) {
return (
<main className="login">
<h1>Set up ShellBook</h1>
<h1>
<Logo size={48} />
Set up ShellBook
</h1>
<p>
Enter the one-time token from the setup-token file in the server data
directory.
+40 -36
View File
@@ -1,10 +1,10 @@
import { ArtifactDownload } from "./ArtifactDownload";
import { useState } from "react";
import hljs from "highlight.js/lib/core";
import bash from "highlight.js/lib/languages/bash";
import type { HostInfo, RenderedStep, Step } from "@shellbook/core";
import type { DownloadState, RunState } from "./events";
import { sshCommand } from "./ssh";
import { CopyButton } from "./ui";
hljs.registerLanguage("bash", bash);
function Script({ script }: { script: string }) {
@@ -28,6 +28,20 @@ function Script({ script }: { script: string }) {
</pre>
);
}
/** One short hint for what a step still needs, without repeating a name. */
export function stepProblems(rendered: RenderedStep): string[] {
const problems: string[] = [];
if (rendered.missing.length)
problems.push(`Fill in ${rendered.missing.join(", ")} to run this step.`);
const unresolvedHost = !!rendered.host?.includes("{{");
for (const [name, error] of Object.entries(rendered.invalid)) {
if (rendered.missing.includes(name)) continue;
// The target follows from a missing value; the hint above already covers it.
if (name === "host" && unresolvedHost && rendered.missing.length) continue;
problems.push(`${name}: ${error}`);
}
return problems;
}
export function StepCard({
step,
rendered,
@@ -47,56 +61,47 @@ export function StepCard({
connected?: boolean;
onArtifactState?(runId: string, name: string, state: DownloadState): void;
}) {
const [notice, setNotice] = useState("");
const invalid =
rendered.missing.length > 0 || Object.keys(rendered.invalid).length > 0;
const problems = stepProblems(rendered);
const invalid = problems.length > 0;
const busy = run?.status === "running" || run?.status === "hostKey";
async function copy(ssh: boolean) {
try {
await navigator.clipboard.writeText(
ssh && host
? sshCommand(host, rendered.script, step.attrs.sudo)
: rendered.script,
);
setNotice("Copied");
} catch {
setNotice("Copy failed. Select and copy the script manually.");
}
}
const target = rendered.local
? "ShellBook server"
: rendered.host && !rendered.host.includes("{{")
? host
? `${host.user}@${host.name}`
: rendered.host
: "no host selected";
return (
<article
className={`step ${run?.status ?? ""}`}
className={`step ${step.kind} ${run?.status ?? ""}`}
aria-label={step.attrs.title ?? step.attrs.id}
>
<header>
<span className="badge">{step.kind}</span>
<span className={`badge kind-${step.kind}`}>{step.kind}</span>
<h3>{step.attrs.title ?? step.attrs.id}</h3>
<span className="target">
{rendered.local
? "local · ShellBook server"
: (rendered.host ?? "No host selected")}
</span>
{step.attrs.sudo && <span className="badge">sudo</span>}
{(step.attrs.confirm ||
(step.kind === "run" && host?.tags.includes("prod"))) && (
<span className="badge">confirm</span>
<span className="badge warn">confirm</span>
)}
<span className={`target ${host || rendered.local ? "" : "unset"}`} title="Runs on">
→ {target}
</span>
</header>
<Script script={rendered.script} />
{invalid && (
<p className="error" role="status">
{rendered.missing.length > 0 &&
`Missing: ${rendered.missing.join(", ")}. `}
{Object.entries(rendered.invalid)
.map(([name, error]) => `${name}: ${error}`)
.join("; ")}
<p className="hint" role="status">
{problems.join(" ")}
</p>
)}
<div className="actions">
<button onClick={() => void copy(false)}>Copy</button>
<button disabled={!host || invalid} onClick={() => void copy(true)}>
Copy as ssh one-liner
</button>
<CopyButton text={() => rendered.script} />
<CopyButton
label="Copy ssh command"
title="An ssh one-liner for your own terminal"
disabled={!host || invalid}
text={() => sshCommand(host!, rendered.script, step.attrs.sudo)}
/>
<span className="spacer" />
<button
className="primary"
@@ -106,10 +111,9 @@ export function StepCard({
{busy ? "Running…" : step.kind === "check" ? "Check" : "Run"}
</button>
</div>
{notice && <small role="status">{notice}</small>}
{run && (
<section className="result" aria-label="Run output">
<div role="status">
<div role="status" className="result-status">
{run.status === "success"
? "✅ Succeeded"
: run.status === "failure"
+19 -9
View File
@@ -9,8 +9,10 @@ import type { TerminalClientMessage } from "@shellbook/core";
export function TerminalSlot({
collapsed = false,
connect = terminalTransport,
onClose,
}: {
collapsed?: boolean;
onClose?: () => void;
connect?: (session: string) => TerminalTransport;
}) {
const container = useRef<HTMLDivElement>(null);
@@ -105,18 +107,26 @@ export function TerminalSlot({
if (!collapsed) refit.current();
}, [collapsed]);
return (
<aside className="terminal" aria-label="Terminal panel" hidden={collapsed}>
<h2>Terminal · main</h2>
<p>
Run `claude` here — it edits notebooks in this workspace; the view
reloads live.
</p>
<div className="actions">
<span role="status">{state}</span>
<aside className="terminal side-panel" aria-label="Terminal panel" hidden={collapsed}>
<header className="panel-header">
<h2>Terminal</h2>
<span role="status" className={`dot-status ${state === "Connected" ? "ok" : state === "Disconnected" ? "bad" : ""}`}>
{state}
</span>
{state === "Disconnected" && (
<button onClick={() => setAttempt((n) => n + 1)}>Reconnect</button>
)}
</div>
<span className="spacer" />
{onClose && (
<button className="icon" aria-label="Close terminal" onClick={onClose}>
×
</button>
)}
</header>
<p className="muted">
tmux session “main” on the ShellBook server. Run <code>claude</code>{" "}
here; notebook edits show up live.
</p>
<div className="terminal-screen" ref={container} />
</aside>
);
+209
View File
@@ -0,0 +1,209 @@
import { useCallback, useEffect, useRef, useState } from "react";
import type { UpdateCheckResponse, UpdateStatusResponse } from "@shellbook/core";
import { settingsApi } from "./settingsApi";
import { Dialog } from "./ui";
type UpdateApi = Pick<typeof settingsApi, "updateStatus" | "checkUpdate" | "startUpdate">;
/** How long a requested update may take to show up in systemd before we say so. */
const START_TIMEOUT_MS = 30_000;
/** systemd timestamps have second resolution; allow for that and small clock steps. */
const START_SLACK_MS = 5_000;
type Watch =
| { phase: "starting" | "running" | "restarting"; since: number }
| { phase: "done" | "failed" | "stalled" };
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString() : "");
/**
* Settings card that starts ShellBook's own update. The server only requests it; systemd
* runs the updater as root and restarts the service, so this card keeps polling through
* the restart and then offers a reload for the new web app.
*/
export function UpdatePanel({ api = settingsApi, pollMs = 2000 }: { api?: UpdateApi; pollMs?: number }) {
const [status, setStatus] = useState<UpdateStatusResponse | "error">();
const [check, setCheck] = useState<UpdateCheckResponse | "checking" | "error">();
const [watch, setWatch] = useState<Watch>();
const [confirming, setConfirming] = useState(false);
const [error, setError] = useState("");
const logRef = useRef<HTMLPreElement>(null);
// Initial load; an update already running (e.g. after a reload) is followed as well.
useEffect(() => {
let active = true;
api.updateStatus().then(
(next) => {
if (!active) return;
setStatus(next);
if (next.state === "running") setWatch({ phase: "running", since: Date.parse(next.startedAt ?? "") || Date.now() });
},
() => active && setStatus("error"),
);
return () => {
active = false;
};
}, [api]);
const following = watch && (watch.phase === "starting" || watch.phase === "running" || watch.phase === "restarting");
const since = watch && "since" in watch ? watch.since : 0;
const poll = useCallback(async () => {
let next: UpdateStatusResponse;
try {
next = await api.updateStatus();
} catch {
// The update restarts ShellBook; the API is gone for a moment.
setWatch((current) => (current && "since" in current ? { ...current, phase: "restarting" } : current));
return;
}
setStatus(next);
const started = next.startedAt !== null && Date.parse(next.startedAt) >= since - START_SLACK_MS;
if (next.state === "running") setWatch({ phase: "running", since });
else if (!started)
setWatch(Date.now() - since > START_TIMEOUT_MS ? { phase: "stalled" } : { phase: "starting", since });
else setWatch({ phase: next.state === "succeeded" ? "done" : "failed" });
}, [api, since]);
useEffect(() => {
if (!following) return;
const timer = setInterval(() => void poll(), pollMs);
return () => clearInterval(timer);
}, [following, poll, pollMs]);
// Keep the newest log lines in view while an update runs.
const log = status && status !== "error" ? status.log : "";
useEffect(() => {
if (following && logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;
}, [log, following]);
const start = async () => {
setConfirming(false);
setError("");
try {
const { requestedAt } = await api.startUpdate();
setWatch({ phase: "starting", since: Date.parse(requestedAt) });
} catch {
setError("Unable to start the update. It may already be running; reload this page.");
}
};
if (status === undefined)
return (
<section className="card">
<h2>Updates</h2>
<p className="muted">Loading…</p>
</section>
);
if (status === "error")
return (
<section className="card">
<h2>Updates</h2>
<p className="error">Unable to load the update status.</p>
</section>
);
return (
<section className="card update-panel" aria-label="Updates">
<h2>Updates</h2>
<dl className="facts">
<dt>Installed</dt>
<dd>{status.current ? <code>{status.current}</code> : "unknown (not a git checkout)"}</dd>
{status.available && status.startedAt && !following && (
<>
<dt>Last update</dt>
<dd>
{status.state === "failed" ? "failed" : status.state === "succeeded" ? "succeeded" : status.state},{" "}
{when(status.finishedAt ?? status.startedAt)}
</dd>
</>
)}
</dl>
{!status.available ? (
<p className="muted">
Updating from the web UI is not set up on this installation. Run <code>shellbook-update</code> as root in the
container (from the Proxmox host: <code>pct exec &lt;ctid&gt; -- shellbook-update</code>); that run also
adds the button here.
</p>
) : (
<>
{watch && (
<p role="status" className={`banner${watch.phase === "failed" || watch.phase === "stalled" ? " error" : ""}`}>
{watch.phase === "starting" && "Starting the update…"}
{watch.phase === "running" && "Updating… This takes a few minutes; ShellBook restarts at the end."}
{watch.phase === "restarting" && "ShellBook is restarting…"}
{watch.phase === "done" && (
<>
Update finished{status.current ? ` (${status.current})` : ""}. Reload to use the new version.
<button className="primary" onClick={() => location.reload()}>
Reload
</button>
</>
)}
{watch.phase === "failed" && "The update failed. The log below shows why."}
{watch.phase === "stalled" &&
"The update did not start. Check systemctl status shellbook-update.path in the container."}
</p>
)}
{error && <p className="banner error">{error}</p>}
{check === "error" && <p className="error">Unable to reach the repository.</p>}
{check && check !== "checking" && check !== "error" && (
check.pinned ? (
<p className="muted">This installation is pinned to a fixed version and is not updated from the branch.</p>
) : check.changes.length === 0 ? (
<p className="ok">Up to date{check.latest ? ` (${check.latest})` : ""}.</p>
) : (
<div>
<p>
{check.changes.length === 1 ? "1 new change" : `${check.changes.length} new changes`} (
<code>{check.current}</code> → <code>{check.latest}</code>):
</p>
<ul className="changes">
{check.changes.map((change) => (
<li key={change.commit}>
<code>{change.commit}</code> {change.subject}
</li>
))}
</ul>
</div>
)
)}
<div className="actions">
<button
disabled={following || check === "checking"}
onClick={() => {
setCheck("checking");
api.checkUpdate().then(setCheck, () => setCheck("error"));
}}
>
{check === "checking" ? "Checking…" : "Check for updates"}
</button>
<button className="primary" disabled={following} onClick={() => setConfirming(true)}>
Update now
</button>
</div>
{status.log && (following || watch?.phase === "failed" || watch?.phase === "done" || !watch) && (
<details open={following || watch?.phase === "failed"}>
<summary>{following ? "Update output" : "Output of the last update"}</summary>
<pre ref={logRef} className="update-log">
{status.log}
</pre>
</details>
)}
</>
)}
{confirming && (
<Dialog title="Update ShellBook?" onClose={() => setConfirming(false)}>
<p>
Downloads the installer from the repository, pulls the newest version, rebuilds and restarts ShellBook. Running
steps are interrupted by the restart; terminal sessions keep running.
</p>
<div className="dialog-actions">
<button onClick={() => setConfirming(false)}>Cancel</button>
<button className="primary" onClick={() => void start()}>
Update now
</button>
</div>
</Dialog>
)}
</section>
);
}
+10
View File
@@ -1,4 +1,7 @@
import type {
HostInfo,
HostInventoryResponse,
SaveHostRequest,
NotebookListResponse,
HostsResponse,
NotebookResponse,
@@ -66,6 +69,8 @@ export interface Api {
baseVersion: string,
): Promise<SaveNotebookResponse>;
run(request: StartRunRequest): Promise<StartRunResponse>;
/** Add a host to the inventory (a notebook's `::host` block); 409 if the name is taken. */
addHost(host: HostInfo): Promise<void>;
events(
receive: (event: ServerEvent) => void,
connection: (connected: boolean) => void,
@@ -93,6 +98,11 @@ export const liveApi: Api = {
baseVersion,
}),
run: (request) => json("/runs", "POST", request),
async addHost(host) {
const { version } = await json<HostInventoryResponse>("/host-management");
const request: SaveHostRequest = { host, baseVersion: version };
await json("/host-management", "POST", request);
},
artifact: (id, name) =>
`/api/runs/${encodeURIComponent(id)}/artifacts/${encodeURIComponent(name)}`,
events(receive, connection) {
+34 -5
View File
@@ -1,5 +1,6 @@
import { isMap, parseDocument } from "yaml";
import {
includePath,
parseNotebook,
type Block,
type ParamDef,
@@ -7,11 +8,7 @@ import {
} from "@shellbook/core";
export function notebookSteps(blocks: Block[]): Step[] {
return blocks.flatMap((b) =>
b.type === "step"
? [b.step]
: b.type === "after"
? notebookSteps(b.blocks)
: [],
b.type === "step" ? [b.step] : "blocks" in b ? notebookSteps(b.blocks) : [],
);
}
const attr = (value: string) =>
@@ -60,6 +57,38 @@ export function stepSnippet(
export function afterSnippet(id: string): string {
return `\n\n:::after{step=${attr(id)}}\nAdd follow-up instructions here.\n:::\n`;
}
/** A section shown (and runnable) only while a choice parameter has this value. */
export function whenSnippet(param: string, value: string): string {
return `\n\n:::when{${param}=${attr(value)}}\nShown only when ${param} is ${value.replace(/[\r\n]/g, " ")}.\n:::\n`;
}
/** Include another notebook; its parameters and steps are namespaced as alias.name. */
export function useSnippet(path: string, alias: string): string {
if (!includePath(path)) throw new Error("Notebook path must be dir/name.md relative to notebooks/");
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(alias) || alias === "shellbook")
throw new Error("Alias must use letters, digits or _ (not shellbook)");
return `\n\n::use{notebook=${attr(path)} as=${alias}}\n`;
}
/** 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. */
export function hostSnippet(): string {
return '\n\n::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}\n';
}
export function addParameter(source: string, def: ParamDef): string {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(def.name))
throw new Error("Invalid parameter name");
+37 -12
View File
@@ -1,12 +1,37 @@
.chat-panel { position: sticky; top: 0; height: 100vh; min-width: 0; display: flex; flex-direction: column; gap: .6rem; padding: 1rem; border-left: 1px solid #64748b; box-sizing: border-box; }
.chat-panel h2, .chat-panel p { margin: .25rem 0; }
.chat-panel select, .chat-panel textarea { width: 100%; box-sizing: border-box; }
.chat-panel label { display: block; }
.chat-messages { flex: 1; min-height: 120px; overflow-y: auto; overflow-wrap: anywhere; }
.chat-messages pre { overflow-x: auto; }
.chat-message { padding: .6rem 0; border-bottom: 1px solid #64748b55; }
.chat-message.user { opacity: .85; }
.chat-shell { margin-top: .5rem; }
.chat-panel form { flex-shrink: 0; }
@media (max-width: 900px) { .chat-panel { position: static; grid-column: 1 / -1; height: min(800px, 100dvh); } }
@media (max-width: 580px) { .with-terminal { display: block; } .chat-panel { padding: .7rem; } }
.chat-panel select,
.chat-panel textarea {
width: 100%;
}
.chat-messages {
flex: 1;
min-height: 120px;
overflow-y: auto;
overflow-wrap: anywhere;
border-top: 1px solid var(--line);
border-bottom: 1px solid var(--line);
}
.chat-messages pre {
overflow-x: auto;
}
.chat-message {
padding: 0.6rem 0;
border-bottom: 1px solid #64748b55;
}
.chat-message.user {
opacity: 0.85;
}
.chat-panel label.chat-shell {
flex-direction: row;
align-items: center;
gap: 6px;
margin-top: 0.5rem;
}
.chat-panel form {
flex-shrink: 0;
}
.chat-panel form .actions {
margin: 8px 0 0;
}
.chat-panel > p {
margin: 0;
}
+14 -1
View File
@@ -41,10 +41,23 @@ export type Action =
state: DownloadState;
}
| ServerEvent
| { type: "requested"; runId: string; request: StartRunRequest };
| { type: "requested"; runId: string; request: StartRunRequest }
/** A runtime value set in the browser, e.g. by a `::host` block's capture. */
| { type: "runtime.set"; notebookPath: string; name: string; value: string };
export function eventReducer(state: Session, event: Action): Session {
if (event.type === "file.changed" || event.type === "file.deleted")
return state;
if (event.type === "runtime.set")
return {
...state,
runtime: {
...state.runtime,
[event.notebookPath]: {
...state.runtime[event.notebookPath],
[event.name]: event.value,
},
},
};
if (event.type === "requested" || event.type === "run.started") {
const info = event.type === "requested" ? event.request : event;
const previous = state.runs[event.runId];
+50 -41
View File
@@ -1,49 +1,58 @@
.hosts-page {
padding: 1rem;
max-width: 70rem;
.host-list {
border: 1px solid var(--line);
border-radius: 8px;
background: var(--panel);
margin: 16px 0;
}
.host-list .empty {
padding: 32px 20px;
margin: 0;
}
.host-row {
display: grid;
grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr) auto;
align-items: center;
gap: 12px;
padding: 12px 16px;
}
.host-row + .host-row {
border-top: 1px solid var(--line);
}
.host-main {
min-width: 0;
}
.hosts-page pre {
.host-main h2 {
font-size: 15px;
margin: 0 0 2px;
}
.host-main code {
color: var(--muted);
font-size: 12.5px;
overflow-wrap: anywhere;
}
.host-meta {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.host-row .actions {
margin: 0;
flex-wrap: nowrap;
}
.public-key pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
background: var(--code);
border: 1px solid var(--line);
border-radius: 5px;
padding: 10px 12px;
font-size: 12px;
}
.hosts-page form {
display: flex;
flex-wrap: wrap;
gap: 0.8rem;
align-items: end;
}
.hosts-page label {
display: flex;
flex-direction: column;
gap: 0.3rem;
flex: 1 1 12rem;
min-width: 0;
}
.hosts-page input,
.hosts-page textarea,
.hosts-page select {
width: 100%;
box-sizing: border-box;
}
.hosts-page article,
.hosts-page [role="dialog"] {
border: 1px solid #777;
padding: 1rem;
margin-block: 1rem;
overflow-wrap: anywhere;
}
.hosts-page .actions {
flex-wrap: wrap;
}
.hosts-page button {
white-space: normal;
}
@media (max-width: 600px) {
.app:has(.hosts-page) {
display: block;
@media (max-width: 760px) {
.host-row {
grid-template-columns: minmax(0, 1fr);
}
.app:has(.hosts-page) .sidebar {
width: auto;
.host-row .actions {
flex-wrap: wrap;
}
}
+41 -24
View File
@@ -1,10 +1,19 @@
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
import type { Api } from "../api";
import { HttpError } from "../api";
import { parseNotebook, renderStep } from "@shellbook/core";
import initial from "./ssh-key.md?raw";
let source = initial;
let version = 1;
import { findStep, parseNotebook, renderStep } from "@shellbook/core";
import sshKey from "./ssh-key.md?raw";
import adminUser from "../../../../templates/workspace/notebooks/admin-user.md?raw";
// 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;
const listeners = new Set<(event: ServerEvent) => void>();
const emit = (event: ServerEvent) =>
@@ -43,20 +52,30 @@ export const mockApi: Api = {
me: async () => ({ authenticated: true }),
login: async () => undefined,
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 }),
notebook: async (path) => ({
path,
source,
notebook: parseNotebook(source),
version: String(version),
}),
save: async (_path, next, base) => {
if (base !== String(version)) throw new HttpError(409);
source = next;
version++;
return { version: String(version) };
notebook: async (path) => {
const { source, version } = file(path);
return {
path,
source,
notebook: parseNotebook(source),
includes: [],
builtins: { "shellbook.public_key": "ssh-ed25519 AAAADEMO shellbook" },
version: String(version),
};
},
addHost: async (host) => {
if (hosts.some((h) => h.name === host.name)) throw new HttpError(409, "Host already exists");
hosts.push({ ...host });
},
save: async (path, next, base) => {
const entry = file(path);
if (base !== String(entry.version)) throw new HttpError(409);
entry.source = next;
entry.version++;
return { version: String(entry.version) };
},
events: (receive, connected) => {
listeners.add(receive);
@@ -67,14 +86,12 @@ export const mockApi: Api = {
},
artifact: () => artifactUrl,
run: async (request: StartRunRequest) => {
const notebook = parseNotebook(source);
const block = notebook.blocks.find(
(b) => b.type === "step" && b.step.attrs.id === request.stepId,
);
if (!block || block.type !== "step") throw new Error("Unknown demo step");
const notebook = parseNotebook(file(request.notebookPath).source);
const step = findStep(notebook.blocks, request.stepId);
if (!step) throw new Error("Unknown demo step");
const rendered = renderStep(
notebook,
block.step,
step,
request.params,
request.runtime,
hosts.map((h) => h.name),
@@ -125,8 +142,8 @@ export const mockApi: Api = {
request.stepId === "keygen"
? rendered.artifacts.filter((name) => !name.endsWith(".pub"))
: [],
captured: block.step.attrs.capture
? { name: block.step.attrs.capture, value: "demo-value" }
captured: step.attrs.capture
? { name: step.attrs.capture, value: "demo-value" }
: undefined,
});
}, 850);
+6 -18
View File
@@ -1,3 +1,4 @@
/* Authoring toolbar above the Markdown editor. */
.authoring {
display: flex;
align-items: end;
@@ -5,30 +6,17 @@
gap: 0.5rem;
margin: 0.75rem 0;
}
.authoring label,
.sidebar form label {
.authoring label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 12px;
}
.authoring form,
.authoring details {
flex-basis: 100%;
}
.sidebar form {
display: flex;
flex-direction: column;
gap: 0.75rem;
margin-top: 1rem;
}
.sidebar input {
min-width: 0;
max-width: 100%;
}
.sidebar nav details {
margin-left: 0.5rem;
}
.sidebar nav summary {
cursor: pointer;
padding: 0.5rem 0;
.authoring input,
.authoring select {
width: auto;
}
+39
View File
@@ -0,0 +1,39 @@
import type { Notebook, ParamValues } from "@shellbook/core";
/**
* Remembers the parameter values typed for a notebook in this browser, so a reload or a
* return visit keeps them. Secrets are never stored, and only declared params are kept.
*/
const key = (path: string) => `shellbook:params:${path}`;
function storable(notebook: Notebook, values: ParamValues): ParamValues {
const kept: ParamValues = {};
for (const def of notebook.params) {
const value = Object.hasOwn(values, def.name) ? values[def.name] : undefined;
if (def.type !== "secret" && value) kept[def.name] = value;
}
return kept;
}
export function recallValues(path: string, notebook: Notebook): ParamValues {
try {
const stored: unknown = JSON.parse(localStorage.getItem(key(path)) ?? "{}");
if (!stored || typeof stored !== "object" || Array.isArray(stored)) return {};
const strings = Object.fromEntries(
Object.entries(stored).filter((entry): entry is [string, string] => typeof entry[1] === "string"),
);
return storable(notebook, strings);
} catch {
return {};
}
}
export function rememberValues(path: string, notebook: Notebook, values: ParamValues): void {
try {
const kept = storable(notebook, values);
if (Object.keys(kept).length) localStorage.setItem(key(path), JSON.stringify(kept));
else localStorage.removeItem(key(path));
} catch {
// Storage may be unavailable (private mode); values then last for this page only.
}
}
+33
View File
@@ -0,0 +1,33 @@
import type { NavigationPage } from "./HeaderNavigation";
/** The page and open notebook, kept in the URL hash so reloads and links keep them. */
export interface Route {
page: NavigationPage;
notebook?: string;
}
const pages: Record<string, NavigationPage> = {
notebooks: "Notebooks",
hosts: "Hosts",
settings: "Settings",
};
export function parseRoute(hash: string): Route {
const [, page = "", ...rest] = hash.replace(/^#/, "").split("/");
const known = pages[page];
if (!known) return { page: "Notebooks" };
if (known !== "Notebooks" || !rest.length) return { page: known };
try {
const notebook = rest.map(decodeURIComponent).join("/");
return notebook ? { page: known, notebook } : { page: known };
} catch {
return { page: known };
}
}
export function routeHash(route: Route): string {
const page = route.page.toLowerCase();
return route.page === "Notebooks" && route.notebook
? `#/${page}/${route.notebook.split("/").map(encodeURIComponent).join("/")}`
: `#/${page}`;
}
+7
View File
@@ -5,6 +5,9 @@ import type {
SessionSettingsResponse,
ClaudeStatusResponse,
SystemInfoResponse,
UpdateCheckResponse,
UpdateStartResponse,
UpdateStatusResponse,
} from "@shellbook/core";
import { HttpError } from "./api";
async function request<T>(path: string, body?: unknown): Promise<T> {
@@ -25,7 +28,11 @@ export const settingsApi = {
password: (body: ChangePasswordRequest) =>
request<void>("/settings/password", body),
revoke: () => request<void>("/settings/sessions/revoke", {}),
logout: () => request<void>("/auth/logout", {}),
session: () => request<SessionSettingsResponse>("/settings/session"),
claude: () => request<ClaudeStatusResponse>("/settings/claude"),
system: () => request<SystemInfoResponse>("/settings/system"),
updateStatus: () => request<UpdateStatusResponse>("/settings/update"),
checkUpdate: () => request<UpdateCheckResponse>("/settings/update/check", {}),
startUpdate: () => request<UpdateStartResponse>("/settings/update", {}),
};
+1116 -423
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -62,9 +62,12 @@ function harness() {
path: "ssh-key.md",
source,
notebook: parseNotebook(source),
includes: [],
builtins: {},
version: "1",
}),
save: vi.fn().mockResolvedValue({ version: "2" }),
addHost: vi.fn().mockResolvedValue(undefined),
run: vi.fn(async (_request: StartRunRequest) => ({ runId: String(++id) })),
events: (callback, connected) => {
receive = callback;
@@ -215,6 +218,8 @@ it("retains edits made while a file reload is in flight", async () => {
path: "ssh-key.md",
source,
notebook: parseNotebook(source),
includes: [],
builtins: {},
version: "2",
}),
);
@@ -247,6 +252,8 @@ Key generation failed. Retry safely.
path: "ssh-key.md",
source: captureSource,
notebook: parseNotebook(captureSource),
includes: [],
builtins: {},
version: "1",
});
await ready(api);
+22
View File
@@ -78,3 +78,25 @@ it("adds frontmatter when absent and rejects invalid YAML or secret defaults", (
}),
).toThrow();
});
it("generates valid chaining snippets", async () => {
const { whenSnippet, useSnippet, hostSnippet } = await import("../authoring");
const base = "---\nparams:\n target: {type: choice, options: [existing, lxc]}\n hostname: {type: name}\n address: {type: string}\n---\n";
const source = base + whenSnippet("target", "lxc") + useSnippet("infra/lxc-container.md", "ct") + hostSnippet();
const notebook = parseNotebook(source);
expect(notebook.diagnostics).toEqual([]);
expect(notebook.blocks.map((b) => b.type).filter((t) => t !== "markdown")).toEqual(["when", "use", "host"]);
expect(() => useSnippet("../x.md", "ct")).toThrow("dir/name.md");
expect(() => useSnippet("x.md", "shellbook")).toThrow("Alias");
});
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");
});
+125
View File
@@ -0,0 +1,125 @@
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { expect, it, vi } from "vitest";
vi.mock("../Editor", () => ({ Editor: () => null }));
import { App } from "../App";
import type { Api } from "../api";
import type { HostInfo, ServerEvent, StartRunRequest } from "@shellbook/core";
import { composeNotebook, parseNotebook } from "@shellbook/core";
const lxc = `---
title: LXC container
params:
proxmox: {type: host, required: true}
hostname: {type: name, required: true}
---
\`\`\`sh {run host="{{proxmox}}" id=create title="Create container" capture=address}
pct create --hostname {{hostname}} --key {{shellbook.public_key}}
\`\`\`
::host{name="{{hostname}}" address="{{address}}" capture=host}
`;
const service = `---
title: Web server
params:
target: {type: choice, options: [existing, lxc], default: existing}
host: {type: host, required: true, default: "{{ct.host}}"}
---
:::when{target=lxc}
::use{notebook="infra/lxc.md" as=ct with="hostname=web-ct"}
:::
\`\`\`sh {check host="{{host}}" id=installed title="Is nginx installed"}
command -v nginx
\`\`\`
`;
const files: Record<string, string> = { "infra/lxc.md": lxc };
const composed = composeNotebook("web.md", parseNotebook(service), p => files[p] === undefined ? undefined : parseNotebook(files[p]!));
function harness() {
let receive: (event: ServerEvent) => void = () => {};
const hosts: HostInfo[] = [{ name: "pve", address: "10.0.0.2", user: "root", port: 22, tags: [] }];
const api: Api = {
create: vi.fn(), move: vi.fn(), deleteNotebook: vi.fn(),
me: vi.fn().mockResolvedValue({}),
login: vi.fn(),
list: vi.fn().mockResolvedValue({ notebooks: [{ path: "web.md", title: "Web server" }] }),
hosts: vi.fn(async () => ({ hosts: [...hosts] })),
notebook: vi.fn().mockResolvedValue({
path: "web.md", source: service, notebook: composed, includes: ["infra/lxc.md"],
builtins: { "shellbook.public_key": "ssh-ed25519 AAAA shellbook" }, version: "1",
}),
save: vi.fn(),
run: vi.fn(async (_request: StartRunRequest) => ({ runId: "1" })),
addHost: vi.fn(async (host: HostInfo) => { hosts.push(host); }),
events: (callback, connected) => { receive = callback; connected(true); return () => {}; },
artifact: () => "/download",
};
return { api, emit: (event: ServerEvent) => act(() => receive(event)) };
}
it("shows the included notebook and its parameters only for the selected option", async () => {
const { api } = harness();
render(<App api={api} />);
const target = await screen.findByLabelText("target");
expect(screen.queryByRole("article", { name: "Create container" })).not.toBeInTheDocument();
expect(screen.queryByRole("group", { name: "LXC container (ct)" })).not.toBeInTheDocument();
fireEvent.change(target, { target: { value: "lxc" } });
const group = screen.getByRole("group", { name: "LXC container (ct)" });
expect(within(group).getByLabelText("hostname *")).toHaveValue("web-ct");
fireEvent.change(within(group).getByLabelText("proxmox *"), { target: { value: "pve" } });
const create = screen.getByRole("article", { name: "Create container" });
expect(create).toHaveTextContent("pct create --hostname web-ct --key 'ssh-ed25519 AAAA shellbook'");
// The parent's host waits for the container; the parent's checks cannot run yet.
expect(screen.getByText("Available after the step that sets ct.host")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Run all checks" })).toBeDisabled();
});
it("adds the created container to Hosts and feeds it into the parent's steps", async () => {
const { api, emit } = harness();
render(<App api={api} />);
fireEvent.change(await screen.findByLabelText("target"), { target: { value: "lxc" } });
fireEvent.change(screen.getByLabelText("proxmox *"), { target: { value: "pve" } });
const card = screen.getByRole("article", { name: "Add host web-ct" });
expect(card).toHaveTextContent("Available after: ct.address");
fireEvent.click(within(screen.getByRole("article", { name: "Create container" })).getByRole("button", { name: "Run" }));
await waitFor(() => expect(api.run).toHaveBeenCalledTimes(1));
const request = vi.mocked(api.run).mock.calls[0]![0];
expect(request).toMatchObject({ stepId: "ct.create", params: { target: "lxc", "ct.proxmox": "pve", "ct.hostname": "web-ct" } });
// Builtins are the server's; the client never sends them.
expect(request.runtime).toEqual({});
emit({ type: "run.finished", runId: "1", exitCode: 0, durationMs: 5, artifacts: [], captured: { name: "ct.address", value: "10.0.30.160" } });
fireEvent.click(within(card).getByRole("button", { name: "Add to Hosts" }));
await waitFor(() => expect(api.addHost).toHaveBeenCalledWith({ name: "web-ct", address: "10.0.30.160", user: "root", port: 22, tags: [] }));
expect(await within(card).findByRole("status")).toHaveTextContent("web-ct is in Hosts");
expect(screen.getByLabelText("host *")).toHaveValue("web-ct");
expect(screen.getByRole("article", { name: "Is nginx installed" })).toHaveTextContent("web-ct");
expect(screen.getByRole("button", { name: "Run all checks" })).toBeEnabled();
});
it("collapses an included group to a remembered summary whose chips open the field", async () => {
const { api } = harness();
const view = render(<App api={api} />);
fireEvent.change(await screen.findByLabelText("target"), { target: { value: "lxc" } });
fireEvent.click(screen.getByRole("button", { name: "LXC container (ct) · 1 missing", expanded: true }));
const group = screen.getByRole("group", { name: "LXC container (ct)" });
expect(within(group).queryByLabelText("proxmox *")).not.toBeInTheDocument();
// Untouched defaults are only counted; what needs attention is listed.
expect(within(group).queryByRole("button", { name: /hostname/ })).not.toBeInTheDocument();
expect(within(group).getByRole("button", { name: "+ 1 at default" })).toBeInTheDocument();
view.unmount();
render(<App api={harness().api} />);
fireEvent.change(await screen.findByLabelText("target"), { target: { value: "lxc" } });
fireEvent.click(screen.getByRole("button", { name: /proxmox.*missing/ }));
await waitFor(() => expect(screen.getByLabelText("proxmox *")).toHaveFocus());
// The rest of the form was never collapsed.
expect(screen.getByLabelText("target")).toBeInTheDocument();
});
it("reloads when an included notebook changes", async () => {
const { api, emit } = harness();
render(<App api={api} />);
await screen.findByLabelText("target");
expect(api.notebook).toHaveBeenCalledTimes(1);
emit({ type: "file.changed", path: "infra/lxc.md" });
await waitFor(() => expect(api.notebook).toHaveBeenCalledTimes(2));
});
+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");
});
+7 -4
View File
@@ -26,6 +26,8 @@ it("adds hosts with accessible fields and optimistic version", async () => {
vi.mocked(json).mockResolvedValue(inventory);
render(<HostsPage />);
await screen.findByText("demo");
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
expect(screen.getByRole("dialog", { name: "Add server" })).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "new" } });
fireEvent.change(screen.getByLabelText("Address"), {
target: { value: "::1" },
@@ -42,7 +44,7 @@ it("sends credentials once and clears password fields", async () => {
vi.mocked(json).mockResolvedValue(inventory);
render(<HostsPage />);
await screen.findByText("demo");
fireEvent.click(screen.getByText("SSH credentials for demo"));
fireEvent.click(screen.getByRole("button", { name: "SSH credentials for demo" }));
fireEvent.change(screen.getByLabelText("Authentication"), {
target: { value: "password" },
});
@@ -79,7 +81,8 @@ it("requires fingerprint confirmation and resends the displayed installation scr
});
render(<HostsPage />);
await screen.findByText("demo");
fireEvent.click(screen.getByText("Install ShellBook key on demo"));
fireEvent.click(screen.getByRole("button", { name: "More actions for demo" }));
fireEvent.click(screen.getByRole("menuitem", { name: "Install ShellBook key on demo" }));
await screen.findByText("literal script");
expect(json).not.toHaveBeenCalledWith(
"/host-management/demo/action",
@@ -104,7 +107,7 @@ it("loads external changes without silently changing the version of an open edit
vi.mocked(json).mockResolvedValue(inventory);
render(<HostsPage />);
await screen.findByText("demo");
fireEvent.click(screen.getByText("Edit demo"));
fireEvent.click(screen.getByRole("button", { name: "Edit demo" }));
vi.mocked(json).mockResolvedValue({ ...inventory, version: "v2" });
window.dispatchEvent(new Event("shellbook:hosts-changed"));
await waitFor(() => expect(json).toHaveBeenCalledTimes(2));
@@ -124,7 +127,7 @@ it("shows the server's reason for a failed connection test without a conflict hi
});
render(<HostsPage />);
await screen.findByText("demo");
fireEvent.click(screen.getByText("Test connection to demo"));
fireEvent.click(screen.getByRole("button", { name: "Test connection to demo" }));
const alert = await screen.findByText(/SSH authentication failed/);
expect(alert.textContent).toBe("SSH authentication failed: check the user and the saved password or key");
});
@@ -75,7 +75,7 @@ it("requires explicit delete confirmation and uses the displayed version", async
deleteNotebook: remove,
} as unknown as Api
}
list={[]}
list={[{ path: "a.md", title: "A" }]}
path="a.md"
version="latest"
onSelect={vi.fn()}
@@ -83,7 +83,10 @@ it("requires explicit delete confirmation and uses the displayed version", async
canLeave={() => true}
/>,
);
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
// The open notebook has an actions menu; deleting asks again in a dialog.
fireEvent.click(screen.getByRole("button", { name: "Actions for A" }));
fireEvent.click(screen.getByRole("menuitem", { name: "Delete" }));
expect(screen.getByRole("dialog", { name: "Delete notebook" })).toHaveTextContent("a.md");
expect(remove).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Confirm delete" }));
await waitFor(() => expect(remove).toHaveBeenCalledWith("a.md", "latest"));
+9
View File
@@ -67,10 +67,19 @@ it("renders system/session/Claude information and opens the terminal", async ()
version: "Claude 1",
loginAppearsPresent: true,
});
vi.spyOn(settingsApi, "updateStatus").mockResolvedValue({
available: true,
state: "idle",
current: "abc1234",
startedAt: null,
finishedAt: null,
log: "",
});
const revoke = vi.spyOn(settingsApi, "revoke").mockResolvedValue();
const open = vi.fn();
render(<SettingsPage openTerminal={open} />);
expect(await screen.findByText("/workspace")).toBeInTheDocument();
expect(await screen.findByRole("button", { name: "Update now" })).toBeInTheDocument();
expect(screen.getByText(/86400 seconds/)).toBeInTheDocument();
expect(screen.getByText("Available: Claude 1")).toBeInTheDocument();
fireEvent.click(screen.getByText("Open terminal to log in"));
+6 -1
View File
@@ -1,4 +1,9 @@
import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest";
afterEach(cleanup);
afterEach(() => {
cleanup();
// The app keeps its route in the URL and typed values in localStorage.
localStorage.clear();
history.replaceState(null, "", "/");
});
+127
View File
@@ -0,0 +1,127 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { expect, it, vi } from "vitest";
vi.mock("../Editor", () => ({
Editor: ({ source, onChange }: { source: string; onChange(value: string): void }) => (
<textarea aria-label="Notebook Markdown" value={source} onChange={(e) => onChange(e.target.value)} />
),
}));
import { parseNotebook } from "@shellbook/core";
import type { RenderedStep } from "@shellbook/core";
import { App } from "../App";
import type { Api } from "../api";
import { parseRoute, routeHash } from "../route";
import { recallValues, rememberValues } from "../paramMemory";
import { stepProblems } from "../StepCard";
import { Dialog } from "../ui";
import source from "../mock/ssh-key.md?raw";
const secretBook = parseNotebook(`---
params:
host: { type: host }
token: { type: secret }
---
# T
`);
it("round-trips page and notebook routes, including encoded segments", () => {
for (const route of [
{ page: "Hosts" as const },
{ page: "Settings" as const },
{ page: "Notebooks" as const, notebook: "ops/linux/a b#1.md" },
])
expect(parseRoute(routeHash(route))).toEqual(route);
expect(routeHash({ page: "Notebooks", notebook: "a b.md" })).toBe("#/notebooks/a%20b.md");
expect(parseRoute("")).toEqual({ page: "Notebooks" });
expect(parseRoute("#/unknown/x")).toEqual({ page: "Notebooks" });
expect(parseRoute("#/notebooks/%E0%A4%A")).toEqual({ page: "Notebooks" });
});
it("remembers typed values but never secrets or undeclared names", () => {
rememberValues("a.md", secretBook, { host: "web", token: "s3cret", other: "x" });
expect(localStorage.getItem("shellbook:params:a.md")).not.toContain("s3cret");
expect(recallValues("a.md", secretBook)).toEqual({ host: "web" });
// Stored data is untrusted: a secret written by hand is still dropped.
localStorage.setItem("shellbook:params:a.md", JSON.stringify({ token: "x", host: 1 }));
expect(recallValues("a.md", secretBook)).toEqual({});
localStorage.setItem("shellbook:params:a.md", "not json");
expect(recallValues("a.md", secretBook)).toEqual({});
rememberValues("a.md", secretBook, {});
expect(localStorage.getItem("shellbook:params:a.md")).toBeNull();
});
it("names a missing value once instead of repeating it as an invalid host", () => {
const rendered: RenderedStep = {
stepId: "s", kind: "check", local: false, host: "{{host}}", script: "id",
artifacts: [], uploads: [], missing: ["host"],
invalid: { host: "Unknown or missing target host" },
};
expect(stepProblems(rendered)).toEqual(["Fill in host to run this step."]);
expect(stepProblems({ ...rendered, host: "gone", missing: [], invalid: { host: "Unknown or missing target host", port: "bad" } }))
.toEqual(["host: Unknown or missing target host", "port: bad"]);
});
it("closes dialogs with Escape", () => {
const close = vi.fn();
render(<Dialog title="Example" onClose={close}><input aria-label="Field" /></Dialog>);
expect(screen.getByLabelText("Field")).toHaveFocus();
fireEvent.keyDown(document, { key: "Escape" });
expect(close).toHaveBeenCalledOnce();
});
function api(): Api {
const notebook = (path: string) => ({ path, source, notebook: parseNotebook(source), includes: [], builtins: {}, version: "1" });
return {
create: vi.fn(), move: vi.fn(), deleteNotebook: vi.fn(),
me: vi.fn().mockResolvedValue({}),
login: vi.fn(),
list: vi.fn().mockResolvedValue({ notebooks: [{ path: "a.md", title: "A" }, { path: "ops/b.md", title: "B" }] }),
hosts: vi.fn().mockResolvedValue({ hosts: [{ name: "staging", user: "admin", address: "x", port: 22, tags: [] }] }),
notebook: vi.fn(async (path: string) => notebook(path)),
save: vi.fn().mockResolvedValue({ version: "2" }),
addHost: vi.fn(),
run: vi.fn(),
events: (_callback, connected) => { connected(true); return () => {}; },
artifact: () => "",
};
}
it("opens the notebook named in the URL, keeps typed values across reloads and shows the route", async () => {
history.replaceState(null, "", "/#/notebooks/ops/b.md");
const first = api();
const view = render(<App api={first} />);
fireEvent.change(await screen.findByLabelText("Target server *"), { target: { value: "staging" } });
expect(first.notebook).toHaveBeenCalledWith("ops/b.md");
expect(first.notebook).not.toHaveBeenCalledWith("a.md");
await waitFor(() => expect(location.hash).toBe("#/notebooks/ops/b.md"));
view.unmount();
render(<App api={api()} />);
await waitFor(() => expect(screen.getByLabelText("Target server *")).toHaveValue("staging"));
fireEvent.click(screen.getByRole("button", { name: "Reset" }));
expect(screen.getByLabelText("Target server *")).toHaveValue("");
fireEvent.click(screen.getByRole("button", { name: "Hosts" }));
await waitFor(() => expect(location.hash).toBe("#/hosts"));
});
it("collapses the parameter form to a remembered summary whose chips open their field", async () => {
const view = render(<App api={api()} />);
fireEvent.change(await screen.findByLabelText("Target server *"), { target: { value: "staging" } });
fireEvent.click(screen.getByRole("button", { name: "Parameters", expanded: true }));
expect(screen.queryByLabelText("Target server *")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: /Target server.*staging/ })).toBeInTheDocument();
view.unmount();
render(<App api={api()} />);
const chip = await screen.findByRole("button", { name: /Target server.*staging/ });
expect(screen.getByRole("button", { name: "Parameters", expanded: false })).toBeInTheDocument();
fireEvent.click(chip);
await waitFor(() => expect(screen.getByLabelText("Target server *")).toHaveFocus());
expect(screen.getByRole("button", { name: "Parameters", expanded: true })).toBeInTheDocument();
});
it("saves the draft with Ctrl+S", async () => {
const live = api();
render(<App api={live} />);
fireEvent.click(await screen.findByRole("button", { name: "Edit Markdown" }));
fireEvent.change(await screen.findByLabelText("Notebook Markdown"), { target: { value: source + "\nMore\n" } });
fireEvent.keyDown(window, { key: "s", ctrlKey: true });
await waitFor(() => expect(live.save).toHaveBeenCalledWith("a.md", source + "\nMore\n", "1"));
});
+115
View File
@@ -0,0 +1,115 @@
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import type { UpdateStatusResponse } from "@shellbook/core";
import { UpdatePanel } from "../UpdatePanel";
const idle: UpdateStatusResponse = {
available: true,
state: "idle",
current: "abc1234",
startedAt: null,
finishedAt: null,
log: "",
};
function fakeApi(statuses: (UpdateStatusResponse | Error)[]) {
let index = 0;
return {
// Returns the statuses in order and then keeps returning the last one.
updateStatus: vi.fn(async () => {
const next = statuses[Math.min(index++, statuses.length - 1)]!;
if (next instanceof Error) throw next;
return next;
}),
checkUpdate: vi.fn(),
startUpdate: vi.fn(),
};
}
it("explains the manual update when the trigger is not installed", async () => {
const api = fakeApi([{ ...idle, available: false }]);
render(<UpdatePanel api={api} />);
expect(await screen.findByText("abc1234")).toBeInTheDocument();
expect(screen.getByText(/not set up on this installation/)).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Update now" })).toBeNull();
});
it("lists the commits an update would bring, or says it is up to date", async () => {
const api = fakeApi([idle]);
api.checkUpdate
.mockResolvedValueOnce({
current: "abc1234",
latest: "def5678",
pinned: false,
changes: [
{ commit: "def5678", subject: "feat(web): newer" },
{ commit: "bbb0000", subject: "fix: older" },
],
})
.mockResolvedValueOnce({ current: "def5678", latest: "def5678", pinned: false, changes: [] })
.mockResolvedValueOnce({ current: "abc1234", latest: null, pinned: true, changes: [] })
.mockRejectedValueOnce(new Error("502"));
render(<UpdatePanel api={api} />);
const check = await screen.findByRole("button", { name: "Check for updates" });
fireEvent.click(check);
expect(await screen.findByText(/2 new changes/)).toBeInTheDocument();
expect(screen.getByText("feat(web): newer")).toBeInTheDocument();
fireEvent.click(check);
expect(await screen.findByText("Up to date (def5678).")).toBeInTheDocument();
fireEvent.click(check);
expect(await screen.findByText(/pinned to a fixed version/)).toBeInTheDocument();
fireEvent.click(check);
expect(await screen.findByText("Unable to reach the repository.")).toBeInTheDocument();
});
it("asks first, then follows the update through the restart and offers a reload", async () => {
const requestedAt = new Date().toISOString();
const startedAt = new Date(Date.parse(requestedAt) + 1000).toISOString();
const api = fakeApi([
idle,
{ ...idle, state: "running", startedAt, log: "Pulling…\nBuilding…" },
new Error("502"),
{ ...idle, state: "succeeded", current: "def5678", startedAt, finishedAt: startedAt, log: "Done" },
]);
api.startUpdate.mockResolvedValue({ requestedAt });
render(<UpdatePanel api={api} pollMs={5} />);
fireEvent.click(await screen.findByRole("button", { name: "Update now" }));
// Nothing starts before the confirmation.
const dialog = screen.getByRole("dialog", { name: "Update ShellBook?" });
expect(api.startUpdate).not.toHaveBeenCalled();
fireEvent.click(within(dialog).getByRole("button", { name: "Update now" }));
await waitFor(() => expect(api.startUpdate).toHaveBeenCalledOnce());
expect(await screen.findByText(/Building…/)).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Update now" })).toBeDisabled();
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Update finished (def5678)"));
expect(screen.getByRole("button", { name: "Reload" })).toBeInTheDocument();
// The restart in between was shown instead of an error.
expect(screen.queryByText(/Unable to load/)).toBeNull();
});
it("does not mistake the previous run for the requested one", async () => {
const requestedAt = new Date().toISOString();
const old = new Date(Date.parse(requestedAt) - 3_600_000).toISOString();
const api = fakeApi([{ ...idle, state: "succeeded", startedAt: old, finishedAt: old, log: "old run" }]);
api.startUpdate.mockResolvedValue({ requestedAt });
render(<UpdatePanel api={api} pollMs={5} />);
fireEvent.click(await screen.findByRole("button", { name: "Update now" }));
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Update now" }));
await waitFor(() => expect(api.updateStatus.mock.calls.length).toBeGreaterThan(3));
expect(screen.getByRole("status")).toHaveTextContent("Starting the update…");
});
it("shows a failed update with its log", async () => {
const requestedAt = new Date().toISOString();
const api = fakeApi([
idle,
{ ...idle, state: "failed", startedAt: requestedAt, finishedAt: requestedAt, log: "pnpm: build failed" },
]);
api.startUpdate.mockResolvedValue({ requestedAt });
render(<UpdatePanel api={api} pollMs={5} />);
fireEvent.click(await screen.findByRole("button", { name: "Update now" }));
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Update now" }));
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("The update failed"));
expect(screen.getByText("pnpm: build failed")).toBeVisible();
expect(screen.getByRole("button", { name: "Update now" })).toBeEnabled();
});
+155
View File
@@ -0,0 +1,155 @@
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
/** Modal dialog: Escape and the backdrop cancel; focus moves into it on open. */
/** The ShellBook mark (public/shellbook.svg); decorative next to the product name. */
export function Logo({ size = 22 }: { size?: number }) {
return <img className="logo" src="/shellbook.svg" width={size} height={size} alt="" />;
}
export function Dialog({
title,
onClose,
children,
wide = false,
}: {
title: string;
onClose(): void;
children: ReactNode;
wide?: boolean;
}) {
const id = useId();
const box = useRef<HTMLElement>(null);
const close = useRef(onClose);
close.current = onClose;
useEffect(() => {
const previous = document.activeElement as HTMLElement | null;
const first = box.current?.querySelector<HTMLElement>(
"input:not([type=hidden]), select, textarea, button:not(.dialog-close)",
);
first?.focus();
const key = (e: KeyboardEvent) => {
if (e.key === "Escape") close.current();
};
document.addEventListener("keydown", key);
return () => {
document.removeEventListener("keydown", key);
previous?.focus?.();
};
}, []);
return (
<div
className="modal-backdrop"
onMouseDown={(e) => {
if (e.target === e.currentTarget) onClose();
}}
>
<section
ref={box}
className={wide ? "dialog wide" : "dialog"}
role="dialog"
aria-modal="true"
aria-labelledby={id}
>
<header>
<h2 id={id}>{title}</h2>
<button type="button" className="dialog-close icon" aria-label="Close" onClick={onClose}>
×
</button>
</header>
{children}
</section>
</div>
);
}
/** A small popup menu; closes on outside click, Escape, or after choosing an item. */
export function Menu({
label,
text = "⋯",
children,
}: {
label: string;
text?: ReactNode;
children: (close: () => void) => ReactNode;
}) {
const [open, setOpen] = useState(false);
const root = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const outside = (e: MouseEvent) => {
if (!root.current?.contains(e.target as Node)) setOpen(false);
};
const key = (e: KeyboardEvent) => {
if (e.key === "Escape") setOpen(false);
};
document.addEventListener("mousedown", outside);
document.addEventListener("keydown", key);
return () => {
document.removeEventListener("mousedown", outside);
document.removeEventListener("keydown", key);
};
}, [open]);
return (
<div className="menu" ref={root}>
<button
type="button"
className="icon"
aria-label={label}
aria-haspopup="menu"
aria-expanded={open}
onClick={() => setOpen(!open)}
>
{text}
</button>
{open && (
<div className="menu-items" role="menu" aria-label={label}>
{children(() => setOpen(false))}
</div>
)}
</div>
);
}
/** Copies text and briefly confirms on the button itself. */
export function CopyButton({
text,
label = "Copy",
disabled,
title,
}: {
text: () => string;
label?: string;
disabled?: boolean;
title?: string;
}) {
const [state, setState] = useState<"" | "done" | "failed">("");
useEffect(() => {
if (!state) return;
const timer = setTimeout(() => setState(""), 1800);
return () => clearTimeout(timer);
}, [state]);
return (
<>
<button
type="button"
disabled={disabled}
title={title}
onClick={async () => {
try {
await navigator.clipboard.writeText(text());
setState("done");
} catch {
setState("failed");
}
}}
>
{label}
</button>
{state && (
<small role="status" className={state === "failed" ? "error" : "ok"}>
{state === "done" ? "Copied" : "Copy failed. Select and copy manually."}
</small>
)}
</>
);
}
+22
View File
@@ -0,0 +1,22 @@
/**
* Per-browser layout preferences (collapsed panels and the like). Never holds data that
* must persist reliably; storage may be missing or blocked, which falls back to defaults.
*/
const key = (name: string) => `shellbook:ui:${name}`;
export function readFlag(name: string, fallback: boolean): boolean {
try {
const stored = localStorage.getItem(key(name));
return stored === null ? fallback : stored === "1";
} catch {
return fallback;
}
}
export function writeFlag(name: string, value: boolean): void {
try {
localStorage.setItem(key(name), value ? "1" : "0");
} catch {
// Unavailable storage only means the choice lasts for this page.
}
}
+8
View File
@@ -49,6 +49,14 @@ scripts from `/opt/shellbook`, which the service user (and the terminal panel)
can modify. A failed build leaves the running service in place; check
`journalctl -u shellbook`.
Settings → Updates shows the installed commit, checks the repository for new
commits, and starts the same update with **Update now**, following its output
through the restart. The button needs the trigger units the installer adds
(`shellbook-update.path` watches `/var/lib/shellbook/update-request` and starts
`shellbook-update.service` as root; output in `/var/log/shellbook-update.log`). Older
installations get them with one `shellbook-update` run from the CLI. If the button
does nothing, check `systemctl status shellbook-update.path shellbook-update`.
Configuration is `/etc/shellbook/env`; data is `/var/lib/shellbook` (back it up
along with workspace and service-user home). `SHELLBOOK_SESSION_SECONDS` defaults
to 2592000 (30 days). Cookies survive restart. Logout clears the browser cookie;
+44
View File
@@ -59,6 +59,22 @@ if [[ -z $(find "$workspace" -mindepth 1 -maxdepth 1 -print -quit) ]]; then
chown -R shellbook:shellbook "$workspace"
runuser -u shellbook -- git -C "$workspace" init
fi
# Offer each shipped notebook template once: updates bring new templates into existing
# workspaces, but never overwrite files or bring back ones the user deleted. The copy runs
# as the service user, so links inside the workspace cannot redirect a root write.
offer_templates() { # <templates dir> <workspace> <offered list>
local file rel
touch "$3"
[[ -d $1/notebooks ]] || return 0
while IFS= read -r -d '' file; do
rel=${file#"$1"/}
grep -qxF -- "$rel" "$3" && continue
runuser -u shellbook -- bash -c 'test -e "$2" || test -L "$2" || install -D -m 644 "$1" "$2"' _ "$file" "$2/$rel"
printf '%s\n' "$rel" >> "$3"
done < <(find "$1/notebooks" -type f -name '*.md' -print0 | sort -z)
}
install -d -m 0750 /etc/shellbook
offer_templates /opt/shellbook/templates/workspace "$workspace" /etc/shellbook/templates-offered
if [[ ! -f /home/shellbook/.ssh/id_ed25519 ]]; then
runuser -u shellbook -- ssh-keygen -q -t ed25519 -N '' -f /home/shellbook/.ssh/id_ed25519 -C shellbook
fi
@@ -104,6 +120,33 @@ PATH=/home/shellbook/.local/bin:/usr/local/bin:/usr/bin:/bin
EOF
fi
chmod 600 /etc/shellbook/env
# Updates from the web UI (#15). The service stays unprivileged and may only change a
# request file in its data directory; systemd then runs the fixed root-owned updater
# above. Its output goes to root-owned /var/log, readable by the service.
data_dir=$(sed -n 's/^SHELLBOOK_DATA_DIR=//p' /etc/shellbook/env)
[[ $data_dir =~ ^/[A-Za-z0-9._/-]+$ ]] || { echo 'Invalid SHELLBOOK_DATA_DIR' >&2; exit 1; }
cat > /etc/systemd/system/shellbook-update.service <<'EOF'
[Unit]
Description=Update ShellBook (requested from the web UI)
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/shellbook-update
StandardOutput=truncate:/var/log/shellbook-update.log
StandardError=inherit
TimeoutStartSec=30min
EOF
cat > /etc/systemd/system/shellbook-update.path <<EOF
[Unit]
Description=Start a ShellBook update when the web UI requests one
[Path]
PathChanged=$data_dir/update-request
Unit=shellbook-update.service
[Install]
WantedBy=paths.target
EOF
cat > /etc/systemd/system/shellbook.service <<'EOF'
[Unit]
Description=ShellBook runbook server
@@ -146,6 +189,7 @@ if [[ -n ${TS_AUTHKEY:-} ]]; then
fi
systemctl daemon-reload
systemctl enable shellbook
systemctl enable --now shellbook-update.path
systemctl restart shellbook
# Wait until the server answers before reporting success.
listen_host=$(sed -n 's/^SHELLBOOK_HOST=//p' /etc/shellbook/env)
+31 -1
View File
@@ -20,4 +20,34 @@ grep -q 'git_app pull --ff-only' "$dir/install.sh" || { echo 'install.sh: existi
# Nothing may remain in the CT's /root after the Proxmox install.
grep -q 'rm -f /root/shellbook-install.env /root/shellbook-install.sh' "$dir/proxmox/create-ct.sh" \
|| { echo 'create-ct.sh: installer files left in the CT' >&2; exit 1; }
printf '8 install script checks passed\n'
# Templates: new ones reach existing workspaces once; existing and deleted files stay as they are.
offer=$(sed -n '/^offer_templates() {/,/^}$/p' "$dir/install.sh")
[[ -n $offer ]] || { echo 'install.sh: offer_templates missing' >&2; exit 1; }
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
(
runuser() { shift 3; "$@"; } # stub: run as the current user
eval "$offer"
mkdir -p "$tmp/t/notebooks/infra" "$tmp/w/notebooks"
printf 'new\n' > "$tmp/t/notebooks/infra/lxc.md"; printf 'shipped\n' > "$tmp/t/notebooks/a.md"
printf 'mine\n' > "$tmp/w/notebooks/a.md"
offer_templates "$tmp/t" "$tmp/w" "$tmp/offered"
[[ $(cat "$tmp/w/notebooks/a.md") == mine && $(cat "$tmp/w/notebooks/infra/lxc.md") == new ]] || { echo 'offer_templates: wrong copy' >&2; exit 1; }
rm "$tmp/w/notebooks/infra/lxc.md"
offer_templates "$tmp/t" "$tmp/w" "$tmp/offered"
[[ ! -e $tmp/w/notebooks/infra/lxc.md ]] || { echo 'offer_templates: deleted template came back' >&2; exit 1; }
[[ $(sort "$tmp/offered" | tr '\n' ' ') == 'notebooks/a.md notebooks/infra/lxc.md ' ]] || { echo 'offer_templates: wrong list' >&2; exit 1; }
)
# Updates from the web UI: the service only touches a request file; root runs the fixed updater.
unit_body() { sed -n "/^cat > \/etc\/systemd\/system\/$1 <<'\{0,1\}EOF'\{0,1\}$/,/^EOF$/p" "$dir/install.sh" | sed '1d;$d'; }
update_service=$(unit_body shellbook-update.service)
update_path=$(unit_body shellbook-update.path)
[[ -n $update_service && -n $update_path ]] || { echo 'install.sh: update units not generated' >&2; exit 1; }
grep -qxF 'ExecStart=/usr/local/sbin/shellbook-update' <<< "$update_service" || { echo 'update unit: wrong ExecStart' >&2; exit 1; }
grep -qxF 'Type=oneshot' <<< "$update_service" || { echo 'update unit: not oneshot' >&2; exit 1; }
[[ $update_service$update_path != */opt/shellbook* ]] || { echo 'update units: reference /opt/shellbook' >&2; exit 1; }
# Root writes its output only below root-owned /var/log, never into the service user's data dir.
grep -qxF 'StandardOutput=truncate:/var/log/shellbook-update.log' <<< "$update_service" || { echo 'update unit: log not in /var/log' >&2; exit 1; }
grep -qxF 'PathChanged=$data_dir/update-request' <<< "$update_path" || { echo 'update path unit: wrong request file' >&2; exit 1; }
grep -qxF 'Unit=shellbook-update.service' <<< "$update_path" || { echo 'update path unit: wrong unit' >&2; exit 1; }
grep -qxF 'systemctl enable --now shellbook-update.path' "$dir/install.sh" || { echo 'install.sh: update trigger not enabled' >&2; exit 1; }
printf '17 install script checks passed\n'
+80 -1
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
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.
- 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
@@ -118,12 +122,79 @@ Info string: `sh {<kind> key=value key="value with spaces" flag}`. Language `sh`
`:::after{step=<id>}` … `:::` — rendered only after that step succeeded in the
current session. `:::after{step=<id> failed}` for the failure case. (remark-directive syntax.)
`:::when{param=a,b}` … `:::` — shown, and its steps runnable, only while the `choice` (or
other non-secret) parameter has one of the listed values. The server refuses to run a
step inside an inactive section. Values must be options of a `choice` parameter.
### 3.5 Artifacts
Each `on=local` run gets a fresh workdir under `data/runs/<run-id>/`. Artifacts are kept
for 24 h (configurable), then deleted. Private keys are flagged sensitive: one download
only, then removed.
### 3.6 Chained notebooks
A notebook can include another one and continue with what it produced, e.g. a service
notebook that first creates an LXC container:
```markdown
:::when{target=lxc}
::use{notebook="infra/lxc-container.md" as=ct with="hostname={{server_name}}"}
:::
```
- `::use{notebook="dir/name.md" as=alias with="p={{x}}, q=1"}` — path relative to
`notebooks/`, no `..`. The server composes the notebook (core `composeNotebook`):
the included params, step ids, captures and templates are namespaced by the alias
(`ct.hostname`, `ct.create`, `{{ct.address}}`) and shown inline as a collapsible
section with its own parameter group. Nested includes chain aliases (`svc.ct.x`); at
most 4 levels. Missing files, cycles and errors inside the included notebook are
errors on the `::use` line. The UI reloads when an included file changes.
- `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
steps of their own notebook, under their local name (`$ROOTPW`).
- Steps are gated only by the values they use (§3.2); an included notebook's empty form
never blocks the parent's steps unless they reference its values.
- 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". Only
steps that reference such a param wait for it.
- `::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
host with that name). `capture` stores the host name as a runtime value so later
steps can target it. The first SSH connection still requires host key confirmation.
- Builtins are server-provided runtime values, never namespaced:
`{{shellbook.public_key}}` is ShellBook's SSH public key. The server sets them on every
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
- Scripts run as `bash -euo pipefail -s` with the script on stdin; no TTY.
@@ -237,6 +308,14 @@ checks and responses disable caching.
service user home; credential contents are never read or returned.
- Listens on `127.0.0.1` or LAN; intended behind Traefik + firewall (LAN/Tailscale only).
- Terminal panel = shell as the service user: same trust level as the app itself.
- Self-update from Settings never gives the service privileges: POST
`/api/settings/update` only writes `<data dir>/update-request`. A root-owned systemd
path unit starts the oneshot `shellbook-update.service`, which runs the fixed
root-owned `/usr/local/sbin/shellbook-update` (it fetches the installer from the
repository and never executes the service-writable checkout) and writes its output
to `/var/log/shellbook-update.log`. The server reads state only through
`systemctl show` and that log; "check for updates" runs `git fetch` into
`FETCH_HEAD` only. A request can only start that fixed updater, nothing else.
- No secrets in notebooks, audit log or artifacts metadata.
## 8. Architecture
+193
View File
@@ -0,0 +1,193 @@
// Chained notebooks (`::use`): pure composition. The server loads the files; core only
// namespaces and merges them, so display and execution keep using one notebook model.
import type { Block, Diagnostic, Notebook, ParamDef, ParamValues, Step } from "./types";
import { includePath } from "./parser";
const template = /\{\{\s*([^{}]+?)\s*\}\}/g;
/** Maximum `::use` nesting (root -> a -> b -> c -> d). */
export const MAX_INCLUDE_DEPTH = 4;
/** Runtime names provided by the server, never namespaced: {{shellbook.public_key}}. */
export const isBuiltin = (name: string) => name.startsWith("shellbook.");
/** Workspace paths a notebook includes directly, in document order. Invalid paths never reach I/O. */
export function notebookIncludes(notebook: Notebook): string[] {
const paths: string[] = [];
const walk = (blocks: Block[]) => {
for (const block of blocks) {
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" || block.type === "group") walk(block.blocks);
}
};
walk(notebook.blocks);
return [...new Set(paths)];
}
const qualify = (alias: string, name: string) => `${alias}.${name}`;
const rewrite = (text: string, alias: string) =>
text.replace(template, (match, name: string) => isBuiltin(name) ? match : `{{${qualify(alias, name)}}}`);
const scoped = (alias: string, scope?: string) => scope ? qualify(alias, scope) : alias;
function prefixStep(step: Step, alias: string): Step {
const a = step.attrs;
return {
...step,
script: rewrite(step.script, alias),
attrs: {
...a,
id: qualify(alias, a.id),
host: a.host === undefined ? undefined : rewrite(a.host, alias),
capture: a.capture === undefined ? undefined : qualify(alias, a.capture),
artifacts: a.artifacts.map(x => rewrite(x, alias)),
uploads: a.uploads.map(u => ({ src: rewrite(u.src, alias), dst: rewrite(u.dst, alias) })),
scope: scoped(alias, a.scope),
},
};
}
/** Namespace a composed notebook's blocks under alias (names, ids, templates, scopes). */
function prefixBlocks(blocks: Block[], alias: string): Block[] {
return blocks.map((block): Block => {
switch (block.type) {
case "markdown": return { ...block, text: rewrite(block.text, alias) };
case "step": return { type: "step", step: prefixStep(block.step, 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 "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 {
...block, id: qualify(alias, block.id), scope: scoped(alias, block.scope),
name: rewrite(block.name, alias), address: rewrite(block.address, alias),
user: rewrite(block.user, alias), port: rewrite(block.port, alias),
capture: block.capture === undefined ? undefined : qualify(alias, block.capture),
};
}
});
}
function prefixParam(def: ParamDef, alias: string): ParamDef {
return {
...def,
name: qualify(alias, def.name),
default: def.default === undefined ? undefined : rewrite(def.default, alias),
scope: scoped(alias, def.scope),
};
}
/** Every step and host id in composed blocks (for duplicate detection). */
function blockIds(blocks: Block[], into: string[] = []): string[] {
for (const block of blocks) {
if (block.type === "step") into.push(block.step.attrs.id);
else if (block.type === "host") into.push(block.id);
else if ("blocks" in block) blockIds(block.blocks, into);
}
return into;
}
/**
* Resolve `::use` blocks: the included notebook's params, steps, captures and ids are
* namespaced by its alias ("ct.hostname") and merged into one notebook. `with` bindings
* become the included params' defaults in the including notebook's namespace.
* Missing files, cycles, nesting deeper than MAX_INCLUDE_DEPTH and errors inside an
* included notebook become error diagnostics on the `::use` line.
*/
export function composeNotebook(path: string, notebook: Notebook, load: (path: string) => Notebook | undefined): Notebook {
return compose(path, notebook, load, [path]);
}
function compose(path: string, notebook: Notebook, load: (path: string) => Notebook | undefined, stack: string[]): Notebook {
const diagnostics: Diagnostic[] = [...notebook.diagnostics];
const params: ParamDef[] = [...notebook.params];
const fail = (message: string, line: number) => diagnostics.push({ severity: "error", message, line });
const resolve = (blocks: Block[]): Block[] => blocks.map((block): Block => {
if (block.type === "after" || block.type === "when" || block.type === "group") return { ...block, blocks: resolve(block.blocks) };
if (block.type !== "use") return block;
const line = block.range.startLine;
// The parser already reported an invalid path; never hand it to the loader.
if (!includePath(block.path)) return block;
if (stack.includes(block.path)) { fail(`Notebook include cycle: ${[...stack, block.path].join(" -> ")}`, line); return block; }
if (stack.length > MAX_INCLUDE_DEPTH) { fail(`Notebook includes are nested deeper than ${MAX_INCLUDE_DEPTH}`, line); return block; }
const loaded = load(block.path);
if (!loaded) { fail(`Included notebook not found: ${block.path}`, line); return block; }
const child = compose(block.path, loaded, load, [...stack, block.path]);
for (const d of child.diagnostics) if (d.severity === "error") fail(`${block.path}${d.line ? `:${d.line}` : ""}: ${d.message}`, line);
const alias = block.scope;
for (const [name, value] of Object.entries(block.bindings)) {
const def = child.params.find(p => p.name === name && !p.scope);
if (!def) fail(`with binds unknown parameter of ${block.path}: ${name}`, line);
else if (def.type === "secret") fail(`with cannot bind secret ${name}; enter it in the form`, line);
}
for (const def of child.params) {
const prefixed = prefixParam(def, alias);
// Bindings are templates in the including notebook's namespace: not rewritten.
if (!def.scope && def.type !== "secret" && Object.hasOwn(block.bindings, def.name)) prefixed.default = block.bindings[def.name];
params.push(prefixed);
}
return { ...block, title: child.title, bindings: { ...block.bindings }, blocks: prefixBlocks(child.blocks, alias) };
});
const blocks = resolve(notebook.blocks);
const seen = new Set<string>();
for (const id of blockIds(blocks)) {
if (seen.has(id) && id.includes(".")) fail(`Duplicate step id after including notebooks: ${id}`, 1);
seen.add(id);
}
return { ...notebook, params, blocks, diagnostics };
}
/** Find a step anywhere in the block tree (after, when, use and group containers). */
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 ("blocks" in block) {
const found = findStep(block.blocks, id);
if (found) return found;
}
}
}
/**
* Whether a step or host block is shown and runnable: every enclosing `:::when` must match
* the resolved parameter values. `:::after` only gates display, not execution.
*/
export function blockActive(notebook: Notebook, id: string, values: ParamValues): boolean {
const walk = (blocks: Block[], active: boolean): boolean | undefined => {
for (const block of blocks) {
if (block.type === "step" && block.step.attrs.id === id) return active;
if (block.type === "host" && block.id === id) return active;
if (block.type === "when") {
const found = walk(block.blocks, active && block.values.includes(values[block.param] ?? ""));
if (found !== undefined) return found;
} else if (block.type === "after" || block.type === "use" || block.type === "group") {
const found = walk(block.blocks, active);
if (found !== undefined) return found;
}
}
return undefined;
};
return walk(notebook.blocks, true) ?? false;
}
/** Whether an included notebook's scope ("ct", "svc.ct") is active, i.e. its `::use` lies in matching `:::when` sections. The root scope ("") always is. */
export function scopeActive(notebook: Notebook, scope: string, values: ParamValues): boolean {
if (!scope) return true;
const walk = (blocks: Block[], active: boolean): boolean | undefined => {
for (const block of blocks) {
if (block.type === "use" && block.scope === scope) return active;
if (!("blocks" in block)) continue;
const found = walk(block.blocks, active && (block.type !== "when" || block.values.includes(values[block.param] ?? "")));
if (found !== undefined) return found;
}
return undefined;
};
return walk(notebook.blocks, true) ?? false;
}
/** Runtime names that steps or host blocks of the notebook set (`capture=`). */
export function captureNames(blocks: Block[], into = new Set<string>()): Set<string> {
for (const block of blocks) {
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 ("blocks" in block) captureNames(block.blocks, into);
}
return into;
}
+149 -28
View File
@@ -1,8 +1,10 @@
// Public API of @shellbook/core. Pure functions, no I/O.
import type { Notebook, ParamValues, RenderedStep, Step } from "./types";
import type { Block, GroupInputs, Notebook, ParamValues, RenderedHost, RenderedStep, Step } from "./types";
import { captureNames, isBuiltin } from "./compose";
export type * from "./types";
export type * from "./protocol";
export { parseNotebook } from "./parser";
export { parseNotebook, includePath } from "./parser";
export { composeNotebook, notebookIncludes, findStep, blockActive, scopeActive, captureNames, isBuiltin, MAX_INCLUDE_DEPTH } from "./compose";
const template = /\{\{\s*([^{}]+?)\s*\}\}/g;
const own = (object: object, key: string) => Object.hasOwn(object, key);
@@ -17,15 +19,20 @@ export function shellQuote(value: string): string {
return /^[A-Za-z0-9._/@:=+\-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
}
/** Resolve defaults ({{other}} references) and validate all params by type. */
/**
* Resolve defaults ({{other}} references) and validate all params by type. Defaults may
* also reference runtime values (captures such as {{ct.host}}, builtins {{shellbook.*}}).
*/
export function resolveParams(
notebook: Notebook,
values: ParamValues,
hostNames: readonly string[],
runtime: ParamValues = {},
): { values: ParamValues; errors: Record<string, string> } {
const effective = dictionary();
const errors = dictionary();
const defs = new Map(notebook.params.map(def => [def.name, def]));
const captures = captureNames(notebook.blocks);
const active = new Set<string>();
const resolve = (name: string): string => {
if (own(effective, name)) return effective[name]!;
@@ -34,9 +41,14 @@ export function resolveParams(
if (active.has(name)) { errors[name] = "Cyclic parameter default"; return ""; }
active.add(name);
let value = own(values, name) ? values[name] ?? "" : "";
let pending = false;
if (!value && def.type !== "secret" && def.default !== undefined) {
value = def.default.replace(template, (match, ref: string) => {
const other = defs.get(ref);
if (!other && (captures.has(ref) || isBuiltin(ref))) {
if (own(runtime, ref) && runtime[ref]) return runtime[ref]!;
errors[name] = `Available after the step that sets ${ref}`; pending = true; return match;
}
if (!other) { errors[name] = `Unknown default reference: ${ref}`; return match; }
if (other.type === "secret") { errors[name] = "Defaults cannot reference secrets"; return match; }
const resolved = resolve(ref);
@@ -46,6 +58,8 @@ export function resolveParams(
});
}
active.delete(name);
// A default still waiting for a captured value is empty, not its literal template.
if (pending) value = "";
effective[name] = value;
if (!value) {
if (def.required) errors[name] ??= "Required parameter is missing";
@@ -63,6 +77,50 @@ export function resolveParams(
return { values: effective, errors };
}
/**
* Shared template substitution for steps and host blocks. A block needs exactly the values
* 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[]) {
const resolved = resolveParams(notebook, values, hostNames, runtime);
const captures = captureNames(notebook.blocks);
const defs = new Map(notebook.params.map(def => [def.name, def]));
const invalid = dictionary();
const missing = new Set<string>();
const ownSecrets = notebook.params.filter(def => def.type === "secret" && (def.scope ?? "") === (scope ?? ""));
// Every set secret of the scope is passed as an env var (secretEnv), so it must be valid.
for (const def of ownSecrets)
if (resolved.values[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 def = defs.get(name);
if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; }
if (!def && !own(runtime, name)) {
// A capture that has not run yet (or a builtin) is pending, not a typo.
if (captures.has(name) || isBuiltin(name)) missing.add(name);
else invalid[name] = "Unknown parameter or runtime value";
return match;
}
const value = def ? resolved.values[name] : runtime[name];
if (def && own(resolved.errors, name)) invalid[name] = resolved.errors[name]!;
if (!value) { missing.add(name); return match; }
if (value.includes("\0")) { invalid[name] = "Value cannot contain NUL"; return match; }
// Never interpolate values with validation errors into scripts or metadata.
if (own(invalid, name)) return match;
return script ? shellQuote(value) : value;
});
return { substitute, readsSecrets, invalid, missing };
}
/**
* The single script substitution path: display and execution consume this result.
* Attributes use raw substitution and separate validation; secrets are env-only.
@@ -74,28 +132,9 @@ export function renderStep(
runtime: ParamValues,
hostNames: readonly string[],
): RenderedStep {
const resolved = resolveParams(notebook, values, hostNames);
const defs = new Map(notebook.params.map(def => [def.name, def]));
const invalid = dictionary();
const missing = new Set<string>();
for (const def of notebook.params) {
if (def.required && !resolved.values[def.name]) missing.add(def.name);
if ((def.required || def.type === "secret") && resolved.values[def.name]
&& own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!;
}
const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => {
const def = defs.get(name);
if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; }
if (!def && !own(runtime, name)) { invalid[name] = "Unknown parameter or runtime value"; return match; }
const value = def ? resolved.values[name] : runtime[name];
if (def && own(resolved.errors, name)) invalid[name] = resolved.errors[name]!;
if (!value) { missing.add(name); return match; }
if (value.includes("\0")) { invalid[name] = "Value cannot contain NUL"; return match; }
// Never interpolate values with validation errors into scripts or metadata.
if (own(invalid, name)) return match;
return script ? shellQuote(value) : value;
});
const { substitute, readsSecrets, invalid, missing } = substitution(notebook, step.attrs.scope, values, runtime, hostNames);
const script = substitute(step.script, true);
readsSecrets(step.script);
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";
const plainFile = (name: string) => !!name && !/[\\/\0\r\n]/.test(name) && !name.includes("..");
@@ -113,15 +152,97 @@ export function renderStep(
return { stepId: step.attrs.id, kind: step.kind, host, local: step.attrs.local, script, artifacts, uploads, missing: [...missing], invalid };
}
/** Resolve a `::host` block with the same rules as hosts.yaml entries. */
export function renderHost(
notebook: Notebook,
block: Extract<Block, { type: "host" }>,
values: ParamValues,
runtime: ParamValues,
hostNames: readonly string[],
): RenderedHost {
const { substitute, invalid, missing } = substitution(notebook, block.scope, values, runtime, hostNames);
const name = substitute(block.name, false), address = substitute(block.address, false);
const user = substitute(block.user, false), portText = substitute(block.port, false);
const port = Number(portText);
if (!/^[A-Za-z0-9._-]+$/.test(name)) invalid.name ??= "Host name may only contain letters, digits, ., _ or -";
if (!address || /[\s\0]/.test(address)) invalid.address ??= "Address cannot be empty or contain whitespace";
if (!/^[A-Za-z0-9._-]+$/.test(user)) invalid.user ??= "User may only contain letters, digits, ., _ or -";
if (!Number.isInteger(port) || port < 1 || port > 65535) invalid.port ??= "Port must be 1-65535";
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. */
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));
return text.replace(template, (match, name: string) => secrets.has(name) ? "••••" : own(values, name) ? values[name]! : match);
return text.replace(template, (match, name: string) => secrets.has(name) ? "••••" : own(values, name) && values[name] ? values[name]! : match);
}
/** Env vars for a run: every secret param under its exact name. Server-side only. */
export function secretEnv(notebook: Notebook, values: ParamValues): Record<string, string> {
/**
* Env vars for a run: the secrets of the step's scope under their local name
* (an included notebook's `ct.TOKEN` is `$TOKEN` in its own steps). Server-side only.
*/
export function secretEnv(notebook: Notebook, values: ParamValues, scope?: string): Record<string, string> {
const env = dictionary();
for (const def of notebook.params) if (def.type === "secret" && own(values, def.name)) env[def.name] = values[def.name]!;
for (const def of notebook.params) {
if (def.type !== "secret" || (def.scope ?? "") !== (scope ?? "") || !own(values, def.name)) continue;
env[def.scope ? def.name.slice(def.scope.length + 1) : def.name] = values[def.name]!;
}
return env;
}
+119 -12
View File
@@ -3,6 +3,10 @@ import type { Block, Notebook, ParamDef, Step, StepAttrs } from "./types";
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
const paramTypes = new Set(["host", "name", "path", "string", "choice", "secret"]);
const identifier = /^[A-Za-z_][A-Za-z0-9_]*$/;
/** Workspace notebook path relative to notebooks/: forward slashes, no `..`, Markdown only. */
export const includePath = (value: string) =>
/^[^\\\0\r\n:]+\.md$/.test(value) && value.split("/").every(part => part && part !== "." && part !== "..");
/** Small attribute scanner: quoted values may contain whitespace, braces and escaped quotes. */
function attributes(text: string, error: (message: string) => void): Map<string, (string | true)[]> {
@@ -42,6 +46,16 @@ function attributes(text: string, error: (message: string) => void): Map<string,
return result;
}
/** 1-based source line of a parameter's key inside the frontmatter, or the first frontmatter line. */
function paramLine(lines: string[], end: number, name: string): number {
const index = lines.findIndex((line, i) => {
if (i === 0 || i >= end || !/^\s/.test(line)) return false;
const rest = line.trimStart();
return rest.startsWith(name) && /^\s*:/.test(rest.slice(name.length));
});
return index > 0 ? index + 1 : 2;
}
export function parseNotebook(source: string): Notebook {
const notebook: Notebook = { title: "Untitled", params: [], blocks: [], diagnostics: [] };
const rawLines = source.split("\n");
@@ -66,22 +80,26 @@ export function parseNotebook(source: string): Notebook {
else if (data.title !== undefined) error("title must be a non-empty string", 2);
if (data.params !== undefined && !record(data.params)) error("params must be a mapping", 2);
if (record(data.params)) for (const [name, raw] of Object.entries(data.params)) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) error(`Invalid parameter name: ${name}`, 2);
if (!record(raw)) { error(`Parameter ${name} must be a mapping`, 2); continue; }
if (!paramTypes.has(String(raw.type))) { error(`Unknown param type for ${name}`, 2); continue; }
// Point at the parameter itself, not just the frontmatter start.
const at = paramLine(lines, end, name);
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) error(`Invalid parameter name: ${name}`, at);
if (!record(raw)) { error(`Parameter ${name} must be a mapping`, at); continue; }
if (!paramTypes.has(String(raw.type))) { error(`Unknown param type for ${name}`, at); continue; }
const def: ParamDef = { name, type: raw.type as ParamDef["type"], required: raw.required === true };
for (const key of Object.keys(raw)) if (!["type", "required", "default", "label", "options"].includes(key)) error(`Unknown parameter field ${key} for ${name}`, 2);
if (raw.required !== undefined && typeof raw.required !== "boolean") error(`required must be boolean for ${name}`, 2);
for (const key of Object.keys(raw)) if (!["type", "required", "default", "label", "options"].includes(key))
// `{ label: a (b, c) }` splits at the comma and turns "c)" into a key without a value.
error(`Unknown parameter field "${key}" for ${name}` + (raw[key] === null ? '. A value containing a comma needs quotes, e.g. label: "a, b"' : ""), at);
if (raw.required !== undefined && typeof raw.required !== "boolean") error(`required must be boolean for ${name}`, at);
if (raw.default !== undefined) {
if (def.type === "secret") error(`Secret ${name} cannot have a default`, 2);
if (def.type === "secret") error(`Secret ${name} cannot have a default`, at);
else if (typeof raw.default === "string" || typeof raw.default === "number" || typeof raw.default === "boolean") def.default = String(raw.default);
else error(`Invalid default for ${name}`, 2);
else error(`Invalid default for ${name}`, at);
}
if (typeof raw.label === "string") def.label = raw.label;
else if (raw.label !== undefined) error(`Invalid label for ${name}`, 2);
else if (raw.label !== undefined) error(`Invalid label for ${name}`, at);
if (Array.isArray(raw.options) && raw.options.every(x => typeof x === "string")) def.options = raw.options;
else if (raw.options !== undefined) error(`Invalid options for ${name}`, 2);
if (def.type === "choice" && !def.options?.length) error(`Choice ${name} needs options`, 2);
else if (raw.options !== undefined) error(`Invalid options for ${name}`, at);
if (def.type === "choice" && !def.options?.length) error(`Choice ${name} needs options`, at);
notebook.params.push(def);
}
}
@@ -90,7 +108,9 @@ export function parseNotebook(source: string): Notebook {
}
const ids = new Set<string>();
const afterRefs: { id: string; line: number }[] = [];
const aliases = new Set<string>();
let stepNumber = 0;
let hostNumber = 0;
let heading: string | undefined;
let i = start;
const parseBlocks = (nested: boolean, depth = 0): Block[] => {
@@ -118,6 +138,93 @@ export function parseNotebook(source: string): Notebook {
blocks.push({ type: "after", stepId: id, onFailure: attrs.has("failed"), blocks: children, range: { startLine: begin + 1, endLine: i } });
markdownStart = i; continue;
}
const when = /^\s{0,3}:::when\{(.*)\}\s*$/.exec(line);
if (when && depth < 100) {
flush(); const begin = i++;
const attrs = attributes(when[1]!, m => error(m, begin + 1));
const [param, raw] = [...attrs][0] ?? [];
const value = raw?.[0];
if (attrs.size !== 1 || typeof value !== "string") error("when requires exactly one param=value[,value]", begin + 1);
const values = typeof value === "string" ? value.split(",").map(v => v.trim()).filter(Boolean) : [];
const def = notebook.params.find(p => p.name === param);
if (param && !def) error(`when references unknown parameter: ${param}`, begin + 1);
else if (def?.type === "secret") error("when cannot test a secret", begin + 1);
else if (def?.options) for (const v of values) if (!def.options.includes(v)) error(`when value is not an option of ${param}: ${v}`, begin + 1);
const children = parseBlocks(true, depth + 1);
if (i === lines.length) error("Unclosed when container", begin + 1);
else i++;
blocks.push({ type: "when", param: param ?? "", values, blocks: children, range: { startLine: begin + 1, endLine: i } });
markdownStart = i; continue;
}
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) {
flush();
const lineNo = i + 1;
const attrs = attributes(leaf[2]!, m => error(m, lineNo));
const get = (key: string): string | undefined => {
const v = attrs.get(key);
if (v && (v.length > 1 || v[0] === true)) error(`${key} requires one value`, lineNo);
return typeof v?.[0] === "string" ? v[0] : undefined;
};
const range = { startLine: lineNo, endLine: lineNo };
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);
const path = get("notebook") ?? "";
const alias = get("as") ?? "";
if (!includePath(path)) error('use requires notebook="dir/name.md" (relative to notebooks/)', lineNo);
if (!identifier.test(alias) || alias === "shellbook") error("use requires as=alias (letters, digits, _; not shellbook)", lineNo);
else if (aliases.has(alias)) error(`Duplicate use alias: ${alias}`, lineNo);
aliases.add(alias);
const bindings = Object.create(null) as Record<string, string>;
for (const value of attrs.get("with") ?? []) {
if (value === true) { error("with requires name=value pairs", lineNo); continue; }
// Values may contain commas; a new binding starts only at ",name=".
for (const pair of value.split(/,(?=\s*[A-Za-z_][A-Za-z0-9_]*\s*=)/)) {
const eq = pair.indexOf("=");
const name = pair.slice(0, Math.max(eq, 0)).trim();
if (eq <= 0 || !identifier.test(name)) error("with requires name=value pairs", lineNo);
else if (Object.hasOwn(bindings, name)) error(`Duplicate with binding: ${name}`, lineNo);
else bindings[name] = pair.slice(eq + 1).trim();
}
}
blocks.push({ type: "use", scope: alias, path, bindings, blocks: [], range });
} else {
hostNumber++;
for (const key of attrs.keys()) if (!["id", "name", "address", "user", "port", "capture"].includes(key)) error(`Unknown host attribute: ${key}`, lineNo);
const id = get("id") || `host-${hostNumber}`;
if (ids.has(id)) error(`Duplicate step id: ${id}`, lineNo);
ids.add(id);
const name = get("name"), address = get("address");
if (!name || !address) error("host requires name and address", lineNo);
const capture = get("capture");
if (capture !== undefined && !identifier.test(capture)) error("Invalid capture name", lineNo);
blocks.push({ type: "host", id, name: name ?? "", address: address ?? "", user: get("user") ?? "root", port: get("port") ?? "22", capture, range });
}
i++; markdownStart = i; continue;
}
const fence = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
if (fence) {
const begin = i;
@@ -166,7 +273,7 @@ export function parseNotebook(source: string): Notebook {
}
if (kind === "check" && (attrs.has("artifacts") || attrs.has("upload"))) error("Checks cannot declare artifacts or uploads", begin + 1);
const capture = get("capture");
if (capture && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(capture)) error("Invalid capture name", begin + 1);
if (capture && !identifier.test(capture)) error("Invalid capture name", begin + 1);
const step: Step = {
kind,
lang: match[1]!,
@@ -186,7 +293,7 @@ export function parseNotebook(source: string): Notebook {
i = end < lines.length ? end + 1 : end; markdownStart = i; continue;
}
heading ??= /^ {0,3}#\s+(.+?)\s*#*\s*$/.exec(line)?.[1];
if (/^\s*:::/.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++;
}
flush(); return blocks;
+36
View File
@@ -35,8 +35,17 @@ export interface NotebookListResponse {
// GET /api/notebooks/:path (path URL-encoded)
export interface NotebookResponse {
path: string;
/** The notebook's own Markdown (what the editor saves). */
source: string;
/** Parsed and composed: `::use` blocks contain the included notebooks (namespaced). */
notebook: Notebook;
/** Workspace paths of all included notebooks (reload when one of them changes). */
includes: string[];
/**
* Server-provided runtime values, e.g. "shellbook.public_key". The server sets them on
* every run itself; clients merge them into the runtime they render with.
*/
builtins: ParamValues;
/** Opaque version for optimistic concurrency on save. */
version: string;
}
@@ -136,6 +145,33 @@ export interface SessionSettingsResponse { lifetimeSeconds: number }
export interface ClaudeStatusResponse { available: boolean; version: string | null; loginAppearsPresent: boolean }
export interface SystemInfoResponse { version: string; workspacePath: string; dataDirPath: string; nodeVersion: string }
// Self-update from the UI (#15). The service stays unprivileged: POST only touches a
// request file that a root-owned systemd path unit watches (deploy/install.sh).
// GET /api/settings/update
export type UpdateState = "idle" | "running" | "succeeded" | "failed" | "unknown";
export interface UpdateStatusResponse {
/** The trigger units are installed; otherwise updates need `shellbook-update` as root. */
available: boolean;
state: UpdateState;
/** Installed commit (short hash) when the app runs from a git checkout. */
current: string | null;
startedAt: string | null;
finishedAt: string | null;
/** End of the last update's output. */
log: string;
}
// POST /api/settings/update/check: fetches the tracked branch, changes nothing else.
export interface UpdateCheckResponse {
current: string | null;
latest: string | null;
/** The checkout is pinned to a ref (SHELLBOOK_REF) and is never pulled. */
pinned: boolean;
/** Commits the update would bring, newest first (at most 50). */
changes: { commit: string; subject: string }[];
}
// POST /api/settings/update: 202, or 409 when unavailable or already running.
export interface UpdateStartResponse { requestedAt: string }
// ---- notebook management (#9) ------------------------------------------------
// Paths are relative to notebooks/. Mutations return 409 on stale versions or occupied targets.
// POST /api/notebooks
+94
View File
@@ -13,6 +13,11 @@ export interface ParamDef {
label?: string;
/** Only for type "choice". */
options?: string[];
/**
* Set for params of an included notebook (`::use`): the alias path ("ct", "ct.base").
* The name is then prefixed ("ct.hostname"); a secret's env var keeps the local name.
*/
scope?: string;
}
/** Param name -> current value. Missing key or "" means "not filled". */
@@ -44,6 +49,8 @@ export interface StepAttrs {
artifacts: string[];
uploads: Upload[];
timeoutSec: number;
/** Alias path when the step comes from an included notebook (see ParamDef.scope). */
scope?: string;
}
/** 1-based, inclusive line range in the notebook source. */
@@ -72,8 +79,95 @@ export type Block =
onFailure: boolean;
blocks: Block[];
range: SourceRange;
}
| {
/** `:::when{param=a,b}` — shown, and its steps runnable, only while param is one of values. */
type: "when";
param: string;
values: string[];
blocks: Block[];
range: SourceRange;
}
| {
/**
* `::use{notebook="dir/x.md" as=alias with="p={{v}}"}` — another workspace notebook inline.
* As parsed, `blocks` is empty; composeNotebook fills it with the namespaced content.
*/
type: "use";
/** Alias path ("ct"; "ct.base" for nested includes). */
scope: string;
/** Workspace notebook path relative to notebooks/. */
path: string;
/** Included notebook's title (set by composeNotebook). */
title?: string;
/** Local param name of the included notebook -> default template in the including notebook. */
bindings: Record<string, string>;
blocks: Block[];
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. */
type: "host";
id: string;
scope?: string;
/** Templates, resolved like step attributes. */
name: string;
address: string;
user: string;
port: string;
/** Runtime value set to the host name once it is in Hosts. */
capture?: string;
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. */
export interface RenderedHost {
id: string;
name: string;
address: string;
user: string;
port: number;
missing: string[];
invalid: Record<string, string>;
}
export interface Diagnostic {
severity: "error" | "warning";
message: string;
+218
View File
@@ -0,0 +1,218 @@
import { describe, expect, it } from "vitest";
import {
blockActive, scopeActive, composeNotebook, findStep, notebookIncludes, parseNotebook, renderHost,
renderStep, resolveParams, secretEnv, type Block, type Notebook,
} from "../src/index";
const lxc = `---
title: LXC container
params:
proxmox: {type: host, required: true}
hostname: {type: name, required: true}
memory: {type: name, default: "2048"}
ROOTPW: {type: secret}
---
# LXC
Creates {{hostname}}.
\`\`\`sh {run host="{{proxmox}}" id=create capture=address}
pct create --hostname {{hostname}} --memory {{memory}} --key {{shellbook.public_key}} --pw "$ROOTPW"
\`\`\`
:::after{step=create}
Created {{address}}.
:::
::host{name="{{hostname}}" address="{{address}}" capture=host}
`;
const service = `---
title: Web server
params:
target: {type: choice, options: [existing, lxc], default: lxc}
service: {type: name, default: web}
host: {type: host, required: true, default: "{{ct.host}}"}
TOKEN: {type: secret}
---
:::when{target=lxc}
::use{notebook="infra/lxc.md" as=ct with="hostname={{service}}-ct, memory=512"}
:::
\`\`\`sh {run host="{{host}}" id=install}
apt-get install -y nginx
\`\`\`
`;
const files: Record<string, string> = { "infra/lxc.md": lxc, "services/web.md": service };
const load = (path: string) => files[path] === undefined ? undefined : parseNotebook(files[path]!);
const composed = () => composeNotebook("services/web.md", parseNotebook(service), load);
function all(blocks: Block[]): Block[] {
return blocks.flatMap(b => "blocks" in b ? [b, ...all(b.blocks)] : [b]);
}
const hosts = ["pve", "web-ct", "existing"];
describe("directives", () => {
it("parses when, use and host blocks", () => {
const n = parseNotebook(service);
expect(n.diagnostics).toEqual([]);
const when = n.blocks.find(b => b.type === "when");
expect(when).toMatchObject({ type: "when", param: "target", values: ["lxc"] });
expect(when?.type === "when" && when.blocks.find(b => b.type === "use")).toMatchObject({
type: "use", scope: "ct", path: "infra/lxc.md", bindings: { hostname: "{{service}}-ct", memory: "512" }, blocks: [],
});
expect(notebookIncludes(n)).toEqual(["infra/lxc.md"]);
const host = parseNotebook(lxc).blocks.find(b => b.type === "host");
expect(host).toMatchObject({ id: "host-1", name: "{{hostname}}", address: "{{address}}", user: "root", port: "22", capture: "host" });
});
it("reports malformed directives", () => {
const bad = parseNotebook(`---
params:
mode: {type: choice, options: [a, b]}
pw: {type: secret}
---
:::when{mode=c}
:::
:::when{nope=a}
:::
:::when{pw=x}
:::
::use{notebook="../x.md" as=1x}
::use{notebook="a.md" as=shellbook}
::use{notebook="a.md" as=a with="x"}
::use{notebook="a.md" as=a}
::host{name=x}
::host{name=x address=y capture=bad-name extra=1}
::use{broken
`);
// Invalid include paths are reported but never handed to the loader.
expect(notebookIncludes(bad)).toEqual(["a.md"]);
const loaded: string[] = [];
composeNotebook("bad.md", bad, p => { loaded.push(p); return undefined; });
expect(loaded).not.toContain("../x.md");
const messages = bad.diagnostics.map(d => d.message);
expect(messages).toEqual(expect.arrayContaining([
"when value is not an option of mode: c",
"when references unknown parameter: nope",
"when cannot test a secret",
'use requires notebook="dir/name.md" (relative to notebooks/)',
"use requires as=alias (letters, digits, _; not shellbook)",
"with requires name=value pairs",
"Duplicate use alias: a",
"host requires name and address",
"Invalid capture name",
"Unknown host attribute: extra",
"Malformed or unexpected directive",
]));
});
});
describe("composeNotebook", () => {
it("namespaces the included notebook and applies with bindings", () => {
const n = composed();
expect(n.diagnostics).toEqual([]);
expect(n.params.map(p => [p.name, p.scope, p.default])).toEqual([
["target", undefined, "lxc"], ["service", undefined, "web"], ["host", undefined, "{{ct.host}}"], ["TOKEN", undefined, undefined],
["ct.proxmox", "ct", undefined], ["ct.hostname", "ct", "{{service}}-ct"], ["ct.memory", "ct", "512"], ["ct.ROOTPW", "ct", undefined],
]);
const create = findStep(n.blocks, "ct.create")!;
expect(create.attrs).toMatchObject({ host: "{{ct.proxmox}}", capture: "ct.address", scope: "ct" });
expect(create.script).toBe('pct create --hostname {{ct.hostname}} --memory {{ct.memory}} --key {{shellbook.public_key}} --pw "$ROOTPW"\n');
const blocks = all(n.blocks);
expect(blocks.find(b => b.type === "after")).toMatchObject({ stepId: "ct.create" });
expect(blocks.find(b => b.type === "host")).toMatchObject({ id: "ct.host-1", scope: "ct", name: "{{ct.hostname}}", capture: "ct.host" });
expect(blocks.find(b => b.type === "use")).toMatchObject({ title: "LXC container", scope: "ct" });
expect(blocks.some(b => b.type === "markdown" && b.text.includes("Creates {{ct.hostname}}."))).toBe(true);
});
it("namespaces nested includes by alias path", () => {
const nested = { ...files, "outer.md": '::use{notebook="services/web.md" as=svc}\n' };
const n = composeNotebook("outer.md", parseNotebook(nested["outer.md"]), p => nested[p as keyof typeof nested] === undefined ? undefined : parseNotebook(nested[p as keyof typeof nested]!));
expect(n.diagnostics).toEqual([]);
expect(n.params.find(p => p.name === "svc.ct.hostname")).toMatchObject({ scope: "svc.ct", default: "{{svc.service}}-ct" });
expect(n.params.find(p => p.name === "svc.host")).toMatchObject({ scope: "svc", default: "{{svc.ct.host}}" });
expect(findStep(n.blocks, "svc.ct.create")?.attrs.scope).toBe("svc.ct");
});
it("reports missing files, cycles, depth, child errors and bad bindings on the use line", () => {
const cases: Record<string, string> = {
"a.md": '\n::use{notebook="b.md" as=b}\n',
"b.md": '::use{notebook="a.md" as=a}\n',
"missing.md": '::use{notebook="nowhere.md" as=x}\n',
"broken.md": '::use{notebook="bad.md" as=x}\n',
"bad.md": "```sh {run bogus}\nx\n```\n",
"bind.md": '::use{notebook="infra/lxc.md" as=x with="nope=1,ROOTPW=2"}\n',
"d0.md": '::use{notebook="d1.md" as=a}\n', "d1.md": '::use{notebook="d2.md" as=a}\n', "d2.md": '::use{notebook="d3.md" as=a}\n',
"d3.md": '::use{notebook="d4.md" as=a}\n', "d4.md": '::use{notebook="d5.md" as=a}\n', "d5.md": "# deep\n",
...files,
};
const get = (p: string) => cases[p] === undefined ? undefined : parseNotebook(cases[p]!);
const errors = (p: string) => composeNotebook(p, get(p)!, get).diagnostics;
expect(errors("a.md")).toEqual([expect.objectContaining({ line: 2, message: expect.stringContaining("Notebook include cycle: a.md -> b.md -> a.md") })]);
expect(errors("missing.md")).toEqual([{ severity: "error", line: 1, message: "Included notebook not found: nowhere.md" }]);
expect(errors("broken.md")[0]?.message).toBe("bad.md:1: Unknown attribute: bogus");
expect(errors("bind.md").map(d => d.message)).toEqual([
"with binds unknown parameter of infra/lxc.md: nope", "with cannot bind secret ROOTPW; enter it in the form",
]);
expect(errors("d0.md").map(d => d.message).join()).toContain("nested deeper than 4");
});
});
describe("rendering chained notebooks", () => {
const values = { target: "lxc", "ct.proxmox": "pve", "ct.ROOTPW": "pw-secret", TOKEN: "tok" };
const runtime = { "shellbook.public_key": "ssh-ed25519 AAAA shellbook" };
it("renders included steps with bindings, builtins and shell quoting", () => {
const n = composed();
const r = renderStep(n, findStep(n.blocks, "ct.create")!, resolveParams(n, values, hosts, runtime).values, runtime, hosts);
expect(r).toMatchObject({ host: "pve", missing: [], invalid: {} });
expect(r.script).toBe("pct create --hostname web-ct --memory 512 --key 'ssh-ed25519 AAAA shellbook' --pw \"$ROOTPW\"\n");
});
it("gates required params per scope and resolves defaults from captures", () => {
const n = composed();
const before = resolveParams(n, values, hosts, runtime);
expect(before.errors.host).toBe("Available after the step that sets ct.host");
// The parent's missing host does not block the included notebook's steps ...
expect(renderStep(n, findStep(n.blocks, "ct.create")!, before.values, runtime, hosts).missing).toEqual([]);
// ... but blocks the parent's own steps until the container is in Hosts.
expect(renderStep(n, findStep(n.blocks, "install")!, before.values, runtime, hosts).missing).toContain("host");
const after = resolveParams(n, values, hosts, { ...runtime, "ct.host": "web-ct" });
expect(after.values.host).toBe("web-ct");
expect(renderStep(n, findStep(n.blocks, "install")!, after.values, { "ct.host": "web-ct" }, hosts)).toMatchObject({ host: "web-ct", missing: [], invalid: {} });
// An included required param blocks only its own scope.
const empty = resolveParams(n, { target: "lxc" }, hosts, runtime).values;
expect(renderStep(n, findStep(n.blocks, "ct.create")!, empty, runtime, hosts).missing).toContain("ct.proxmox");
expect(renderStep(n, findStep(n.blocks, "install")!, { ...empty, host: "existing" }, runtime, hosts).missing).toEqual([]);
});
it("activates when sections by resolved choice", () => {
const n = composed();
expect(blockActive(n, "ct.create", { target: "lxc" })).toBe(true);
expect(blockActive(n, "ct.host-1", { target: "lxc" })).toBe(true);
expect(blockActive(n, "ct.create", { target: "existing" })).toBe(false);
expect(blockActive(n, "install", { target: "existing" })).toBe(true);
expect(blockActive(n, "unknown", {})).toBe(false);
expect(scopeActive(n, "", {})).toBe(true);
expect(scopeActive(n, "ct", { target: "lxc" })).toBe(true);
expect(scopeActive(n, "ct", { target: "existing" })).toBe(false);
expect(scopeActive(n, "nope", { target: "lxc" })).toBe(false);
});
it("passes secrets only to their own scope under the local name", () => {
const n = composed();
expect(secretEnv(n, values, "ct")).toEqual({ ROOTPW: "pw-secret" });
expect(secretEnv(n, values)).toEqual({ TOKEN: "tok" });
});
it("resolves and validates host blocks", () => {
const n = composed();
const block = all(n.blocks).find(b => b.type === "host") as Extract<Block, { type: "host" }>;
const rv = resolveParams(n, values, hosts, runtime).values;
expect(renderHost(n, block, rv, runtime, hosts)).toMatchObject({ name: "web-ct", missing: ["ct.address"] });
expect(renderHost(n, block, rv, { "ct.address": "10.0.30.160" }, hosts)).toEqual({
id: "ct.host-1", name: "web-ct", address: "10.0.30.160", user: "root", port: 22, missing: [], invalid: {},
});
const bad: Notebook = parseNotebook('::host{name="a b" address="x y" user=r/oot port=0}\n');
expect(Object.keys(renderHost(bad, bad.blocks[0] as Extract<Block, { type: "host" }>, {}, {}, []).invalid).sort()).toEqual(["address", "name", "port", "user"]);
});
});
+12 -1
View File
@@ -80,6 +80,14 @@ describe("parser", () => {
])("reports malformed input without throwing: %s", (source, message) => {
expect(parseNotebook(source).diagnostics.some(d => d.message.includes(message))).toBe(true);
});
it("points an unquoted comma in a flow-mapping label at the parameter line with a fix", () => {
const n = parseNotebook("---\ntitle: T\nparams:\n host: { type: host }\n key: { type: secret, label: Auth key (optional, else log in) }\n---\n# T\n");
expect(n.diagnostics).toEqual([{
severity: "error",
line: 5,
message: 'Unknown parameter field "else log in)" for key. A value containing a comma needs quotes, e.g. label: "a, b"',
}]);
});
it("uses title fallback, numeric step ids, CRLF ranges and exact script whitespace", () => {
expect(parseNotebook("").title).toBe("Untitled");
const n = parseNotebook("---\r\ntitle: Front\r\n---\r\n# Heading\r\n```sh {run}\r\n echo x \r\n\r\n```\r\n");
@@ -124,7 +132,8 @@ describe("rendering and secrets", () => {
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 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(r.script).toBe("{{x}} {{unknown}} {{empty}}\n");
});
@@ -153,6 +162,8 @@ describe("rendering and secrets", () => {
it("renders prose with raw values and handles inherited names safely", () => {
const n = book(" x: {type: string}");
expect(renderText("{{x}} {{toString}}", { x: "a & b" }, n)).toBe("a & b {{toString}}");
// An unset value stays visible as its template instead of vanishing ("on ****").
expect(renderText("on **{{x}}**", { x: "" }, n)).toBe("on **{{x}}**");
expect(render(n, {}, {}).invalid.x).toBeUndefined();
expect(render(n, {}, {}).missing).toContain("x");
});
+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");
});
});
+50 -2
View File
@@ -48,7 +48,9 @@ Non-secret defaults may reference other parameters.
Use `{{name}}` in prose, attributes and scripts. Script substitution is already
shell-quoted by ShellBook's core: write `id {{user}}`, not `id '{{user}}'`.
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"`.
## Step syntax and every attribute
@@ -111,4 +113,50 @@ add `failed` for failure. Refer to a real step ID. Each local run gets a fresh
uploads to transfer earlier results. Artifacts expire after 24 hours by default;
private keys are sensitive, downloadable once, then removed. Do not commit them.
See the three notebooks for complete SSH-key, read-only hardening and Debian package examples.
## Choices, chaining and new hosts
````markdown
:::when{target=lxc}
Shown, and runnable, only while the choice parameter `target` is `lxc` (or `a,b` for several).
::use{notebook="infra/lxc-container.md" as=ct with="hostname={{server_name}}"}
:::
```sh {run host="{{host}}" id=install}
apt-get install -y nginx
```
````
- `::use` includes another notebook (path relative to `notebooks/`). Its parameters
appear in their own form group as `alias.name`; refer to its captures as
`{{ct.address}}` and to its steps as `ct.<id>`. `with` sets defaults for its
parameters using this notebook's names. Never bind secrets.
- Defaults may reference captures: `host: { type: host, required: true, default: "{{ct.host}}" }`.
Only reference captures of *another* notebook from required parameters; within one
notebook make such parameters optional (e.g. `ctid: { type: name, default: "{{nextid}}" }`).
- `::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=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`.
## 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
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
```
:::
@@ -0,0 +1,97 @@
---
title: Create an LXC container on Proxmox
params:
proxmox: { type: host, required: true, label: Proxmox host }
hostname: { type: name, required: true, label: Container hostname }
ctid: { type: name, default: "{{nextid}}", label: Container ID (empty = next free) }
os: { type: choice, options: [debian-12-standard, debian-13-standard, ubuntu-24.04-standard], default: debian-12-standard, label: Template }
cores: { type: name, default: "2", label: CPU cores }
memory: { type: name, default: "2048", label: Memory (MiB) }
swap: { type: name, default: "512", label: Swap (MiB) }
disk: { type: name, default: "8", label: Disk (GiB) }
storage: { type: name, default: local-lvm, label: Disk storage }
template_storage: { type: name, default: local, label: Template storage }
bridge: { type: name, default: vmbr0, label: Network bridge }
net: { type: string, default: "ip=dhcp", label: "IP config (ip=dhcp or ip=10.0.0.5/24,gw=10.0.0.1)" }
---
# Create LXC container {{hostname}}
Creates an unprivileged container on **{{proxmox}}** (connects as a user that may run
`pct`, usually root), starts it with ShellBook's SSH key for root, and adds it to
Hosts. Other notebooks can include this one with
`::use{notebook="infra/lxc-container.md" as=ct}` and target the new machine through
its `host` capture (`ct.host` with that alias).
```sh {check host="{{proxmox}}" id=pve title="Proxmox tools are available"}
command -v pct
command -v pveam
command -v pvesh
```
```sh {check host="{{proxmox}}" id=next-id title="Next free container ID" capture=nextid}
pvesh get /cluster/nextid
```
```sh {check host="{{proxmox}}" id=id-free title="Container ID is free"}
if pct status {{ctid}} > /dev/null 2>&1; then
echo "Container {{ctid}} already exists" >&2
exit 1
fi
```
The template step refreshes the template index and downloads the newest
**{{os}}** template if it is not on **{{template_storage}}** yet.
```sh {run host="{{proxmox}}" id=template title="Download template" capture=template timeout=900}
pveam update > /dev/null
name=$(pveam available --section system | awk -v prefix={{os}} 'index($2, prefix) == 1 { print $2 }' | sort -V | tail -n 1)
if [ -z "$name" ]; then
echo "No template matching {{os}} is available" >&2
exit 1
fi
if ! pveam list {{template_storage}} | grep -qF "$name"; then
pveam download {{template_storage}} "$name" >&2
fi
printf '%s:vztmpl/%s\n' {{template_storage}} "$name"
```
```sh {run host="{{proxmox}}" id=create title="Create and start container" confirm timeout=600}
keys=$(mktemp)
trap 'rm -f "$keys"' EXIT
printf '%s\n' {{shellbook.public_key}} > "$keys"
pct create {{ctid}} {{template}} \
--hostname {{hostname}} \
--cores {{cores}} --memory {{memory}} --swap {{swap}} \
--rootfs {{storage}}:{{disk}} \
--net0 name=eth0,bridge={{bridge}},{{net}} \
--unprivileged 1 --features nesting=1 --onboot 1 \
--ssh-public-keys "$keys"
pct start {{ctid}}
```
The next check waits for the container's address and prints its SSH host key
fingerprints (stderr). Compare them with the fingerprint ShellBook shows on the first
connection.
```sh {check host="{{proxmox}}" id=address title="Wait for the container address" capture=address timeout=120}
ip=""
for _ in $(seq 1 45); do
ip=$(pct exec {{ctid}} -- hostname -I 2> /dev/null | awk '{ print $1 }' || true)
[ -n "$ip" ] && break
sleep 2
done
if [ -z "$ip" ]; then
echo "Container {{ctid}} has no IP address yet" >&2
exit 1
fi
pct exec {{ctid}} -- sh -c 'for key in /etc/ssh/ssh_host_*_key.pub; do ssh-keygen -lf "$key"; done' >&2 || true
printf '%s\n' "$ip"
```
::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}
```sh {check host="{{host}}" id=login title="ShellBook can log in"}
uname -a
head -n 2 /etc/os-release
```
@@ -0,0 +1,50 @@
---
title: Install a web server (nginx)
params:
target: { type: choice, options: [lxc, existing], default: lxc, label: Install on }
server_name: { type: name, required: true, default: web, label: Server name }
host: { type: host, required: true, default: "{{ct.host}}", label: Target server }
---
# Install nginx on {{host}}
Example of a chained notebook. Choose **Install on: lxc** to create a fresh Proxmox
container first (its form appears below), or **existing** to pick a server from
Hosts. The install steps then target **Target server**, which defaults to the new
container once it is in Hosts.
:::when{target=lxc}
## New container
::use{notebook="infra/lxc-container.md" as=ct with="hostname={{server_name}}"}
:::
## Install
Runs as root, or through passwordless `sudo -n` for other users.
```sh {check host="{{host}}" id=apt title="Debian/Ubuntu with apt and systemd"}
command -v apt-get
command -v systemctl
```
```sh {check host="{{host}}" id=installed title="nginx is installed"}
dpkg-query -W -f='${Status}\n' nginx | grep -qx 'install ok installed'
```
```sh {run host="{{host}}" id=install title="Install and start nginx" confirm timeout=600}
if [ "$(id -u)" -eq 0 ]; then as_root=""; else as_root="sudo -n"; fi
$as_root apt-get update
$as_root env DEBIAN_FRONTEND=noninteractive apt-get install -y nginx
$as_root systemctl enable --now nginx
```
```sh {check host="{{host}}" id=active title="nginx is running and answers"}
systemctl is-active nginx
timeout 5 bash -c 'exec 3<>/dev/tcp/127.0.0.1/80'
```
:::after{step=install}
nginx is installed on **{{host}}**. Put your site into `/etc/nginx/sites-available/`
and review the firewall before exposing it.
:::