Compare commits

..
18 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
63 changed files with 4451 additions and 1295 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] **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] **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] **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 ## 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] **Watcher timing tests:** full parallel test run on Windows delays fs events >100 ms; keep watcher test debounce/quiet windows generous.
- [2026-11-16] **HTTP errors:** server httpError messages (4xx/502/503) are user-facing and shown by the web client; 500 messages are not. Keep 4xx/502 messages free of secrets. - [2026-11-16] **HTTP errors:** server httpError messages (4xx/502/503) are user-facing and shown by the web client; 500 messages are not. Keep 4xx/502 messages free of secrets.
- [2026-11-16] **CJS named imports in the bundle:** `import { utils } from "ssh2"` passes Vitest but crashes `node dist/main.js`; import CommonJS packages via default export. `test/bundle.test.ts` starts the real bundle. - [2026-11-16] **CJS named imports in the bundle:** `import { utils } from "ssh2"` passes Vitest but crashes `node dist/main.js`; import CommonJS packages via default export. `test/bundle.test.ts` starts the real bundle.
- [2026-11-16] **Capture defaults (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 ## Archive
+3 -3
View File
@@ -2,7 +2,7 @@
> Always-loaded. Everything else is on-demand. Update TOC when files change. > Always-loaded. Everything else is on-demand. Update TOC when files change.
## Current Focus ## Current Focus
- [2026-11-16] M0–M3 (#1–#4) 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. - [2026-11-16] Open: #5/#6 need a real CT 501 deploy (bootstrap.sh one-liner, setup token, real SSH run, tmux terminal). Not yet verified in a real browser or against real OpenSSH.
## Invariants ## Invariants
@@ -15,7 +15,7 @@
- Everything doable from the web UI; files are storage, not the only way in. - Everything doable from the web UI; files are storage, not the only way in.
## Table of Contents ## Table of Contents
- `architecture.md` — 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 - `attempts.md` — 4 entries — marimo + marimo-pair trial and why it was dropped
- `open.md` — 2 entries — open design questions (sudo password, chat history) - `open.md` — 2 entries — open design questions (sudo password, chat history)
- `gotchas.md` — 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 # ShellBook
Notebook-style runbooks for Linux servers. Notebook-style runbooks for Linux servers.
+5 -1
View File
@@ -10,6 +10,7 @@ import { createNotebookWatcher } from "./watch";
import { registerAuth, type AuthOptions } from "./auth"; import { registerAuth, type AuthOptions } from "./auth";
import { registerStatic } from "./static"; import { registerStatic } from "./static";
import { chatPlugin } from "./chat"; import { chatPlugin } from "./chat";
import { defaultUpdateOptions, registerUpdate, type UpdateOptions } from "./update";
export interface AppOptions { export interface AppOptions {
logger?: boolean; logger?: boolean;
@@ -26,6 +27,8 @@ export interface AppOptions {
/** Watch workspace notebooks and publish file.changed/file.deleted on /api/events. */ /** Watch workspace notebooks and publish file.changed/file.deleted on /api/events. */
watchNotebooks?: boolean; watchNotebooks?: boolean;
terminal?: Omit<TerminalOptions, "workspaceDir">; 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/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/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/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> { export async function buildApp(options: AppOptions = {}): Promise<FastifyInstance> {
const config = loadConfig(options.config); const config = loadConfig(options.config);
@@ -41,6 +44,7 @@ export async function buildApp(options: AppOptions = {}): Promise<FastifyInstanc
const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false }); const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false });
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth }); if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
await registerSettings(app, config); await registerSettings(app, config);
await registerUpdate(app, { ...defaultUpdateOptions(config.dataDir), ...options.update });
await app.register(websocket); await app.register(websocket);
const builtins = () => builtinValues(config); const builtins = () => builtinValues(config);
await app.register(workspacePlugin, { config, builtins }); await app.register(workspacePlugin, { config, builtins });
+3 -6
View File
@@ -23,12 +23,9 @@ export function prepareRun(notebook: Notebook, req: StartRunRequest, hosts: Host
const runtime: ParamValues = Object.assign(Object.create(null) as ParamValues, const runtime: ParamValues = Object.assign(Object.create(null) as ParamValues,
Object.fromEntries(Object.entries(req.runtime).filter(([name]) => !isBuiltin(name))), builtins); Object.fromEntries(Object.entries(req.runtime).filter(([name]) => !isBuiltin(name))), builtins);
const resolved = resolveParams(notebook, req.params, names, runtime); const resolved = resolveParams(notebook, req.params, names, runtime);
// Only parameters of the step's own scope gate it (an included notebook's form does not block the parent). // A step needs exactly the values it uses (core renderStep, spec §3.6): referenced params,
// Same rule as core's renderStep: required params and secrets of the step's scope gate it; // required secrets its script reads and every set secret of its scope (passed as env).
// other params only matter when the step references them (checked by renderStep below). // Unused required params never block it, so guided notebooks run early steps first.
const scope = step.attrs.scope ?? "";
const gating = notebook.params.filter(def => (def.scope ?? "") === scope && (def.required || def.type === "secret"));
if (gating.some(def => Object.hasOwn(resolved.errors, def.name))) throw httpError(400, "Parameters are missing or invalid");
if (!blockActive(notebook, step.attrs.id, resolved.values)) throw httpError(400, "Step is not part of the selected options"); if (!blockActive(notebook, step.attrs.id, resolved.values)) throw httpError(400, "Step is not part of the selected options");
const rendered = renderStep(notebook, step, resolved.values, runtime, names); const rendered = renderStep(notebook, step, resolved.values, runtime, names);
if (rendered.missing.length || Object.keys(rendered.invalid).length) throw httpError(400, "Step parameters are missing or invalid"); if (rendered.missing.length || Object.keys(rendered.invalid).length) throw httpError(400, "Step parameters are missing or invalid");
+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 });
});
}
+35 -4
View File
@@ -4,7 +4,7 @@ import os from "node:os";
import path from "node:path"; import path from "node:path";
import { generateKeyPairSync } from "node:crypto"; import { generateKeyPairSync } from "node:crypto";
import type { HostInfo, NotebookResponse, StartRunRequest } from "@shellbook/core"; import type { HostInfo, NotebookResponse, StartRunRequest } from "@shellbook/core";
import { findStep } from "@shellbook/core"; import { findStep, parseNotebook } from "@shellbook/core";
import { buildApp } from "../src/app"; import { buildApp } from "../src/app";
import { loadConfig, type ServerConfig } from "../src/config"; import { loadConfig, type ServerConfig } from "../src/config";
import { prepareRun } from "../src/runs"; import { prepareRun } from "../src/runs";
@@ -100,13 +100,13 @@ describe("chained notebooks on the server", () => {
expect(prepared.rendered.script).toBe("pct create --hostname web-ct --key 'ssh-ed25519 SERVER' --pw \"$ROOTPW\"\n"); expect(prepared.rendered.script).toBe("pct create --hostname web-ct --key 'ssh-ed25519 SERVER' --pw \"$ROOTPW\"\n");
expect(prepared.host?.name).toBe("pve"); expect(prepared.host?.name).toBe("pve");
expect(prepared.env).toEqual({ ROOTPW: "root-pw" }); expect(prepared.env).toEqual({ ROOTPW: "root-pw" });
expect(() => prepareRun(notebook, request("install", values), hosts, builtins)).toThrow("Parameters are missing or invalid"); expect(() => prepareRun(notebook, request("install", values), hosts, builtins)).toThrow("Step parameters are missing or invalid");
const parent = prepareRun(notebook, request("install", values, { "ct.host": "web-ct" }), hosts, builtins); const parent = prepareRun(notebook, request("install", values, { "ct.host": "web-ct" }), hosts, builtins);
expect(parent.host?.name).toBe("web-ct"); expect(parent.host?.name).toBe("web-ct");
expect(parent.env).toEqual({ TOKEN: "token" }); expect(parent.env).toEqual({ TOKEN: "token" });
// Container steps are refused when "existing host" is selected; the included form gates its own steps. // Container steps are refused when "existing host" is selected; the included form gates its own steps.
expect(() => prepareRun(notebook, request("ct.create", { ...values, target: "existing" }), hosts, builtins)).toThrow("Step is not part of the selected options"); expect(() => prepareRun(notebook, request("ct.create", { ...values, target: "existing" }), hosts, builtins)).toThrow("Step is not part of the selected options");
expect(() => prepareRun(notebook, request("ct.create", { target: "lxc" }), hosts, builtins)).toThrow("Parameters are missing or invalid"); expect(() => prepareRun(notebook, request("ct.create", { target: "lxc" }), hosts, builtins)).toThrow("Step parameters are missing or invalid");
// Without a server key the builtin stays missing even if a client sends one. // Without a server key the builtin stays missing even if a client sends one.
expect(() => prepareRun(notebook, request("ct.create", values, { "shellbook.public_key": "ssh-ed25519 CLIENT" }), hosts, {})).toThrow("Step parameters are missing or invalid"); expect(() => prepareRun(notebook, request("ct.create", values, { "shellbook.public_key": "ssh-ed25519 CLIENT" }), hosts, {})).toThrow("Step parameters are missing or invalid");
}); });
@@ -146,7 +146,7 @@ pct create {{ctid}}
expect(prepared.rendered.script).toContain("printf '%s\\n' 'ssh-ed25519 AAAAKEY shellbook' > \"$keys\""); expect(prepared.rendered.script).toContain("printf '%s\\n' 'ssh-ed25519 AAAAKEY shellbook' > \"$keys\"");
expect(prepared.rendered.script).toContain("pct create 105 local:vztmpl/debian-12-standard_12.7-1_amd64.tar.zst \\\n --hostname web \\"); expect(prepared.rendered.script).toContain("pct create 105 local:vztmpl/debian-12-standard_12.7-1_amd64.tar.zst \\\n --hostname web \\");
expect(prepared.rendered.script).toContain("--net0 name=eth0,bridge=vmbr0,'ip=10.0.30.160/24,gw=10.0.30.1'"); expect(prepared.rendered.script).toContain("--net0 name=eth0,bridge=vmbr0,'ip=10.0.30.160/24,gw=10.0.30.1'");
expect(() => prepareRun(notebook, request("install", { ...values, target: "existing" }), hosts, {})).toThrow("Parameters are missing or invalid"); expect(() => prepareRun(notebook, request("install", { ...values, target: "existing" }), hosts, {})).toThrow("Step parameters are missing or invalid");
expect(prepareRun(notebook, request("install", { target: "existing", host: "existing" }), hosts, {}).host?.name).toBe("existing"); expect(prepareRun(notebook, request("install", { target: "existing", host: "existing" }), hosts, {}).host?.name).toBe("existing");
}); });
@@ -157,3 +157,34 @@ pct create {{ctid}}
expect(res.json().message).toBe("Step is not part of the selected options"); expect(res.json().message).toBe("Step is not part of the selected options");
}); });
}); });
describe("guided notebooks (#16)", () => {
const guided = parseNotebook(`---
params:
host: {type: host, required: true}
user: {type: name, required: true}
TOKEN: {type: secret, required: true}
---
:::group{title="1. Server"}
::param{name=host}
\`\`\`sh {check host="{{host}}" id=first}
true
\`\`\`
:::
\`\`\`sh {run host="{{host}}" id=later}
useradd {{user}} && curl -H "Authorization: $TOKEN" https://example.invalid
\`\`\`
`);
it("runs an early step before later required values are filled", () => {
expect(guided.diagnostics).toEqual([]);
expect(prepareRun(guided, request("first", { host: "pve" }), hosts).rendered.script).toBe("true\n");
expect(() => prepareRun(guided, request("later", { host: "pve", TOKEN: "t" }), hosts)).toThrow("Step parameters are missing or invalid");
expect(() => prepareRun(guided, request("later", { host: "pve", user: "ops" }), hosts)).toThrow("Step parameters are missing or invalid");
expect(prepareRun(guided, request("later", { host: "pve", user: "ops", TOKEN: "t" }), hosts).env).toEqual({ TOKEN: "t" });
});
it("still refuses an invalid secret even when the step does not read it", () => {
expect(() => prepareRun(guided, request("first", { host: "pve", TOKEN: "a\0b" }), hosts)).toThrow("Step parameters are missing or invalid");
});
});
-2
View File
@@ -181,8 +181,6 @@ describe("pipeline helpers", () => {
}); });
it("refuses missing or invalid parameters before execution", () => { it("refuses missing or invalid parameters before execution", () => {
const notebook: Notebook = { title: "Test", params: [{ name: "required", type: "string", required: true }], blocks: [{ type: "step", step: step() }], diagnostics: [] }; const notebook: Notebook = { title: "Test", params: [{ name: "required", type: "string", required: true }], blocks: [{ type: "step", step: step() }], diagnostics: [] };
vi.mocked(resolveParams).mockReturnValueOnce({ values: {}, errors: { required: "missing" } });
expect(() => prepareRun(notebook, request(), [])).toThrow("Parameters are missing or invalid");
vi.mocked(renderStep).mockReturnValueOnce({ ...rendered(), missing: ["required"] }); vi.mocked(renderStep).mockReturnValueOnce({ ...rendered(), missing: ["required"] });
expect(() => prepareRun(notebook, request(), [])).toThrow("Step parameters are missing or invalid"); expect(() => prepareRun(notebook, request(), [])).toThrow("Step parameters are missing or invalid");
}); });
+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 charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="dark light" /> <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> <title>ShellBook</title>
</head> </head>
<body> <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

