diff --git a/.agents/mind/architecture.md b/.agents/mind/architecture.md index c015117..513599e 100644 --- a/.agents/mind/architecture.md +++ b/.agents/mind/architecture.md @@ -9,5 +9,6 @@ - [2026-11-16] **Deploy:** Node 22 from the official nodejs.org tarball verified against SHASUMS256; node-pty 1.1.0 has no Linux prebuilds, so the installer adds build-essential + python3. - [2026-11-16] **Settings (#10):** browser setup consumes private setup-token; cookies are bound to the password hash, and sign-out-all atomically rotates the persisted secret. Browser auth mutations serialize and close active WebSockets. +- [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. ## Archive diff --git a/.agents/mind/gotchas.md b/.agents/mind/gotchas.md index 46d0432..a97d91f 100644 --- a/.agents/mind/gotchas.md +++ b/.agents/mind/gotchas.md @@ -7,4 +7,6 @@ - [2026-11-16] **Env names:** single data dir variable is `SHELLBOOK_DATA_DIR` (server config, auth, CLI, installer). SSH key: `SHELLBOOK_SSH_KEY`. - [2026-11-16] **Exit codes vs errors:** a non-zero script exit is a normal result (check ❌) and goes only in run.finished; run.error is for transport/setup failures. +- [2026-11-16] **Notebook root symlinks (#9):** validating only child components after realpath(root) permits a symlinked notebooks root. Notebook reads and mutations validate the root itself before walking children; regression-covered. Workspace CLI/filesystem writers remain trusted against concurrent path swaps. + ## Archive diff --git a/.agents/mind/index.md b/.agents/mind/index.md index 5a30581..0a25f9a 100644 --- a/.agents/mind/index.md +++ b/.agents/mind/index.md @@ -17,4 +17,4 @@ - `architecture.md` — 8 entries — why custom app, stack, AI integration, workspace split - `attempts.md` — 2 entries — marimo + marimo-pair trial and why it was dropped - `open.md` — 2 entries — open design questions -- `gotchas.md` — 5 entries — integration foot-guns (CRLF scripts, host-key event order, tmux vs systemd, env names) +- `gotchas.md` — 6 entries — integration foot-guns (CRLF scripts, host-key event order, tmux vs systemd, env names) diff --git a/apps/server/src/workspace/index.ts b/apps/server/src/workspace/index.ts index 4e5d922..245922b 100644 --- a/apps/server/src/workspace/index.ts +++ b/apps/server/src/workspace/index.ts @@ -1,5 +1,6 @@ +import { atomicNotebookWrite, notebookRoot, notebookManagement } from "./notebooks"; import { createHash } from "node:crypto"; -import { readFile, writeFile, readdir, realpath, lstat } from "node:fs/promises"; +import { readFile, readdir, realpath, lstat } from "node:fs/promises"; import path from "node:path"; import { parse } from "yaml"; import { parseNotebook, type HostInfo } from "@shellbook/core"; @@ -34,6 +35,8 @@ export async function safeFile(root: string, name: string): Promise { } export async function readNotebook(config: ServerConfig, name: string) { + // Name rules apply to creating notebooks only; existing files (git, Claude) stay readable. + await notebookRoot(config); if (!name.endsWith(".md")) throw httpError(400, "Only Markdown notebooks are allowed"); const file = await safeFile(path.join(config.workspaceDir, "notebooks"), name); return { file, source: await readFile(file, "utf8") }; @@ -71,6 +74,7 @@ export class SerialQueue { export async function workspacePlugin(app: FastifyInstance, { config }: { config: ServerConfig }) { const saves = new SerialQueue(); + notebookManagement(app, config, saves); app.get("/api/hosts", async () => ({ hosts: await readHosts(config) })); app.get("/api/notebooks", async () => { const notebooks: { path: string; title: string }[] = []; @@ -84,6 +88,7 @@ export async function workspacePlugin(app: FastifyInstance, { config }: { config } } } + await notebookRoot(config); await walk(path.join(config.workspaceDir, "notebooks")); return { notebooks: notebooks.sort((a, b) => a.path.localeCompare(b.path)) }; }); @@ -93,10 +98,10 @@ export async function workspacePlugin(app: FastifyInstance, { config }: { config }); app.put<{ Params: { path: string }; Body: { source: string; baseVersion: string } }>("/api/notebooks/:path", async req => { if (!req.body || typeof req.body.source !== "string" || typeof req.body.baseVersion !== "string") throw httpError(400, "Invalid save request"); - return saves.run(req.params.path, async () => { + return saves.run("notebooks", async () => { const { file, source } = await readNotebook(config, req.params.path); if (version(source) !== req.body.baseVersion) throw httpError(409, "Notebook changed"); - await writeFile(file, req.body.source, "utf8"); + await atomicNotebookWrite(file, req.body.source); return { version: version(req.body.source) }; }); }); diff --git a/apps/server/src/workspace/notebooks.ts b/apps/server/src/workspace/notebooks.ts new file mode 100644 index 0000000..a9d0987 --- /dev/null +++ b/apps/server/src/workspace/notebooks.ts @@ -0,0 +1,183 @@ +import { randomUUID } from "node:crypto"; +import { + lstat, + mkdir, + realpath, + writeFile, + rename, + unlink, + rmdir, + link, +} from "node:fs/promises"; +import path from "node:path"; +import type { FastifyInstance } from "fastify"; +import type { + CreateNotebookRequest, + MoveNotebookRequest, + DeleteNotebookRequest, +} from "@shellbook/core"; +import { httpError, readNotebook, SerialQueue, version } from "./index"; +import type { ServerConfig } from "../config"; + +export function notebookName(name: string): string { + if ( + typeof name !== "string" || + name.length > 240 || + !name.endsWith(".md") || + name + .split("/") + .some( + (p) => + !/^[A-Za-z0-9][A-Za-z0-9 _.-]*$/.test(p) || + p.includes("..") || + /[. ]$/.test(p) || + /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p), + ) + ) { + throw httpError( + 400, + "Use a relative .md path with letters, numbers, spaces, dots, underscores or hyphens", + ); + } + return name; +} + +/** Validate the root before resolving any notebook path. */ +export async function notebookRoot(config: ServerConfig): Promise { + const root = path.join(await realpath(config.workspaceDir), "notebooks"); + try { + const info = await lstat(root); + if (info.isSymbolicLink() || !info.isDirectory()) + throw httpError( + 400, + "Symlinks and non-directory parents are not allowed", + ); + } catch (e) { + if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e; + } + return root; +} + +/** Walk every component; never follow symlinks. */ +export async function notebookDestination( + config: ServerConfig, + name: string, +): Promise { + notebookName(name); + let current = await notebookRoot(config); + const parts = name.split("/"); + for (let i = 0; i < parts.length; i++) { + current = path.join(current, parts[i]!); + try { + const info = await lstat(current); + if ( + info.isSymbolicLink() || + (i < parts.length - 1 && !info.isDirectory()) + ) + throw httpError( + 400, + "Symlinks and non-directory parents are not allowed", + ); + } catch (e) { + if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e; + } + } + return current; +} + +export async function atomicNotebookWrite( + file: string, + source: string, + exclusive = false, +) { + await mkdir(path.dirname(file), { recursive: true }); + const temp = path.join(path.dirname(file), `.shellbook-${randomUUID()}.tmp`); + try { + await writeFile(temp, source, { + encoding: "utf8", + flag: "wx", + mode: 0o600, + }); + // link publishes a complete file without replacing an existing destination. + if (exclusive) await link(temp, file); + else await rename(temp, file); + } catch (e) { + if ((e as NodeJS.ErrnoException).code === "EEXIST") + throw httpError(409, "Notebook already exists"); + throw e; + } finally { + await unlink(temp).catch(() => {}); + } +} +async function prune(config: ServerConfig, file: string) { + // Same resolved root as the file path; stop at it, never walk above it. + const root = await notebookRoot(config); + for (let dir = path.dirname(file); dir.startsWith(root + path.sep); dir = path.dirname(dir)) { + try { + await rmdir(dir); + } catch (e) { + if ( + ["ENOTEMPTY", "EEXIST", "ENOENT"].includes( + (e as NodeJS.ErrnoException).code ?? "", + ) + ) + return; + throw e; + } + } +} +export function notebookManagement( + app: FastifyInstance, + config: ServerConfig, + queue: SerialQueue, +) { + app.post<{ Body: CreateNotebookRequest }>("/api/notebooks", async (req) => + queue.run("notebooks", async () => { + if (!req.body || typeof req.body.source !== "string") + throw httpError(400, "Invalid notebook"); + const file = await notebookDestination(config, req.body.path); + await atomicNotebookWrite(file, req.body.source, true); + return { path: req.body.path, version: version(req.body.source) }; + }), + ); + for (const operation of ["rename", "duplicate"] as const) { + app.post<{ Params: { path: string }; Body: MoveNotebookRequest }>( + `/api/notebooks/:path/${operation}`, + async (req) => + queue.run("notebooks", async () => { + if (!req.body || typeof req.body.baseVersion !== "string") + throw httpError(400, "Missing baseVersion"); + // Only the new path must satisfy the create rules; the source may predate them. + const { file: original, source } = await readNotebook(config, req.params.path); + if (version(source) !== req.body.baseVersion) + throw httpError(409, "Notebook changed"); + const target = await notebookDestination(config, req.body.path); + await atomicNotebookWrite(target, source, true); + if (operation === "rename") { + try { + await unlink(original); + } catch (e) { + await unlink(target); + throw e; + } + await prune(config, original); + } + return { path: req.body.path, version: version(source) }; + }), + ); + } + app.delete<{ Params: { path: string }; Body: DeleteNotebookRequest }>( + "/api/notebooks/:path", + async (req) => + queue.run("notebooks", async () => { + if (!req.body || typeof req.body.baseVersion !== "string") + throw httpError(400, "Missing baseVersion"); + const { file, source } = await readNotebook(config, req.params.path); + if (version(source) !== req.body.baseVersion) + throw httpError(409, "Notebook changed"); + await unlink(file); + await prune(config, file); + return { deleted: true }; + }), + ); +} diff --git a/apps/server/test/notebooks.test.ts b/apps/server/test/notebooks.test.ts new file mode 100644 index 0000000..0d5bbec --- /dev/null +++ b/apps/server/test/notebooks.test.ts @@ -0,0 +1,304 @@ +import { afterEach, expect, it } from "vitest"; +import { mkdtemp, mkdir, rm, symlink, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { buildApp } from "../src/app"; +import { notebookName, notebookDestination } from "../src/workspace/notebooks"; +import { setPassword } from "../src/auth/credentials"; +const dirs: string[] = []; +afterEach(async () => { + for (const dir of dirs.splice(0)) + await rm(dir, { recursive: true, force: true }); +}); +async function setup(auth = false) { + const dir = await mkdtemp(join(tmpdir(), "shellbook-notebooks-")); + dirs.push(dir); + await mkdir(join(dir, "notebooks")); + await setPassword(dir, "test password"); + return { + dir, + app: await buildApp({ + config: { workspaceDir: dir, dataDir: dir }, + auth: auth ? { dataDir: dir } : false, + }), + }; +} +it.each([ + "../x.md", + "/x.md", + "C:/x.md", + "a\\x.md", + "a/../x.md", + "a//x.md", + "a.txt", + "a/./x.md", + "nul.md", + "x\u0000.md", + "a./x.md", +])("rejects invalid notebook path %s", (name) => { + expect(() => notebookName(name)).toThrow(); +}); +it("rejects symlink parents, files and notebook root", async () => { + const { app, dir } = await setup(); + try { + await mkdir(join(dir, "outside")); + await symlink( + join(dir, "outside"), + join(dir, "notebooks", "linked"), + "junction", + ); + await expect( + notebookDestination({ workspaceDir: dir } as never, "linked/new.md"), + ).rejects.toThrow("Symlinks"); + await rm(join(dir, "notebooks"), { recursive: true }); + await symlink(join(dir, "outside"), join(dir, "notebooks"), "junction"); + await expect( + notebookDestination({ workspaceDir: dir } as never, "new.md"), + ).rejects.toThrow("Symlinks"); + } finally { + await app.close(); + } +}); +it("creates, duplicates, moves, saves and deletes with conflicts and prunes folders", async () => { + const { app, dir } = await setup(); + const url = (p: string) => `/api/notebooks/${encodeURIComponent(p)}`; + try { + const created = await app.inject({ + method: "POST", + url: "/api/notebooks", + payload: { path: "old/a.md", source: "# A\n" }, + }); + expect(created.statusCode).toBe(200); + let baseVersion = created.json().version; + expect( + ( + await app.inject({ + method: "POST", + url: "/api/notebooks", + payload: { path: "old/a.md", source: "overwrite" }, + }) + ).statusCode, + ).toBe(409); + for (const op of ["rename", "duplicate"]) { + expect( + ( + await app.inject({ + method: "POST", + url: url("old/a.md") + `/${op}`, + payload: { path: "new/b.md", baseVersion: "stale" }, + }) + ).statusCode, + ).toBe(409); + } + expect( + ( + await app.inject({ + method: "POST", + url: url("old/a.md") + "/duplicate", + payload: { path: "copy.md", baseVersion }, + }) + ).statusCode, + ).toBe(200); + expect( + ( + await app.inject({ + method: "POST", + url: url("old/a.md") + "/rename", + payload: { path: "copy.md", baseVersion }, + }) + ).statusCode, + ).toBe(409); + expect( + ( + await app.inject({ + method: "POST", + url: url("old/a.md") + "/rename", + payload: { path: "new/b.md", baseVersion }, + }) + ).statusCode, + ).toBe(200); + await expect(stat(join(dir, "notebooks", "old"))).rejects.toThrow(); + expect((await app.inject(url("new/b.md"))).json().source).toBe("# A\n"); + const saved = await app.inject({ + method: "PUT", + url: url("new/b.md"), + payload: { source: "# B", baseVersion }, + }); + expect(saved.statusCode).toBe(200); + baseVersion = saved.json().version; + expect( + ( + await app.inject({ + method: "DELETE", + url: url("new/b.md"), + payload: { baseVersion: "stale" }, + }) + ).statusCode, + ).toBe(409); + expect( + ( + await app.inject({ + method: "DELETE", + url: url("new/b.md"), + payload: { baseVersion }, + }) + ).statusCode, + ).toBe(200); + await expect(stat(join(dir, "notebooks", "new"))).rejects.toThrow(); + expect((await app.inject(url("new/b.md"))).statusCode).toBe(404); + } finally { + await app.close(); + } +}); +it("guards every management route with session and origin checks", async () => { + const { app } = await setup(true); + try { + const login = await app.inject({ + method: "POST", + url: "/api/auth/login", + payload: { password: "test password" }, + }); + const cookie = String(login.headers["set-cookie"]).split(";")[0]!; + for (const [method, url] of [ + ["POST", "/api/notebooks"], + ["POST", "/api/notebooks/a.md/rename"], + ["POST", "/api/notebooks/a.md/duplicate"], + ["DELETE", "/api/notebooks/a.md"], + ] as const) { + expect((await app.inject({ method, url, payload: {} })).statusCode).toBe( + 401, + ); + expect( + ( + await app.inject({ + method, + url, + payload: {}, + headers: { cookie, origin: "https://evil.test" }, + }) + ).statusCode, + ).toBe(403); + } + } finally { + await app.close(); + } +}); + +it("rejects notebook reads through a symlinked notebooks root", async () => { + const { app, dir } = await setup(); + try { + const { writeFile } = await import("node:fs/promises"); + await mkdir(join(dir, "outside")); + await writeFile(join(dir, "outside", "secret.md"), "private"); + await rm(join(dir, "notebooks"), { recursive: true }); + await symlink(join(dir, "outside"), join(dir, "notebooks"), "junction"); + expect((await app.inject("/api/notebooks/secret.md")).statusCode).toBe(400); + } finally { + await app.close(); + } +}); + +it("publishes create/move/delete changes to other tabs through the watcher", async () => { + const { vi } = await import("vitest"); + const { EventsHub } = await import("../src/runs"); + const dir = await mkdtemp(join(tmpdir(), "shellbook-events-")); + dirs.push(dir); + await mkdir(join(dir, "notebooks")); + const hub = new EventsHub(); + const events: unknown[] = []; + hub.subscribe((event) => events.push(event)); + const app = await buildApp({ + config: { workspaceDir: dir, dataDir: dir }, + auth: false, + events: hub, + watchNotebooks: true, + }); + try { + const created = await app.inject({ + method: "POST", + url: "/api/notebooks", + payload: { path: "old/a.md", source: "# A" }, + }); + await vi.waitFor(() => + expect(events).toContainEqual({ type: "file.changed", path: "old/a.md" }), + ); + expect( + ( + await app.inject({ + method: "POST", + url: "/api/notebooks/old%2Fa.md/rename", + payload: { path: "new/a.md", baseVersion: created.json().version }, + }) + ).statusCode, + ).toBe(200); + await vi.waitFor(() => { + expect(events).toContainEqual({ type: "file.deleted", path: "old/a.md" }); + expect(events).toContainEqual({ type: "file.changed", path: "new/a.md" }); + }); + await app.inject({ + method: "DELETE", + url: "/api/notebooks/new%2Fa.md", + payload: { baseVersion: created.json().version }, + }); + await vi.waitFor(() => + expect(events).toContainEqual({ type: "file.deleted", path: "new/a.md" }), + ); + } finally { + await app.close(); + } +}); +it("does not overwrite concurrent creates", async () => { + const { app } = await setup(); + try { + const responses = await Promise.all( + ["one", "two"].map((source) => + app.inject({ + method: "POST", + url: "/api/notebooks", + payload: { path: "race.md", source }, + }), + ), + ); + expect(responses.map((r) => r.statusCode).sort()).toEqual([200, 409]); + } finally { + await app.close(); + } +}); + +it("still opens and saves existing notebooks whose names the create rules would reject", async () => { + const { app, dir } = await setup(); + try { + const { writeFile } = await import("node:fs/promises"); + // Written by git or Claude, not through the create API. + await writeFile(join(dir, "notebooks", "Übersicht (alt).md"), "# Old\n"); + const name = encodeURIComponent("Übersicht (alt).md"); + const read = await app.inject(`/api/notebooks/${name}`); + expect(read.statusCode).toBe(200); + const save = await app.inject({ method: "PUT", url: `/api/notebooks/${name}`, payload: { source: "# New\n", baseVersion: read.json().version } }); + expect(save.statusCode).toBe(200); + const moved = await app.inject({ method: "POST", url: `/api/notebooks/${name}/rename`, payload: { path: "uebersicht.md", baseVersion: save.json().version } }); + expect(moved.statusCode).toBe(200); + expect((await app.inject("/api/notebooks/uebersicht.md")).statusCode).toBe(200); + } finally { + await app.close(); + } +}); + +it("never removes folders outside notebooks/ when the workspace path is a symlink", async () => { + const real = await mkdtemp(join(tmpdir(), "shellbook-real-")); + const linkParent = await mkdtemp(join(tmpdir(), "shellbook-link-")); + dirs.push(real, linkParent); + await mkdir(join(real, "notebooks")); + const workspace = join(linkParent, "ws"); + await symlink(real, workspace, "junction"); + const app = await buildApp({ config: { workspaceDir: workspace, dataDir: real }, auth: false }); + try { + const created = await app.inject({ method: "POST", url: "/api/notebooks", payload: { path: "a/x.md", source: "# X\n" } }); + expect(created.statusCode).toBe(200); + const deleted = await app.inject({ method: "DELETE", url: `/api/notebooks/${encodeURIComponent("a/x.md")}`, payload: { baseVersion: created.json().version } }); + expect(deleted.statusCode).toBe(200); + expect((await stat(join(real, "notebooks"))).isDirectory()).toBe(true); + } finally { + await app.close(); + } +}); diff --git a/apps/web/README.md b/apps/web/README.md index 9a87b64..2a42c03 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -82,3 +82,31 @@ and reconnect. App tests drive the SSH-key fixture through keygen, sensitive art downloads (including 410), after sections, capture substitution, and authorize artifact provenance. Real tmux/Claude login and browser terminal rendering still need an interactive server check. + +## Notebook management and authoring + +The sidebar groups notebooks into folders and filters by title or path. **New notebook** +asks for a name, optional folder and title, then opens a valid starter with a host +parameter, a read-only check, and a confirmed run placeholder. **Rename / move** and +**Duplicate** take a destination path relative to `notebooks/` (including `.md`). +Folders are created automatically; empty folders disappear after moves or deletes. +**Delete** requires explicit confirmation. Names use letters, numbers, spaces, dots, +underscores and hyphens; traversal, absolute paths, symlinks and Windows device names +are rejected. Management needs a real server; the demo reports that limitation. + +In edit mode, the toolbar inserts Check, Run, Artifacts, Upload or Capture examples +at the cursor, targeting the local ShellBook server or a declared host parameter. +Review example commands and file names before execution. **Parameter** adds a YAML +mapping via a form (including choice options and secret rules), preserving unrelated +YAML and comments. **After step** selects an existing step for conditional instructions. +**Format help** explains attributes and parameter references. Save and live preview +continue to use the core parser. Attribute editing remains available in Markdown. + +All mutations use authenticated, same-origin API calls. Save, move, duplicate and +delete use optimistic versions (409 means stale content or an occupied destination). +Files publish atomically, and the existing watcher refreshes other tabs' lists and +clean open documents. External rename/delete retains the old open draft with a +notice; select the new path from the refreshed list. Unsaved edits require confirmation +before navigation or management. External filesystem writers must be trusted: as with +other workspace operations, symlink checks cannot prevent a privileged local process +from swapping path components between filesystem calls. diff --git a/apps/web/package.json b/apps/web/package.json index d9f5155..7d92dfc 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -19,7 +19,8 @@ "codemirror": "^6.0.1", "highlight.js": "^11.10.0", "@xterm/xterm": "^5.5.0", - "@xterm/addon-fit": "^0.10.0" + "@xterm/addon-fit": "^0.10.0", + "yaml": "^2.6.1" }, "devDependencies": { "@types/react": "^18.3.12", diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 723b214..fede150 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -28,6 +28,7 @@ import type { StartRunRequest, Step, } from "@shellbook/core"; +import { NotebookList } from "./NotebookList"; import { HttpError } from "./api"; import type { Api } from "./api"; import { emptySession, eventReducer, stepKey } from "./events"; @@ -129,6 +130,14 @@ export function App({ api }: { api: Api }) { .catch((e) => setError(String(e))); const close = api.events((event: ServerEvent) => { const open = current.current; + if (event.type === "file.changed" || event.type === "file.deleted") { + void api + .list() + .then((result) => { + if (active) setList(result.notebooks); + }) + .catch((e) => setError(String(e))); + } if (event.type === "file.changed" && event.path === open.doc?.path) { if (open.dirty) setConflict(true); else void load(event.path); @@ -334,21 +343,28 @@ export function App({ api }: { api: Api }) {

ShellBookRUNBOOKS

- + !dirty || window.confirm("Discard unsaved edits?")} + onSelect={(next) => { + if (!dirty || window.confirm("Discard unsaved edits?")) + void load(next); + }} + onChanged={async (next) => { + const result = await api.list(); + setList(result.notebooks); + if (next) await load(next); + else { + ++loadSequence.current; + setDoc(undefined); + setSource(""); + setConflict(false); + } + }} + /> {import.meta.env.VITE_MOCK === "1" ? "DEMO · " : ""} {connected diff --git a/apps/web/src/AuthoringToolbar.tsx b/apps/web/src/AuthoringToolbar.tsx new file mode 100644 index 0000000..1111972 --- /dev/null +++ b/apps/web/src/AuthoringToolbar.tsx @@ -0,0 +1,170 @@ +import { useState } from "react"; +import { parseNotebook, type ParamDef } from "@shellbook/core"; +import { + addParameter, + afterSnippet, + notebookSteps, + stepSnippet, + type InsertKind, +} from "./authoring"; +export function AuthoringToolbar({ + source, + insert, + replace, +}: { + source: string; + insert(text: string): void; + replace(text: string): void; +}) { + const notebook = parseNotebook(source); + const hosts = notebook.params.filter((p) => p.type === "host"); + const [target, setTarget] = useState("local"); + const [param, setParam] = useState(false); + const [error, setError] = useState(""); + const [type, setType] = useState("string"); + const [after, setAfter] = useState(""); + const steps = notebookSteps(notebook.blocks); + return ( +
+ + {( + [ + "Check step", + "Run step", + "Artifacts", + "Upload", + "Capture", + ] as InsertKind[] + ).map((kind) => ( + + ))} + + + + {param && ( +
{ + e.preventDefault(); + const data = new FormData(e.currentTarget); + const def: ParamDef = { + name: String(data.get("name")), + type, + required: data.has("required"), + }; + if (data.get("label")) def.label = String(data.get("label")); + if (type !== "secret" && data.get("default")) + def.default = String(data.get("default")); + if (type === "choice") + def.options = String(data.get("options")) + .split("\n") + .map((s) => s.trim()) + .filter(Boolean); + try { + replace(addParameter(source, def)); + setParam(false); + setError(""); + } catch (err) { + setError(String(err)); + } + }} + > + + + + + {type !== "secret" && ( + + )} + {type === "choice" && ( +