From 443bf944b83f38af6d6c4388e1509c034e590812 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Mon, 16 Nov 2026 00:08:30 +0100 Subject: [PATCH] feat(web): add shell-first runbook UI and mock demo (#2) Add notebook parameters, literal highlighted scripts, copy helpers, streamed runs, host-key confirmation, artifacts, conditional notes, login and optimistic Markdown editing. Keep the temporary core renderer isolated to mock mode. Use React and Vite for the UI, react-markdown for safe Markdown rendering, highlight.js for shell syntax, and CodeMirror 6 for Markdown editing. Add Testing Library, jsdom and Vitest for component and event-state coverage. Validate pnpm install, root typecheck and test (29 web tests, 1 server test), plus normal and mock web builds. Core contracts remain unchanged; real backend execution awaits the parallel core/server implementations. --- apps/web/README.md | 35 + apps/web/index.html | 13 + apps/web/package.json | 32 + apps/web/src/App.tsx | 547 +++++++ apps/web/src/Editor.tsx | 35 + apps/web/src/ParamsForm.tsx | 69 + apps/web/src/StepCard.tsx | 145 ++ apps/web/src/TerminalSlot.tsx | 9 + apps/web/src/api.ts | 80 + apps/web/src/events.ts | 108 ++ apps/web/src/main.tsx | 15 + apps/web/src/mock/api.ts | 123 ++ apps/web/src/mock/core.ts | 204 +++ apps/web/src/mock/ssh-key.md | 36 + apps/web/src/ssh.ts | 24 + apps/web/src/style.css | 441 ++++++ apps/web/src/tests/app.test.tsx | 217 +++ apps/web/src/tests/components.test.tsx | 177 +++ apps/web/src/tests/events.test.ts | 105 ++ apps/web/src/tests/setup.ts | 4 + apps/web/src/tests/ssh.test.ts | 29 + apps/web/tsconfig.json | 10 + apps/web/vite.config.ts | 29 + apps/web/vitest.config.ts | 6 + pnpm-lock.yaml | 2019 +++++++++++++++++++++++- 25 files changed, 4510 insertions(+), 2 deletions(-) create mode 100644 apps/web/README.md create mode 100644 apps/web/index.html create mode 100644 apps/web/package.json create mode 100644 apps/web/src/App.tsx create mode 100644 apps/web/src/Editor.tsx create mode 100644 apps/web/src/ParamsForm.tsx create mode 100644 apps/web/src/StepCard.tsx create mode 100644 apps/web/src/TerminalSlot.tsx create mode 100644 apps/web/src/api.ts create mode 100644 apps/web/src/events.ts create mode 100644 apps/web/src/main.tsx create mode 100644 apps/web/src/mock/api.ts create mode 100644 apps/web/src/mock/core.ts create mode 100644 apps/web/src/mock/ssh-key.md create mode 100644 apps/web/src/ssh.ts create mode 100644 apps/web/src/style.css create mode 100644 apps/web/src/tests/app.test.tsx create mode 100644 apps/web/src/tests/components.test.tsx create mode 100644 apps/web/src/tests/events.test.ts create mode 100644 apps/web/src/tests/setup.ts create mode 100644 apps/web/src/tests/ssh.test.ts create mode 100644 apps/web/tsconfig.json create mode 100644 apps/web/vite.config.ts create mode 100644 apps/web/vitest.config.ts diff --git a/apps/web/README.md b/apps/web/README.md new file mode 100644 index 0000000..8148991 --- /dev/null +++ b/apps/web/README.md @@ -0,0 +1,35 @@ +# ShellBook web + +From the repository root, install with `npx -y pnpm@9.15.0 install`. + +PowerShell demo (no server or core implementation required): + +```powershell +$env:VITE_MOCK = '1' +npx -y pnpm@9.15.0 --filter @shellbook/web dev +``` + +Open the Vite URL (normally http://localhost:5173). Select staging, run the checks +(one deliberately fails), generate demo artifacts, and authorize the key to try +confirmation. Production demonstrates the **changed host key** warning. No commands +execute and downloaded artifacts contain dummy text. Mock frontmatter parameters +are fixed to the spec example; body edits preview and save in memory only. + +Normal backend mode: + +```powershell +Remove-Item Env:VITE_MOCK -ErrorAction SilentlyContinue +npx -y pnpm@9.15.0 --filter @shellbook/web dev +``` + +Vite proxies `/api`, including WebSocket upgrades, to 127.0.0.1:8080. Normal builds +use core directly. `src/mock/core.ts` is a temporary fixture renderer selected +only by the VITE_MOCK alias; remove it and that alias when core lands. Never deploy +a build made with VITE_MOCK=1. The terminal slot is intentionally empty until M4. + +`npx -y pnpm@9.15.0 --filter @shellbook/web test` runs jsdom component and reducer +tests. `... --filter @shellbook/web build` builds production assets. Clipboard APIs +require HTTPS or localhost. SSH copy uses a quoted heredoc (a multiline paste), +with strict bash flags matching server execution; secret env values are never copied. +Steps using secret environment variables require the operator to provide them when +pasting manually. WebSocket disconnects disable execution and require a page reload. diff --git a/apps/web/index.html b/apps/web/index.html new file mode 100644 index 0000000..2145fc9 --- /dev/null +++ b/apps/web/index.html @@ -0,0 +1,13 @@ + + + + + + + ShellBook + + +
+ + + diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..9c707c9 --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,32 @@ +{ + "name": "@shellbook/web", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@shellbook/core": "workspace:*", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-markdown": "^9.0.1", + "@codemirror/lang-markdown": "^6.3.1", + "@codemirror/view": "^6.35.0", + "codemirror": "^6.0.1", + "highlight.js": "^11.10.0" + }, + "devDependencies": { + "@types/react": "^18.3.12", + "@types/react-dom": "^18.3.1", + "@vitejs/plugin-react": "^4.3.4", + "vite": "^5.4.11", + "vitest": "^2.1.5", + "jsdom": "^25.0.1", + "@testing-library/react": "^16.1.0", + "@testing-library/jest-dom": "^6.6.3" + } +} diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx new file mode 100644 index 0000000..1a670d3 --- /dev/null +++ b/apps/web/src/App.tsx @@ -0,0 +1,547 @@ +import { + lazy, + Suspense, + useCallback, + useEffect, + useReducer, + useRef, + useState, +} from "react"; +import ReactMarkdown from "react-markdown"; +import { + parseNotebook, + renderStep, + renderText, + resolveParams, +} from "@shellbook/core"; +import type { + Block, + HostInfo, + NotebookResponse, + NotebookSummary, + ParamValues, + ServerEvent, + StartRunRequest, + Step, +} from "@shellbook/core"; +import { HttpError } from "./api"; +import type { Api } from "./api"; +import { emptySession, eventReducer, stepKey } from "./events"; +import { ParamsForm } from "./ParamsForm"; +import { StepCard } from "./StepCard"; +import { TerminalSlot } from "./TerminalSlot"; +const Editor = lazy(() => + import("./Editor").then((module) => ({ default: module.Editor })), +); + +function steps(blocks: Block[]): Step[] { + return blocks.flatMap((block) => + block.type === "step" + ? [block.step] + : block.type === "after" + ? steps(block.blocks) + : [], + ); +} +export function App({ api }: { api: Api }) { + const [auth, setAuth] = useState<"loading" | "login" | "ready">("loading"); + const [password, setPassword] = useState(""); + const [list, setList] = useState([]); + const [hosts, setHosts] = useState([]); + const [doc, setDoc] = useState(); + const [source, setSource] = useState(""); + const [values, setValues] = useState({}); + const [edit, setEdit] = useState(false); + const [terminal, setTerminal] = useState(false); + const [conflict, setConflict] = useState(false); + const [error, setError] = useState(""); + const [connected, setConnected] = useState(false); + const [session, dispatch] = useReducer(eventReducer, emptySession); + const [confirm, setConfirm] = useState(); + const requests = useRef(new Map()); + const [pending, setPending] = useState>(new Set()); + const [checkIds, setCheckIds] = useState([]); + const loadSequence = useRef(0); + const dirty = !!doc && source !== doc.source; + const current = useRef({ doc, dirty, source }); + current.current = { doc, dirty, source }; + const load = useCallback( + async (path: string) => { + const sequence = ++loadSequence.current; + const sourceAtRequest = current.current.source; + try { + const next = await api.notebook(path); + if (sequence !== loadSequence.current) return; + const same = current.current.doc?.path === path; + if ( + current.current.dirty && + current.current.source !== sourceAtRequest + ) { + setConflict(true); + return; + } + setDoc(next); + setSource(next.source); + setConflict(false); + setError(""); + if (!same) { + setValues({}); + setEdit(false); + setCheckIds([]); + } + } catch (e) { + setError(String(e)); + } + }, + [api], + ); + useEffect(() => { + void api + .me() + .then(() => setAuth("ready")) + .catch((e) => { + if (e instanceof HttpError && e.status === 401) setAuth("login"); + else setError(String(e)); + }); + }, [api]); + useEffect(() => { + if (auth !== "ready") return; + let active = true; + void Promise.all([api.list(), api.hosts()]) + .then(([notebooks, inventory]) => { + if (!active) return; + setList(notebooks.notebooks); + setHosts(inventory.hosts); + if (notebooks.notebooks[0]) void load(notebooks.notebooks[0].path); + }) + .catch((e) => setError(String(e))); + const close = api.events((event: ServerEvent) => { + const open = current.current; + if (event.type === "file.changed" && event.path === open.doc?.path) { + if (open.dirty) setConflict(true); + else void load(event.path); + } else if ( + event.type === "file.deleted" && + event.path === open.doc?.path + ) { + setConflict(true); + setError("This notebook was deleted on disk. Your draft is retained."); + } else dispatch(event); + }, setConnected); + return () => { + active = false; + close(); + }; + }, [api, auth, load]); + useEffect(() => { + const guard = (e: BeforeUnloadEvent) => { + if (dirty) { + e.preventDefault(); + e.returnValue = ""; + } + }; + window.addEventListener("beforeunload", guard); + return () => window.removeEventListener("beforeunload", guard); + }, [dirty]); + + const notebook = doc + ? edit + ? parseNotebook(source) + : doc.notebook + : undefined; + const resolved = notebook + ? resolveParams( + notebook, + values, + hosts.map((h) => h.name), + ) + : { values: {}, errors: {} }; + const path = doc?.path ?? ""; + const runtime = session.runtime[path] ?? {}; + const runFor = (id: string) => + session.runs[session.latest[stepKey(path, id)] ?? ""]; + async function start(request: StartRunRequest) { + const key = stepKey(request.notebookPath, request.stepId); + setPending((previous) => new Set(previous).add(key)); + try { + const { runId } = await api.run(request); + requests.current.set(runId, request); + dispatch({ type: "requested", runId, request }); + } catch (e) { + setError(String(e)); + } finally { + setPending((previous) => { + const next = new Set(previous); + next.delete(key); + return next; + }); + } + } + function requestRun(step: Step) { + if (!notebook || !doc || dirty) return; + const rendered = renderStep( + notebook, + step, + resolved.values, + runtime, + hosts.map((h) => h.name), + ); + if ( + rendered.missing.length || + Object.keys(rendered.invalid).length || + pending.has(stepKey(path, step.attrs.id)) + ) + return; + const request: StartRunRequest = { + notebookPath: path, + stepId: step.attrs.id, + params: { ...resolved.values }, + runtime: { ...runtime }, + artifactSources: { ...session.artifactSources[path] }, + }; + const host = hosts.find((h) => h.name === rendered.host); + if ( + step.kind === "run" && + (step.attrs.confirm || host?.tags.includes("prod")) + ) + setConfirm(request); + else void start(request); + } + function blocks(items: Block[]): React.ReactNode { + if (!notebook) return null; + return items.map((block, i) => { + if (block.type === "markdown") + return ( +
+ + {renderText( + block.text, + { ...runtime, ...resolved.values }, + notebook, + )} + +
+ ); + if (block.type === "after") { + const run = runFor(block.stepId); + return run && + run.status === (block.onFailure ? "failure" : "success") ? ( +
+ {blocks(block.blocks)} +
+ ) : null; + } + const rendered = renderStep( + notebook, + block.step, + resolved.values, + runtime, + hosts.map((h) => h.name), + ); + return ( + h.name === rendered.host)} + run={runFor(block.step.attrs.id)} + artifact={api.artifact} + connected={ + connected && + !dirty && + !pending.has(stepKey(path, block.step.attrs.id)) + } + onRun={() => requestRun(block.step)} + /> + ); + }); + } + async function save() { + if (!doc) return; + try { + const saved = await api.save(path, source, doc.version); + setDoc({ + ...doc, + source, + notebook: parseNotebook(source), + version: saved.version, + }); + setConflict(false); + } catch (e) { + if (e instanceof HttpError && e.status === 409) setConflict(true); + else setError(String(e)); + } + } + const keyPrompt = Object.values(session.runs).find( + (run) => run.status === "hostKey" && requests.current.has(run.runId), + ); + if (auth === "login") + return ( +
+

ShellBook

+

Sign in to your workspace

+
{ + e.preventDefault(); + void api + .login(password) + .then(() => { + setPassword(""); + setError(""); + setAuth("ready"); + }) + .catch(() => { + setPassword(""); + setError("Login failed"); + }); + }} + > + + +
+ {error &&

{error}

} +
+ ); + return ( +
+ +
+
+ {doc?.notebook.title ?? "Loading workspace…"} + + +
+ {error && ( +

+ {error} + +

+ )} + {conflict && ( +
+ The file changed on disk. Your draft has been retained. + +
+ )} + {notebook && ( + <> + + setValues((previous) => ({ ...previous, [name]: value })) + } + /> +
+ {edit && ( +
+
+ Markdown editor {dirty ? "· unsaved" : ""} + +
+ Loading editor…

}> + +
+

+ Live preview below. Save changes before running steps. +

+
+ )} + {notebook.diagnostics.map((d, i) => ( +

+ {d.line && `Line ${d.line}: `} + {d.message} +

+ ))} +
+ + {checkIds.length > 0 && ( + + ✅{" "} + { + checkIds.filter((id) => runFor(id)?.status === "success") + .length + }{" "} + / {checkIds.length} · ❌{" "} + { + checkIds.filter((id) => runFor(id)?.status === "failure") + .length + } + + )} +
+ {blocks(notebook.blocks)} +
+ + )} +
+ {terminal && } + {confirm && ( +
+
+

Confirm execution

+

+ Run “{confirm.stepId}” with the displayed parameters? This step + can change the target host. +

+ + +
+
+ )} + {keyPrompt?.hostKey && ( +
+
+

+ {keyPrompt.hostKey.changed + ? "⚠ HOST KEY CHANGED" + : "Unknown SSH host key"} +

+ {keyPrompt.hostKey.changed && ( +

+ STOP: a different key is already trusted. This may indicate a + man-in-the-middle attack. Verify the fingerprint independently + before accepting. +

+ )} +

+ Verify the key for {keyPrompt.hostKey.host}{" "} + through a trusted channel. +

+ {keyPrompt.hostKey.fingerprint} +
+ + +
+
+
+ )} +
+ ); +} diff --git a/apps/web/src/Editor.tsx b/apps/web/src/Editor.tsx new file mode 100644 index 0000000..6f53332 --- /dev/null +++ b/apps/web/src/Editor.tsx @@ -0,0 +1,35 @@ +import { useEffect, useRef } from "react"; +import { EditorView } from "@codemirror/view"; +import { basicSetup } from "codemirror"; +import { markdown } from "@codemirror/lang-markdown"; + +export function Editor({ + source, + onChange, +}: { + source: string; + onChange(source: string): void; +}) { + const root = useRef(null); + const change = useRef(onChange); + change.current = onChange; + useEffect(() => { + const view = new EditorView({ + doc: source, + parent: root.current!, + extensions: [ + basicSetup, + markdown(), + EditorView.lineWrapping, + EditorView.contentAttributes.of({ "aria-label": "Notebook Markdown" }), + EditorView.updateListener.of((update) => { + if (update.docChanged) change.current(update.state.doc.toString()); + }), + ], + }); + return () => view.destroy(); + // Editor lifetime matches edit mode. Parent remounts after reload. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + return
; +} diff --git a/apps/web/src/ParamsForm.tsx b/apps/web/src/ParamsForm.tsx new file mode 100644 index 0000000..88d11e4 --- /dev/null +++ b/apps/web/src/ParamsForm.tsx @@ -0,0 +1,69 @@ +import type { HostInfo, Notebook, ParamValues } from "@shellbook/core"; + +export function ParamsForm({ + notebook, + values, + errors, + hosts, + onChange, +}: { + notebook: Notebook; + values: ParamValues; + errors: Record; + hosts: HostInfo[]; + onChange(name: string, value: string): void; +}) { + return ( +
e.preventDefault()} + > + {notebook.params.map((param) => { + const id = `param-${param.name}`; + const common = { + id, + required: param.required, + value: values[param.name] ?? "", + "aria-labelledby": `${id}-label`, + "aria-invalid": !!errors[param.name], + "aria-describedby": errors[param.name] ? `${id}-error` : undefined, + onChange: ( + e: React.ChangeEvent, + ) => onChange(param.name, e.target.value), + }; + return ( + + ); + })} + + ); +} diff --git a/apps/web/src/StepCard.tsx b/apps/web/src/StepCard.tsx new file mode 100644 index 0000000..4efacb6 --- /dev/null +++ b/apps/web/src/StepCard.tsx @@ -0,0 +1,145 @@ +import { useState } from "react"; +import hljs from "highlight.js/lib/core"; +import bash from "highlight.js/lib/languages/bash"; +import type { HostInfo, RenderedStep, Step } from "@shellbook/core"; +import type { RunState } from "./events"; +import { sshCommand } from "./ssh"; +hljs.registerLanguage("bash", bash); + +function Script({ script }: { script: string }) { + // Highlight each plain segment separately so unresolved templates stay visible. + return ( +
+      
+        {script
+          .split(/(\{\{[^}]+\}\})/g)
+          .map((part, i) =>
+            part.startsWith("{{") ? (
+              {part}
+            ) : (
+              
+            ),
+          )}
+      
+    
+ ); +} +export function StepCard({ + step, + rendered, + host, + run, + onRun, + artifact, + connected = true, +}: { + step: Step; + rendered: RenderedStep; + host?: HostInfo; + run?: RunState; + onRun(): void; + artifact(id: string, name: string): string; + connected?: boolean; +}) { + const [notice, setNotice] = useState(""); + const invalid = + rendered.missing.length > 0 || Object.keys(rendered.invalid).length > 0; + const busy = run?.status === "running" || run?.status === "hostKey"; + async function copy(ssh: boolean) { + try { + await navigator.clipboard.writeText( + ssh && host + ? sshCommand(host, rendered.script, step.attrs.sudo) + : rendered.script, + ); + setNotice("Copied"); + } catch { + setNotice("Copy failed. Select and copy the script manually."); + } + } + return ( +
+
+ {step.kind} +

{step.attrs.title ?? step.attrs.id}

+ + {rendered.local + ? "local · ShellBook server" + : (rendered.host ?? "No host selected")} + + {step.attrs.sudo && sudo} + {(step.attrs.confirm || + (step.kind === "run" && host?.tags.includes("prod"))) && ( + confirm + )} +
+