+284 -137
View File
@@ -14,6 +14,7 @@ import {
import ReactMarkdown from "react-markdown"; import ReactMarkdown from "react-markdown";
import { import {
blockActive, blockActive,
groupInputs,
notebookIncludes, notebookIncludes,
parseNotebook, parseNotebook,
renderHost, renderHost,
@@ -38,10 +39,15 @@ import { HostsPage } from "./HostsPage";
import { HttpError } from "./api"; import { HttpError } from "./api";
import type { Api } from "./api"; import type { Api } from "./api";
import { emptySession, eventReducer, stepKey } from "./events"; import { emptySession, eventReducer, stepKey } from "./events";
import { ParamsForm, type ParamGroup } from "./ParamsForm"; import { ParamField, ParamsForm, type ParamGroup } from "./ParamsForm";
import { GroupSection } from "./GroupSection";
import { HostBlockCard } from "./HostBlockCard"; import { HostBlockCard } from "./HostBlockCard";
import { StepCard } from "./StepCard"; import { StepCard } from "./StepCard";
import { ChatPanel } from "./ChatPanel"; import { ChatPanel } from "./ChatPanel";
import { parseRoute, routeHash } from "./route";
import { recallValues, rememberValues } from "./paramMemory";
import { Dialog, Logo } from "./ui";
import { readFlag, writeFlag } from "./uiPrefs";
const TerminalSlot = lazy(() => const TerminalSlot = lazy(() =>
import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })), import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })),
); );
@@ -51,28 +57,26 @@ const Editor = lazy(() =>
function steps(blocks: Block[]): Step[] { function steps(blocks: Block[]): Step[] {
return blocks.flatMap((block) => return blocks.flatMap((block) =>
block.type === "step" block.type === "step" ? [block.step] : "blocks" in block ? steps(block.blocks) : [],
? [block.step]
: block.type === "markdown" || block.type === "host"
? []
: steps(block.blocks),
); );
} }
/** Included notebooks (`::use`, nested too) as parameter groups. */ type UseBlock = Extract<Block, { type: "use" }>;
function includedGroups(blocks: Block[]): ParamGroup[] { /** Included notebooks (`::use`, nested too), whose parameters the form shows as groups. */
return blocks.flatMap((block): ParamGroup[] => function includes(blocks: Block[]): UseBlock[] {
block.type === "use" return blocks.flatMap((block): UseBlock[] =>
? [{ scope: block.scope, title: `${block.title ?? block.path} (${block.scope})` }, ...includedGroups(block.blocks)] block.type === "use" ? [block, ...includes(block.blocks)] : "blocks" in block ? includes(block.blocks) : [],
: block.type === "after" || block.type === "when"
? includedGroups(block.blocks)
: [],
); );
} }
/** Values that are set; unset ones stay visible as `{{name}}` in prose. */
function setValuesOnly(values: ParamValues): ParamValues {
return Object.fromEntries(Object.entries(values).filter(([, value]) => value));
}
export function App({ api }: { api: Api }) { export function App({ api }: { api: Api }) {
const initialRoute = useRef(parseRoute(location.hash));
const [auth, setAuth] = useState<"loading" | "login" | "setup" | "ready">("loading"); 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 [password, setPassword] = useState("");
const [list, setList] = useState<NotebookSummary[]>([]); const [list, setList] = useState<NotebookSummary[]>();
const [hosts, setHosts] = useState<HostInfo[]>([]); const [hosts, setHosts] = useState<HostInfo[]>([]);
const [doc, setDoc] = useState<NotebookResponse>(); const [doc, setDoc] = useState<NotebookResponse>();
const [source, setSource] = useState(""); const [source, setSource] = useState("");
@@ -80,6 +84,7 @@ export function App({ api }: { api: Api }) {
const [edit, setEdit] = useState(false); const [edit, setEdit] = useState(false);
const [terminal, setTerminal] = useState(false); const [terminal, setTerminal] = useState(false);
const [chat, setChat] = useState(false); const [chat, setChat] = useState(false);
const [paramsOpen, setParamsOpen] = useState(() => readFlag("params-open", true));
const [terminalOpened, setTerminalOpened] = useState(false); const [terminalOpened, setTerminalOpened] = useState(false);
const [conflict, setConflict] = useState(false); const [conflict, setConflict] = useState(false);
const [error, setError] = useState(""); const [error, setError] = useState("");
@@ -113,7 +118,7 @@ export function App({ api }: { api: Api }) {
setConflict(false); setConflict(false);
setError(""); setError("");
if (!same) { if (!same) {
setValues({}); setValues(recallValues(path, next.notebook));
setEdit(false); setEdit(false);
setCheckIds([]); setCheckIds([]);
} }
@@ -123,6 +128,7 @@ export function App({ api }: { api: Api }) {
}, },
[api], [api],
); );
const leave = () => !current.current.dirty || window.confirm("Discard unsaved edits?");
useEffect(() => { useEffect(() => {
void api void api
.me() .me()
@@ -144,7 +150,10 @@ export function App({ api }: { api: Api }) {
if (!active) return; if (!active) return;
setList(notebooks.notebooks); setList(notebooks.notebooks);
setHosts(inventory.hosts); 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))); .catch((e) => setError(String(e)));
const close = api.events((event: ServerEvent) => { const close = api.events((event: ServerEvent) => {
@@ -190,6 +199,25 @@ export function App({ api }: { api: Api }) {
window.addEventListener("beforeunload", guard); window.addEventListener("beforeunload", guard);
return () => window.removeEventListener("beforeunload", guard); return () => window.removeEventListener("beforeunload", guard);
}, [dirty]); }, [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. // The saved notebook comes composed from the server; a draft shows its includes after saving.
const notebook = doc const notebook = doc
@@ -206,8 +234,14 @@ export function App({ api }: { api: Api }) {
? resolveParams(notebook, values, hostNames, runtime) ? resolveParams(notebook, values, hostNames, runtime)
: { values: {}, errors: {} }; : { values: {}, errors: {} };
const active = (id: string) => !!notebook && blockActive(notebook, id, resolved.values); const active = (id: string) => !!notebook && blockActive(notebook, id, resolved.values);
const groups = notebook const groups: ParamGroup[] = notebook
? includedGroups(notebook.blocks).filter((group) => scopeActive(notebook, group.scope, resolved.values)) ? includes(notebook.blocks)
.filter((block) => scopeActive(notebook, block.scope, resolved.values))
.map((block) => ({
scope: block.scope,
title: `${block.title ?? block.path} (${block.scope})`,
status: groupInputs(notebook, block, values, hostNames, runtime).status,
}))
: []; : [];
const activeChecks = notebook const activeChecks = notebook
? steps(notebook.blocks).filter((s) => s.kind === "check" && active(s.attrs.id)) ? steps(notebook.blocks).filter((s) => s.kind === "check" && active(s.attrs.id))
@@ -218,6 +252,10 @@ export function App({ api }: { api: Api }) {
}; };
const runFor = (id: string) => const runFor = (id: string) =>
session.runs[session.latest[stepKey(path, id)] ?? ""]; 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) { async function start(request: StartRunRequest) {
const key = stepKey(request.notebookPath, request.stepId); const key = stepKey(request.notebookPath, request.stepId);
setPending((previous) => new Set(previous).add(key)); setPending((previous) => new Set(previous).add(key));
@@ -265,21 +303,46 @@ export function App({ api }: { api: Api }) {
setConfirm(request); setConfirm(request);
else void start(request); else void start(request);
} }
const changeValue = (name: string, value: string) => changeValues({ ...values, [name]: value });
function blocks(items: Block[]): React.ReactNode { function blocks(items: Block[]): React.ReactNode {
if (!notebook) return null; if (!notebook) return null;
const prose = (text: string) => renderText(text, setValuesOnly({ ...runtime, ...resolved.values }), notebook);
return items.map((block, i) => { return items.map((block, i) => {
if (block.type === "markdown") if (block.type === "markdown")
return ( return (
<div className="prose" key={i}> <div className="prose" key={i}>
<ReactMarkdown> <ReactMarkdown>{prose(block.text)}</ReactMarkdown>
{renderText(
block.text,
{ ...runtime, ...resolved.values },
notebook,
)}
</ReactMarkdown>
</div> </div>
); );
if (block.type === "param") {
const def = notebook.params.find((param) => param.name === block.name);
// The parser reports unknown names; the panel still lists every parameter.
return def ? (
<div className="inline-param" key={i}>
<ParamField
param={def}
value={resolved.values[def.name]}
error={resolved.errors[def.name]}
hosts={hosts}
idPrefix={`inline-${i}-${block.range.startLine}`}
onChange={changeValue}
/>
</div>
) : null;
}
if (block.type === "group")
return (
<GroupSection
key={`${path}:${block.range.startLine}`}
title={prose(block.title)}
inputs={groupInputs(notebook, block, values, hostNames, runtime)}
params={notebook.params}
storageKey={`${path}:${block.title}`}
defaultOpen={!block.collapsed}
>
{blocks(block.blocks)}
</GroupSection>
);
if (block.type === "when") if (block.type === "when")
return block.values.includes(resolved.values[block.param] ?? "") ? ( return block.values.includes(resolved.values[block.param] ?? "") ? (
<div className="when" key={i}> <div className="when" key={i}>
@@ -288,19 +351,21 @@ export function App({ api }: { api: Api }) {
) : null; ) : null;
if (block.type === "use") if (block.type === "use")
return ( return (
<details className="included" open key={i}> <GroupSection
<summary> key={`${path}:use:${block.scope}`}
{block.title ?? block.path} className="included"
<small> title={block.title ?? block.path}
{block.path} · as {block.scope} subtitle={`${block.path} · as ${block.scope}`}
</small> inputs={groupInputs(notebook, block, values, hostNames, runtime)}
</summary> params={notebook.params}
storageKey={`${path}:use:${block.scope}`}
>
{block.blocks.length ? ( {block.blocks.length ? (
blocks(block.blocks) blocks(block.blocks)
) : ( ) : (
<p className="muted">Save the notebook to load {block.path}.</p> <p className="muted">Save the notebook to load {block.path}.</p>
)} )}
</details> </GroupSection>
); );
if (block.type === "host") { if (block.type === "host") {
const rendered = renderHost(notebook, block, resolved.values, runtime, hostNames); const rendered = renderHost(notebook, block, resolved.values, runtime, hostNames);
@@ -360,6 +425,8 @@ export function App({ api }: { api: Api }) {
); );
}); });
} }
const canSave =
dirty && !conflict && !notebook?.diagnostics.some((d) => d.severity === "error");
async function save() { async function save() {
if (!doc) return; if (!doc) return;
try { try {
@@ -379,15 +446,45 @@ export function App({ api }: { api: Api }) {
else setError(String(e)); 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( const keyPrompt = Object.values(session.runs).find(
(run) => run.status === "hostKey" && requests.current.has(run.runId), (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 === "setup") return <SetupScreen onComplete={() => setAuth("ready")} />;
if (auth === "login") if (auth === "login")
return ( return (
<main className="login"> <main className="login">
<h1>ShellBook</h1> <h1>
<p>Sign in to your workspace</p> <Logo size={48} />
ShellBook<span>RUNBOOKS</span>
</h1>
<p className="muted">Sign in to your workspace</p>
<form <form
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
@@ -417,24 +514,57 @@ export function App({ api }: { api: Api }) {
</label> </label>
<button className="primary">Sign in</button> <button className="primary">Sign in</button>
</form> </form>
{error && <p role="alert">{error}</p>} {error && <p role="alert" className="error">{error}</p>}
</main> </main>
); );
return ( return (
<div className={`app ${terminal || chat ? "with-terminal" : ""}`}> <div className="app">
<aside className="sidebar"> <header className="topbar">
<h1> <span className="brand">
ShellBook<span>RUNBOOKS</span> <Logo />
</h1> ShellBook
{import.meta.env.VITE_MOCK === "1" && <span className="chip">demo</span>}
</span>
<HeaderNavigation page={page} onChange={setPage} />
<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 <NotebookList
api={api} api={api}
list={list} list={list ?? []}
path={path} path={path}
version={doc?.version} version={doc?.version}
canLeave={() => !dirty || window.confirm("Discard unsaved edits?")} canLeave={leave}
onSelect={(next) => { onSelect={(next) => {
if (!dirty || window.confirm("Discard unsaved edits?")) if (next !== path && leave()) void load(next);
void load(next);
}} }}
onChanged={async (next) => { onChanged={async (next) => {
const result = await api.list(); const result = await api.list();
@@ -448,41 +578,20 @@ export function App({ api }: { api: Api }) {
} }
}} }}
/> />
<small className="connection">
{import.meta.env.VITE_MOCK === "1" ? "DEMO · " : ""}
{connected
? "● Events connected"
: "○ Events disconnected · reload to reconnect"}
</small>
</aside> </aside>
<main> )}
<HeaderNavigation page={page} onChange={setPage} /> <main className="main">
{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 && ( {error && (
<p className="banner error" role="alert"> <p className="banner error" role="alert">
{error} {error}
<button onClick={() => location.reload()}>Retry</button> <button onClick={() => location.reload()}>Retry</button>
</p> </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 && ( {conflict && (
<div className="banner error" role="alert"> <div className="banner error" role="alert">
The file changed on disk. Your draft has been retained. The file changed on disk. Your draft has been retained.
@@ -496,30 +605,97 @@ export function App({ api }: { api: Api }) {
</button> </button>
</div> </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 && ( {notebook && (
<> <div className={`notebook-layout${paramsOpen ? "" : " params-collapsed"}`}>
<ParamsForm <ParamsForm
notebook={notebook} notebook={notebook}
values={resolved.values} values={resolved.values}
errors={resolved.errors} errors={resolved.errors}
hosts={hosts} hosts={hosts}
groups={groups} groups={groups}
onChange={(name, value) => open={paramsOpen}
setValues((previous) => ({ ...previous, [name]: value })) onToggle={(next) => {
} writeFlag("params-open", next);
setParamsOpen(next);
}}
onChange={changeValue}
onReset={() => changeValues({})}
/> />
<div className="notebook"> <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 && ( {edit && (
<section> <section className="editor-panel">
<div className="actions"> <div className="actions">
<strong>Markdown editor {dirty ? "· unsaved" : ""}</strong> <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 <button
className="primary" className="primary"
disabled={ disabled={!canSave}
!dirty ||
conflict ||
notebook.diagnostics.some((d) => d.severity === "error")
}
onClick={() => void save()} onClick={() => void save()}
> >
Save Save
@@ -538,72 +714,43 @@ export function App({ api }: { api: Api }) {
</section> </section>
)} )}
{notebook.diagnostics.map((d, i) => ( {notebook.diagnostics.map((d, i) => (
<p role="alert" className="error" key={i}> <p role="alert" className="banner error" key={i}>
{d.line && `Line ${d.line}: `} {d.line && `Line ${d.line}: `}
{d.message} {d.message}
</p> </p>
))} ))}
<div className="actions">
<button
disabled={
!connected ||
dirty ||
activeChecks.length === 0 ||
!activeChecks.every(runnable) ||
steps(notebook.blocks).some(
(s) =>
runFor(s.attrs.id)?.status === "running" ||
pending.has(stepKey(path, s.attrs.id)),
)
}
onClick={() => {
setCheckIds(activeChecks.map((s) => s.attrs.id));
activeChecks.forEach(requestRun);
}}
>
Run all checks
</button>
{checkIds.length > 0 && (
<span role="status">
✅{" "}
{
checkIds.filter((id) => runFor(id)?.status === "success")
.length
}{" "}
/ {checkIds.length} · ❌{" "}
{
checkIds.filter((id) => runFor(id)?.status === "failure")
.length
}
</span>
)}
</div>
{blocks(notebook.blocks)} {blocks(notebook.blocks)}
</article>
</div> </div>
</>
)} )}
</div> </div>
</main> </main>
{chat && <ChatPanel notebookPath={doc?.path} openNotebook={path => { {chat && (
if (!dirty || window.confirm("Discard unsaved edits?")) void load(path); <ChatPanel
}} openTerminal={() => { setChat(false); setTerminalOpened(true); setTerminal(true); }} />} notebookPath={doc?.path}
openNotebook={(next) => {
if (leave()) {
setPage("Notebooks");
void load(next);
}
}}
openTerminal={openTerminal}
onClose={() => setChat(false)}
/>
)}
{terminalOpened && ( {terminalOpened && (
<Suspense fallback={<p>Loading terminal...</p>}> <Suspense fallback={<p>Loading terminal…</p>}>
<TerminalSlot collapsed={!terminal} /> <TerminalSlot collapsed={!terminal} onClose={() => setTerminal(false)} />
</Suspense> </Suspense>
)} )}
</div>
{confirm && ( {confirm && (
<div className="modal-backdrop"> <Dialog title="Confirm execution" onClose={() => setConfirm(undefined)}>
<section
role="dialog"
aria-modal="true"
aria-labelledby="confirm-title"
>
<h2 id="confirm-title">Confirm execution</h2>
<p> <p>
Run “{confirm.stepId}” with the displayed parameters? This step Run “{confirm.stepId}” with the displayed parameters? This step
can change the target host. can change the target host.
</p> </p>
<div className="dialog-actions">
<button onClick={() => setConfirm(undefined)}>Cancel</button> <button onClick={() => setConfirm(undefined)}>Cancel</button>
<button <button
className="primary" className="primary"
@@ -614,8 +761,8 @@ export function App({ api }: { api: Api }) {
> >
Confirm and run Confirm and run
</button> </button>
</section>
</div> </div>
</Dialog>
)} )}
{keyPrompt?.hostKey && <HostKeyConfirmation {keyPrompt?.hostKey && <HostKeyConfirmation
{...keyPrompt.hostKey} {...keyPrompt.hostKey}
+32
View File
@@ -3,7 +3,9 @@ import { parseNotebook, type ParamDef } from "@shellbook/core";
import { import {
addParameter, addParameter,
afterSnippet, afterSnippet,
groupSnippet,
hostSnippet, hostSnippet,
paramFieldSnippet,
notebookSteps, notebookSteps,
stepSnippet, stepSnippet,
useSnippet, useSnippet,
@@ -28,6 +30,7 @@ export function AuthoringToolbar({
const [after, setAfter] = useState(""); const [after, setAfter] = useState("");
const [when, setWhen] = useState(""); const [when, setWhen] = useState("");
const [include, setInclude] = useState(false); const [include, setInclude] = useState(false);
const [field, setField] = useState("");
const steps = notebookSteps(notebook.blocks); const steps = notebookSteps(notebook.blocks);
const choices = notebook.params.flatMap((p) => const choices = notebook.params.flatMap((p) =>
p.type === "choice" ? (p.options ?? []).map((o) => ({ param: p.name, option: o })) : [], p.type === "choice" ? (p.options ?? []).map((o) => ({ param: p.name, option: o })) : [],
@@ -104,6 +107,27 @@ export function AuthoringToolbar({
> >
Insert when section Insert when section
</button> </button>
<button type="button" onClick={() => insert(groupSnippet())}>
Group
</button>
<label>
Field in text
<select value={field} onChange={(e) => setField(e.target.value)}>
<option value="">Choose a parameter</option>
{notebook.params.map((p) => (
<option key={p.name} value={p.name}>
{p.name}
</option>
))}
</select>
</label>
<button
type="button"
disabled={!notebook.params.some((p) => p.name === field)}
onClick={() => insert(paramFieldSnippet(field))}
>
Insert field
</button>
<button type="button" onClick={() => setInclude(!include)}> <button type="button" onClick={() => setInclude(!include)}>
Use notebook Use notebook
</button> </button>
@@ -227,6 +251,14 @@ export function AuthoringToolbar({
adds a created machine to Hosts. {"{{shellbook.public_key}}"} is adds a created machine to Hosts. {"{{shellbook.public_key}}"} is
ShellBook's SSH public key. ShellBook's SSH public key.
</p> </p>
<p>
Guided text: {"::param{name=host}"} on its own line shows that
parameter&apos;s input there (same value as the panel).{" "}
{':::group{title="Network" collapsed}'} … {":::"} is a collapsible
section for anything; its outline is orange while needed values are
missing, green when all are filled, grey when only optional ones remain.
{" collapsed"} starts it closed. Groups never block steps.
</p>
<p> <p>
Artifact and upload snippets are examples: choose files and commands Artifact and upload snippets are examples: choose files and commands
appropriate to your runbook before running. appropriate to your runbook before running.
+10 -5
View File
@@ -12,8 +12,8 @@ const connectChat = (): ChatSocket => new WebSocket(`${location.protocol === "ht
type Message = { role: "user" | "assistant" | "tool"; text: string; path?: string }; 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. */ /** notebookPath and openNotebook use app paths (relative to notebooks/); the chat wire uses workspace paths. */
export function ChatPanel({ notebookPath, openNotebook, openTerminal, connect = connectChat }: { export function ChatPanel({ notebookPath, openNotebook, openTerminal, onClose, connect = connectChat }: {
notebookPath?: string; openNotebook(path: string): void; openTerminal(): void; connect?: () => ChatSocket; notebookPath?: string; openNotebook(path: string): void; openTerminal(): void; onClose?(): void; connect?: () => ChatSocket;
}) { }) {
const [history, setHistory] = useState<ChatConversation[]>([]); const [history, setHistory] = useState<ChatConversation[]>([]);
const [selected, setSelected] = useState(""); const [selected, setSelected] = useState("");
@@ -68,10 +68,15 @@ export function ChatPanel({ notebookPath, openNotebook, openTerminal, connect =
setError(""); setLogin(false); setSummary(""); setAllowShell(false); 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."); } } 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"> return <aside className="chat-panel side-panel" aria-label="Chat panel">
<header className="panel-header">
<h2>Chat with Claude</h2> <h2>Chat with Claude</h2>
<div className="actions"><button disabled={busy} onClick={() => choose("")}>New conversation</button> <span className="spacer" />
{!ready && <button onClick={() => setAttempt(n => n + 1)}>Reconnect chat</button>}</div> {!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)}> <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>)} <option value="">New conversation</option>{[...history].reverse().map(c => <option key={c.id} value={c.id}>{c.title}</option>)}
</select></label> </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>
);
}
+189 -93
View File
@@ -9,8 +9,15 @@ import type {
import { json } from "./api"; import { json } from "./api";
import "./hosts.css"; import "./hosts.css";
import { HostKeyConfirmation } from "./HostKeyConfirmation"; import { HostKeyConfirmation } from "./HostKeyConfirmation";
import { CopyButton, Dialog, Menu } from "./ui";
const base = "/host-management"; const base = "/host-management";
const url = (name: string) => `${base}/${encodeURIComponent(name)}`; 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 = { const empty: HostInfo = {
name: "", name: "",
address: "", address: "",
@@ -23,6 +30,8 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
const [draft, setDraft] = useState<HostInfo>({ ...empty }); const [draft, setDraft] = useState<HostInfo>({ ...empty });
const [editVersion, setEditVersion] = useState(""); const [editVersion, setEditVersion] = useState("");
const [editing, setEditing] = useState<string>(); const [editing, setEditing] = useState<string>();
/** The add/edit server dialog is open. */
const [form, setForm] = useState(false);
const [credentialHost, setCredentialHost] = useState<string>(); const [credentialHost, setCredentialHost] = useState<string>();
const [type, setType] = useState<HostCredentialInput["type"]>("shellbook"); const [type, setType] = useState<HostCredentialInput["type"]>("shellbook");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
@@ -84,54 +93,101 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
); );
} }
} }
return ( const closeForm = () => {
<section className="hosts-page" aria-label="Server management"> setForm(false);
<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();
setEditing(undefined); setEditing(undefined);
setDraft({ ...empty }); setDraft({ ...empty });
}) };
} const closeCredentials = () => {
> setCredentialHost(undefined);
Reload hosts setPassword("");
setPrivateKey("");
setPassphrase("");
};
return (
<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>
<button
className="primary"
disabled={!inventory}
onClick={() => {
setEditing(undefined);
setDraft({ ...empty });
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 && ( {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"> <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) => ( {inventory.hosts.map((host) => (
<article key={host.name}> <article key={host.name} className="host-row" aria-label={host.name}>
<div className="host-main">
<h2>{host.name}</h2> <h2>{host.name}</h2>
<p> <code>
{host.user}@{host.address}:{host.port} {host.user}@{host.address}
</p> {host.port === 22 ? "" : `:${host.port}`}
<p>{host.tags.join(", ")}</p> </code>
<p> </div>
Authentication: {host.credential.type}{" "} <div className="host-meta">
{host.credential.fingerprint}{" "} {host.tags.map((tag) => (
{host.credential.setAt && `set ${host.credential.setAt}`} <span key={tag} className={`chip ${tag === "prod" ? "warn" : ""}`}>
</p> {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"> <div className="actions">
<button <button
disabled={busy} 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={() => { onClick={() => {
setEditing(host.name); setEditing(host.name);
setEditVersion(inventory.version); setEditVersion(inventory.version);
@@ -142,12 +198,15 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
port: host.port, port: host.port,
tags: host.tags, tags: host.tags,
}); });
setError("");
setForm(true);
}} }}
> >
Edit {host.name} Edit
</button> </button>
<button <button
disabled={busy} disabled={busy}
aria-label={`SSH credentials for ${host.name}`}
onClick={() => { onClick={() => {
setCredentialHost(host.name); setCredentialHost(host.name);
setType("shellbook"); setType("shellbook");
@@ -156,32 +215,36 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
setPassphrase(""); setPassphrase("");
}} }}
> >
SSH credentials for {host.name} Credentials
</button>
<button
disabled={busy}
onClick={() =>
void perform(() => action(host.name, { action: "test" }))
}
>
Test connection to {host.name}
</button> </button>
<Menu label={`More actions for ${host.name}`}>
{(close) => (
<>
<button <button
role="menuitem"
disabled={busy || host.credential.type !== "password"} disabled={busy || host.credential.type !== "password"}
onClick={() => title={
host.credential.type === "password"
? undefined
: "Needs a saved password"
}
onClick={() => {
close();
void perform(async () => { void perform(async () => {
const { script } = await json<{ script: string }>( const { script } = await json<{ script: string }>(
`${url(host.name)}/install-key`, `${url(host.name)}/install-key`,
); );
setInstall({ host: host.name, script }); setInstall({ host: host.name, script });
}) });
} }}
> >
Install ShellBook key on {host.name} Install ShellBook key on {host.name}
</button> </button>
<button <button
role="menuitem"
disabled={busy} disabled={busy}
onClick={() => { onClick={() => {
close();
if ( if (
window.confirm( window.confirm(
`Forget trusted SSH host key for ${host.name}? The next connection requires verification.`, `Forget trusted SSH host key for ${host.name}? The next connection requires verification.`,
@@ -193,11 +256,14 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
}); });
}} }}
> >
Forget host key for {host.name} Forget host key
</button> </button>
<button <button
role="menuitem"
className="danger"
disabled={busy} disabled={busy}
onClick={() => { onClick={() => {
close();
if ( if (
window.confirm( window.confirm(
`Delete ${host.name} and its stored credential?`, `Delete ${host.name} and its stored credential?`,
@@ -214,12 +280,33 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
> >
Delete {host.name} Delete {host.name}
</button> </button>
</>
)}
</Menu>
</div> </div>
</article> </article>
))} ))}
</div> </div>
<h2>{editing ? `Edit ${editing}` : "Add server"}</h2> <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}
>
<form <form
className="grid-form"
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
void perform(async () => { void perform(async () => {
@@ -231,8 +318,7 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
baseVersion: editing ? editVersion : inventory.version, baseVersion: editing ? editVersion : inventory.version,
}, },
); );
setEditing(undefined); closeForm();
setDraft({ ...empty });
await load(); await load();
onChange?.(); onChange?.();
}); });
@@ -243,6 +329,7 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
<input <input
required required
pattern="[A-Za-z0-9._-]+" pattern="[A-Za-z0-9._-]+"
placeholder="web-1"
value={draft.name} value={draft.name}
onChange={(e) => setDraft({ ...draft, name: e.target.value })} onChange={(e) => setDraft({ ...draft, name: e.target.value })}
/> />
@@ -251,6 +338,7 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
Address Address
<input <input
required required
placeholder="10.0.0.5 or host.example.org"
value={draft.address} value={draft.address}
onChange={(e) => onChange={(e) =>
setDraft({ ...draft, address: e.target.value }) setDraft({ ...draft, address: e.target.value })
@@ -278,8 +366,8 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
} }
/> />
</label> </label>
<label> <label className="full">
Tags (comma separated) Tags (comma separated; “prod” asks before every run)
<input <input
value={draft.tags.join(",")} value={draft.tags.join(",")}
onChange={(e) => onChange={(e) =>
@@ -293,31 +381,35 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
} }
/> />
</label> </label>
<button disabled={busy}>Save server</button> {error && (
<button <p role="alert" className="error full">
type="button" {error}
onClick={() => { </p>
setEditing(undefined); )}
setDraft({ ...empty }); <div className="dialog-actions full">
}} <button type="button" onClick={closeForm}>
> Cancel
New server
</button> </button>
<button className="primary" disabled={busy}>
Save server
</button>
</div>
</form> </form>
</Dialog>
)}
</> </>
)} )}
{credentialHost && ( {credentialHost && (
<section <Dialog
role="dialog" title={`SSH credentials for ${credentialHost}`}
aria-modal="true" onClose={closeCredentials}
aria-label={`SSH credentials for ${credentialHost}`}
> >
<h2>SSH credentials for {credentialHost}</h2> <p className="muted">
<p>
Saved secrets cannot be read back. Blank fields do not represent the Saved secrets cannot be read back. Blank fields do not represent the
existing credential. existing credential.
</p> </p>
<form <form
className="stack"
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
const credential: HostCredentialInput = const credential: HostCredentialInput =
@@ -372,6 +464,7 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
Private key Private key
<textarea <textarea
required required
rows={6}
value={privateKey} value={privateKey}
onChange={(e) => setPrivateKey(e.target.value)} onChange={(e) => setPrivateKey(e.target.value)}
/> />
@@ -402,35 +495,40 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
</label> </label>
</> </>
)} )}
<button disabled={busy}>Save authentication</button> {error && (
<button <p role="alert" className="error">
type="button" {error}
onClick={() => { </p>
setCredentialHost(undefined); )}
setPassword(""); <div className="dialog-actions">
setPrivateKey(""); <button type="button" onClick={closeCredentials}>
setPassphrase("");
}}
>
Cancel Cancel
</button> </button>
<button className="primary" disabled={busy}>
Save authentication
</button>
</div>
</form> </form>
</section> </Dialog>
)} )}
{install && ( {install && (
<section <Dialog
role="dialog" wide
aria-modal="true" title={`Install ShellBook key on ${install.host}`}
aria-label="Install ShellBook key" onClose={() => setInstall(undefined)}
> >
<h2>Install ShellBook key on {install.host}</h2> <p className="muted">
<p>
This exact script runs using the stored password. After success, This exact script runs using the stored password. After success,
select ShellBook key in SSH credentials to remove the saved select ShellBook key in SSH credentials to remove the saved
password. password.
</p> </p>
<pre>{install.script}</pre> <pre className="script">{install.script}</pre>
<div className="dialog-actions">
<button onClick={() => setInstall(undefined)}>
Cancel installation
</button>
<button <button
className="primary"
disabled={busy} disabled={busy}
onClick={() => onClick={() =>
void perform(() => void perform(() =>
@@ -443,10 +541,8 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
> >
Run displayed script Run displayed script
</button> </button>
<button onClick={() => setInstall(undefined)}> </div>
Cancel installation </Dialog>
</button>
</section>
)} )}
{trust && ( {trust && (
<HostKeyConfirmation <HostKeyConfirmation
+100 -54
View File
@@ -3,6 +3,7 @@ import { useState } from "react";
import type { NotebookSummary } from "@shellbook/core"; import type { NotebookSummary } from "@shellbook/core";
import type { Api } from "./api"; import type { Api } from "./api";
import { newNotebook } from "./authoring"; import { newNotebook } from "./authoring";
import { Dialog, Menu } from "./ui";
type Node = { folders: Map<string, Node>; files: NotebookSummary[] }; type Node = { folders: Map<string, Node>; files: NotebookSummary[] };
function tree(list: NotebookSummary[]): Node { function tree(list: NotebookSummary[]): Node {
const root: Node = { folders: new Map(), files: [] }; const root: Node = { folders: new Map(), files: [] };
@@ -40,6 +41,10 @@ export function NotebookList({
>(); >();
const [error, setError] = useState(""); const [error, setError] = useState("");
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const choose = (op: "rename" | "duplicate" | "delete") => {
setAction(op);
setError("");
};
const render = (node: Node) => ( const render = (node: Node) => (
<> <>
{[...node.folders] {[...node.folders]
@@ -51,54 +56,28 @@ export function NotebookList({
</details> </details>
))} ))}
{node.files.map((item) => ( {node.files.map((item) => (
<button <div
className={item.path === path ? "selected" : ""} className={`notebook-item ${item.path === path ? "selected" : ""}`}
key={item.path} key={item.path}
>
<button
aria-current={item.path === path ? "page" : undefined}
title={item.path}
onClick={() => onSelect(item.path)} onClick={() => onSelect(item.path)}
> >
{item.title} {item.title}
<small>{item.path}</small>
</button> </button>
))} {item.path === path && (
</> <Menu label={`Actions for ${item.title}`}>
); {(close) =>
return ( (["rename", "duplicate", "delete"] as const).map((op) => (
<>
<label>
Search notebooks
<input
type="search"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</label>
<button
onClick={() => {
setAction("new");
setError("");
}}
>
New notebook
</button>
<nav aria-label="Notebooks">
{render(
tree(
list.filter((n) =>
`${n.path} ${n.title}`
.toLowerCase()
.includes(search.toLowerCase()),
),
),
)}
</nav>
{path && (
<div className="actions">
{(["rename", "duplicate", "delete"] as const).map((op) => (
<button <button
key={op} key={op}
role="menuitem"
className={op === "delete" ? "danger" : ""}
onClick={() => { onClick={() => {
setAction(op); close();
setError(""); choose(op);
}} }}
> >
{op === "rename" {op === "rename"
@@ -107,11 +86,64 @@ export function NotebookList({
? "Duplicate" ? "Duplicate"
: "Delete"} : "Delete"}
</button> </button>
))} ))
</div> }
</Menu>
)} )}
</div>
))}
</>
);
const shown = list.filter((n) =>
`${n.path} ${n.title}`.toLowerCase().includes(search.toLowerCase()),
);
return (
<>
<div className="sidebar-tools">
<input
type="search"
aria-label="Search notebooks"
placeholder="Search notebooks"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
<button
className="icon"
aria-label="New notebook"
title="New notebook"
onClick={() => {
setAction("new");
setError("");
}}
>
+
</button>
</div>
<nav aria-label="Notebooks">
{render(tree(shown))}
{!shown.length && (
<p className="muted">
{list.length ? "No notebook matches." : "No notebooks yet."}
</p>
)}
</nav>
{action && ( {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 <form
className="stack"
key={`${action}:${path}`} key={`${action}:${path}`}
aria-label="Manage notebook" aria-label="Manage notebook"
onSubmit={async (e) => { onSubmit={async (e) => {
@@ -158,18 +190,22 @@ export function NotebookList({
} }
}} }}
> >
<strong> {action === "delete" ? (
{action === "delete" <p>
? `Delete ${path}? This cannot be undone.` Delete <code>{path}</code>? This cannot be undone.
: action === "new" </p>
? "New notebook" ) : (
: `${action} ${path}`} action !== "new" && (
</strong> <p className="muted">
From <code>{path}</code>
</p>
)
)}
{action === "new" ? ( {action === "new" ? (
<> <>
<label> <label>
Name Name
<input name="name" required /> <input name="name" required placeholder="debian-upgrade" />
</label> </label>
<label> <label>
Folder (optional) Folder (optional)
@@ -196,9 +232,12 @@ export function NotebookList({
</label> </label>
) )
)} )}
<button disabled={busy}> {error && (
{action === "delete" ? "Confirm delete" : "Apply"} <p role="alert" className="error">
</button> {error}
</p>
)}
<div className="dialog-actions">
<button <button
type="button" type="button"
disabled={busy} disabled={busy}
@@ -206,8 +245,15 @@ export function NotebookList({
> >
Cancel Cancel
</button> </button>
{error && <p role="alert">{error}</p>} <button
className={action === "delete" ? "danger" : "primary"}
disabled={busy}
>
{action === "delete" ? "Confirm delete" : "Apply"}
</button>
</div>
</form> </form>
</Dialog>
)} )}
</> </>
); );
+197 -39
View File
@@ -1,54 +1,63 @@
import type { HostInfo, Notebook, ParamDef, 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. */ /** An included notebook (`::use`) whose parameters the form shows as a group. */
export interface ParamGroup { export interface ParamGroup {
scope: string; scope: string;
title: string; title: string;
/** Input status of the included notebook (core groupInputs), shown as the outline color. */
status?: InputStatus;
} }
export function ParamsForm({ const groupFlag = (title: string) => `params-group:${title}`;
notebook,
values, /** The label a parameter is shown with; included ones without a label use their local name. */
errors, 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, hosts,
groups = [], idPrefix = "param",
onChange, onChange,
}: { }: {
notebook: Notebook; param: ParamDef;
values: ParamValues; value: string | undefined;
errors: Record<string, string>; error: string | undefined;
hosts: HostInfo[]; hosts: HostInfo[];
/** Active included notebooks; parameters of inactive ones are hidden. */ idPrefix?: string;
groups?: ParamGroup[];
onChange(name: string, value: string): void; onChange(name: string, value: string): void;
}) { }) {
const field = (param: ParamDef) => { const id = `${idPrefix}-${param.name}`;
const id = `param-${param.name}`; const label = paramLabel(param);
const local = param.scope ? param.name.slice(param.scope.length + 1) : param.name;
const common = { const common = {
id, id,
required: param.required, required: param.required,
value: values[param.name] ?? "", value: value ?? "",
"aria-labelledby": `${id}-label`, "aria-labelledby": `${id}-label`,
"aria-invalid": !!errors[param.name], "aria-invalid": !!error,
"aria-describedby": errors[param.name] ? `${id}-error` : undefined, // Red only for a wrong value; an empty field just still needs one.
onChange: ( className: error && value ? "invalid" : undefined,
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>, "aria-describedby": error ? `${id}-error` : undefined,
) => onChange(param.name, e.target.value), onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => onChange(param.name, e.target.value),
}; };
return ( return (
<label key={param.name} htmlFor={id}> <label htmlFor={id}>
<span id={`${id}-label`}> <span id={`${id}-label`} title={label}>
{param.label ?? local} {label}
{param.required && <b title="Required"> *</b>} {param.required && <b title="Required"> *</b>}
</span> </span>
{param.type === "host" || param.type === "choice" ? ( {param.type === "host" || param.type === "choice" ? (
<select {...common}> <select {...common}>
<option value="">Select…</option> <option value="">Select…</option>
{(param.type === "host" {(param.type === "host" ? hosts.map((h) => h.name) : (param.options ?? [])).map((option) => (
? hosts.map((h) => h.name)
: (param.options ?? [])
).map((option) => (
<option key={option}>{option}</option> <option key={option}>{option}</option>
))} ))}
</select> </select>
@@ -60,29 +69,178 @@ export function ParamsForm({
spellCheck={false} spellCheck={false}
/> />
)} )}
{errors[param.name] && ( {error && (
<small id={`${id}-error`} className="error"> // An empty field only needs a value: say so quietly; a wrong value is an error.
{errors[param.name]} <small id={`${id}-error`} className={value ? "error" : "muted"}>
{error}
</small> </small>
)} )}
</label> </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 ( return (
<form <form
className="params" className={`params${open ? "" : " collapsed"}`}
aria-label="Notebook parameters" aria-label="Notebook parameters"
onSubmit={(e) => e.preventDefault()} onSubmit={(e) => e.preventDefault()}
> >
{notebook.params.filter((param) => !param.scope).map(field)} <header>
{groups.map((group) => { <h2>
const params = notebook.params.filter((param) => param.scope === group.scope); <button
return params.length ? ( type="button"
<fieldset key={group.scope}> className="params-toggle"
<legend>{group.title}</legend> aria-expanded={open}
{params.map(field)} 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> </fieldset>
) : null; );
})} })}
</form> </form>
); );
+95 -47
View File
@@ -6,46 +6,68 @@ import type {
} from "@shellbook/core"; } from "@shellbook/core";
import { settingsApi } from "./settingsApi"; import { settingsApi } from "./settingsApi";
import { PasswordForm } from "./PasswordForm"; 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 [info, setInfo] = useState<SystemInfoResponse>();
const [claude, setClaude] = useState<ClaudeStatusResponse>(); const [claude, setClaude] = useState<ClaudeStatusResponse | "error">();
const [session, setSession] = useState<SessionSettingsResponse>(); const [session, setSession] = useState<SessionSettingsResponse>();
const [message, setMessage] = useState(""); const [message, setMessage] = useState("");
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
useEffect(() => { useEffect(() => {
let active = true; let active = true;
Promise.all([ const failed = () => {
settingsApi.system(), if (active) setMessage("Unable to load settings. Sign in again or retry.");
settingsApi.claude(), };
settingsApi.session(), // Independent requests: the slower Claude check must not hold back the rest.
]) settingsApi.system().then((i) => active && setInfo(i), failed);
.then(([i, c, s]) => { settingsApi.session().then((s) => active && setSession(s), failed);
if (active) { settingsApi.claude().then(
setInfo(i); (c) => active && setClaude(c),
setClaude(c); () => active && setClaude("error"),
setSession(s); );
}
})
.catch(() => {
if (active)
setMessage("Unable to load settings. Sign in again or retry.");
});
return () => { return () => {
active = false; active = false;
}; };
}, []); }, []);
return ( return (
<div className="notebook"> <div className="page settings-page">
<header className="page-header">
<div>
<h1>Settings</h1> <h1>Settings</h1>
<section> <p className="muted">Sign-in, the Claude CLI and this installation.</p>
<h2>Password and sessions</h2> </div>
<PasswordForm submit={settingsApi.password} /> </header>
{session && ( {message && (
<p> <p role="status" className="banner">
Session lifetime: {session.lifetimeSeconds} seconds ( {message}
{session.lifetimeSeconds / 86400} days).
</p> </p>
)} )}
<section className="card">
<h2>Password and sessions</h2>
<PasswordForm submit={settingsApi.password} />
<hr />
{session && (
<p className="muted">
Sessions last {duration(session.lifetimeSeconds)} (
{session.lifetimeSeconds} seconds).
</p>
)}
<div className="actions">
<button <button
disabled={busy} disabled={busy}
onClick={async () => { onClick={async () => {
@@ -64,47 +86,73 @@ export function SettingsPage({ openTerminal }: { openTerminal: () => void }) {
> >
Sign out all sessions Sign out all sessions
</button> </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> <section className="card">
<h2>Claude CLI</h2> <h2>Claude CLI</h2>
{claude ? ( {claude === undefined ? (
<> <p className="muted">Checking the Claude CLI…</p>
<p> ) : claude === "error" ? (
<p className="error">Unable to check the Claude CLI.</p>
) : (
<ul className="checklist">
<li className={claude.available ? "ok" : "bad"}>
{claude.available {claude.available
? `Available: ${claude.version}` ? `Available: ${claude.version}`
: "Claude is unavailable on PATH or did not respond."} : "Claude is unavailable on PATH or did not respond."}
</p> </li>
<p> <li className={claude.loginAppearsPresent ? "ok" : "bad"}>
{claude.loginAppearsPresent {claude.loginAppearsPresent
? "Credentials file exists; login may be available." ? "Credentials file exists; login may be available."
: "No credentials file found."} : "No credentials file found."}
</p> </li>
</> </ul>
) : (
<p>Checking CLI...</p>
)} )}
<button onClick={openTerminal}>Open terminal to log in</button> <p className="muted">
<p> Run <code>claude</code> in the terminal, then <code>/login</code>.
Run <code>claude</code>, then <code>/login</code>. Credentials are Credentials are checked for existence only.
checked for existence only.
</p> </p>
<div className="actions">
<button onClick={openTerminal}>Open terminal to log in</button>
</div>
</section> </section>
<section> <section className="card">
<h2>About/System</h2> <h2>About this installation</h2>
{info && ( {info ? (
<dl> <dl className="facts">
<dt>ShellBook version</dt> <dt>ShellBook version</dt>
<dd>{info.version}</dd> <dd>{info.version}</dd>
<dt>Workspace</dt> <dt>Workspace</dt>
<dd>{info.workspacePath}</dd> <dd>
<code>{info.workspacePath}</code>
</dd>
<dt>Data directory</dt> <dt>Data directory</dt>
<dd>{info.dataDirPath}</dd> <dd>
<code>{info.dataDirPath}</code>
</dd>
<dt>Node version</dt> <dt>Node version</dt>
<dd>{info.nodeVersion}</dd> <dd>{info.nodeVersion}</dd>
</dl> </dl>
) : (
<p className="muted">Loading…</p>
)} )}
</section> </section>
{message && <p role="status">{message}</p>} <UpdatePanel />
</div> </div>
); );
} }
+5 -1
View File
@@ -1,9 +1,13 @@
import { PasswordForm } from "./PasswordForm"; import { PasswordForm } from "./PasswordForm";
import { settingsApi } from "./settingsApi"; import { settingsApi } from "./settingsApi";
import { Logo } from "./ui";
export function SetupScreen({ onComplete }: { onComplete: () => void }) { export function SetupScreen({ onComplete }: { onComplete: () => void }) {
return ( return (
<main className="login"> <main className="login">
<h1>Set up ShellBook</h1> <h1>
<Logo size={48} />
Set up ShellBook
</h1>
<p> <p>
Enter the one-time token from the setup-token file in the server data Enter the one-time token from the setup-token file in the server data
directory. directory.
+40 -36
View File
@@ -1,10 +1,10 @@
import { ArtifactDownload } from "./ArtifactDownload"; import { ArtifactDownload } from "./ArtifactDownload";
import { useState } from "react";
import hljs from "highlight.js/lib/core"; import hljs from "highlight.js/lib/core";
import bash from "highlight.js/lib/languages/bash"; import bash from "highlight.js/lib/languages/bash";
import type { HostInfo, RenderedStep, Step } from "@shellbook/core"; import type { HostInfo, RenderedStep, Step } from "@shellbook/core";
import type { DownloadState, RunState } from "./events"; import type { DownloadState, RunState } from "./events";
import { sshCommand } from "./ssh"; import { sshCommand } from "./ssh";
import { CopyButton } from "./ui";
hljs.registerLanguage("bash", bash); hljs.registerLanguage("bash", bash);
function Script({ script }: { script: string }) { function Script({ script }: { script: string }) {
@@ -28,6 +28,20 @@ function Script({ script }: { script: string }) {
</pre> </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({ export function StepCard({
step, step,
rendered, rendered,
@@ -47,56 +61,47 @@ export function StepCard({
connected?: boolean; connected?: boolean;
onArtifactState?(runId: string, name: string, state: DownloadState): void; onArtifactState?(runId: string, name: string, state: DownloadState): void;
}) { }) {
const [notice, setNotice] = useState(""); const problems = stepProblems(rendered);
const invalid = const invalid = problems.length > 0;
rendered.missing.length > 0 || Object.keys(rendered.invalid).length > 0;
const busy = run?.status === "running" || run?.status === "hostKey"; const busy = run?.status === "running" || run?.status === "hostKey";
async function copy(ssh: boolean) { const target = rendered.local
try { ? "ShellBook server"
await navigator.clipboard.writeText( : rendered.host && !rendered.host.includes("{{")
ssh && host ? host
? sshCommand(host, rendered.script, step.attrs.sudo) ? `${host.user}@${host.name}`
: rendered.script, : rendered.host
); : "no host selected";
setNotice("Copied");
} catch {
setNotice("Copy failed. Select and copy the script manually.");
}
}
return ( return (
<article <article
className={`step ${run?.status ?? ""}`} className={`step ${step.kind} ${run?.status ?? ""}`}
aria-label={step.attrs.title ?? step.attrs.id} aria-label={step.attrs.title ?? step.attrs.id}
> >
<header> <header>
<span className="badge">{step.kind}</span> <span className={`badge kind-${step.kind}`}>{step.kind}</span>
<h3>{step.attrs.title ?? step.attrs.id}</h3> <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.sudo && <span className="badge">sudo</span>}
{(step.attrs.confirm || {(step.attrs.confirm ||
(step.kind === "run" && host?.tags.includes("prod"))) && ( (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> </header>
<Script script={rendered.script} /> <Script script={rendered.script} />
{invalid && ( {invalid && (
<p className="error" role="status"> <p className="hint" role="status">
{rendered.missing.length > 0 && {problems.join(" ")}
`Missing: ${rendered.missing.join(", ")}. `}
{Object.entries(rendered.invalid)
.map(([name, error]) => `${name}: ${error}`)
.join("; ")}
</p> </p>
)} )}
<div className="actions"> <div className="actions">
<button onClick={() => void copy(false)}>Copy</button> <CopyButton text={() => rendered.script} />
<button disabled={!host || invalid} onClick={() => void copy(true)}> <CopyButton
Copy as ssh one-liner label="Copy ssh command"
</button> title="An ssh one-liner for your own terminal"
disabled={!host || invalid}
text={() => sshCommand(host!, rendered.script, step.attrs.sudo)}
/>
<span className="spacer" /> <span className="spacer" />
<button <button
className="primary" className="primary"
@@ -106,10 +111,9 @@ export function StepCard({
{busy ? "Running…" : step.kind === "check" ? "Check" : "Run"} {busy ? "Running…" : step.kind === "check" ? "Check" : "Run"}
</button> </button>
</div> </div>
{notice && <small role="status">{notice}</small>}
{run && ( {run && (
<section className="result" aria-label="Run output"> <section className="result" aria-label="Run output">
<div role="status"> <div role="status" className="result-status">
{run.status === "success" {run.status === "success"
? "✅ Succeeded" ? "✅ Succeeded"
: run.status === "failure" : run.status === "failure"
+19 -9
View File
@@ -9,8 +9,10 @@ import type { TerminalClientMessage } from "@shellbook/core";
export function TerminalSlot({ export function TerminalSlot({
collapsed = false, collapsed = false,
connect = terminalTransport, connect = terminalTransport,
onClose,
}: { }: {
collapsed?: boolean; collapsed?: boolean;
onClose?: () => void;
connect?: (session: string) => TerminalTransport; connect?: (session: string) => TerminalTransport;
}) { }) {
const container = useRef<HTMLDivElement>(null); const container = useRef<HTMLDivElement>(null);
@@ -105,18 +107,26 @@ export function TerminalSlot({
if (!collapsed) refit.current(); if (!collapsed) refit.current();
}, [collapsed]); }, [collapsed]);
return ( return (
<aside className="terminal" aria-label="Terminal panel" hidden={collapsed}> <aside className="terminal side-panel" aria-label="Terminal panel" hidden={collapsed}>
<h2>Terminal · main</h2> <header className="panel-header">
<p> <h2>Terminal</h2>
Run `claude` here — it edits notebooks in this workspace; the view <span role="status" className={`dot-status ${state === "Connected" ? "ok" : state === "Disconnected" ? "bad" : ""}`}>
reloads live. {state}
</p> </span>
<div className="actions">
<span role="status">{state}</span>
{state === "Disconnected" && ( {state === "Disconnected" && (
<button onClick={() => setAttempt((n) => n + 1)}>Reconnect</button> <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} /> <div className="terminal-screen" ref={container} />
</aside> </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>
);
}
+18 -5
View File
@@ -8,11 +8,7 @@ import {
} from "@shellbook/core"; } from "@shellbook/core";
export function notebookSteps(blocks: Block[]): Step[] { export function notebookSteps(blocks: Block[]): Step[] {
return blocks.flatMap((b) => return blocks.flatMap((b) =>
b.type === "step" b.type === "step" ? [b.step] : "blocks" in b ? notebookSteps(b.blocks) : [],
? [b.step]
: b.type === "markdown" || b.type === "host"
? []
: notebookSteps(b.blocks),
); );
} }
const attr = (value: string) => const attr = (value: string) =>
@@ -72,6 +68,23 @@ export function useSnippet(path: string, alias: string): string {
throw new Error("Alias must use letters, digits or _ (not shellbook)"); throw new Error("Alias must use letters, digits or _ (not shellbook)");
return `\n\n::use{notebook=${attr(path)} as=${alias}}\n`; return `\n\n::use{notebook=${attr(path)} as=${alias}}\n`;
} }
/** A titled, collapsible container; its outline shows whether its inputs are filled in. */
export function groupSnippet(title = "Group title"): string {
return `
:::group{title=${attr(title)}}
Explain this part here.
:::
`;
}
/** The parameter's input field at this point of the text. */
export function paramFieldSnippet(name: string): string {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error("Invalid parameter name");
return `
::param{name=${name}}
`;
}
/** Add the machine a notebook created to Hosts; replace the example templates. */ /** Add the machine a notebook created to Hosts; replace the example templates. */
export function hostSnippet(): string { export function hostSnippet(): string {
return '\n\n::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}\n'; return '\n\n::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}\n';
+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 select,
.chat-panel h2, .chat-panel p { margin: .25rem 0; } .chat-panel textarea {
.chat-panel select, .chat-panel textarea { width: 100%; box-sizing: border-box; } width: 100%;
.chat-panel label { display: block; } }
.chat-messages { flex: 1; min-height: 120px; overflow-y: auto; overflow-wrap: anywhere; } .chat-messages {
.chat-messages pre { overflow-x: auto; } flex: 1;
.chat-message { padding: .6rem 0; border-bottom: 1px solid #64748b55; } min-height: 120px;
.chat-message.user { opacity: .85; } overflow-y: auto;
.chat-shell { margin-top: .5rem; } overflow-wrap: anywhere;
.chat-panel form { flex-shrink: 0; } border-top: 1px solid var(--line);
@media (max-width: 900px) { .chat-panel { position: static; grid-column: 1 / -1; height: min(800px, 100dvh); } } border-bottom: 1px solid var(--line);
@media (max-width: 580px) { .with-terminal { display: block; } .chat-panel { padding: .7rem; } } }
.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;
}
+50 -41
View File
@@ -1,49 +1,58 @@
.hosts-page { .host-list {
padding: 1rem; border: 1px solid var(--line);
max-width: 70rem; 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; 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; white-space: pre-wrap;
overflow-wrap: anywhere; overflow-wrap: anywhere;
background: var(--code);
border: 1px solid var(--line);
border-radius: 5px;
padding: 10px 12px;
font-size: 12px;
} }
.hosts-page form { @media (max-width: 760px) {
display: flex; .host-row {
flex-wrap: wrap; grid-template-columns: minmax(0, 1fr);
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;
} }
.app:has(.hosts-page) .sidebar { .host-row .actions {
width: auto; flex-wrap: wrap;
} }
} }
+25 -12
View File
@@ -2,9 +2,18 @@ import type { ServerEvent, StartRunRequest } from "@shellbook/core";
import type { Api } from "../api"; import type { Api } from "../api";
import { HttpError } from "../api"; import { HttpError } from "../api";
import { findStep, parseNotebook, renderStep } from "@shellbook/core"; import { findStep, parseNotebook, renderStep } from "@shellbook/core";
import initial from "./ssh-key.md?raw"; import sshKey from "./ssh-key.md?raw";
let source = initial; import adminUser from "../../../../templates/workspace/notebooks/admin-user.md?raw";
let version = 1; // Demo notebooks, editable in this browser session only.
const files: Record<string, { title: string; source: string; version: number }> = {
"ssh-key.md": { title: "New server SSH key", source: sshKey, version: 1 },
"admin-user.md": { title: "Create an admin user", source: adminUser, version: 1 },
};
const file = (path: string) => {
const entry = files[path];
if (!entry) throw new HttpError(404);
return entry;
};
let counter = 0; let counter = 0;
const listeners = new Set<(event: ServerEvent) => void>(); const listeners = new Set<(event: ServerEvent) => void>();
const emit = (event: ServerEvent) => const emit = (event: ServerEvent) =>
@@ -43,26 +52,30 @@ export const mockApi: Api = {
me: async () => ({ authenticated: true }), me: async () => ({ authenticated: true }),
login: async () => undefined, login: async () => undefined,
list: async () => ({ list: async () => ({
notebooks: [{ path: "ssh-key.md", title: "New server SSH key" }], notebooks: Object.entries(files).map(([path, entry]) => ({ path, title: entry.title })),
}), }),
hosts: async () => ({ hosts }), hosts: async () => ({ hosts }),
notebook: async (path) => ({ notebook: async (path) => {
const { source, version } = file(path);
return {
path, path,
source, source,
notebook: parseNotebook(source), notebook: parseNotebook(source),
includes: [], includes: [],
builtins: { "shellbook.public_key": "ssh-ed25519 AAAADEMO shellbook" }, builtins: { "shellbook.public_key": "ssh-ed25519 AAAADEMO shellbook" },
version: String(version), version: String(version),
}), };
},
addHost: async (host) => { addHost: async (host) => {
if (hosts.some((h) => h.name === host.name)) throw new HttpError(409, "Host already exists"); if (hosts.some((h) => h.name === host.name)) throw new HttpError(409, "Host already exists");
hosts.push({ ...host }); hosts.push({ ...host });
}, },
save: async (_path, next, base) => { save: async (path, next, base) => {
if (base !== String(version)) throw new HttpError(409); const entry = file(path);
source = next; if (base !== String(entry.version)) throw new HttpError(409);
version++; entry.source = next;
return { version: String(version) }; entry.version++;
return { version: String(entry.version) };
}, },
events: (receive, connected) => { events: (receive, connected) => {
listeners.add(receive); listeners.add(receive);
@@ -73,7 +86,7 @@ export const mockApi: Api = {
}, },
artifact: () => artifactUrl, artifact: () => artifactUrl,
run: async (request: StartRunRequest) => { run: async (request: StartRunRequest) => {
const notebook = parseNotebook(source); const notebook = parseNotebook(file(request.notebookPath).source);
const step = findStep(notebook.blocks, request.stepId); const step = findStep(notebook.blocks, request.stepId);
if (!step) throw new Error("Unknown demo step"); if (!step) throw new Error("Unknown demo step");
const rendered = renderStep( const rendered = renderStep(
+6 -18
View File
@@ -1,3 +1,4 @@
/* Authoring toolbar above the Markdown editor. */
.authoring { .authoring {
display: flex; display: flex;
align-items: end; align-items: end;
@@ -5,30 +6,17 @@
gap: 0.5rem; gap: 0.5rem;
margin: 0.75rem 0; margin: 0.75rem 0;
} }
.authoring label, .authoring label {
.sidebar form label {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 0.25rem; gap: 0.25rem;
font-size: 12px;
} }
.authoring form, .authoring form,
.authoring details { .authoring details {
flex-basis: 100%; flex-basis: 100%;
} }
.sidebar form { .authoring input,
display: flex; .authoring select {
flex-direction: column; width: auto;
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;
} }
+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, SessionSettingsResponse,
ClaudeStatusResponse, ClaudeStatusResponse,
SystemInfoResponse, SystemInfoResponse,
UpdateCheckResponse,
UpdateStartResponse,
UpdateStatusResponse,
} from "@shellbook/core"; } from "@shellbook/core";
import { HttpError } from "./api"; import { HttpError } from "./api";
async function request<T>(path: string, body?: unknown): Promise<T> { async function request<T>(path: string, body?: unknown): Promise<T> {
@@ -25,7 +28,11 @@ export const settingsApi = {
password: (body: ChangePasswordRequest) => password: (body: ChangePasswordRequest) =>
request<void>("/settings/password", body), request<void>("/settings/password", body),
revoke: () => request<void>("/settings/sessions/revoke", {}), revoke: () => request<void>("/settings/sessions/revoke", {}),
logout: () => request<void>("/auth/logout", {}),
session: () => request<SessionSettingsResponse>("/settings/session"), session: () => request<SessionSettingsResponse>("/settings/session"),
claude: () => request<ClaudeStatusResponse>("/settings/claude"), claude: () => request<ClaudeStatusResponse>("/settings/claude"),
system: () => request<SystemInfoResponse>("/settings/system"), system: () => request<SystemInfoResponse>("/settings/system"),
updateStatus: () => request<UpdateStatusResponse>("/settings/update"),
checkUpdate: () => request<UpdateCheckResponse>("/settings/update/check", {}),
startUpdate: () => request<UpdateStartResponse>("/settings/update", {}),
}; };
+1116 -465
View File
File diff suppressed because it is too large Load Diff
+11
View File
@@ -89,3 +89,14 @@ it("generates valid chaining snippets", async () => {
expect(() => useSnippet("../x.md", "ct")).toThrow("dir/name.md"); expect(() => useSnippet("../x.md", "ct")).toThrow("dir/name.md");
expect(() => useSnippet("x.md", "shellbook")).toThrow("Alias"); expect(() => useSnippet("x.md", "shellbook")).toThrow("Alias");
}); });
it("generates valid group and parameter field snippets", async () => {
const { groupSnippet, paramFieldSnippet } = await import("../authoring");
const base = "---\nparams:\n hostname: {type: name}\n---\n";
const notebook = parseNotebook(base + groupSnippet('Say "hi"') + paramFieldSnippet("hostname"));
expect(notebook.diagnostics).toEqual([]);
expect(notebook.blocks.filter((b) => b.type !== "markdown")).toEqual([
expect.objectContaining({ type: "group", title: 'Say "hi"', collapsed: false }),
expect.objectContaining({ type: "param", name: "hostname" }),
]);
expect(() => paramFieldSnippet("a b")).toThrow("Invalid parameter name");
});
+19
View File
@@ -96,6 +96,25 @@ it("adds the created container to Hosts and feeds it into the parent's steps", a
expect(screen.getByRole("button", { name: "Run all checks" })).toBeEnabled(); 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 () => { it("reloads when an included notebook changes", async () => {
const { api, emit } = harness(); const { api, emit } = harness();
render(<App api={api} />); render(<App api={api} />);
+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); vi.mocked(json).mockResolvedValue(inventory);
render(<HostsPage />); render(<HostsPage />);
await screen.findByText("demo"); 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("Name"), { target: { value: "new" } });
fireEvent.change(screen.getByLabelText("Address"), { fireEvent.change(screen.getByLabelText("Address"), {
target: { value: "::1" }, target: { value: "::1" },
@@ -42,7 +44,7 @@ it("sends credentials once and clears password fields", async () => {
vi.mocked(json).mockResolvedValue(inventory); vi.mocked(json).mockResolvedValue(inventory);
render(<HostsPage />); render(<HostsPage />);
await screen.findByText("demo"); 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"), { fireEvent.change(screen.getByLabelText("Authentication"), {
target: { value: "password" }, target: { value: "password" },
}); });
@@ -79,7 +81,8 @@ it("requires fingerprint confirmation and resends the displayed installation scr
}); });
render(<HostsPage />); render(<HostsPage />);
await screen.findByText("demo"); 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"); await screen.findByText("literal script");
expect(json).not.toHaveBeenCalledWith( expect(json).not.toHaveBeenCalledWith(
"/host-management/demo/action", "/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); vi.mocked(json).mockResolvedValue(inventory);
render(<HostsPage />); render(<HostsPage />);
await screen.findByText("demo"); 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" }); vi.mocked(json).mockResolvedValue({ ...inventory, version: "v2" });
window.dispatchEvent(new Event("shellbook:hosts-changed")); window.dispatchEvent(new Event("shellbook:hosts-changed"));
await waitFor(() => expect(json).toHaveBeenCalledTimes(2)); 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 />); render(<HostsPage />);
await screen.findByText("demo"); 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/); const alert = await screen.findByText(/SSH authentication failed/);
expect(alert.textContent).toBe("SSH authentication failed: check the user and the saved password or key"); 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, deleteNotebook: remove,
} as unknown as Api } as unknown as Api
} }
list={[]} list={[{ path: "a.md", title: "A" }]}
path="a.md" path="a.md"
version="latest" version="latest"
onSelect={vi.fn()} onSelect={vi.fn()}
@@ -83,7 +83,10 @@ it("requires explicit delete confirmation and uses the displayed version", async
canLeave={() => true} 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(); expect(remove).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Confirm delete" })); fireEvent.click(screen.getByRole("button", { name: "Confirm delete" }));
await waitFor(() => expect(remove).toHaveBeenCalledWith("a.md", "latest")); 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", version: "Claude 1",
loginAppearsPresent: true, 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 revoke = vi.spyOn(settingsApi, "revoke").mockResolvedValue();
const open = vi.fn(); const open = vi.fn();
render(<SettingsPage openTerminal={open} />); render(<SettingsPage openTerminal={open} />);
expect(await screen.findByText("/workspace")).toBeInTheDocument(); expect(await screen.findByText("/workspace")).toBeInTheDocument();
expect(await screen.findByRole("button", { name: "Update now" })).toBeInTheDocument();
expect(screen.getByText(/86400 seconds/)).toBeInTheDocument(); expect(screen.getByText(/86400 seconds/)).toBeInTheDocument();
expect(screen.getByText("Available: Claude 1")).toBeInTheDocument(); expect(screen.getByText("Available: Claude 1")).toBeInTheDocument();
fireEvent.click(screen.getByText("Open terminal to log in")); fireEvent.click(screen.getByText("Open terminal to log in"));
+6 -1
View File
@@ -1,4 +1,9 @@
import "@testing-library/jest-dom/vitest"; import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react"; import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest"; 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 can modify. A failed build leaves the running service in place; check
`journalctl -u shellbook`. `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 Configuration is `/etc/shellbook/env`; data is `/var/lib/shellbook` (back it up
along with workspace and service-user home). `SHELLBOOK_SESSION_SECONDS` defaults along with workspace and service-user home). `SHELLBOOK_SESSION_SECONDS` defaults
to 2592000 (30 days). Cookies survive restart. Logout clears the browser cookie; to 2592000 (30 days). Cookies survive restart. Logout clears the browser cookie;
+28
View File
@@ -120,6 +120,33 @@ PATH=/home/shellbook/.local/bin:/usr/local/bin:/usr/bin:/bin
EOF EOF
fi fi
chmod 600 /etc/shellbook/env 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' cat > /etc/systemd/system/shellbook.service <<'EOF'
[Unit] [Unit]
Description=ShellBook runbook server Description=ShellBook runbook server
@@ -162,6 +189,7 @@ if [[ -n ${TS_AUTHKEY:-} ]]; then
fi fi
systemctl daemon-reload systemctl daemon-reload
systemctl enable shellbook systemctl enable shellbook
systemctl enable --now shellbook-update.path
systemctl restart shellbook systemctl restart shellbook
# Wait until the server answers before reporting success. # Wait until the server answers before reporting success.
listen_host=$(sed -n 's/^SHELLBOOK_HOST=//p' /etc/shellbook/env) listen_host=$(sed -n 's/^SHELLBOOK_HOST=//p' /etc/shellbook/env)
+14 -1
View File
@@ -37,4 +37,17 @@ tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
[[ ! -e $tmp/w/notebooks/infra/lxc.md ]] || { echo 'offer_templates: deleted template came back' >&2; exit 1; } [[ ! -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; } [[ $(sort "$tmp/offered" | tr '\n' ' ') == 'notebooks/a.md notebooks/infra/lxc.md ' ]] || { echo 'offer_templates: wrong list' >&2; exit 1; }
) )
printf '9 install script checks passed\n' # 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'
+46 -6
View File
@@ -93,7 +93,11 @@ Download the private key above, then save it:
- **Substitution in scripts is shell-safe**: the value is inserted shell-quoted when it - **Substitution in scripts is shell-safe**: the value is inserted shell-quoted when it
contains anything outside `[A-Za-z0-9._/@:=+-]`. The displayed script and the executed contains anything outside `[A-Za-z0-9._/@:=+-]`. The displayed script and the executed
script are the same string. One function does this (`core/shellQuote`), nowhere else. script are the same string. One function does this (`core/shellQuote`), nowhere else.
- A step with a missing required param shows the script with `{{name}}` highlighted and a disabled Run button. - A step needs exactly the values it uses: every param and runtime value it references, and
the required secrets its script reads as `$NAME`/`${NAME}`. While one is missing the script
shows `{{name}}` highlighted and Run is disabled. Required params the step does not use never
block it, so a guided notebook (§3.7) runs its first steps before later values are entered.
Set secrets of the step's notebook are always validated, because all are passed as env vars.
### 3.3 Step attributes ### 3.3 Step attributes
@@ -149,12 +153,11 @@ notebook that first creates an LXC container:
- `with` sets defaults of the included params, written in the including notebook's - `with` sets defaults of the included params, written in the including notebook's
namespace. Secrets cannot be bound; they are entered in the form and passed only to namespace. Secrets cannot be bound; they are entered in the form and passed only to
steps of their own notebook, under their local name (`$ROOTPW`). steps of their own notebook, under their local name (`$ROOTPW`).
- Required params gate only steps of their own notebook (scope); a step also needs every - Steps are gated only by the values they use (§3.2); an included notebook's empty form
value it references. never blocks the parent's steps unless they reference its values.
- Non-secret defaults may reference captures and builtins (`default: "{{ct.host}}"`). Until - Non-secret defaults may reference captures and builtins (`default: "{{ct.host}}"`). Until
the value exists the field shows "Available after the step that sets ct.host". A the value exists the field shows "Available after the step that sets ct.host". Only
required param that waits for a capture of its own notebook would block the step steps that reference such a param wait for it.
producing it; make such params optional.
- `::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}` adds - `::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}` adds
the machine to Hosts (same validation as the Hosts page; never overwrites a different the machine to Hosts (same validation as the Hosts page; never overwrites a different
host with that name). `capture` stores the host name as a runtime value so later host with that name). `capture` stores the host name as a runtime value so later
@@ -163,6 +166,35 @@ notebook that first creates an LXC container:
`{{shellbook.public_key}}` is ShellBook's SSH public key. The server sets them on every `{{shellbook.public_key}}` is ShellBook's SSH public key. The server sets them on every
run; client-sent values are ignored. run; client-sent values are ignored.
### 3.7 Guided text: parameter fields and groups
Authors can ask for each value where the text explains it:
```markdown
:::group{title="1. Network" collapsed}
Pick the bridge the container joins:
::param{name=bridge}
:::
```
- `::param{name=x}` on its own line shows the input of the declared parameter `x` at that
point. It is bound to the same value as the parameter panel, which still lists every
parameter. Inside an included notebook the name is namespaced like everything else.
- `:::group{title="…" collapsed}` … `:::` is a titled, collapsible container for any
blocks, including nested groups. `collapsed` starts it closed; the user's choice is
remembered per notebook. The title may use `{{name}}` like prose. Groups are purely
presentational: unlike `:::when` they never hide or block steps.
- A group's **inputs** are its `::param` fields, the parameters its steps and `::host`
blocks reference (those are needed: the step cannot run without them) and, for a
`::use` section, the included notebook's parameters. Inactive `:::when` sections and
runtime values are ignored. Core `groupInputs` computes the status, shown as the outline
color and in words: orange (missing) while a required or needed input is empty or a
value is invalid, green (filled) when every input has a value, grey (optional) when
only optional inputs are empty or there are none.
- Included notebooks (`::use`) are shown as groups with the same status, so a reusable
group is a notebook included where it is needed.
## 4. Execution ## 4. Execution
- Scripts run as `bash -euo pipefail -s` with the script on stdin; no TTY. - Scripts run as `bash -euo pipefail -s` with the script on stdin; no TTY.
@@ -276,6 +308,14 @@ checks and responses disable caching.
service user home; credential contents are never read or returned. 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). - 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. - 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. - No secrets in notebooks, audit log or artifacts metadata.
## 8. Architecture ## 8. Architecture
+10 -8
View File
@@ -15,7 +15,7 @@ export function notebookIncludes(notebook: Notebook): string[] {
const walk = (blocks: Block[]) => { const walk = (blocks: Block[]) => {
for (const block of blocks) { for (const block of blocks) {
if (block.type === "use" && !block.blocks.length) { if (includePath(block.path)) paths.push(block.path); } if (block.type === "use" && !block.blocks.length) { if (includePath(block.path)) paths.push(block.path); }
else if (block.type === "after" || block.type === "when" || block.type === "use") walk(block.blocks); else if (block.type === "after" || block.type === "when" || block.type === "use" || block.type === "group") walk(block.blocks);
} }
}; };
walk(notebook.blocks); walk(notebook.blocks);
@@ -53,6 +53,8 @@ function prefixBlocks(blocks: Block[], alias: string): Block[] {
case "after": return { ...block, stepId: qualify(alias, block.stepId), blocks: prefixBlocks(block.blocks, alias) }; case "after": return { ...block, stepId: qualify(alias, block.stepId), blocks: prefixBlocks(block.blocks, alias) };
case "when": return { ...block, param: qualify(alias, block.param), blocks: prefixBlocks(block.blocks, alias) }; case "when": return { ...block, param: qualify(alias, block.param), blocks: prefixBlocks(block.blocks, alias) };
case "use": return { ...block, scope: qualify(alias, block.scope), bindings: {}, blocks: prefixBlocks(block.blocks, alias) }; case "use": return { ...block, scope: qualify(alias, block.scope), bindings: {}, blocks: prefixBlocks(block.blocks, alias) };
case "group": return { ...block, title: rewrite(block.title, alias), blocks: prefixBlocks(block.blocks, alias) };
case "param": return { ...block, name: qualify(alias, block.name) };
case "host": return { case "host": return {
...block, id: qualify(alias, block.id), scope: scoped(alias, block.scope), ...block, id: qualify(alias, block.id), scope: scoped(alias, block.scope),
name: rewrite(block.name, alias), address: rewrite(block.address, alias), name: rewrite(block.name, alias), address: rewrite(block.address, alias),
@@ -77,7 +79,7 @@ function blockIds(blocks: Block[], into: string[] = []): string[] {
for (const block of blocks) { for (const block of blocks) {
if (block.type === "step") into.push(block.step.attrs.id); if (block.type === "step") into.push(block.step.attrs.id);
else if (block.type === "host") into.push(block.id); else if (block.type === "host") into.push(block.id);
else if (block.type !== "markdown") blockIds(block.blocks, into); else if ("blocks" in block) blockIds(block.blocks, into);
} }
return into; return into;
} }
@@ -98,7 +100,7 @@ function compose(path: string, notebook: Notebook, load: (path: string) => Noteb
const params: ParamDef[] = [...notebook.params]; const params: ParamDef[] = [...notebook.params];
const fail = (message: string, line: number) => diagnostics.push({ severity: "error", message, line }); const fail = (message: string, line: number) => diagnostics.push({ severity: "error", message, line });
const resolve = (blocks: Block[]): Block[] => blocks.map((block): Block => { const resolve = (blocks: Block[]): Block[] => blocks.map((block): Block => {
if (block.type === "after" || block.type === "when") return { ...block, blocks: resolve(block.blocks) }; if (block.type === "after" || block.type === "when" || block.type === "group") return { ...block, blocks: resolve(block.blocks) };
if (block.type !== "use") return block; if (block.type !== "use") return block;
const line = block.range.startLine; const line = block.range.startLine;
// The parser already reported an invalid path; never hand it to the loader. // The parser already reported an invalid path; never hand it to the loader.
@@ -132,11 +134,11 @@ function compose(path: string, notebook: Notebook, load: (path: string) => Noteb
return { ...notebook, params, blocks, diagnostics }; return { ...notebook, params, blocks, diagnostics };
} }
/** Find a step anywhere in the block tree (after, when and use containers). */ /** Find a step anywhere in the block tree (after, when, use and group containers). */
export function findStep(blocks: Block[], id: string): Step | undefined { export function findStep(blocks: Block[], id: string): Step | undefined {
for (const block of blocks) { for (const block of blocks) {
if (block.type === "step" && block.step.attrs.id === id) return block.step; if (block.type === "step" && block.step.attrs.id === id) return block.step;
if (block.type === "after" || block.type === "when" || block.type === "use") { if ("blocks" in block) {
const found = findStep(block.blocks, id); const found = findStep(block.blocks, id);
if (found) return found; if (found) return found;
} }
@@ -155,7 +157,7 @@ export function blockActive(notebook: Notebook, id: string, values: ParamValues)
if (block.type === "when") { if (block.type === "when") {
const found = walk(block.blocks, active && block.values.includes(values[block.param] ?? "")); const found = walk(block.blocks, active && block.values.includes(values[block.param] ?? ""));
if (found !== undefined) return found; if (found !== undefined) return found;
} else if (block.type === "after" || block.type === "use") { } else if (block.type === "after" || block.type === "use" || block.type === "group") {
const found = walk(block.blocks, active); const found = walk(block.blocks, active);
if (found !== undefined) return found; if (found !== undefined) return found;
} }
@@ -171,7 +173,7 @@ export function scopeActive(notebook: Notebook, scope: string, values: ParamValu
const walk = (blocks: Block[], active: boolean): boolean | undefined => { const walk = (blocks: Block[], active: boolean): boolean | undefined => {
for (const block of blocks) { for (const block of blocks) {
if (block.type === "use" && block.scope === scope) return active; if (block.type === "use" && block.scope === scope) return active;
if (block.type === "markdown" || block.type === "step" || block.type === "host") continue; if (!("blocks" in block)) continue;
const found = walk(block.blocks, active && (block.type !== "when" || block.values.includes(values[block.param] ?? ""))); const found = walk(block.blocks, active && (block.type !== "when" || block.values.includes(values[block.param] ?? "")));
if (found !== undefined) return found; if (found !== undefined) return found;
} }
@@ -185,7 +187,7 @@ export function captureNames(blocks: Block[], into = new Set<string>()): Set<str
for (const block of blocks) { for (const block of blocks) {
if (block.type === "step" && block.step.attrs.capture) into.add(block.step.attrs.capture); if (block.type === "step" && block.step.attrs.capture) into.add(block.step.attrs.capture);
else if (block.type === "host" && block.capture) into.add(block.capture); else if (block.type === "host" && block.capture) into.add(block.capture);
else if (block.type !== "markdown" && block.type !== "step" && block.type !== "host") captureNames(block.blocks, into); else if ("blocks" in block) captureNames(block.blocks, into);
} }
return into; return into;
} }
+77 -11
View File
@@ -1,5 +1,5 @@
// Public API of @shellbook/core. Pure functions, no I/O. // Public API of @shellbook/core. Pure functions, no I/O.
import type { Block, Notebook, ParamValues, RenderedHost, RenderedStep, Step } from "./types"; import type { Block, GroupInputs, Notebook, ParamValues, RenderedHost, RenderedStep, Step } from "./types";
import { captureNames, isBuiltin } from "./compose"; import { captureNames, isBuiltin } from "./compose";
export type * from "./types"; export type * from "./types";
export type * from "./protocol"; export type * from "./protocol";
@@ -78,8 +78,10 @@ export function resolveParams(
} }
/** /**
* Shared template substitution for steps and host blocks. Required params gate only * Shared template substitution for steps and host blocks. A block needs exactly the values
* blocks of their own scope: an included notebook's form does not block the parent. * it uses (spec §3.6): referenced parameters and runtime values, and for scripts the
* required secrets of its scope that the script reads. Required parameters it does not
* use never block it, so guided notebooks can run early steps before later values exist.
*/ */
function substitution(notebook: Notebook, scope: string | undefined, values: ParamValues, runtime: ParamValues, hostNames: readonly string[]) { function substitution(notebook: Notebook, scope: string | undefined, values: ParamValues, runtime: ParamValues, hostNames: readonly string[]) {
const resolved = resolveParams(notebook, values, hostNames, runtime); const resolved = resolveParams(notebook, values, hostNames, runtime);
@@ -87,12 +89,18 @@ function substitution(notebook: Notebook, scope: string | undefined, values: Par
const defs = new Map(notebook.params.map(def => [def.name, def])); const defs = new Map(notebook.params.map(def => [def.name, def]));
const invalid = dictionary(); const invalid = dictionary();
const missing = new Set<string>(); const missing = new Set<string>();
for (const def of notebook.params) { const ownSecrets = notebook.params.filter(def => def.type === "secret" && (def.scope ?? "") === (scope ?? ""));
if ((def.scope ?? "") !== (scope ?? "")) continue; // Every set secret of the scope is passed as an env var (secretEnv), so it must be valid.
if (def.required && !resolved.values[def.name]) missing.add(def.name); for (const def of ownSecrets)
if ((def.required || def.type === "secret") && resolved.values[def.name] if (resolved.values[def.name] && own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!;
&& own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!; /** A required secret the script reads as $NAME or ${NAME} (its local name) must be set. */
const readsSecrets = (script: string) => {
for (const def of ownSecrets) {
const local = def.scope ? def.name.slice(def.scope.length + 1) : def.name;
if (def.required && !resolved.values[def.name] && new RegExp("\\$\\{?" + local + "(?![A-Za-z0-9_])").test(script))
missing.add(def.name);
} }
};
const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => { const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => {
const def = defs.get(name); const def = defs.get(name);
if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; } if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; }
@@ -110,7 +118,7 @@ function substitution(notebook: Notebook, scope: string | undefined, values: Par
if (own(invalid, name)) return match; if (own(invalid, name)) return match;
return script ? shellQuote(value) : value; return script ? shellQuote(value) : value;
}); });
return { substitute, invalid, missing }; return { substitute, readsSecrets, invalid, missing };
} }
/** /**
@@ -124,8 +132,9 @@ export function renderStep(
runtime: ParamValues, runtime: ParamValues,
hostNames: readonly string[], hostNames: readonly string[],
): RenderedStep { ): RenderedStep {
const { substitute, invalid, missing } = substitution(notebook, step.attrs.scope, values, runtime, hostNames); const { substitute, readsSecrets, invalid, missing } = substitution(notebook, step.attrs.scope, values, runtime, hostNames);
const script = substitute(step.script, true); const script = substitute(step.script, true);
readsSecrets(step.script);
const host = step.attrs.local || step.attrs.host === undefined ? undefined : substitute(step.attrs.host, false); const host = step.attrs.local || step.attrs.host === undefined ? undefined : substitute(step.attrs.host, false);
if (!step.attrs.local && (!host || !hostNames.includes(host))) invalid.host ??= "Unknown or missing target host"; if (!step.attrs.local && (!host || !hostNames.includes(host))) invalid.host ??= "Unknown or missing target host";
const plainFile = (name: string) => !!name && !/[\\/\0\r\n]/.test(name) && !name.includes(".."); const plainFile = (name: string) => !!name && !/[\\/\0\r\n]/.test(name) && !name.includes("..");
@@ -162,10 +171,67 @@ export function renderHost(
return { id: block.id, name, address, user, port, missing: [...missing], invalid }; return { id: block.id, name, address, user, port, missing: [...missing], invalid };
} }
/**
* Input status of a container block (`:::group`, `::use`; spec §3.7). Its inputs are its
* `::param` fields, the parameters its steps and host blocks reference (those are needed:
* the step cannot run without them) and, for `::use`, the included notebook's parameters.
* Sections of inactive `:::when` blocks are ignored; runtime values are not inputs.
*/
export function groupInputs(
notebook: Notebook,
block: Block,
values: ParamValues,
hostNames: readonly string[],
runtime: ParamValues = {},
): GroupInputs {
const resolved = resolveParams(notebook, values, hostNames, runtime);
const defs = new Map(notebook.params.map(def => [def.name, def]));
const params: string[] = [];
const needed = new Set<string>();
const add = (name: string, need: boolean) => {
const def = defs.get(name);
if (!def) return;
if (!params.includes(name)) params.push(name);
if (need || def.required) needed.add(name);
};
const references = (text: string) => { for (const match of text.matchAll(template)) add(match[1]!, true); };
const walk = (items: Block[]) => {
for (const item of items) {
switch (item.type) {
case "param": add(item.name, false); break;
case "step": {
const attrs = item.step.attrs;
// In display order: the target first, then the script.
if (attrs.host !== undefined) references(attrs.host);
references(item.step.script);
attrs.artifacts.forEach(references);
for (const upload of attrs.uploads) { references(upload.src); references(upload.dst); }
break;
}
case "host": [item.name, item.address, item.user, item.port].forEach(references); break;
case "when": if (item.values.includes(resolved.values[item.param] ?? "")) walk(item.blocks); break;
case "use":
for (const def of notebook.params) if (def.scope === item.scope) add(def.name, false);
walk(item.blocks); break;
case "after": case "group": walk(item.blocks); break;
case "markdown": break;
}
}
};
walk([block]);
const filled = (name: string) => !!resolved.values[name];
const missing = params.filter(name => needed.has(name) && !filled(name));
const invalid = params.filter(name => filled(name) && own(resolved.errors, name));
const status = missing.length || invalid.length ? "missing"
: !params.length ? "none"
: params.every(filled) ? "filled" : "optional";
return { status, params, missing, invalid };
}
/** Substitute prose without quoting; secrets always appear masked. */ /** Substitute prose without quoting; secrets always appear masked. */
export function renderText(text: string, values: ParamValues, notebook: Notebook): string { export function renderText(text: string, values: ParamValues, notebook: Notebook): string {
const secrets = new Set(notebook.params.filter(def => def.type === "secret").map(def => def.name)); const secrets = new Set(notebook.params.filter(def => def.type === "secret").map(def => def.name));
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);
} }
/** /**
+50 -13
View File
@@ -46,6 +46,16 @@ function attributes(text: string, error: (message: string) => void): Map<string,
return result; 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 { export function parseNotebook(source: string): Notebook {
const notebook: Notebook = { title: "Untitled", params: [], blocks: [], diagnostics: [] }; const notebook: Notebook = { title: "Untitled", params: [], blocks: [], diagnostics: [] };
const rawLines = source.split("\n"); const rawLines = source.split("\n");
@@ -70,22 +80,26 @@ export function parseNotebook(source: string): Notebook {
else if (data.title !== undefined) error("title must be a non-empty string", 2); 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 (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 (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); // Point at the parameter itself, not just the frontmatter start.
if (!record(raw)) { error(`Parameter ${name} must be a mapping`, 2); continue; } const at = paramLine(lines, end, name);
if (!paramTypes.has(String(raw.type))) { error(`Unknown param type for ${name}`, 2); continue; } 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 }; 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); for (const key of Object.keys(raw)) if (!["type", "required", "default", "label", "options"].includes(key))
if (raw.required !== undefined && typeof raw.required !== "boolean") error(`required must be boolean for ${name}`, 2); // `{ 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 (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 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; 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; 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); else if (raw.options !== undefined) error(`Invalid options for ${name}`, at);
if (def.type === "choice" && !def.options?.length) error(`Choice ${name} needs options`, 2); if (def.type === "choice" && !def.options?.length) error(`Choice ${name} needs options`, at);
notebook.params.push(def); notebook.params.push(def);
} }
} }
@@ -142,7 +156,24 @@ export function parseNotebook(source: string): Notebook {
blocks.push({ type: "when", param: param ?? "", values, blocks: children, range: { startLine: begin + 1, endLine: i } }); blocks.push({ type: "when", param: param ?? "", values, blocks: children, range: { startLine: begin + 1, endLine: i } });
markdownStart = i; continue; markdownStart = i; continue;
} }
const leaf = /^\s{0,3}::(use|host)\{(.*)\}\s*$/.exec(line); const group = /^\s{0,3}:::group\{(.*)\}\s*$/.exec(line);
if (group && depth < 100) {
flush(); const begin = i++;
const attrs = attributes(group[1]!, m => error(m, begin + 1));
for (const key of attrs.keys()) if (!["title", "collapsed"].includes(key)) error(`Unknown group attribute: ${key}`, begin + 1);
const title = attrs.get("title");
if (title?.length !== 1 || typeof title[0] !== "string" || !title[0].trim()) error('group requires title="…"', begin + 1);
if (attrs.has("collapsed") && attrs.get("collapsed")![0] !== true) error("collapsed must be a flag", begin + 1);
const children = parseBlocks(true, depth + 1);
if (i === lines.length) error("Unclosed group container", begin + 1);
else i++;
blocks.push({
type: "group", title: typeof title?.[0] === "string" ? title[0] : "", collapsed: attrs.has("collapsed"),
blocks: children, range: { startLine: begin + 1, endLine: i },
});
markdownStart = i; continue;
}
const leaf = /^\s{0,3}::(use|host|param)\{(.*)\}\s*$/.exec(line);
if (leaf) { if (leaf) {
flush(); flush();
const lineNo = i + 1; const lineNo = i + 1;
@@ -153,7 +184,13 @@ export function parseNotebook(source: string): Notebook {
return typeof v?.[0] === "string" ? v[0] : undefined; return typeof v?.[0] === "string" ? v[0] : undefined;
}; };
const range = { startLine: lineNo, endLine: lineNo }; const range = { startLine: lineNo, endLine: lineNo };
if (leaf[1] === "use") { if (leaf[1] === "param") {
for (const key of attrs.keys()) if (key !== "name") error(`Unknown param attribute: ${key}`, lineNo);
const name = get("name") ?? "";
if (!name) error("param requires name=parameter", lineNo);
else if (!notebook.params.some(def => def.name === name)) error(`param references unknown parameter: ${name}`, lineNo);
blocks.push({ type: "param", name, range });
} else if (leaf[1] === "use") {
for (const key of attrs.keys()) if (!["notebook", "as", "with"].includes(key)) error(`Unknown use attribute: ${key}`, lineNo); for (const key of attrs.keys()) if (!["notebook", "as", "with"].includes(key)) error(`Unknown use attribute: ${key}`, lineNo);
const path = get("notebook") ?? ""; const path = get("notebook") ?? "";
const alias = get("as") ?? ""; const alias = get("as") ?? "";
@@ -256,7 +293,7 @@ export function parseNotebook(source: string): Notebook {
i = end < lines.length ? end + 1 : end; markdownStart = i; continue; i = end < lines.length ? end + 1 : end; markdownStart = i; continue;
} }
heading ??= /^ {0,3}#\s+(.+?)\s*#*\s*$/.exec(line)?.[1]; heading ??= /^ {0,3}#\s+(.+?)\s*#*\s*$/.exec(line)?.[1];
if (/^\s*:::/.test(line) || /^\s{0,3}::(use|host)\b/.test(line)) error("Malformed or unexpected directive", i + 1); if (/^\s*:::/.test(line) || /^\s{0,3}::(use|host|param)\b/.test(line)) error("Malformed or unexpected directive", i + 1);
i++; i++;
} }
flush(); return blocks; flush(); return blocks;
+27
View File
@@ -145,6 +145,33 @@ export interface SessionSettingsResponse { lifetimeSeconds: number }
export interface ClaudeStatusResponse { available: boolean; version: string | null; loginAppearsPresent: boolean } export interface ClaudeStatusResponse { available: boolean; version: string | null; loginAppearsPresent: boolean }
export interface SystemInfoResponse { version: string; workspacePath: string; dataDirPath: string; nodeVersion: string } 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) ------------------------------------------------ // ---- notebook management (#9) ------------------------------------------------
// Paths are relative to notebooks/. Mutations return 409 on stale versions or occupied targets. // Paths are relative to notebooks/. Mutations return 409 on stale versions or occupied targets.
// POST /api/notebooks // POST /api/notebooks
+37
View File
@@ -105,6 +105,26 @@ export type Block =
blocks: Block[]; blocks: Block[];
range: SourceRange; range: SourceRange;
} }
| {
/** `::param{name=x}` — the parameter's input field at this point of the text. */
type: "param";
/** Parameter name (namespaced like `ct.hostname` inside an included notebook). */
name: string;
range: SourceRange;
}
| {
/**
* `:::group{title="…" collapsed}` — a titled, collapsible container for any blocks.
* Purely presentational: it never gates display or execution.
*/
type: "group";
/** Template; `{{name}}` is substituted like prose. */
title: string;
/** `collapsed` flag: starts closed until the user opens it. */
collapsed: boolean;
blocks: Block[];
range: SourceRange;
}
| { | {
/** `::host{name= address= user= port= capture=}` — add a machine to Hosts from the notebook. */ /** `::host{name= address= user= port= capture=}` — add a machine to Hosts from the notebook. */
type: "host"; type: "host";
@@ -120,6 +140,23 @@ export type Block =
range: SourceRange; range: SourceRange;
}; };
/**
* How far the inputs of a group (or included notebook) are filled in:
* "missing" — a needed value is empty or a value is invalid; "filled" — every input has a
* value; "optional" — only optional inputs are empty; "none" — the group has no inputs.
*/
export type InputStatus = "none" | "optional" | "filled" | "missing";
export interface GroupInputs {
status: InputStatus;
/** Parameters the group asks for or uses, in document order. */
params: string[];
/** Needed (required, or referenced by a step or host block) but empty. */
missing: string[];
/** Filled but invalid. */
invalid: string[];
}
/** A `::host` block with all templates resolved. */ /** A `::host` block with all templates resolved. */
export interface RenderedHost { export interface RenderedHost {
id: string; id: string;
+1 -1
View File
@@ -46,7 +46,7 @@ const files: Record<string, string> = { "infra/lxc.md": lxc, "services/web.md":
const load = (path: string) => files[path] === undefined ? undefined : parseNotebook(files[path]!); const load = (path: string) => files[path] === undefined ? undefined : parseNotebook(files[path]!);
const composed = () => composeNotebook("services/web.md", parseNotebook(service), load); const composed = () => composeNotebook("services/web.md", parseNotebook(service), load);
function all(blocks: Block[]): Block[] { function all(blocks: Block[]): Block[] {
return blocks.flatMap(b => b.type === "markdown" || b.type === "step" || b.type === "host" ? [b] : [b, ...all(b.blocks)]); return blocks.flatMap(b => "blocks" in b ? [b, ...all(b.blocks)] : [b]);
} }
const hosts = ["pve", "web-ct", "existing"]; const hosts = ["pve", "web-ct", "existing"];
+12 -1
View File
@@ -80,6 +80,14 @@ describe("parser", () => {
])("reports malformed input without throwing: %s", (source, message) => { ])("reports malformed input without throwing: %s", (source, message) => {
expect(parseNotebook(source).diagnostics.some(d => d.message.includes(message))).toBe(true); 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", () => { it("uses title fallback, numeric step ids, CRLF ranges and exact script whitespace", () => {
expect(parseNotebook("").title).toBe("Untitled"); 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"); 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", () => { it("blocks missing and invalid used params, unknown variables and invalid hosts", () => {
const n = book(" x: {type: name}\n required: {type: string, required: true}\n unused: {type: name}", "{{x}} {{unknown}} {{empty}}", "host=missing"); const n = book(" x: {type: name}\n required: {type: string, required: true}\n unused: {type: name}", "{{x}} {{unknown}} {{empty}}", "host=missing");
const r = render(n, { x: "bad value", unused: "bad value" }, { empty: "" }); const r = render(n, { x: "bad value", unused: "bad value" }, { empty: "" });
expect(r.missing).toEqual(["required", "empty"]); // An unused required param does not block the step (guided notebooks, spec §3.6).
expect(r.missing).toEqual(["empty"]);
expect(Object.keys(r.invalid).sort()).toEqual(["host", "unknown", "x"]); expect(Object.keys(r.invalid).sort()).toEqual(["host", "unknown", "x"]);
expect(r.script).toBe("{{x}} {{unknown}} {{empty}}\n"); expect(r.script).toBe("{{x}} {{unknown}} {{empty}}\n");
}); });
@@ -153,6 +162,8 @@ describe("rendering and secrets", () => {
it("renders prose with raw values and handles inherited names safely", () => { it("renders prose with raw values and handles inherited names safely", () => {
const n = book(" x: {type: string}"); const n = book(" x: {type: string}");
expect(renderText("{{x}} {{toString}}", { x: "a & b" }, n)).toBe("a & b {{toString}}"); 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, {}, {}).invalid.x).toBeUndefined();
expect(render(n, {}, {}).missing).toContain("x"); 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");
});
});
+24 -1
View File
@@ -48,7 +48,9 @@ Non-secret defaults may reference other parameters.
Use `{{name}}` in prose, attributes and scripts. Script substitution is already Use `{{name}}` in prose, attributes and scripts. Script substitution is already
shell-quoted by ShellBook's core: write `id {{user}}`, not `id '{{user}}'`. shell-quoted by ShellBook's core: write `id {{user}}`, not `id '{{user}}'`.
Do not invent escaping rules or assume templates expand like shell variables. Do not invent escaping rules or assume templates expand like shell variables.
Missing required parameters disable execution. In shell strings use ordinary A step runs once every value it uses is set: its `{{…}}` references and the required
secrets its script reads as `$NAME`. Unused required parameters do not block it, so
early steps can run before later values are known. In shell strings use ordinary
shell variables where needed, e.g. `destination={{destination}}` then `"$destination"`. shell variables where needed, e.g. `destination={{destination}}` then `"$destination"`.
## Step syntax and every attribute ## Step syntax and every attribute
@@ -135,5 +137,26 @@ apt-get install -y nginx
offers to add a created machine to Hosts and stores its name in `{{host}}`. offers to add a created machine to Hosts and stores its name in `{{host}}`.
- `{{shellbook.public_key}}` is ShellBook's SSH public key, e.g. for `pct create --ssh-public-keys`. - `{{shellbook.public_key}}` is ShellBook's SSH public key, e.g. for `pct create --ssh-public-keys`.
## Guided text: fields and groups
````markdown
:::group{title="1. Network" collapsed}
Pick the bridge the container joins:
::param{name=bridge}
```sh {check host="{{host}}" id=bridge-exists}
ip link show {{bridge}}
```
:::
````
- `::param{name=x}` on its own line shows parameter `x`'s input at that point (same
value as the parameter panel). Use it to ask for each value where it is explained.
- `:::group{title="…"}` … `:::` is a collapsible section for anything (text, fields,
steps, nested groups); `collapsed` starts it closed. Its outline is orange while a
required field or a parameter its steps use is empty, green when all its inputs are
filled, grey otherwise. Groups never hide or block steps; use `:::when` for that.
See the notebooks for complete SSH-key, read-only hardening, Debian package, LXC See the notebooks for complete SSH-key, read-only hardening, Debian package, LXC
container (`infra/lxc-container.md`) and chained service (`services/web-server.md`) examples. container (`infra/lxc-container.md`) and chained service (`services/web-server.md`) examples.
@@ -0,0 +1,58 @@
---
title: Create an admin user
params:
host: { type: host, required: true, label: Target server }
user: { type: name, required: true, label: User name }
pubkey: { type: string, required: true, label: Public SSH key }
shell: { type: path, default: /bin/bash, label: Login shell }
---
# Create an admin user
A guided runbook: each section asks for what it needs where it is explained. A
section's outline turns green once its values are filled in. For Debian hosts;
runs need passwordless sudo and ask for confirmation.
:::group{title="1. Pick the server"}
Choose the machine from Hosts. This check only reads state.
::param{name=host}
```sh {check host="{{host}}" id=can-sudo title="Passwordless sudo works" sudo}
true
```
:::
:::group{title="2. Describe the user"}
Pick a login name (letters, digits, `.`, `_`, `-`) and paste the public key the
user logs in with, e.g. the content of their `~/.ssh/id_ed25519.pub`.
::param{name=user}
::param{name=pubkey}
::param{name=shell}
```sh {check host="{{host}}" id=user-free title="User does not exist yet"}
! id {{user}}
```
:::
:::group{title="3. Create the user"}
Creates **{{user}}** in the `sudo` group and authorizes the key.
```sh {run host="{{host}}" id=create title="Create user and authorize key" sudo confirm}
useradd --create-home --shell {{shell}} --groups sudo {{user}}
install -d -m 700 -o {{user}} -g {{user}} /home/{{user}}/.ssh
printf '%s\n' {{pubkey}} > /home/{{user}}/.ssh/authorized_keys
chown {{user}}:{{user}} /home/{{user}}/.ssh/authorized_keys
chmod 600 /home/{{user}}/.ssh/authorized_keys
```
:::
:::group{title="4. Verify" collapsed}
```sh {check host="{{host}}" id=verify title="User is in sudo and has the key" sudo}
id -nG {{user}} | grep -qw sudo
test -s /home/{{user}}/.ssh/authorized_keys
```
:::
@@ -20,8 +20,8 @@ params:
Creates an unprivileged container on **{{proxmox}}** (connects as a user that may run 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 `pct`, usually root), starts it with ShellBook's SSH key for root, and adds it to
Hosts. Other notebooks can include this one with Hosts. Other notebooks can include this one with
`::use{notebook="infra/lxc-container.md" as=ct}` and target the new machine as `::use{notebook="infra/lxc-container.md" as=ct}` and target the new machine through
`{{ct.host}}`. its `host` capture (`ct.host` with that alias).
```sh {check host="{{proxmox}}" id=pve title="Proxmox tools are available"} ```sh {check host="{{proxmox}}" id=pve title="Proxmox tools are available"}
command -v pct command -v pct