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.
This commit is contained in:
Florian Schmidt
2026-11-16 00:08:30 +01:00
parent d06f4336ae
commit 443bf944b8
25 changed files with 4510 additions and 2 deletions
+547
View File
@@ -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<NotebookSummary[]>([]);
const [hosts, setHosts] = useState<HostInfo[]>([]);
const [doc, setDoc] = useState<NotebookResponse>();
const [source, setSource] = useState("");
const [values, setValues] = useState<ParamValues>({});
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<StartRunRequest>();
const requests = useRef(new Map<string, StartRunRequest>());
const [pending, setPending] = useState<Set<string>>(new Set());
const [checkIds, setCheckIds] = useState<string[]>([]);
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 (
<div className="prose" key={i}>
<ReactMarkdown>
{renderText(
block.text,
{ ...runtime, ...resolved.values },
notebook,
)}
</ReactMarkdown>
</div>
);
if (block.type === "after") {
const run = runFor(block.stepId);
return run &&
run.status === (block.onFailure ? "failure" : "success") ? (
<section className="after" key={i}>
{blocks(block.blocks)}
</section>
) : null;
}
const rendered = renderStep(
notebook,
block.step,
resolved.values,
runtime,
hosts.map((h) => h.name),
);
return (
<StepCard
key={block.step.attrs.id}
step={block.step}
rendered={rendered}
host={hosts.find((h) => 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 (
<main className="login">
<h1>ShellBook</h1>
<p>Sign in to your workspace</p>
<form
onSubmit={(e) => {
e.preventDefault();
void api
.login(password)
.then(() => {
setPassword("");
setError("");
setAuth("ready");
})
.catch(() => {
setPassword("");
setError("Login failed");
});
}}
>
<label>
Password
<input
autoFocus
type="password"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</label>
<button className="primary">Sign in</button>
</form>
{error && <p role="alert">{error}</p>}
</main>
);
return (
<div className={`app ${terminal ? "with-terminal" : ""}`}>
<aside className="sidebar">
<h1>
ShellBook<span>RUNBOOKS</span>
</h1>
<nav aria-label="Notebooks">
{list.map((item) => (
<button
className={path === item.path ? "selected" : ""}
key={item.path}
onClick={() => {
if (!dirty || window.confirm("Discard unsaved edits?"))
void load(item.path);
}}
>
{item.title}
<small>{item.path}</small>
</button>
))}
</nav>
<small className="connection">
{import.meta.env.VITE_MOCK === "1" ? "DEMO · " : ""}
{connected
? "● Events connected"
: "○ Events disconnected · reload to reconnect"}
</small>
</aside>
<main>
<div className="toolbar">
<span>{doc?.notebook.title ?? "Loading workspace…"}</span>
<button onClick={() => setEdit(!edit)}>
{edit ? "Close editor" : "Edit Markdown"}
</button>
<button
aria-expanded={terminal}
onClick={() => setTerminal(!terminal)}
>
Terminal {terminal ? "→" : "←"}
</button>
</div>
{error && (
<p className="banner error" role="alert">
{error}
<button onClick={() => location.reload()}>Retry</button>
</p>
)}
{conflict && (
<div className="banner error" role="alert">
The file changed on disk. Your draft has been retained.
<button
onClick={() => {
if (!dirty || window.confirm("Discard your draft and reload?"))
void load(path);
}}
>
Reload from disk
</button>
</div>
)}
{notebook && (
<>
<ParamsForm
notebook={notebook}
values={resolved.values}
errors={resolved.errors}
hosts={hosts}
onChange={(name, value) =>
setValues((previous) => ({ ...previous, [name]: value }))
}
/>
<div className="notebook">
{edit && (
<section>
<div className="actions">
<strong>Markdown editor {dirty ? "· unsaved" : ""}</strong>
<button
className="primary"
disabled={
!dirty ||
conflict ||
notebook.diagnostics.some((d) => d.severity === "error")
}
onClick={() => void save()}
>
Save
</button>
</div>
<Suspense fallback={<p>Loading editor…</p>}>
<Editor
key={`${path}:${doc?.version}`}
source={source}
onChange={setSource}
/>
</Suspense>
<p className="muted">
Live preview below. Save changes before running steps.
</p>
</section>
)}
{notebook.diagnostics.map((d, i) => (
<p role="alert" className="error" key={i}>
{d.line && `Line ${d.line}: `}
{d.message}
</p>
))}
<div className="actions">
<button
disabled={
!connected ||
dirty ||
Object.keys(resolved.errors).length > 0 ||
steps(notebook.blocks).some(
(s) =>
runFor(s.attrs.id)?.status === "running" ||
pending.has(stepKey(path, s.attrs.id)),
)
}
onClick={() => {
const checks = steps(notebook.blocks).filter(
(s) => s.kind === "check",
);
setCheckIds(checks.map((s) => s.attrs.id));
checks.forEach(requestRun);
}}
>
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)}
</div>
</>
)}
</main>
{terminal && <TerminalSlot />}
{confirm && (
<div className="modal-backdrop">
<section
role="dialog"
aria-modal="true"
aria-labelledby="confirm-title"
>
<h2 id="confirm-title">Confirm execution</h2>
<p>
Run “{confirm.stepId}” with the displayed parameters? This step
can change the target host.
</p>
<button onClick={() => setConfirm(undefined)}>Cancel</button>
<button
className="primary"
onClick={() => {
void start(confirm);
setConfirm(undefined);
}}
>
Confirm and run
</button>
</section>
</div>
)}
{keyPrompt?.hostKey && (
<div className="modal-backdrop">
<section
role="dialog"
aria-modal="true"
aria-labelledby="hostkey-title"
>
<h2 id="hostkey-title">
{keyPrompt.hostKey.changed
? "⚠ HOST KEY CHANGED"
: "Unknown SSH host key"}
</h2>
{keyPrompt.hostKey.changed && (
<p className="error">
STOP: a different key is already trusted. This may indicate a
man-in-the-middle attack. Verify the fingerprint independently
before accepting.
</p>
)}
<p>
Verify the key for <strong>{keyPrompt.hostKey.host}</strong>{" "}
through a trusted channel.
</p>
<code>{keyPrompt.hostKey.fingerprint}</code>
<div className="actions">
<button
onClick={() =>
dispatch({
type: "run.error",
runId: keyPrompt.runId,
message: "Host key rejected",
})
}
>
Reject
</button>
<button
onClick={() => {
const request = requests.current.get(keyPrompt.runId)!;
dispatch({
type: "run.error",
runId: keyPrompt.runId,
message: "Retrying with accepted host key",
});
void start({
...request,
acceptHostKey: keyPrompt.hostKey!.fingerprint,
});
}}
>
Trust this fingerprint and retry
</button>
</div>
</section>
</div>
)}
</div>
);
}